vortex_array/aggregate_fn/
accumulator_grouped.rs1use 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
40pub type GroupedAccumulatorRef = Box<dyn DynGroupedAccumulator>;
42
43pub enum GroupedArray {
49 ListView(ListViewArray),
51 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 pub fn elements(&self) -> &ArrayRef {
70 match self {
71 Self::ListView(groups) => groups.elements(),
72 Self::FixedSizeList(groups) => groups.elements(),
73 }
74 }
75
76 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 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 pub fn len(&self) -> usize {
94 match self {
95 Self::ListView(groups) => groups.len(),
96 Self::FixedSizeList(groups) => groups.len(),
97 }
98 }
99
100 pub fn is_empty(&self) -> bool {
102 self.len() == 0
103 }
104
105 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
134pub enum GroupRanges {
136 ListView {
138 ranges: Vec<(usize, usize)>,
140 },
141 FixedSizeList {
143 len: usize,
145 size: usize,
147 },
148}
149
150impl GroupRanges {
151 pub fn len(&self) -> usize {
153 match self {
154 Self::ListView { ranges } => ranges.len(),
155 Self::FixedSizeList { len, .. } => *len,
156 }
157 }
158
159 pub fn is_empty(&self) -> bool {
161 self.len() == 0
162 }
163
164 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 pub fn iter(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
177 (0..self.len()).map(|index| self.range(index))
178 }
179}
180
181pub struct GroupedAccumulator<V: AggregateFnVTable> {
186 vtable: V,
188 options: V::Options,
190 aggregate_fn: AggregateFnRef,
192 dtypes: AggregateDTypes,
194 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 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
219pub trait DynGroupedAccumulator: 'static + Send {
222 fn accumulate_list(&mut self, groups: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()>;
224
225 fn flush(&mut self) -> VortexResult<ArrayRef>;
228
229 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 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 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 if let Some(kernel) = ctx
303 .aggregate_kernels()
304 .find_grouped_encoding_kernel(elements.encoding_id(), self.aggregate_fn.id())
305 {
306 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 if let Some(kernel) = ctx
317 .aggregate_kernels()
318 .find_grouped_kernel(self.aggregate_fn.id())
319 {
320 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 elements = elements.execute(ctx)?;
336 }
337
338 let elements = elements.execute::<Columnar>(ctx)?.into_array();
339 let grouped = unsafe { groups.with_elements_unchecked(elements)? };
342
343 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}