Skip to main content

vortex_array/aggregate_fn/
accumulator_grouped.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::mem;
5
6use arrow_buffer::ArrowNativeType;
7use vortex_buffer::Buffer;
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10use vortex_error::vortex_bail;
11use vortex_error::vortex_ensure_eq;
12use vortex_error::vortex_panic;
13use vortex_mask::Mask;
14
15use crate::ArrayRef;
16use crate::Canonical;
17use crate::Columnar;
18use crate::ExecutionCtx;
19use crate::IntoArray;
20use crate::aggregate_fn::Accumulator;
21use crate::aggregate_fn::AggregateDTypes;
22use crate::aggregate_fn::AggregateFn;
23use crate::aggregate_fn::AggregateFnRef;
24use crate::aggregate_fn::AggregateFnVTable;
25use crate::aggregate_fn::DynAccumulator;
26use crate::arrays::ChunkedArray;
27use crate::arrays::FixedSizeListArray;
28use crate::arrays::ListViewArray;
29use crate::arrays::fixed_size_list::FixedSizeListArrayExt;
30use crate::arrays::fixed_size_list::FixedSizeListArraySlotsExt;
31use crate::arrays::listview::ListViewArraySlotsExt;
32use crate::builders::builder_with_capacity_in;
33use crate::builtins::ArrayBuiltins;
34use crate::columnar::AnyColumnar;
35use crate::dtype::DType;
36use crate::dtype::NativePType;
37use crate::executor::max_iterations;
38use crate::match_each_integer_ptype;
39
40/// Reference-counted type-erased grouped accumulator.
41pub type GroupedAccumulatorRef = Box<dyn DynGroupedAccumulator>;
42
43/// A batch of grouped values to aggregate.
44///
45/// Each outer list value is one group, and the inner element array is shared by all groups.
46/// Aggregate implementations can inspect the concrete grouped representation directly, or ask for
47/// derived ranges when their algorithm is expressed in terms of `(offset, size)` pairs.
48pub enum GroupedArray {
49    /// Groups represented as a list-view array with per-group offsets and sizes.
50    ListView(ListViewArray),
51    /// Groups represented as a fixed-size list array.
52    FixedSizeList(FixedSizeListArray),
53}
54
55impl From<ListViewArray> for GroupedArray {
56    fn from(groups: ListViewArray) -> Self {
57        Self::ListView(groups)
58    }
59}
60
61impl From<FixedSizeListArray> for GroupedArray {
62    fn from(groups: FixedSizeListArray) -> Self {
63        Self::FixedSizeList(groups)
64    }
65}
66
67impl GroupedArray {
68    /// The inner element array shared by all groups.
69    pub fn elements(&self) -> &ArrayRef {
70        match self {
71            Self::ListView(groups) => groups.elements(),
72            Self::FixedSizeList(groups) => groups.elements(),
73        }
74    }
75
76    /// Return the `(offset, size)` ranges describing each group in `elements`.
77    pub fn group_ranges(&self, ctx: &mut ExecutionCtx) -> VortexResult<GroupRanges> {
78        match self {
79            Self::ListView(groups) => list_view_group_ranges(groups, ctx),
80            Self::FixedSizeList(groups) => Ok(fixed_size_list_group_ranges(groups)),
81        }
82    }
83
84    /// Return the per-group validity mask.
85    pub fn group_validity(&self, ctx: &mut ExecutionCtx) -> VortexResult<Mask> {
86        match self {
87            Self::ListView(groups) => groups.validity()?.execute_mask(groups.len(), ctx),
88            Self::FixedSizeList(groups) => groups.validity()?.execute_mask(groups.len(), ctx),
89        }
90    }
91
92    /// The number of groups in this batch.
93    pub fn len(&self) -> usize {
94        match self {
95            Self::ListView(groups) => groups.len(),
96            Self::FixedSizeList(groups) => groups.len(),
97        }
98    }
99
100    /// Returns true when this batch contains no groups.
101    pub fn is_empty(&self) -> bool {
102        self.len() == 0
103    }
104
105    /// Returns true when every group is valid.
106    pub fn all_groups_valid(&self, ctx: &mut ExecutionCtx) -> VortexResult<bool> {
107        Ok(self.group_validity(ctx)?.all_true())
108    }
109
110    unsafe fn with_elements_unchecked(&self, elements: ArrayRef) -> VortexResult<Self> {
111        Ok(match self {
112            Self::ListView(groups) => unsafe {
113                ListViewArray::new_unchecked(
114                    elements,
115                    groups.offsets().clone(),
116                    groups.sizes().clone(),
117                    groups.validity()?,
118                )
119            }
120            .into(),
121            Self::FixedSizeList(groups) => unsafe {
122                FixedSizeListArray::new_unchecked(
123                    elements,
124                    groups.list_size(),
125                    groups.validity()?,
126                    groups.len(),
127                )
128            }
129            .into(),
130        })
131    }
132}
133
134/// The physical ranges of a grouped array.
135pub enum GroupRanges {
136    /// Explicit ranges extracted from a list-view array.
137    ListView {
138        /// The `(offset, size)` ranges.
139        ranges: Vec<(usize, usize)>,
140    },
141    /// Uniform ranges derived from a fixed-size list array.
142    FixedSizeList {
143        /// The number of groups.
144        len: usize,
145        /// The number of elements in each group.
146        size: usize,
147    },
148}
149
150impl GroupRanges {
151    /// The number of groups described by these ranges.
152    pub fn len(&self) -> usize {
153        match self {
154            Self::ListView { ranges } => ranges.len(),
155            Self::FixedSizeList { len, .. } => *len,
156        }
157    }
158
159    /// Returns true when there are no groups.
160    pub fn is_empty(&self) -> bool {
161        self.len() == 0
162    }
163
164    /// Return the `(offset, size)` range for the group at `index`.
165    fn range(&self, index: usize) -> (usize, usize) {
166        match self {
167            Self::ListView { ranges } => ranges[index],
168            Self::FixedSizeList { len, size } => {
169                assert!(index < *len, "range index out of bounds");
170                (index * size, *size)
171            }
172        }
173    }
174
175    /// Iterate over all `(offset, size)` group ranges.
176    pub fn iter(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
177        (0..self.len()).map(|index| self.range(index))
178    }
179}
180
181/// An accumulator used for computing grouped aggregates.
182///
183/// Note that the groups must be processed in order, and the accumulator does not support random
184/// access to groups.
185pub struct GroupedAccumulator<V: AggregateFnVTable> {
186    /// The vtable of the aggregate function.
187    vtable: V,
188    /// The options of the aggregate function.
189    options: V::Options,
190    /// Type-erased aggregate function used for kernel dispatch.
191    aggregate_fn: AggregateFnRef,
192    /// The input, partial, and result dtypes lent to every vtable call.
193    dtypes: AggregateDTypes,
194    /// The accumulated state for prior batches of groups.
195    partials: Vec<ArrayRef>,
196}
197
198impl<V: AggregateFnVTable> GroupedAccumulator<V> {
199    pub fn try_new(vtable: V, options: V::Options, dtype: DType) -> VortexResult<Self> {
200        let dtypes = AggregateDTypes::try_new(&vtable, &options, dtype)?;
201
202        Ok(Self::from_dtypes(vtable, options, dtypes))
203    }
204
205    /// Build a grouped accumulator over dtypes that are already resolved.
206    pub(super) fn from_dtypes(vtable: V, options: V::Options, dtypes: AggregateDTypes) -> Self {
207        let aggregate_fn = AggregateFn::new(vtable.clone(), options.clone()).erased();
208
209        Self {
210            vtable,
211            options,
212            aggregate_fn,
213            dtypes,
214            partials: vec![],
215        }
216    }
217}
218
219/// A trait object for type-erased grouped accumulators, used for dynamic dispatch when the aggregate
220/// function is not known at compile time.
221pub trait DynGroupedAccumulator: 'static + Send {
222    /// Accumulate a list of groups into the accumulator.
223    fn accumulate_list(&mut self, groups: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()>;
224
225    /// Finish the accumulation and return the partial aggregate results for all groups.
226    /// Resets the accumulator state for the next round of accumulation.
227    fn flush(&mut self) -> VortexResult<ArrayRef>;
228
229    /// Finish the accumulation and return the final aggregate results for all groups.
230    /// Resets the accumulator state for the next round of accumulation.
231    fn finish(&mut self) -> VortexResult<ArrayRef>;
232}
233
234impl<V: AggregateFnVTable> DynGroupedAccumulator for GroupedAccumulator<V> {
235    fn accumulate_list(&mut self, groups: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()> {
236        let elements_dtype = match groups.dtype() {
237            DType::List(elem, _) => elem,
238            DType::FixedSizeList(elem, ..) => elem,
239            _ => vortex_bail!(
240                "Input DType mismatch: expected List or FixedSizeList, got {}",
241                groups.dtype()
242            ),
243        };
244        vortex_ensure_eq!(
245            elements_dtype.as_ref(),
246            &self.dtypes.dtype,
247            "Input DType mismatch"
248        );
249
250        // We first execute the groups until it is a ListView or FixedSizeList, since we only
251        // dispatch the aggregate kernel over the elements of these arrays.
252        let canonical = match groups.clone().execute::<Columnar>(ctx)? {
253            Columnar::Canonical(c) => c,
254            Columnar::Constant(c) => c.into_array().execute::<Canonical>(ctx)?,
255        };
256        match canonical {
257            Canonical::List(groups) => self.accumulate_grouped_array(groups.into(), ctx),
258            Canonical::FixedSizeList(groups) => self.accumulate_grouped_array(groups.into(), ctx),
259            _ => {
260                vortex_panic!("We checked the DType above, so this should never happen")
261            }
262        }
263    }
264
265    fn flush(&mut self) -> VortexResult<ArrayRef> {
266        if self.partials.len() == 1 {
267            return Ok(self.partials.pop().vortex_expect("checked one partial"));
268        }
269        // Pass the `Vec` itself so that this shares the `try_new` instance of other callers.
270        Ok(ChunkedArray::try_new(
271            mem::take(&mut self.partials),
272            self.dtypes.partial_dtype.clone(),
273        )?
274        .into_array())
275    }
276
277    fn finish(&mut self) -> VortexResult<ArrayRef> {
278        let states = self.flush()?;
279        let results = self
280            .vtable
281            .finalize(self.dtypes.args(&self.options), states)?;
282
283        vortex_ensure_eq!(
284            results.dtype(),
285            &self.dtypes.return_dtype,
286            "Return DType mismatch"
287        );
288
289        Ok(results)
290    }
291}
292
293impl<V: AggregateFnVTable> GroupedAccumulator<V> {
294    fn accumulate_grouped_array(
295        &mut self,
296        groups: GroupedArray,
297        ctx: &mut ExecutionCtx,
298    ) -> VortexResult<()> {
299        let mut elements = groups.elements().clone();
300        for _ in 0..max_iterations() {
301            // Try a registered grouped kernel for the current element encoding.
302            if let Some(kernel) = ctx
303                .aggregate_kernels()
304                .find_grouped_encoding_kernel(elements.encoding_id(), self.aggregate_fn.id())
305            {
306                // SAFETY: we assume that elements execution is safe
307                let kernel_groups = unsafe { groups.with_elements_unchecked(elements.clone())? };
308                if let Some(result) =
309                    kernel.grouped_aggregate(&self.aggregate_fn, &kernel_groups, ctx)?
310                {
311                    return self.push_result(result);
312                }
313            }
314
315            // Try a grouped kernel for the current aggregate regardless of element encoding.
316            if let Some(kernel) = ctx
317                .aggregate_kernels()
318                .find_grouped_kernel(self.aggregate_fn.id())
319            {
320                // SAFETY: we preserve the grouped shape and validity while replacing the
321                // elements with another representation of the same logical array.
322                let kernel_groups = unsafe { groups.with_elements_unchecked(elements.clone())? };
323                if let Some(result) =
324                    kernel.grouped_aggregate(&self.aggregate_fn, &kernel_groups, ctx)?
325                {
326                    return self.push_result(result);
327                }
328            }
329
330            if elements.is::<AnyColumnar>() {
331                break;
332            }
333
334            // Execute one step and try again
335            elements = elements.execute(ctx)?;
336        }
337
338        let elements = elements.execute::<Columnar>(ctx)?.into_array();
339        // SAFETY: we preserve the grouped shape and validity while replacing the elements with an
340        // executed form of the same logical array.
341        let grouped = unsafe { groups.with_elements_unchecked(elements)? };
342
343        // Otherwise, we iterate the offsets and sizes and accumulate each group one by one.
344        self.accumulate_grouped_fallback(&grouped, ctx)
345    }
346
347    fn accumulate_grouped_fallback(
348        &mut self,
349        grouped: &GroupedArray,
350        ctx: &mut ExecutionCtx,
351    ) -> VortexResult<()> {
352        let mut accumulator = Accumulator::try_new(
353            self.vtable.clone(),
354            self.options.clone(),
355            self.dtypes.dtype.clone(),
356        )?;
357        let mut states =
358            builder_with_capacity_in(&self.dtypes.partial_dtype, grouped.len(), ctx.allocator());
359        let group_ranges = grouped.group_ranges(ctx)?;
360        let group_validity = grouped.group_validity(ctx)?;
361
362        for ((offset, size), valid) in group_ranges.iter().zip(group_validity.iter()) {
363            if valid {
364                let group = grouped.elements().slice(offset..offset + size)?;
365                accumulator.accumulate(&group, ctx)?;
366                states.append_scalar(&accumulator.flush()?)?;
367            } else {
368                states.append_null()
369            }
370        }
371
372        self.push_result(states.finish())
373    }
374
375    fn push_result(&mut self, state: ArrayRef) -> VortexResult<()> {
376        vortex_ensure_eq!(
377            state.dtype(),
378            &self.dtypes.partial_dtype,
379            "State DType mismatch"
380        );
381        self.partials.push(state);
382        Ok(())
383    }
384}
385fn list_view_group_ranges(
386    groups: &ListViewArray,
387    ctx: &mut ExecutionCtx,
388) -> VortexResult<GroupRanges> {
389    let offsets = groups.offsets();
390    let sizes = groups.sizes().cast(offsets.dtype().clone())?;
391
392    let ranges = match_each_integer_ptype!(offsets.dtype().as_ptype(), |O| {
393        execute_group_ranges::<O>(offsets, sizes, ctx)
394    })?;
395
396    Ok(GroupRanges::ListView { ranges })
397}
398
399fn execute_group_ranges<O: NativePType + ArrowNativeType>(
400    offsets: &ArrayRef,
401    sizes: ArrayRef,
402    ctx: &mut ExecutionCtx,
403) -> VortexResult<Vec<(usize, usize)>> {
404    let offsets = offsets.clone().execute::<Buffer<O>>(ctx)?;
405    let sizes = sizes.execute::<Buffer<O>>(ctx)?;
406    Ok(collect_group_ranges(&offsets, &sizes))
407}
408
409fn collect_group_ranges<O: ArrowNativeType>(offsets: &[O], sizes: &[O]) -> Vec<(usize, usize)> {
410    offsets
411        .iter()
412        .zip(sizes)
413        .map(|(offset, size)| {
414            (
415                offset.to_usize().vortex_expect("Offset value is not usize"),
416                size.to_usize().vortex_expect("Size value is not usize"),
417            )
418        })
419        .collect()
420}
421
422fn fixed_size_list_group_ranges(groups: &FixedSizeListArray) -> GroupRanges {
423    GroupRanges::FixedSizeList {
424        len: groups.len(),
425        size: groups.list_size() as usize,
426    }
427}
428
429#[cfg(test)]
430mod tests {
431    use std::sync::LazyLock;
432
433    use vortex_error::VortexResult;
434    use vortex_session::VortexSession;
435
436    use crate::ArrayRef;
437    use crate::IntoArray;
438    use crate::VortexSessionExecute;
439    use crate::aggregate_fn::DynGroupedAccumulator;
440    use crate::aggregate_fn::GroupedAccumulator;
441    use crate::aggregate_fn::NumericalAggregateOpts;
442    use crate::aggregate_fn::fns::count::Count;
443    use crate::arrays::Chunked;
444    use crate::arrays::PrimitiveArray;
445    use crate::assert_arrays_eq;
446    use crate::dtype::DType;
447    use crate::dtype::Nullability::NonNullable;
448    use crate::dtype::PType;
449
450    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
451
452    fn accumulator() -> VortexResult<GroupedAccumulator<Count>> {
453        GroupedAccumulator::try_new(
454            Count,
455            NumericalAggregateOpts::default(),
456            DType::Primitive(PType::I32, NonNullable),
457        )
458    }
459
460    fn state(values: impl IntoIterator<Item = u64>) -> ArrayRef {
461        PrimitiveArray::from_iter(values).into_array()
462    }
463
464    #[test]
465    fn test_flush_single_partial_returns_original_array() -> VortexResult<()> {
466        let mut accumulator = accumulator()?;
467        let state = state([1, 2, 3]);
468        accumulator.push_result(state.clone())?;
469
470        let flushed = accumulator.flush()?;
471
472        assert!(ArrayRef::ptr_eq(&flushed, &state));
473        Ok(())
474    }
475
476    #[test]
477    fn test_flush_multiple_partials_returns_chunked_array() -> VortexResult<()> {
478        let mut accumulator = accumulator()?;
479        accumulator.push_result(state([1, 2]))?;
480        accumulator.push_result(state([3, 4]))?;
481
482        let flushed = accumulator.flush()?;
483
484        assert!(flushed.is::<Chunked>());
485        assert_eq!(flushed.len(), 4);
486        assert_arrays_eq!(
487            &flushed,
488            &state([1, 2, 3, 4]),
489            &mut SESSION.create_execution_ctx()
490        );
491        assert!(accumulator.flush()?.is_empty());
492        Ok(())
493    }
494
495    #[test]
496    fn test_flush_without_partials_returns_empty_chunked_array() -> VortexResult<()> {
497        let mut accumulator = accumulator()?;
498
499        let flushed = accumulator.flush()?;
500
501        assert!(flushed.is::<Chunked>());
502        assert!(flushed.is_empty());
503        assert_eq!(flushed.dtype(), &DType::Primitive(PType::U64, NonNullable));
504        Ok(())
505    }
506}