comphead commented on code in PR #7795:
URL: https://github.com/apache/datafusion-comet/pull/7795#discussion_r4743955530


##########
native/spark-expr/src/agg_funcs/avg_decimal.rs:
##########
@@ -590,12 +591,43 @@ impl GroupsAccumulator for AvgDecimalGroupsAccumulator {
         ])
     }
 
+    /// Each row's own partial state, as `state` emits it for a group holding 
only that row: the
+    /// value and a count of one, or a zero sum and count for a null or 
filtered-out row. A value
+    /// outside the sum's precision is an overflow, which nulls its sum and 
count.
     fn convert_to_state(
         &self,
-        _values: &[ArrayRef],
-        _opt_filter: Option<&arrow::array::BooleanArray>,
+        values: &[ArrayRef],
+        opt_filter: Option<&arrow::array::BooleanArray>,
     ) -> Result<Vec<ArrayRef>> {
-        not_impl_err!("Input batch conversion to state not implemented")
+        let values = values[0].as_primitive::<Decimal128Type>();
+        let filter_nulls = opt_filter.map(filter_to_nulls);
+        let included = NullBuffer::union(filter_nulls.as_ref(), 
values.nulls());
+
+        let mut sums = Vec::with_capacity(values.len());
+        let mut counts = Vec::with_capacity(values.len());
+        let mut is_not_null = BooleanBufferBuilder::new(values.len());
+        for (idx, &value) in values.values().iter().enumerate() {
+            if included
+                .as_ref()
+                .is_some_and(|included| included.is_null(idx))
+            {
+                sums.push(0);
+                counts.push(0);
+                is_not_null.append(true);
+            } else {
+                sums.push(value);
+                counts.push(1);
+                is_not_null.append(self.sum_bounds.contains(value));
+            }
+        }

Review Comment:
   This loop runs once per input row for every batch after the probe decides to 
skip, so it is the hot path of the feature. Under the new gate the sum 
precision is always the input precision plus 10, so 
`self.sum_bounds.contains(value)` cannot fail and every state is valid. When 
`values.precision()` is below the sum precision, the conversion can work on 
whole buffers. With `included == None`, reuse `values.values().clone()` for the 
sums and `Int64Array::from_value(1, values.len())` for the counts, with no 
validity bitmap. Otherwise, zero the excluded sums with one 
`values.values().iter().zip(included.iter()).map(..).collect()` and build the 
counts from the same bits. That drops the `BooleanBufferBuilder` and the 
per-row branch. The bounds check can stay for the equal-precision case (a 
`DECIMAL(38, s)` input, which the gate no longer admits) that 
`convert_to_state_matches_one_row_groups` builds. I did not run or benchmark 
this.



##########
native/core/src/execution/jni_api.rs:
##########
@@ -1033,6 +1037,29 @@ pub extern "system" fn 
Java_org_apache_comet_Native_setOutputStream(
     })
 }
 
+/// Whether `avg` is built as `AvgDecimal` (a decimal result; any other result 
is Comet's Float64
+/// `Avg`, which cannot convert rows to states) and no order of adding its 
values can overflow the
+/// sum. Skipping changes the order in which the final aggregate adds a 
group's values, and a sum
+/// that leaves its precision stays null, so `[M, 1 - M]` in each of two tasks 
gives 1 + 1 when
+/// aggregated but overflows at 1 + M when skipped. Spark gives the sum 10 
more digits than the
+/// input up to precision 38, so a sum below 38 has all of them, and a group 
needs more than 10^10
+/// values before any partial sum can leave it.
+fn avg_decimal_cannot_overflow(avg: &Avg) -> bool {
+    let decimal_precision = |datatype: Option<&ProtoDataType>| match datatype {
+        Some(datatype) if datatype.type_id == DataTypeId::Decimal as i32 => {
+            match datatype.type_info.as_ref()?.datatype_struct.as_ref()? {
+                DatatypeStruct::Decimal(decimal) => Some(decimal.precision),
+                _ => None,
+            }
+        }
+        _ => None,
+    };
+    avg.child.is_some()
+        && decimal_precision(avg.datatype.as_ref()).is_some()
+        && decimal_precision(avg.sum_datatype.as_ref())
+            .is_some_and(|precision| precision < DECIMAL128_MAX_PRECISION as 
i32)

Review Comment:
   `jni_api.rs` already imports `serde::to_arrow_datatype`, and the planner 
calls it on these same two fields before it picks `AvgDecimal`. Using it here 
keeps the gate's idea of a decimal `AVG` identical to the planner's and removes 
the hand-written proto walk and the three new non-test imports:
   
   ```rust
   avg.child.is_some()
       && matches!(avg.datatype.as_ref().map(to_arrow_datatype), 
Some(ArrowDataType::Decimal128(..)))
       && matches!(
           avg.sum_datatype.as_ref().map(to_arrow_datatype),
           Some(ArrowDataType::Decimal128(p, _)) if p < DECIMAL128_MAX_PRECISION
       )
   ```
   
   `to_arrow_datatype` unwraps a decimal type without `type_info`, so the test 
case at line 2806 would go. The serde never sends that, and the planner would 
hit the same unwrap. I did not compile this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to