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