← Back to Pull requests

refactor: deduplicate Legacy/Ansi/Try integer SUM accumulators in sum_int.rs #7780

Open
EyobelG opened this pull request with 810 lines diff across 3 files
View on GitHub
EyobelG EyobelG commented on Nov 29, 2026 05:13 UTC
Author

Summary


  • Deduplicates the Legacy/Ansi/Try row (SumIntegerAccumulator) and grouped (SumIntGroupsAccumulator) integer SUM accumulators in native/spark-expr/src/agg_funcs/sum_int.rs (-235 net lines).

  • Introduces an OverflowMode trait (LegacyMode, AnsiMode, TryMode) and a single dispatch_int_array helper for Int64/Int32/Int16/Int8 dispatch.

  • Unifies SumIntegerAccumulator<M> and SumIntGroupsAccumulator<M> for Legacy and Ansi, and reuses dispatch_int_array + the generic sum loops for Try while preserving Try's has_all_nulls semantics.
  • Closes #6976.

    Test plan


  • Updated unit test instantiations in native/spark-expr/src/agg_funcs/sum_int.rs (mod tests).

  • No local Rust toolchain available in this environment — relying on CI to run cargo test -p datafusion-comet-spark-expr sum_int, cargo clippy, and cargo fmt --check.
  • Diff: 810 lines (+393 / -417) across 3 files Reviewer: comphead Review duration: 5131m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.46) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 810 lines diff across 3 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.95 · 4 substantive comment(s)
    0.95
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    6 items
    coderfender coderfender commented on Nov 29, 2026 16:50 UTC
    Contributor

    Thank you for the PR. Could you please also add some benches to see if we are impacting on performance with the refactor ?

    comphead comphead commented on code on Nov 30, 2026 18:56 UTC
    Code Review
    native/spark-expr/src/agg_funcs/sum_int.rs:1
    @@ -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>>;
     }

    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.

    comphead comphead commented on code on Nov 30, 2026 18:56 UTC
    Code Review
    native/spark-expr/src/agg_funcs/sum_int.rs:1
    @@ -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)? {

    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.

    comphead comphead commented on code on Nov 30, 2026 18:56 UTC
    Code Review
    native/spark-expr/src/agg_funcs/sum_int.rs:1
    @@ -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(

    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.

    comphead comphead commented on Nov 30, 2026 18:56 UTC
    Reviewer

    I compared each mode against the old code and found no behaviour change. Legacy still wraps, Ansi still raises sum_overflow_error() (same long and try_add payload), and Try keeps its separate has_all_nulls state and merge logic. The per-group overflow skip is unchanged. The real saving is about 235 lines in sum_int.rs, since the 24-line net figure includes the new 207-line bench. The remaining concerns are that the trait lets TryMode be plugged into accumulators that cannot handle it, and that there are no before/after bench numbers for a change to hot loops. I did not compile or run anything.

    Reviewers
    Assignees
    EyobelG EyobelG
    Labels
    risk: low confidence: 87.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 45.9% (MEDIUM) · Higher = larger blast radius
    45.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.8% · Lower = rushed or shallow review
    87.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.6% · Safe to merge
    5.6%