Skip to main content

vortex_functions/
list_sum.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_array::ArrayRef;
5use vortex_array::Canonical;
6use vortex_array::Columnar;
7use vortex_array::ExecutionCtx;
8use vortex_array::IntoArray;
9use vortex_array::aggregate_fn::AggregateFnVTable;
10use vortex_array::aggregate_fn::DynGroupedAccumulator;
11use vortex_array::aggregate_fn::GroupedAccumulator;
12use vortex_array::aggregate_fn::NumericalAggregateOpts;
13use vortex_array::aggregate_fn::fns::sum_v2::SumV2;
14use vortex_array::arrays::ConstantArray;
15use vortex_array::dtype::DType;
16use vortex_array::scalar_fn::Arity;
17use vortex_array::scalar_fn::ChildName;
18use vortex_array::scalar_fn::ExecutionArgs;
19use vortex_array::scalar_fn::ScalarFnId;
20use vortex_array::scalar_fn::ScalarFnVTable;
21use vortex_error::VortexResult;
22use vortex_error::vortex_bail;
23use vortex_error::vortex_err;
24use vortex_session::VortexSession;
25use vortex_session::registry::CachedId;
26
27/// Sum of the elements in each list of a `List` or `FixedSizeList` typed array.
28///
29/// Follows SQL `SUM` semantics per list, matching DuckDB's `list_sum`: null lists, empty
30/// lists, and lists whose elements are all null yield a null sum; null elements are skipped.
31/// Integer and decimal overflow yields a null sum value, matching [`SumV2`]. The result dtype
32/// follows [`SumV2`]'s widening rules and is always nullable.
33///
34/// NaN handling for float elements is controlled by [`NumericalAggregateOpts`]: with
35/// `skip_nans` (the default) NaN values contribute nothing, otherwise any NaN poisons the
36/// list's sum to NaN.
37#[derive(Clone)]
38pub struct ListSum;
39
40impl ScalarFnVTable for ListSum {
41    type Options = NumericalAggregateOpts;
42
43    fn id(&self) -> ScalarFnId {
44        static ID: CachedId = CachedId::new("vortex.list.sum");
45        *ID
46    }
47
48    fn serialize(&self, options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
49        Ok(Some(options.serialize()))
50    }
51
52    fn deserialize(
53        &self,
54        metadata: &[u8],
55        _session: &VortexSession,
56    ) -> VortexResult<Self::Options> {
57        NumericalAggregateOpts::deserialize(metadata)
58    }
59
60    fn arity(&self, _options: &Self::Options) -> Arity {
61        Arity::Exact(1)
62    }
63
64    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
65        match child_idx {
66            0 => ChildName::from("input"),
67            _ => unreachable!("Invalid child index {child_idx} for list_sum()"),
68        }
69    }
70
71    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
72        let elem_dtype = match &arg_dtypes[0] {
73            DType::List(elem, _) | DType::FixedSizeList(elem, ..) => elem.as_ref(),
74            other => {
75                vortex_bail!("list_sum() requires List or FixedSizeList, got {other}")
76            }
77        };
78        SumV2
79            .return_dtype(options, elem_dtype)
80            .ok_or_else(|| vortex_err!("list_sum() cannot sum elements of type {elem_dtype}"))
81    }
82
83    fn execute(
84        &self,
85        options: &Self::Options,
86        args: &dyn ExecutionArgs,
87        ctx: &mut ExecutionCtx,
88    ) -> VortexResult<ArrayRef> {
89        let input = args.get(0)?;
90
91        let elem_dtype = match input.dtype() {
92            DType::List(elem, _) | DType::FixedSizeList(elem, ..) => elem.as_ref().clone(),
93            other => {
94                vortex_bail!("list_sum() requires List or FixedSizeList, got {other}")
95            }
96        };
97
98        let columnar = input.execute::<Columnar>(ctx)?;
99
100        match columnar {
101            Columnar::Constant(constant) => {
102                // Canonicalize one row of the constant and broadcast its sum.
103                let one_row = ConstantArray::new(constant.scalar().clone(), 1)
104                    .into_array()
105                    .execute::<Canonical>(ctx)?
106                    .into_array();
107                let sum =
108                    list_sum_impl(one_row, elem_dtype, options, ctx)?.execute_scalar(0, ctx)?;
109                Ok(ConstantArray::new(sum, constant.len()).into_array())
110            }
111            Columnar::Canonical(canonical) => {
112                list_sum_impl(canonical.into_array(), elem_dtype, options, ctx)
113            }
114        }
115    }
116
117    fn is_strict(&self, _options: &Self::Options) -> bool {
118        // A null list sums to null, which is all that strictness requires. Element nulls are part
119        // of the list value rather than row-level nulls, and a valid list may still sum to null
120        // (empty, all-null, or overflow) since strictness is only one-directional.
121        true
122    }
123
124    fn is_infallible(&self, _options: &Self::Options) -> bool {
125        true
126    }
127}
128
129/// Sum each list of a canonical `array` into one value per list.
130fn list_sum_impl(
131    canonical: ArrayRef,
132    elem_dtype: DType,
133    options: &NumericalAggregateOpts,
134    ctx: &mut ExecutionCtx,
135) -> VortexResult<ArrayRef> {
136    let mut acc = GroupedAccumulator::try_new(SumV2, *options, elem_dtype)?;
137    acc.accumulate_list(&canonical, ctx)?;
138    acc.finish()
139}
140
141#[cfg(test)]
142mod tests {
143    use std::sync::Arc;
144    use std::sync::LazyLock;
145
146    use prost::Message;
147    use rstest::rstest;
148    use vortex_array::ArrayRef;
149    use vortex_array::IntoArray;
150    use vortex_array::VortexSessionExecute;
151    use vortex_array::aggregate_fn::NumericalAggregateOpts;
152    use vortex_array::arrays::BoolArray;
153    use vortex_array::arrays::ConstantArray;
154    use vortex_array::arrays::FixedSizeListArray;
155    use vortex_array::arrays::ListArray;
156    use vortex_array::arrays::ListViewArray;
157    use vortex_array::arrays::PrimitiveArray;
158    use vortex_array::assert_arrays_eq;
159    use vortex_array::dtype::DType;
160    use vortex_array::dtype::Nullability;
161    use vortex_array::dtype::PType;
162    use vortex_array::proto::expr as pb;
163    use vortex_array::scalar::Scalar;
164    use vortex_array::scalar_fn::ScalarFnVTable;
165    use vortex_array::validity::Validity;
166    use vortex_buffer::buffer;
167    use vortex_error::VortexResult;
168    use vortex_expr::ArrayExprExt;
169    use vortex_expr::Expression;
170    use vortex_expr::proto::ExprSerializeProtoExt;
171    use vortex_expr::root;
172    use vortex_session::VortexSession;
173
174    use crate::expr::list_sum;
175    use crate::expr::list_sum_opts;
176    use crate::list_sum::ListSum;
177
178    static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
179        let session = VortexSession::empty();
180
181        vortex_array::initialize(&session);
182
183        crate::initialize(&session);
184
185        session
186    });
187
188    fn create_list_elements() -> ArrayRef {
189        PrimitiveArray::from_option_iter::<i32, _>([
190            Some(1),
191            Some(2),
192            Some(3),
193            Some(4),
194            Some(5),
195            Some(6),
196            None,
197        ])
198        .into_array()
199    }
200
201    #[rstest]
202    #[case(buffer![0u32, 2, 5, 5, 7].into_array())]
203    #[case(buffer![0u64, 2, 5, 5, 7].into_array())]
204    fn test_list_sum(#[case] offsets: ArrayRef) -> VortexResult<()> {
205        let mut ctx = SESSION.create_execution_ctx();
206        let elements = create_list_elements();
207        let list =
208            ListArray::try_new(elements, offsets, Validity::NonNullable, &mut ctx)?.into_array();
209        let result = list.apply(&list_sum(root()))?;
210        let mut ctx = SESSION.create_execution_ctx();
211        // [1, 2] = 3; [3, 4, 5] = 12; [] = null; [6, null] = 6 (nulls skipped).
212        let expected =
213            PrimitiveArray::from_option_iter::<i64, _>([Some(3), Some(12), None, Some(6)]);
214        assert_arrays_eq!(result, expected, &mut ctx);
215        Ok(())
216    }
217
218    #[test]
219    fn test_nullable_list_sum() -> VortexResult<()> {
220        let mut ctx = SESSION.create_execution_ctx();
221        let elements = create_list_elements();
222        let list = ListArray::try_new(
223            elements,
224            buffer![0u32, 2, 5, 5, 7].into_array(),
225            Validity::Array(BoolArray::from_iter([true, false, true, false]).into_array()),
226            &mut ctx,
227        )?
228        .into_array();
229        let result = list.apply(&list_sum(root()))?;
230
231        let mut ctx = SESSION.create_execution_ctx();
232        // Row 1 and 3 are null lists; row 2 is a valid but empty list.
233        let expected = PrimitiveArray::from_option_iter::<i64, _>([Some(3), None, None, None]);
234        assert_arrays_eq!(result, expected, &mut ctx);
235        Ok(())
236    }
237
238    #[test]
239    fn test_all_null_elements_sum_to_null() -> VortexResult<()> {
240        let mut ctx = SESSION.create_execution_ctx();
241        let elements = PrimitiveArray::from_option_iter::<i32, _>([None, None, Some(1)]);
242        let list = ListArray::try_new(
243            elements.into_array(),
244            buffer![0u32, 2, 3].into_array(),
245            Validity::NonNullable,
246            &mut ctx,
247        )?
248        .into_array();
249        let result = list.apply(&list_sum(root()))?;
250
251        let mut ctx = SESSION.create_execution_ctx();
252        let expected = PrimitiveArray::from_option_iter::<i64, _>([None, Some(1)]);
253        assert_arrays_eq!(result, expected, &mut ctx);
254        Ok(())
255    }
256
257    #[test]
258    fn test_overflow_sums_to_null() -> VortexResult<()> {
259        let mut ctx = SESSION.create_execution_ctx();
260        let elements = PrimitiveArray::from_iter([i64::MAX, 1, 1, 2]);
261        let list = ListArray::try_new(
262            elements.into_array(),
263            buffer![0u32, 2, 4].into_array(),
264            Validity::NonNullable,
265            &mut ctx,
266        )?
267        .into_array();
268        let result = list.apply(&list_sum(root()))?;
269
270        let mut ctx = SESSION.create_execution_ctx();
271        let expected = PrimitiveArray::from_option_iter::<i64, _>([None, Some(3)]);
272        assert_arrays_eq!(result, expected, &mut ctx);
273        Ok(())
274    }
275
276    #[test]
277    fn test_unsigned_widening() -> VortexResult<()> {
278        let mut ctx = SESSION.create_execution_ctx();
279        let elements = PrimitiveArray::from_iter([1u8, 2, 3]);
280        let list = ListArray::try_new(
281            elements.into_array(),
282            buffer![0u32, 3].into_array(),
283            Validity::NonNullable,
284            &mut ctx,
285        )?
286        .into_array();
287        let result = list.apply(&list_sum(root()))?;
288
289        let mut ctx = SESSION.create_execution_ctx();
290        let expected = PrimitiveArray::from_option_iter::<u64, _>([Some(6)]);
291        assert_arrays_eq!(result, expected, &mut ctx);
292        Ok(())
293    }
294
295    #[test]
296    fn test_bool_elements() -> VortexResult<()> {
297        let mut ctx = SESSION.create_execution_ctx();
298        let elements = BoolArray::from_iter([true, true, false, true]);
299        let list = ListArray::try_new(
300            elements.into_array(),
301            buffer![0u32, 3, 4].into_array(),
302            Validity::NonNullable,
303            &mut ctx,
304        )?
305        .into_array();
306        let result = list.apply(&list_sum(root()))?;
307
308        let mut ctx = SESSION.create_execution_ctx();
309        let expected = PrimitiveArray::from_option_iter::<u64, _>([Some(2), Some(1)]);
310        assert_arrays_eq!(result, expected, &mut ctx);
311        Ok(())
312    }
313
314    #[test]
315    fn test_nan_skipped_by_default() -> VortexResult<()> {
316        let mut ctx = SESSION.create_execution_ctx();
317        let elements = PrimitiveArray::from_iter([1.0f64, f64::NAN, 2.0]);
318        let list = ListArray::try_new(
319            elements.into_array(),
320            buffer![0u32, 3].into_array(),
321            Validity::NonNullable,
322            &mut ctx,
323        )?
324        .into_array();
325        let result = list.apply(&list_sum(root()))?;
326
327        let mut ctx = SESSION.create_execution_ctx();
328        let expected = PrimitiveArray::from_option_iter::<f64, _>([Some(3.0)]);
329        assert_arrays_eq!(result, expected, &mut ctx);
330        Ok(())
331    }
332
333    #[test]
334    fn test_all_nan_list_sums_to_zero() -> VortexResult<()> {
335        let mut ctx = SESSION.create_execution_ctx();
336        // NaN elements are *valid*: with the default `skip_nans` they contribute nothing, but
337        // the list still has valid elements, so the sum is `0.0` rather than null (unlike an
338        // all-null list).
339        let elements = PrimitiveArray::from_iter([f64::NAN, f64::NAN]);
340        let list = ListArray::try_new(
341            elements.into_array(),
342            buffer![0u32, 2].into_array(),
343            Validity::NonNullable,
344            &mut ctx,
345        )?
346        .into_array();
347        let result = list.apply(&list_sum(root()))?;
348
349        let mut ctx = SESSION.create_execution_ctx();
350        let expected = PrimitiveArray::from_option_iter::<f64, _>([Some(0.0)]);
351        assert_arrays_eq!(result, expected, &mut ctx);
352        Ok(())
353    }
354
355    #[test]
356    fn test_nan_poisons_with_include_nans() -> VortexResult<()> {
357        let mut ctx = SESSION.create_execution_ctx();
358        let elements = PrimitiveArray::from_iter([1.0f64, f64::NAN, 2.0]);
359        let list = ListArray::try_new(
360            elements.into_array(),
361            buffer![0u32, 3].into_array(),
362            Validity::NonNullable,
363            &mut ctx,
364        )?
365        .into_array();
366        let result = list.apply(&list_sum_opts(
367            root(),
368            NumericalAggregateOpts::include_nans(),
369        ))?;
370
371        let mut ctx = SESSION.create_execution_ctx();
372        assert!(result.is_valid(0, &mut ctx)?);
373        let result = result.execute::<PrimitiveArray>(&mut ctx)?;
374        assert!(result.as_slice::<f64>()[0].is_nan());
375        Ok(())
376    }
377
378    #[test]
379    fn test_listview_sum() -> VortexResult<()> {
380        let mut ctx = SESSION.create_execution_ctx();
381        let elements = create_list_elements();
382        // Overlapping and out-of-order views over the shared elements.
383        let lv = ListViewArray::new(
384            elements,
385            buffer![5u32, 0, 4, 1].into_array(),
386            buffer![2u32, 3, 0, 2].into_array(),
387            Validity::NonNullable,
388            &mut ctx,
389        )
390        .into_array();
391        let result = lv.apply(&list_sum(root()))?;
392
393        let mut ctx = SESSION.create_execution_ctx();
394        // [6, null] = 6; [1, 2, 3] = 6; [] = null; [2, 3] = 5.
395        let expected =
396            PrimitiveArray::from_option_iter::<i64, _>([Some(6), Some(6), None, Some(5)]);
397        assert_arrays_eq!(result, expected, &mut ctx);
398        Ok(())
399    }
400
401    fn create_fixed_size_list(validity: Validity) -> ArrayRef {
402        // 4 lists of size 2 over 8 primitive elements.
403        let elements = PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6, 7, 8]).into_array();
404        FixedSizeListArray::new(elements, 2, validity, 4).into_array()
405    }
406
407    #[test]
408    fn test_fixed_size_list_sum() -> VortexResult<()> {
409        let fsl = create_fixed_size_list(Validity::NonNullable);
410        let result = fsl.apply(&list_sum(root()))?;
411
412        let mut ctx = SESSION.create_execution_ctx();
413        let expected =
414            PrimitiveArray::from_option_iter::<i64, _>([Some(3), Some(7), Some(11), Some(15)]);
415        assert_arrays_eq!(result, expected, &mut ctx);
416        Ok(())
417    }
418
419    #[test]
420    fn test_fixed_size_list_sum_nullable() -> VortexResult<()> {
421        let fsl = create_fixed_size_list(Validity::Array(
422            BoolArray::from_iter([true, false, true, false]).into_array(),
423        ));
424        let result = fsl.apply(&list_sum(root()))?;
425
426        let mut ctx = SESSION.create_execution_ctx();
427        let expected = PrimitiveArray::from_option_iter::<i64, _>([Some(3), None, Some(11), None]);
428        assert_arrays_eq!(result, expected, &mut ctx);
429        Ok(())
430    }
431
432    #[test]
433    fn test_list_sum_take() -> VortexResult<()> {
434        let mut ctx = SESSION.create_execution_ctx();
435        let elements = create_list_elements();
436        let list = ListArray::try_new(
437            elements,
438            buffer![0u32, 2, 5, 5, 7].into_array(),
439            Validity::NonNullable,
440            &mut ctx,
441        )?
442        .into_array();
443        let taken = list.take(buffer![3u64, 0, 2].into_array())?;
444
445        let result = taken.apply(&list_sum(root()))?;
446        let mut ctx = SESSION.create_execution_ctx();
447        let expected = PrimitiveArray::from_option_iter::<i64, _>([Some(6), Some(3), None]);
448        assert_arrays_eq!(result, expected, &mut ctx);
449        Ok(())
450    }
451
452    #[test]
453    fn test_list_sum_slice() -> VortexResult<()> {
454        let mut ctx = SESSION.create_execution_ctx();
455        let elements = create_list_elements();
456        let list = ListArray::try_new(
457            elements,
458            buffer![0u32, 2, 5, 5, 7].into_array(),
459            Validity::NonNullable,
460            &mut ctx,
461        )?
462        .into_array();
463        let sliced = list.slice(1..4)?;
464
465        let result = sliced.apply(&list_sum(root()))?;
466        let mut ctx = SESSION.create_execution_ctx();
467        let expected = PrimitiveArray::from_option_iter::<i64, _>([Some(12), None, Some(6)]);
468        assert_arrays_eq!(result, expected, &mut ctx);
469        Ok(())
470    }
471
472    #[test]
473    fn test_empty_array() -> VortexResult<()> {
474        let mut ctx = SESSION.create_execution_ctx();
475        let elements = PrimitiveArray::from_iter([0i32; 0]);
476        let list = ListArray::try_new(
477            elements.into_array(),
478            buffer![0u32].into_array(),
479            Validity::NonNullable,
480            &mut ctx,
481        )?
482        .into_array();
483        let result = list.apply(&list_sum(root()))?;
484
485        let mut ctx = SESSION.create_execution_ctx();
486        assert_arrays_eq!(
487            result,
488            PrimitiveArray::from_option_iter::<i64, _>([]),
489            &mut ctx
490        );
491        Ok(())
492    }
493
494    #[test]
495    fn test_constant_list_sum() -> VortexResult<()> {
496        let mut ctx = SESSION.create_execution_ctx();
497        let elements = create_list_elements();
498        let list = ListArray::try_new(
499            elements,
500            buffer![0u32, 2, 5, 5, 7].into_array(),
501            Validity::NonNullable,
502            &mut ctx,
503        )?
504        .into_array();
505        let mut ctx = SESSION.create_execution_ctx();
506        let scalar = list.execute_scalar(1, &mut ctx)?;
507
508        let constant = ConstantArray::new(scalar, 3).into_array();
509        let result = constant.apply(&list_sum(root()))?;
510        let expected = PrimitiveArray::from_option_iter::<i64, _>([Some(12), Some(12), Some(12)]);
511        assert_arrays_eq!(result, expected, &mut ctx);
512        Ok(())
513    }
514
515    #[test]
516    fn test_null_scalar_list_sum() -> VortexResult<()> {
517        let null_scalar = Scalar::null(DType::List(
518            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
519            Nullability::Nullable,
520        ));
521        let array = ConstantArray::new(null_scalar, 2).into_array();
522        let result = array.apply(&list_sum(root()))?;
523
524        let mut ctx = SESSION.create_execution_ctx();
525        assert!(!result.is_valid(0, &mut ctx)?);
526        assert!(!result.is_valid(1, &mut ctx)?);
527        assert_arrays_eq!(
528            result,
529            PrimitiveArray::from_option_iter([None::<i64>, None]),
530            &mut ctx
531        );
532        Ok(())
533    }
534
535    #[test]
536    fn test_unsupported_dtypes() {
537        let opts = NumericalAggregateOpts::default();
538        // Non-list inputs are rejected.
539        assert!(
540            ListSum
541                .return_dtype(
542                    &opts,
543                    &[DType::Primitive(PType::I32, Nullability::NonNullable)]
544                )
545                .is_err()
546        );
547        // Non-numeric element types are rejected.
548        assert!(
549            ListSum
550                .return_dtype(
551                    &opts,
552                    &[DType::List(
553                        Arc::new(DType::Utf8(Nullability::NonNullable)),
554                        Nullability::NonNullable,
555                    )],
556                )
557                .is_err()
558        );
559    }
560
561    #[test]
562    fn test_display() {
563        assert_eq!(list_sum(root()).to_string(), "vortex.list.sum($)");
564        assert_eq!(
565            list_sum_opts(root(), NumericalAggregateOpts::include_nans()).to_string(),
566            "vortex.list.sum($, opts=skip_nans=false)"
567        );
568    }
569
570    #[test]
571    fn test_proto_round_trip() -> VortexResult<()> {
572        for expr in [
573            list_sum(root()),
574            list_sum_opts(root(), NumericalAggregateOpts::include_nans()),
575        ] {
576            let proto = expr.serialize_proto()?;
577            let buf = proto.encode_to_vec();
578            let decoded = pb::Expr::decode(buf.as_slice())?;
579            let session = VortexSession::empty();
580            vortex_array::initialize(&session);
581            crate::initialize(&session);
582            let deser = Expression::from_proto(&decoded, &session)?;
583            assert_eq!(expr, deser);
584        }
585        Ok(())
586    }
587}