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


##########
native/spark-expr/src/agg_funcs/sum_int.rs:
##########
@@ -285,127 +286,120 @@ impl Accumulator for SlidingSumIntegerAccumulator {
     }
 }
 
-#[derive(Debug)]
-struct SumIntegerAccumulatorLegacy {
-    sum: Option<i64>,
+trait OverflowMode: Send + Sync + std::fmt::Debug {
+    fn add(lhs: i64, rhs: i64) -> DFResult<Option<i64>>;
 }
 
-impl SumIntegerAccumulatorLegacy {
-    fn new() -> Self {
-        Self { sum: None }
+#[derive(Debug)]
+struct LegacyMode;
+
+impl OverflowMode for LegacyMode {
+    fn add(lhs: i64, rhs: i64) -> DFResult<Option<i64>> {
+        Ok(Some(lhs.add_wrapping(rhs)))
     }
 }
 
-impl Accumulator for SumIntegerAccumulatorLegacy {
-    fn update_batch(&mut self, values: &[ArrayRef]) -> DFResult<()> {
-        fn update_sum<T>(int_array: &PrimitiveArray<T>, mut sum: i64) -> 
DFResult<i64>
-        where
-            T: ArrowPrimitiveType,
-        {
-            for i in 0..int_array.len() {
-                if !int_array.is_null(i) {
-                    let v = int_array.value(i).to_i64().ok_or_else(|| {
-                        DataFusionError::Internal(format!(
-                            "Failed to convert value {:?} to i64",
-                            int_array.value(i)
-                        ))
-                    })?;
-                    sum = v.add_wrapping(sum);
-                }
-            }
-            Ok(sum)
-        }
-
-        let values = &values[0];
-        if values.len() == values.null_count() {
-            return Ok(());
-        }
+#[derive(Debug)]
+struct AnsiMode;
 
-        let running_sum = self.sum.unwrap_or(0);
-        let sum = match values.data_type() {
-            DataType::Int64 => 
update_sum(as_primitive_array::<Int64Type>(values), running_sum)?,
-            DataType::Int32 => 
update_sum(as_primitive_array::<Int32Type>(values), running_sum)?,
-            DataType::Int16 => 
update_sum(as_primitive_array::<Int16Type>(values), running_sum)?,
-            DataType::Int8 => 
update_sum(as_primitive_array::<Int8Type>(values), running_sum)?,
-            _ => {
-                return Err(DataFusionError::Internal(format!(
-                    "unsupported data type: {:?}",
-                    values.data_type()
-                )));
-            }
-        };
-        self.sum = Some(sum);
-        Ok(())
+impl OverflowMode for AnsiMode {
+    fn add(lhs: i64, rhs: i64) -> DFResult<Option<i64>> {
+        lhs.add_checked(rhs)
+            .map(Some)
+            .map_err(|_| sum_overflow_error())
     }
+}
 
-    fn evaluate(&mut self) -> DFResult<ScalarValue> {
-        Ok(ScalarValue::Int64(self.sum))
+#[derive(Debug)]
+struct TryMode;
+
+impl OverflowMode for TryMode {
+    fn add(lhs: i64, rhs: i64) -> DFResult<Option<i64>> {
+        Ok(lhs.add_checked(rhs).ok())
     }
+}
 
-    fn size(&self) -> usize {
-        std::mem::size_of_val(self)
+trait IntArrayOp {
+    type Output;
+    fn call<T: ArrowPrimitiveType>(self, array: &PrimitiveArray<T>) -> 
DFResult<Self::Output>;
+}
+
+fn dispatch_int_array<O: IntArrayOp>(values: &ArrayRef, op: O) -> 
DFResult<O::Output> {
+    match values.data_type() {
+        DataType::Int64 => op.call(as_primitive_array::<Int64Type>(values)),
+        DataType::Int32 => op.call(as_primitive_array::<Int32Type>(values)),
+        DataType::Int16 => op.call(as_primitive_array::<Int16Type>(values)),
+        DataType::Int8 => op.call(as_primitive_array::<Int8Type>(values)),
+        other => Err(DataFusionError::Internal(format!(
+            "Unsupported data type for SumInteger: {other:?}"
+        ))),
     }
+}
 
-    fn state(&mut self) -> DFResult<Vec<ScalarValue>> {
-        Ok(vec![ScalarValue::Int64(self.sum)])
+fn sum_int_array<T: ArrowPrimitiveType, M: OverflowMode>(
+    int_array: &PrimitiveArray<T>,
+    mut sum: i64,
+) -> DFResult<Option<i64>> {
+    for i in 0..int_array.len() {
+        if !int_array.is_null(i) {
+            let v = int_array.value(i).to_i64().ok_or_else(|| {
+                DataFusionError::Internal(format!(
+                    "Failed to convert value {:?} to i64",
+                    int_array.value(i)
+                ))
+            })?;
+            match M::add(sum, v)? {

Review Comment:
   This loop and the grouped one at line 573 now call `M::add` and apply `?` on 
a `DFResult<Option<i64>>` per row, where the old Legacy loop was a bare 
`add_wrapping`. After monomorphization I expect LLVM to inline `add` and drop 
the dead branches for `Legacy` and `Ansi`, but I did not run it and 
`DataFusionError` is a large `Err` payload. The bench added in `887a87a454` is 
the right tool, but the PR description has no before/after numbers and the 
request in 
https://github.com/apache/datafusion-comet/pull/7780#issuecomment-7259218152 is 
still open. Please post `cargo bench --bench sum_int` results for `main` 
against this branch, in particular `sum_int_row` and `sum_int_groups` for 
`i64_no_nulls_legacy` and `i32_no_nulls_legacy` where the old loop was 
simplest. The bench uses only public API, so the same file can run on `main`.



##########
native/spark-expr/src/agg_funcs/sum_int.rs:
##########
@@ -285,127 +286,120 @@ impl Accumulator for SlidingSumIntegerAccumulator {
     }
 }
 
-#[derive(Debug)]
-struct SumIntegerAccumulatorLegacy {
-    sum: Option<i64>,
+trait OverflowMode: Send + Sync + std::fmt::Debug {
+    fn add(lhs: i64, rhs: i64) -> DFResult<Option<i64>>;
 }

Review Comment:
   `add` returns `DFResult<Option<i64>>`, but `None` only ever comes from 
`TryMode`. `LegacyMode` and `AnsiMode` always return `Some`, so the `None => 
return Ok(None)` arm in `sum_int_array` is dead for them and `M::add(...)?` in 
`SumIntGroupsAccumulator::merge_batch` (line 659) stores the `Option` directly 
into `sums`. Because `SumIntegerAccumulator<M>` and 
`SumIntGroupsAccumulator<M>` are bounded only by `OverflowMode`, 
`SumIntegerAccumulator::<TryMode>` and `SumIntGroupsAccumulator::<TryMode>` 
compile but are wrong. They lack `has_all_nulls`, so an overflowed group is 
indistinguishable from an all-null one, and the next batch restarts from 
`unwrap_or(0)`. A narrower contract would make that unrepresentable, for 
example an infallible `fn add(lhs, rhs) -> DFResult<i64>` for the Legacy/Ansi 
accumulators, with `Try` calling `add_checked` directly in `RowSumOp` and 
`TryGroupSumOp`. That also drops the `Option` wrapping from the Legacy/Ansi 
inner loops.



##########
native/spark-expr/src/agg_funcs/sum_int.rs:
##########
@@ -482,19 +454,13 @@ impl Accumulator for SumIntegerAccumulatorTry {
         }
 
         let running_sum = self.sum.unwrap_or(0);
-        let sum = match values.data_type() {
-            DataType::Int64 => 
update_sum(as_primitive_array::<Int64Type>(values), running_sum)?,
-            DataType::Int32 => 
update_sum(as_primitive_array::<Int32Type>(values), running_sum)?,
-            DataType::Int16 => 
update_sum(as_primitive_array::<Int16Type>(values), running_sum)?,
-            DataType::Int8 => 
update_sum(as_primitive_array::<Int8Type>(values), running_sum)?,
-            _ => {
-                return Err(DataFusionError::Internal(format!(
-                    "unsupported data type: {:?}",
-                    values.data_type()
-                )));
-            }
-        };
-        self.sum = sum;
+        self.sum = dispatch_int_array(

Review Comment:
   This PR reroutes the `Try` row `update_batch` through `RowSumOp::<TryMode>`, 
but the `tests` module has no test that builds `SumIntegerAccumulatorTry`. The 
`Try` grouped accumulator has `test_try_update_batch_with_filter` and 
`test_try_size_counts_group_state`. The Scala `try_sum` tests I found in 
`CometAggregateSuite.scala` are the null cases and the loop near line 2481, and 
I did not check whether they overflow an integer column. A short unit test 
covering overflow in one batch staying `NULL` after a second batch, an all-null 
batch leaving `NULL`, and `merge_batch` after overflow would pin the behaviour 
this refactor must preserve.



-- 
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