vortex_array/aggregate_fn/
accumulator_grouped.rs1use 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_eq;
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
38pub type GroupedAccumulatorRef = Box<dyn DynGroupedAccumulator>;
40
41pub enum GroupedArray {
47 ListView(ListViewArray),
49 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 pub fn elements(&self) -> &ArrayRef {
68 match self {
69 Self::ListView(groups) => groups.elements(),
70 Self::FixedSizeList(groups) => groups.elements(),
71 }
72 }
73
74 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 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 pub fn len(&self) -> usize {
92 match self {
93 Self::ListView(groups) => groups.len(),
94 Self::FixedSizeList(groups) => groups.len(),
95 }
96 }
97
98 pub fn is_empty(&self) -> bool {
100 self.len() == 0
101 }
102
103 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
132pub enum GroupRanges {
134 ListView {
136 ranges: Vec<(usize, usize)>,
138 },
139 FixedSizeList {
141 len: usize,
143 size: usize,
145 },
146}
147
148impl GroupRanges {
149 pub fn len(&self) -> usize {
151 match self {
152 Self::ListView { ranges } => ranges.len(),
153 Self::FixedSizeList { len, .. } => *len,
154 }
155 }
156
157 pub fn is_empty(&self) -> bool {
159 self.len() == 0
160 }
161
162 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 pub fn iter(&self) -> impl Iterator<Item = (usize, usize)> + '_ {
175 (0..self.len()).map(|index| self.range(index))
176 }
177}
178
179pub struct GroupedAccumulator<V: AggregateFnVTable> {
184 vtable: V,
186 options: V::Options,
188 aggregate_fn: AggregateFnRef,
190 dtypes: AggregateDTypes,
192 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 dtypes = AggregateDTypes::try_new(&vtable, &options, dtype)?;
199
200 Ok(Self::from_dtypes(vtable, options, dtypes))
201 }
202
203 pub(super) fn from_dtypes(vtable: V, options: V::Options, dtypes: AggregateDTypes) -> Self {
205 let aggregate_fn = AggregateFn::new(vtable.clone(), options.clone()).erased();
206
207 Self {
208 vtable,
209 options,
210 aggregate_fn,
211 dtypes,
212 partials: vec![],
213 }
214 }
215}
216
217pub trait DynGroupedAccumulator: 'static + Send {
220 fn accumulate_list(&mut self, groups: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()>;
222
223 fn flush(&mut self) -> VortexResult<ArrayRef>;
226
227 fn finish(&mut self) -> VortexResult<ArrayRef>;
230}
231
232impl<V: AggregateFnVTable> DynGroupedAccumulator for GroupedAccumulator<V> {
233 fn accumulate_list(&mut self, groups: &ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()> {
234 let elements_dtype = match groups.dtype() {
235 DType::List(elem, _) => elem,
236 DType::FixedSizeList(elem, ..) => elem,
237 _ => vortex_bail!(
238 "Input DType mismatch: expected List or FixedSizeList, got {}",
239 groups.dtype()
240 ),
241 };
242 vortex_ensure_eq!(
243 elements_dtype.as_ref(),
244 &self.dtypes.dtype,
245 "Input DType mismatch"
246 );
247
248 let canonical = match groups.clone().execute::<Columnar>(ctx)? {
251 Columnar::Canonical(c) => c,
252 Columnar::Constant(c) => c.into_array().execute::<Canonical>(ctx)?,
253 };
254 match canonical {
255 Canonical::List(groups) => self.accumulate_grouped_array(groups.into(), ctx),
256 Canonical::FixedSizeList(groups) => self.accumulate_grouped_array(groups.into(), ctx),
257 _ => vortex_panic!("We checked the DType above, so this should never happen"),
258 }
259 }
260
261 fn flush(&mut self) -> VortexResult<ArrayRef> {
262 let mut states = std::mem::take(&mut self.partials);
263 if states.len() == 1 {
264 return Ok(states.pop().vortex_expect("checked one partial"));
265 }
266 Ok(ChunkedArray::try_new(states, self.dtypes.partial_dtype.clone())?.into_array())
267 }
268
269 fn finish(&mut self) -> VortexResult<ArrayRef> {
270 let states = self.flush()?;
271 let results = self
272 .vtable
273 .finalize(self.dtypes.args(&self.options), states)?;
274
275 vortex_ensure_eq!(
276 results.dtype(),
277 &self.dtypes.return_dtype,
278 "Return DType mismatch"
279 );
280
281 Ok(results)
282 }
283}
284
285impl<V: AggregateFnVTable> GroupedAccumulator<V> {
286 fn accumulate_grouped_array(
287 &mut self,
288 groups: GroupedArray,
289 ctx: &mut ExecutionCtx,
290 ) -> VortexResult<()> {
291 let mut elements = groups.elements().clone();
292 let session = ctx.session().clone();
293
294 for _ in 0..max_iterations() {
295 if let Some(kernel) = session
297 .aggregate_fns()
298 .find_grouped_encoding_kernel(elements.encoding_id(), self.aggregate_fn.id())
299 {
300 let kernel_groups = unsafe { groups.with_elements_unchecked(elements.clone())? };
302 if let Some(result) =
303 kernel.grouped_aggregate(&self.aggregate_fn, &kernel_groups, ctx)?
304 {
305 return self.push_result(result);
306 }
307 }
308
309 if let Some(kernel) = session
311 .aggregate_fns()
312 .find_grouped_kernel(self.aggregate_fn.id())
313 {
314 let kernel_groups = unsafe { groups.with_elements_unchecked(elements.clone())? };
317 if let Some(result) =
318 kernel.grouped_aggregate(&self.aggregate_fn, &kernel_groups, ctx)?
319 {
320 return self.push_result(result);
321 }
322 }
323
324 if elements.is::<AnyColumnar>() {
325 break;
326 }
327
328 elements = elements.execute(ctx)?;
330 }
331
332 let elements = elements.execute::<Columnar>(ctx)?.into_array();
333 let grouped = unsafe { groups.with_elements_unchecked(elements)? };
336
337 self.accumulate_grouped_fallback(&grouped, ctx)
339 }
340
341 fn accumulate_grouped_fallback(
342 &mut self,
343 grouped: &GroupedArray,
344 ctx: &mut ExecutionCtx,
345 ) -> VortexResult<()> {
346 let mut accumulator = Accumulator::try_new(
347 self.vtable.clone(),
348 self.options.clone(),
349 self.dtypes.dtype.clone(),
350 )?;
351 let mut states =
352 builder_with_capacity_in(&self.dtypes.partial_dtype, grouped.len(), ctx.allocator());
353 let group_ranges = grouped.group_ranges(ctx)?;
354 let group_validity = grouped.group_validity(ctx)?;
355
356 for ((offset, size), valid) in group_ranges.iter().zip(group_validity.iter()) {
357 if valid {
358 let group = grouped.elements().slice(offset..offset + size)?;
359 accumulator.accumulate(&group, ctx)?;
360 states.append_scalar(&accumulator.flush()?)?;
361 } else {
362 states.append_null()
363 }
364 }
365
366 self.push_result(states.finish())
367 }
368
369 fn push_result(&mut self, state: ArrayRef) -> VortexResult<()> {
370 vortex_ensure_eq!(
371 state.dtype(),
372 &self.dtypes.partial_dtype,
373 "State DType mismatch"
374 );
375 self.partials.push(state);
376 Ok(())
377 }
378}
379fn list_view_group_ranges(
380 groups: &ListViewArray,
381 ctx: &mut ExecutionCtx,
382) -> VortexResult<GroupRanges> {
383 let offsets = groups.offsets();
384 let sizes = groups.sizes().cast(offsets.dtype().clone())?;
385
386 let ranges = match_each_integer_ptype!(offsets.dtype().as_ptype(), |O| {
387 let offsets = offsets.clone().execute::<Buffer<O>>(ctx)?;
388 let sizes = sizes.execute::<Buffer<O>>(ctx)?;
389 offsets
390 .as_ref()
391 .iter()
392 .zip(sizes.as_ref().iter())
393 .map(|(offset, size)| {
394 (
395 offset.to_usize().vortex_expect("Offset value is not usize"),
396 size.to_usize().vortex_expect("Size value is not usize"),
397 )
398 })
399 .collect::<Vec<_>>()
400 });
401
402 Ok(GroupRanges::ListView { ranges })
403}
404
405fn fixed_size_list_group_ranges(groups: &FixedSizeListArray) -> GroupRanges {
406 GroupRanges::FixedSizeList {
407 len: groups.len(),
408 size: groups.list_size() as usize,
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use vortex_error::VortexResult;
415
416 use crate::ArrayRef;
417 use crate::IntoArray;
418 use crate::aggregate_fn::DynGroupedAccumulator;
419 use crate::aggregate_fn::GroupedAccumulator;
420 use crate::aggregate_fn::NumericalAggregateOpts;
421 use crate::aggregate_fn::fns::count::Count;
422 use crate::arrays::Chunked;
423 use crate::arrays::PrimitiveArray;
424 use crate::dtype::DType;
425 use crate::dtype::Nullability::NonNullable;
426 use crate::dtype::PType;
427
428 fn accumulator() -> VortexResult<GroupedAccumulator<Count>> {
429 GroupedAccumulator::try_new(
430 Count,
431 NumericalAggregateOpts::default(),
432 DType::Primitive(PType::I32, NonNullable),
433 )
434 }
435
436 fn state(values: impl IntoIterator<Item = u64>) -> ArrayRef {
437 PrimitiveArray::from_iter(values).into_array()
438 }
439
440 #[test]
441 fn test_flush_single_partial_returns_original_array() -> VortexResult<()> {
442 let mut accumulator = accumulator()?;
443 let state = state([1, 2, 3]);
444 accumulator.push_result(state.clone())?;
445
446 let flushed = accumulator.flush()?;
447
448 assert!(ArrayRef::ptr_eq(&flushed, &state));
449 Ok(())
450 }
451
452 #[test]
453 fn test_flush_multiple_partials_returns_chunked_array() -> VortexResult<()> {
454 let mut accumulator = accumulator()?;
455 accumulator.push_result(state([1, 2]))?;
456 accumulator.push_result(state([3, 4]))?;
457
458 let flushed = accumulator.flush()?;
459
460 assert!(flushed.is::<Chunked>());
461 assert_eq!(flushed.len(), 4);
462 Ok(())
463 }
464
465 #[test]
466 fn test_flush_without_partials_returns_empty_chunked_array() -> VortexResult<()> {
467 let mut accumulator = accumulator()?;
468
469 let flushed = accumulator.flush()?;
470
471 assert!(flushed.is::<Chunked>());
472 assert!(flushed.is_empty());
473 Ok(())
474 }
475}