Skip to main content

vortex_array/aggregate_fn/fns/sum_v2/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! SQL-style sums with explicit overflow and empty-input state.
5//!
6//! [`SumV2`] returns null when there are no valid values, while [`Sum`] returns zero. Tracking empty
7//! input separately from overflow requires a different partial representation. A separate aggregate
8//! preserves compatibility with the scalar partials stored by older Vortex files.
9
10mod grouped;
11pub(crate) use grouped::BoolGroupedSumV2EncodingKernel;
12pub(crate) use grouped::PrimitiveGroupedSumV2EncodingKernel;
13use vortex_error::VortexExpect;
14use vortex_error::VortexResult;
15use vortex_error::vortex_bail;
16use vortex_error::vortex_ensure;
17use vortex_error::vortex_err;
18use vortex_session::VortexSession;
19use vortex_session::registry::CachedId;
20
21use crate::ArrayRef;
22use crate::ArrayView;
23use crate::Canonical;
24use crate::Columnar;
25use crate::ExecutionCtx;
26use crate::aggregate_fn::Accumulator;
27use crate::aggregate_fn::AggregateArgs;
28use crate::aggregate_fn::AggregateFnId;
29use crate::aggregate_fn::AggregateFnVTable;
30use crate::aggregate_fn::DynAccumulator;
31use crate::aggregate_fn::NumericalAggregateOpts;
32use crate::aggregate_fn::fns::sum::Sum;
33use crate::aggregate_fn::fns::sum::SumState;
34use crate::aggregate_fn::fns::sum::accumulate_bool;
35use crate::aggregate_fn::fns::sum::accumulate_decimal;
36use crate::aggregate_fn::fns::sum::accumulate_primitive;
37use crate::aggregate_fn::fns::sum::checked_add_sum_states;
38use crate::aggregate_fn::fns::sum::make_zero_state;
39use crate::aggregate_fn::fns::sum::multiply_constant;
40use crate::arrays::Struct;
41use crate::arrays::struct_::StructArrayExt;
42use crate::builtins::ArrayBuiltins;
43use crate::dtype::DType;
44use crate::dtype::FieldName;
45use crate::dtype::FieldNames;
46use crate::dtype::Nullability;
47use crate::dtype::PType;
48use crate::dtype::StructFields;
49use crate::scalar::Scalar;
50use crate::scalar::ScalarValue;
51use crate::scalar_fn::builtin::operators::BooleanOperator;
52use crate::stats::Precision;
53use crate::stats::Stat;
54use crate::stats::StatsProviderExt;
55use crate::validity::Validity;
56
57const SUM_FIELD: &str = "sum";
58const IS_OVERFLOW_FIELD: &str = "is_overflow";
59const IS_EMPTY_FIELD: &str = "is_empty";
60
61/// Return the SQL-style sum of an array.
62///
63/// Unlike [`sum`](crate::aggregate_fn::fns::sum::sum), this returns null when the array has no
64/// valid values.
65pub fn sum_v2(array: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<Scalar> {
66    let mut acc = Accumulator::try_new(
67        SumV2,
68        NumericalAggregateOpts::default(),
69        array.dtype().clone(),
70    )?;
71    acc.accumulate(array, ctx)?;
72    acc.finish()
73}
74
75/// Sum an array, returning null when it has no valid values or if the sum overflows.
76///
77/// This aggregate intentionally has a distinct ID and partial representation from the legacy
78/// [`Sum`]. Keeping `vortex.sum` unchanged preserves the scalar partials stored by older Vortex
79/// files, while `SumV2` can use an explicit `{ sum, is_overflow, is_empty }` state.
80///
81/// NaN handling for float inputs is controlled by [`NumericalAggregateOpts`]. With `skip_nans`
82/// (the default), NaN values contribute nothing but still make the input non-empty. Otherwise,
83/// any NaN value poisons the sum to NaN.
84#[derive(Clone, Copy, Debug)]
85pub struct SumV2;
86
87impl SumV2 {
88    /// Build an encoding kernel's partial from a widened primitive sum.
89    ///
90    /// `sum` must have dtype `u64`, `i64`, or `f64`. A null sum records overflow and overrides
91    /// `is_empty`. Set `is_empty` only when there were no valid inputs. Valid NaNs make the input
92    /// non-empty even when skipped. The returned struct and its fields are non-null.
93    pub fn partial_from_sum(sum: Scalar, is_empty: bool) -> VortexResult<Scalar> {
94        vortex_ensure!(
95            matches!(
96                sum.dtype(),
97                DType::Primitive(PType::U64 | PType::I64 | PType::F64, _)
98            ),
99            "Expected a widened primitive sum, got {}",
100            sum.dtype(),
101        );
102
103        let sum_dtype = sum.dtype().as_nonnullable();
104        let is_overflow = sum.is_null();
105        let sum = if is_overflow {
106            Scalar::zero_value(&sum_dtype)
107        } else {
108            sum.cast(&sum_dtype)?
109        };
110
111        Ok(Scalar::struct_(
112            sum_v2_partial_dtype(sum_dtype),
113            vec![
114                sum,
115                Scalar::bool(is_overflow, Nullability::NonNullable),
116                Scalar::bool(is_empty && !is_overflow, Nullability::NonNullable),
117            ],
118        ))
119    }
120}
121
122impl AggregateFnVTable for SumV2 {
123    type Options = NumericalAggregateOpts;
124    type Partial = SumV2Partial;
125
126    fn id(&self) -> AggregateFnId {
127        static ID: CachedId = CachedId::new("vortex.sum_v2");
128        *ID
129    }
130
131    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
132        Ok(Some(options.serialize()))
133    }
134
135    fn deserialize(
136        &self,
137        metadata: &[u8],
138        _session: &VortexSession,
139    ) -> VortexResult<Self::Options> {
140        NumericalAggregateOpts::deserialize(metadata)
141    }
142
143    fn return_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
144        Sum.return_dtype(options, input_dtype)
145    }
146
147    fn partial_dtype(&self, options: &Self::Options, input_dtype: &DType) -> Option<DType> {
148        self.return_dtype(options, input_dtype)
149            .map(sum_v2_partial_dtype)
150    }
151
152    fn empty_partial(&self, args: AggregateArgs<'_, Self::Options>) -> VortexResult<Self::Partial> {
153        Ok(SumV2Partial::empty(args.return_dtype))
154    }
155
156    fn partial_from_scalar(
157        &self,
158        args: AggregateArgs<'_, Self::Options>,
159        scalar: &Scalar,
160    ) -> VortexResult<Self::Partial> {
161        let mut partial = SumV2Partial::empty(args.return_dtype);
162        let (sum, is_overflow, is_empty) = decode_partial_scalar(scalar, args.return_dtype)?;
163
164        // Adding the parsed value to the zero state cannot overflow; treat a decimal value that
165        // no longer fits its precision as an already-overflowed partial.
166        let overflowed = checked_add_sum_value(&mut partial.sum, args.return_dtype, sum)?;
167        partial.is_overflow = is_overflow || overflowed;
168        partial.is_empty = is_empty && !partial.is_overflow;
169        Ok(partial)
170    }
171
172    fn merge_partials(
173        &self,
174        args: AggregateArgs<'_, Self::Options>,
175        mut acc: Self::Partial,
176        partial: Self::Partial,
177    ) -> VortexResult<Self::Partial> {
178        if acc.is_overflow {
179            return Ok(acc);
180        }
181        if partial.is_overflow {
182            // An overflowed state keeps its last valid sum, so an empty accumulator adopts the
183            // incoming sum rather than reporting zero.
184            if acc.is_empty {
185                acc.sum = partial.sum;
186            }
187            acc.is_overflow = true;
188            acc.is_empty = false;
189            return Ok(acc);
190        }
191        if partial.is_empty {
192            return Ok(acc);
193        }
194        acc.is_overflow = checked_add_sum_states(&mut acc.sum, args.return_dtype, &partial.sum)?;
195        acc.is_empty = false;
196        Ok(acc)
197    }
198
199    fn to_scalar(
200        &self,
201        args: AggregateArgs<'_, Self::Options>,
202        partial: &Self::Partial,
203    ) -> VortexResult<Scalar> {
204        Ok(Scalar::struct_(
205            args.partial_dtype.clone(),
206            vec![
207                sum_state_scalar(partial, args.return_dtype, Nullability::NonNullable),
208                Scalar::bool(partial.is_overflow, Nullability::NonNullable),
209                Scalar::bool(partial.is_empty, Nullability::NonNullable),
210            ],
211        ))
212    }
213
214    fn is_saturated(
215        &self,
216        _args: AggregateArgs<'_, Self::Options>,
217        partial: &Self::Partial,
218    ) -> bool {
219        partial.is_overflow || matches!(&partial.sum, SumState::Float(value) if value.is_nan())
220    }
221
222    fn try_accumulate(
223        &self,
224        args: AggregateArgs<'_, Self::Options>,
225        partial: &mut Self::Partial,
226        batch: &ArrayRef,
227        _ctx: &mut ExecutionCtx,
228    ) -> VortexResult<bool> {
229        if args.options.skip_nans || !matches!(&partial.sum, SumState::Float(_)) {
230            return Ok(false);
231        }
232
233        match batch.statistics().get_as::<u64>(Stat::NaNCount) {
234            Precision::Exact(0) => Ok(false),
235            Precision::Exact(_) => {
236                let SumState::Float(sum) = &mut partial.sum else {
237                    unreachable!("checked float sum state")
238                };
239                *sum = f64::NAN;
240                partial.is_empty = false;
241                Ok(true)
242            }
243            _ => Ok(false),
244        }
245    }
246
247    fn accumulate(
248        &self,
249        args: AggregateArgs<'_, Self::Options>,
250        partial: &mut Self::Partial,
251        batch: &Columnar,
252        ctx: &mut ExecutionCtx,
253    ) -> VortexResult<()> {
254        if partial.is_overflow {
255            return Ok(());
256        }
257
258        if let Columnar::Constant(constant) = batch {
259            if !constant.scalar().is_null() && !constant.is_empty() {
260                partial.is_empty = false;
261            }
262            if args.options.skip_nans
263                && constant
264                    .scalar()
265                    .as_primitive_opt()
266                    .is_some_and(|primitive| primitive.is_nan())
267            {
268                return Ok(());
269            }
270            if let Some(product) =
271                multiply_constant(constant.scalar(), constant.len(), args.return_dtype)?
272            {
273                if product.is_null() {
274                    partial.is_overflow = true;
275                    partial.is_empty = false;
276                } else {
277                    partial.is_overflow =
278                        checked_add_sum_state(&mut partial.sum, args.return_dtype, &product)?;
279                    partial.is_empty = false;
280                }
281            }
282            return Ok(());
283        }
284
285        let any_valid = partial.is_empty && has_valid_value(batch, ctx)?;
286        let result = match batch {
287            Columnar::Canonical(canonical) => match canonical {
288                Canonical::Primitive(array) => {
289                    accumulate_primitive(&mut partial.sum, array, ctx, args.options.skip_nans)
290                }
291                Canonical::Bool(array) => accumulate_bool(&mut partial.sum, array, ctx),
292                Canonical::Decimal(array) => {
293                    accumulate_decimal(&mut partial.sum, args.return_dtype, array, ctx)
294                }
295                _ => {
296                    vortex_bail!("Unsupported canonical type for sum_v2: {}", batch.dtype())
297                }
298            },
299            Columnar::Constant(_) => unreachable!(),
300        };
301
302        if any_valid {
303            partial.is_empty = false;
304        }
305        if result? {
306            partial.is_overflow = true;
307            partial.is_empty = false;
308        }
309        Ok(())
310    }
311
312    fn finalize(
313        &self,
314        _args: AggregateArgs<'_, Self::Options>,
315        partials: ArrayRef,
316    ) -> VortexResult<ArrayRef> {
317        if let Some(partials) = partials.as_opt::<Struct>() {
318            return finalize_struct(partials);
319        }
320
321        let sum = partials.get_item(SUM_FIELD)?;
322        let is_invalid = partials
323            .get_item(IS_OVERFLOW_FIELD)?
324            .boolean(partials.get_item(IS_EMPTY_FIELD)?, BooleanOperator::Or)?
325            .fill_null(true)?;
326        sum.mask(is_invalid.not()?)
327    }
328
329    fn finalize_scalar(
330        &self,
331        args: AggregateArgs<'_, Self::Options>,
332        partial: &Self::Partial,
333    ) -> VortexResult<Scalar> {
334        if partial.is_overflow || partial.is_empty {
335            return Ok(Scalar::null(args.return_dtype.as_nullable()));
336        }
337        Ok(sum_state_scalar(
338            partial,
339            args.return_dtype,
340            Nullability::Nullable,
341        ))
342    }
343}
344
345fn finalize_struct(partials: ArrayView<'_, Struct>) -> VortexResult<ArrayRef> {
346    let sum = partials.unmasked_field_by_name(SUM_FIELD)?.clone();
347    let is_overflow = partials.unmasked_field_by_name(IS_OVERFLOW_FIELD)?.clone();
348    let is_empty = partials.unmasked_field_by_name(IS_EMPTY_FIELD)?.clone();
349
350    let is_invalid = is_overflow
351        .boolean(is_empty, BooleanOperator::Or)?
352        .fill_null(true)?;
353    let mut is_valid = is_invalid.not()?;
354    match partials.struct_validity() {
355        Validity::NonNullable | Validity::AllValid => {}
356        validity => {
357            is_valid = is_valid.boolean(validity.to_array(partials.len()), BooleanOperator::And)?;
358        }
359    }
360
361    sum.mask(is_valid)
362}
363
364/// In-memory state for SumV2 accumulation.
365pub struct SumV2Partial {
366    sum: SumState,
367    is_overflow: bool,
368    is_empty: bool,
369}
370
371impl SumV2Partial {
372    /// The state of a group with no accumulated values.
373    fn empty(return_dtype: &DType) -> Self {
374        Self {
375            sum: make_zero_state(return_dtype),
376            is_overflow: false,
377            is_empty: true,
378        }
379    }
380}
381
382fn has_valid_value(batch: &Columnar, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
383    let (validity, len) = match batch {
384        Columnar::Canonical(Canonical::Primitive(array)) => {
385            (array.as_ref().validity()?, array.as_ref().len())
386        }
387        Columnar::Canonical(Canonical::Bool(array)) => {
388            (array.as_ref().validity()?, array.as_ref().len())
389        }
390        Columnar::Canonical(Canonical::Decimal(array)) => {
391            (array.as_ref().validity()?, array.as_ref().len())
392        }
393        Columnar::Canonical(_) => return Ok(false),
394        Columnar::Constant(constant) => {
395            return Ok(!constant.is_empty() && !constant.scalar().is_null());
396        }
397    };
398    Ok(validity.execute_mask(len, ctx)?.true_count() > 0)
399}
400
401/// Reads the `sum`, `is_overflow` and `is_empty` fields of a partial scalar.
402///
403/// This reads the struct values directly, because building a [`Scalar`] for each field costs more
404/// than the merge itself.
405fn decode_partial_scalar<'a>(
406    scalar: &'a Scalar,
407    return_dtype: &DType,
408) -> VortexResult<(&'a ScalarValue, bool, bool)> {
409    vortex_ensure!(!scalar.is_null(), "SumV2 partial must not be null");
410
411    let (DType::Struct(fields, _), Some(ScalarValue::Tuple(values))) =
412        (scalar.dtype(), scalar.value())
413    else {
414        vortex_bail!("SumV2 partial must be a struct, got {}", scalar.dtype());
415    };
416
417    let field_index = |name: &str| {
418        fields
419            .find(name)
420            .ok_or_else(|| vortex_err!("SumV2 partial is missing the {name} field"))
421    };
422    let bool_field = |name: &str| -> VortexResult<bool> {
423        match &values[field_index(name)?] {
424            Some(ScalarValue::Bool(value)) => Ok(*value),
425            _ => {
426                vortex_bail!("SumV2 partial field {name} must be a non-null bool")
427            }
428        }
429    };
430
431    let sum_index = field_index(SUM_FIELD)?;
432    let sum_dtype = fields
433        .field_dtypes()
434        .nth(sum_index)
435        .vortex_expect("field index from find is in bounds");
436    validate_sum_field_dtype(sum_dtype, return_dtype)?;
437
438    let sum = values[sum_index]
439        .as_ref()
440        .ok_or_else(|| vortex_err!("SumV2 partial sum must not be null"))?;
441
442    Ok((
443        sum,
444        bool_field(IS_OVERFLOW_FIELD)?,
445        bool_field(IS_EMPTY_FIELD)?,
446    ))
447}
448
449fn validate_sum_field_dtype(sum_dtype: &DType, return_dtype: &DType) -> VortexResult<()> {
450    vortex_ensure!(
451        sum_dtype.nullability() == Nullability::NonNullable
452            && sum_dtype.eq_ignore_nullability(return_dtype),
453        "SumV2 partial value has dtype {}, expected {}",
454        sum_dtype,
455        return_dtype.as_nonnullable(),
456    );
457    Ok(())
458}
459
460fn checked_add_sum_state(
461    state: &mut SumState,
462    return_dtype: &DType,
463    other: &Scalar,
464) -> VortexResult<bool> {
465    let other = other
466        .value()
467        .ok_or_else(|| vortex_err!("Can't extract present value from null scalar"))?;
468    checked_add_sum_value(state, return_dtype, other)
469}
470
471fn checked_add_sum_value(
472    state: &mut SumState,
473    return_dtype: &DType,
474    other: &ScalarValue,
475) -> VortexResult<bool> {
476    Ok(match (state, other) {
477        (SumState::Unsigned(sum), ScalarValue::Primitive(other)) => {
478            checked_add_u64(sum, other.cast::<u64>()?)
479        }
480        (SumState::Signed(sum), ScalarValue::Primitive(other)) => {
481            checked_add_i64(sum, other.cast::<i64>()?)
482        }
483        (SumState::Float(sum), ScalarValue::Primitive(other)) => {
484            *sum += other.cast::<f64>()?;
485            false
486        }
487        (SumState::Decimal(value), ScalarValue::Decimal(other)) => {
488            let dtype = return_dtype
489                .as_decimal_opt()
490                .vortex_expect("decimal sum result dtype");
491            match value.checked_add(other) {
492                Some(result) if result.fits_in_precision(*dtype) => {
493                    *value = result;
494                    false
495                }
496                Some(_) | None => true,
497            }
498        }
499        (_, other) => {
500            vortex_bail!("SumV2 cannot add {other} to a {return_dtype} sum")
501        }
502    })
503}
504
505fn sum_v2_partial_dtype(sum_dtype: DType) -> DType {
506    DType::Struct(sum_v2_partial_fields(sum_dtype), Nullability::Nullable)
507}
508
509fn sum_v2_partial_fields(sum_dtype: DType) -> StructFields {
510    StructFields::new(
511        FieldNames::from_iter([
512            FieldName::from(SUM_FIELD),
513            FieldName::from(IS_OVERFLOW_FIELD),
514            FieldName::from(IS_EMPTY_FIELD),
515        ]),
516        vec![
517            sum_dtype.as_nonnullable(),
518            DType::Bool(Nullability::NonNullable),
519            DType::Bool(Nullability::NonNullable),
520        ],
521    )
522}
523
524fn sum_state_scalar(
525    partial: &SumV2Partial,
526    return_dtype: &DType,
527    nullability: Nullability,
528) -> Scalar {
529    match &partial.sum {
530        SumState::Unsigned(value) => Scalar::primitive(*value, nullability),
531        SumState::Signed(value) => Scalar::primitive(*value, nullability),
532        SumState::Float(value) => Scalar::primitive(*value, nullability),
533        SumState::Decimal(value) => Scalar::decimal(
534            *value,
535            *return_dtype
536                .as_decimal_opt()
537                .vortex_expect("decimal sum result dtype"),
538            nullability,
539        ),
540    }
541}
542
543fn checked_add_u64(sum: &mut u64, value: u64) -> bool {
544    match sum.checked_add(value) {
545        Some(result) => {
546            *sum = result;
547            false
548        }
549        None => true,
550    }
551}
552
553fn checked_add_i64(sum: &mut i64, value: i64) -> bool {
554    match sum.checked_add(value) {
555        Some(result) => {
556            *sum = result;
557            false
558        }
559        None => true,
560    }
561}
562
563#[cfg(test)]
564mod tests;