Skip to main content

datafusion_functions_aggregate_common/aggregate/
groups_accumulator.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Utilities for implementing GroupsAccumulator
6//! Adapter that makes [`GroupsAccumulator`] out of [`Accumulator`]
7
8pub mod accumulate;
9pub mod bool_op;
10pub mod nulls;
11pub mod prim_op;
12
13use std::mem::{size_of, size_of_val};
14use std::sync::{Arc, OnceLock};
15
16use arrow::array::new_empty_array;
17use arrow::{
18    array::{ArrayRef, AsArray, BooleanArray, PrimitiveArray},
19    compute,
20    compute::take_arrays,
21    datatypes::UInt32Type,
22};
23use datafusion_common::{Result, ScalarValue, arrow_datafusion_err};
24use datafusion_expr_common::accumulator::{
25    Accumulator, AggregateMetric, AggregateMetricRecorder, AggregateMetrics,
26};
27use datafusion_expr_common::groups_accumulator::{
28    EmitTo, GroupSelection, GroupsAccumulator,
29};
30
31/// An adapter that implements [`GroupsAccumulator`] for any [`Accumulator`]
32///
33/// While [`Accumulator`] are simpler to implement and can support
34/// more general calculations (like retractable window functions),
35/// they are not as fast as a specialized `GroupsAccumulator`. This
36/// interface bridges the gap so the group by operator only operates
37/// in terms of [`Accumulator`].
38///
39/// Internally, this adapter creates a new [`Accumulator`] for each group which
40/// stores the state for that group. This both requires an allocation for each
41/// Accumulator, internal indices, as well as whatever internal allocations the
42/// Accumulator itself requires.
43///
44/// For example, a `MinAccumulator` that computes the minimum string value with
45/// a [`ScalarValue::Utf8`]. That will require at least two allocations per group
46/// (one for the `MinAccumulator` and one for the `ScalarValue::Utf8`).
47///
48/// ```text
49///                       ┌─────────────────────────────────┐
50///                       │MinAccumulator {                 │
51///                ┌─────▶│ min: ScalarValue::Utf8("A")     │───────┐
52///                │      │}                                │       │
53///                │      └─────────────────────────────────┘       └───────▶   "A"
54///    ┌─────┐     │      ┌─────────────────────────────────┐
55///    │  0  │─────┘      │MinAccumulator {                 │
56///    ├─────┤     ┌─────▶│ min: ScalarValue::Utf8("Z")     │───────────────▶   "Z"
57///    │  1  │─────┘      │}                                │
58///    └─────┘            └─────────────────────────────────┘                   ...
59///      ...                 ...
60///    ┌─────┐            ┌────────────────────────────────┐
61///    │ N-2 │            │MinAccumulator {                │
62///    ├─────┤            │  min: ScalarValue::Utf8("A")   │────────────────▶   "A"
63///    │ N-1 │─────┐      │}                               │
64///    └─────┘     │      └────────────────────────────────┘
65///                │      ┌────────────────────────────────┐        ┌───────▶   "Q"
66///                │      │MinAccumulator {                │        │
67///                └─────▶│  min: ScalarValue::Utf8("Q")   │────────┘
68///                       │}                               │
69///                       └────────────────────────────────┘
70///
71///
72///  Logical group         Current Min/Max value for that group stored
73///     number             as a ScalarValue which points to an
74///                        individually allocated String
75/// ```
76///
77/// # Optimizations
78///
79/// The adapter minimizes the number of calls to [`Accumulator::update_batch`]
80/// by first collecting the input rows for each group into a contiguous array
81/// using [`compute::take`]
82pub struct GroupsAccumulatorAdapter {
83    factory: Box<dyn Fn() -> Result<Box<dyn Accumulator>> + Send>,
84
85    /// state for each group, stored in group_index order
86    states: Vec<AccumulatorState>,
87
88    /// Current memory usage, in bytes.
89    ///
90    /// Note this is incrementally updated with deltas to avoid the
91    /// call to size() being a bottleneck. We saw size() being a
92    /// bottleneck in earlier implementations when there were many
93    /// distinct groups.
94    allocation_bytes: usize,
95
96    /// Metrics supplied by the aggregate execution operator.
97    metrics: Option<Arc<dyn AggregateMetrics>>,
98
99    /// Optional aggregate-owned metric timed once for a grouped update batch.
100    grouped_update_metric: OnceLock<Option<Arc<dyn AggregateMetric>>>,
101
102    /// Buffers reused by every call to `invoke_per_accumulator`
103    scratch: Scratch,
104}
105
106/// Per-batch buffers of [`GroupsAccumulatorAdapter`], kept between batches so
107/// that each batch does not allocate them again. Their capacity is part of
108/// [`GroupsAccumulatorAdapter::allocation_bytes`].
109#[derive(Default)]
110struct Scratch {
111    /// Group indexes that have rows in the batch, in order of first
112    /// appearance in the batch
113    groups_with_rows: Vec<usize>,
114
115    /// `offsets[i]` is the index into `batch_indices` where the rows for
116    /// `groups_with_rows[i]` start
117    offsets: Vec<usize>,
118
119    /// Indices into the batch rows, with the rows of each group contiguous
120    batch_indices: Vec<u32>,
121}
122
123/// A scratch buffer keeps its capacity after a batch unless that capacity is
124/// more than this many entries and more than [`SCRATCH_RETAIN_RATIO`] times
125/// what the batch used. Then it shrinks to the smaller of the two. This stops
126/// one unusually large batch from holding memory for all the batches after it.
127const MAX_RETAINED_SCRATCH_ENTRIES: usize = 64 * 1024;
128
129/// See [`MAX_RETAINED_SCRATCH_ENTRIES`]
130const SCRATCH_RETAIN_RATIO: usize = 4;
131
132impl Scratch {
133    fn allocated_size(&self) -> usize {
134        self.groups_with_rows.allocated_size()
135            + self.offsets.allocated_size()
136            + self.batch_indices.allocated_size()
137    }
138
139    /// Shrink each buffer that is much larger than the batch that just used
140    /// it. Call this after the batch, before the buffers are cleared for the
141    /// next batch.
142    fn release_oversized(&mut self) {
143        fn release_if_oversized<T>(buffer: &mut Vec<T>) {
144            let keep = SCRATCH_RETAIN_RATIO * buffer.len();
145            if buffer.capacity() > MAX_RETAINED_SCRATCH_ENTRIES
146                && buffer.capacity() > keep
147            {
148                // The batch is done with the contents, so clear them first
149                // and the shrink has nothing to copy
150                buffer.clear();
151                buffer.shrink_to(MAX_RETAINED_SCRATCH_ENTRIES.min(keep));
152            }
153        }
154        release_if_oversized(&mut self.groups_with_rows);
155        release_if_oversized(&mut self.offsets);
156        release_if_oversized(&mut self.batch_indices);
157    }
158}
159
160/// Maximum number of prepared group inputs retained while timing an
161/// aggregate-owned grouped subphase.
162const GROUPED_METRIC_PREPARATION_CHUNK_SIZE: usize = 64;
163
164struct AccumulatorState {
165    /// [`Accumulator`] that stores the per-group state
166    accumulator: Box<dyn Accumulator>,
167
168    /// scratch space: indexes in the input array that will be fed to
169    /// this accumulator. Stores indexes as `u32` to match the arrow
170    /// `take` kernel input.
171    indices: Vec<u32>,
172}
173
174impl AccumulatorState {
175    fn new(accumulator: Box<dyn Accumulator>) -> Self {
176        Self {
177            accumulator,
178            indices: vec![],
179        }
180    }
181
182    /// Returns the amount of memory taken by this structure and its accumulator
183    fn size(&self) -> usize {
184        self.accumulator.size() + size_of_val(self) + self.indices.allocated_size()
185    }
186}
187
188impl GroupsAccumulatorAdapter {
189    /// Create a new adapter that will create a new [`Accumulator`]
190    /// for each group, using the specified factory function
191    pub fn new<F>(factory: F) -> Self
192    where
193        F: Fn() -> Result<Box<dyn Accumulator>> + Send + 'static,
194    {
195        Self {
196            factory: Box::new(factory),
197            states: vec![],
198            allocation_bytes: 0,
199            metrics: None,
200            grouped_update_metric: OnceLock::new(),
201            scratch: Scratch::default(),
202        }
203    }
204
205    /// Creates an accumulator with this adapter's optional metrics.
206    fn create_accumulator(&self) -> Result<Box<dyn Accumulator>> {
207        let mut accumulator = (self.factory)()?;
208        if let Some(metrics) = &self.metrics {
209            accumulator.set_metrics(Arc::clone(metrics));
210        }
211        self.grouped_update_metric
212            .get_or_init(|| accumulator.grouped_update_batch_metric());
213        Ok(accumulator)
214    }
215
216    /// Returns the aggregate-owned grouped-update metric, if the first
217    /// accumulator this adapter created exposed one.
218    ///
219    /// The cell is seeded by [`Self::create_accumulator`], so this returns
220    /// `None` until at least one accumulator has been built.
221    fn grouped_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
222        self.grouped_update_metric.get().and_then(Clone::clone)
223    }
224
225    /// Ensure that self.accumulators has total_num_groups
226    fn make_accumulators_if_needed(&mut self, total_num_groups: usize) -> Result<()> {
227        // can't shrink
228        assert!(total_num_groups >= self.states.len());
229        let vec_size_pre = self.states.allocated_size();
230
231        // instantiate new accumulators
232        let new_accumulators = total_num_groups - self.states.len();
233        for _ in 0..new_accumulators {
234            let accumulator = self.create_accumulator()?;
235            let state = AccumulatorState::new(accumulator);
236            self.add_allocation(state.size());
237            self.states.push(state);
238        }
239
240        self.adjust_allocation(vec_size_pre, self.states.allocated_size());
241        Ok(())
242    }
243
244    /// invokes f(accumulator, values) for each group that has values
245    /// in group_indices.
246    ///
247    /// This function first reorders the input and filter so that
248    /// values for each group_index are contiguous and then invokes f
249    /// on the contiguous ranges, to minimize per-row overhead
250    ///
251    /// ```text
252    /// ┌─────────┐   ┌─────────┐   ┌ ─ ─ ─ ─ ┐                       ┌─────────┐   ┌ ─ ─ ─ ─ ┐
253    /// │ ┌─────┐ │   │ ┌─────┐ │     ┌─────┐              ┏━━━━━┓    │ ┌─────┐ │     ┌─────┐
254    /// │ │  2  │ │   │ │ 200 │ │   │ │  t  │ │            ┃  0  ┃    │ │ 200 │ │   │ │  t  │ │
255    /// │ ├─────┤ │   │ ├─────┤ │     ├─────┤              ┣━━━━━┫    │ ├─────┤ │     ├─────┤
256    /// │ │  2  │ │   │ │ 100 │ │   │ │  f  │ │            ┃  0  ┃    │ │ 300 │ │   │ │  t  │ │
257    /// │ ├─────┤ │   │ ├─────┤ │     ├─────┤              ┣━━━━━┫    │ ├─────┤ │     ├─────┤
258    /// │ │  0  │ │   │ │ 200 │ │   │ │  t  │ │            ┃  1  ┃    │ │ 200 │ │   │ │NULL │ │
259    /// │ ├─────┤ │   │ ├─────┤ │     ├─────┤   ────────▶  ┣━━━━━┫    │ ├─────┤ │     ├─────┤
260    /// │ │  1  │ │   │ │ 200 │ │   │ │NULL │ │            ┃  2  ┃    │ │ 200 │ │   │ │  t  │ │
261    /// │ ├─────┤ │   │ ├─────┤ │     ├─────┤              ┣━━━━━┫    │ ├─────┤ │     ├─────┤
262    /// │ │  0  │ │   │ │ 300 │ │   │ │  t  │ │            ┃  2  ┃    │ │ 100 │ │   │ │  f  │ │
263    /// │ └─────┘ │   │ └─────┘ │     └─────┘              ┗━━━━━┛    │ └─────┘ │     └─────┘
264    /// └─────────┘   └─────────┘   └ ─ ─ ─ ─ ┘                       └─────────┘   └ ─ ─ ─ ─ ┘
265    ///
266    /// logical group   values      opt_filter           logical group  values       opt_filter
267    /// ```
268    fn invoke_per_accumulator<F>(
269        &mut self,
270        values: &[ArrayRef],
271        group_indices: &[usize],
272        opt_filter: Option<&BooleanArray>,
273        total_num_groups: usize,
274        f: F,
275    ) -> Result<()>
276    where
277        F: Fn(&mut dyn Accumulator, &[ArrayRef]) -> Result<()>,
278    {
279        self.make_accumulators_if_needed(total_num_groups)?;
280
281        assert_eq!(values[0].len(), group_indices.len());
282
283        // Take the scratch buffers out of `self` for the batch, and put them
284        // back on every return path, including errors
285        let mut scratch = std::mem::take(&mut self.scratch);
286        let scratch_size_pre = scratch.allocated_size();
287        let result = self.invoke_per_accumulator_with_scratch(
288            &mut scratch,
289            values,
290            group_indices,
291            opt_filter,
292            f,
293        );
294        scratch.release_oversized();
295        self.adjust_allocation(scratch_size_pre, scratch.allocated_size());
296        self.scratch = scratch;
297        result
298    }
299
300    /// Body of [`Self::invoke_per_accumulator`], with its scratch buffers
301    fn invoke_per_accumulator_with_scratch<F>(
302        &mut self,
303        scratch: &mut Scratch,
304        values: &[ArrayRef],
305        group_indices: &[usize],
306        opt_filter: Option<&BooleanArray>,
307        f: F,
308    ) -> Result<()>
309    where
310        F: Fn(&mut dyn Accumulator, &[ArrayRef]) -> Result<()>,
311    {
312        let Scratch {
313            groups_with_rows,
314            offsets,
315            batch_indices,
316        } = scratch;
317
318        // groups_with_rows holds a list of group indexes that have any rows
319        // that need to be accumulated, stored in order of first appearance in
320        // this batch
321        groups_with_rows.clear();
322
323        // figure out which input rows correspond to which groups.
324        // Note that self.state.indices starts empty for all groups (it is
325        // cleared out below), so an empty one is exactly a group that this
326        // batch has not reached yet.
327        // Charge retained scratch capacity only when a push grows a vector,
328        // avoiding another pass over every group after indexing.
329        let mut indices_allocation_delta = 0;
330        for (idx, group_index) in group_indices.iter().enumerate() {
331            let indices = &mut self.states[*group_index].indices;
332            if indices.is_empty() {
333                groups_with_rows.push(*group_index);
334            }
335            if indices.len() < indices.capacity() {
336                indices.push(idx as u32);
337            } else {
338                let size_pre = indices.allocated_size();
339                indices.push(idx as u32);
340                indices_allocation_delta += indices.allocated_size() - size_pre;
341            }
342        }
343        self.add_allocation(indices_allocation_delta);
344
345        // batch_indices holds indices into values, each group is contiguous
346        batch_indices.clear();
347        batch_indices
348            .try_reserve(group_indices.len())
349            .map_err(|e| {
350                arrow_datafusion_err!(arrow::error::ArrowError::MemoryError(
351                    e.to_string()
352                ))
353            })?;
354
355        // offsets[i] is index into batch_indices where the rows for
356        // groups_with_rows[i] start
357        offsets.clear();
358        offsets.push(0);
359
360        let mut offset_so_far = 0;
361        for &group_index in groups_with_rows.iter() {
362            let indices = &self.states[group_index].indices;
363            batch_indices.extend_from_slice(indices);
364            offset_so_far += indices.len();
365            offsets.push(offset_so_far);
366        }
367        // Move the buffer into an array without a copy, for the take kernels
368        let indices_array =
369            PrimitiveArray::<UInt32Type>::from(std::mem::take(batch_indices));
370
371        // reorder the values and opt_filter by batch_indices so that
372        // all values for each group are contiguous, then invoke the
373        // accumulator once per group with values
374        let values = take_arrays(values, &indices_array, None)?;
375        let opt_filter = get_filter_at_indices(opt_filter, &indices_array)?;
376
377        // The take kernels only borrow the indices, so the array holds the
378        // only reference to the buffer and we can get it back without a copy
379        let (_, indices_buffer, _) = indices_array.into_parts();
380        *batch_indices = indices_buffer.into_inner().into_vec().unwrap_or_default();
381
382        let grouped_update_metric = self.grouped_metric();
383
384        let mut sizes_pre = 0;
385        let mut sizes_post = 0;
386        let has_grouped_update_metric = grouped_update_metric.is_some();
387        let mut metric_recorder = AggregateMetricRecorder::new(grouped_update_metric);
388        let result: Result<()> = (|| {
389            if !has_grouped_update_metric {
390                // Keep the pre-metrics single-pass path for accumulators that
391                // do not expose an aggregate-owned submetric.
392                for (&group_idx, offsets) in
393                    groups_with_rows.iter().zip(offsets.windows(2))
394                {
395                    sizes_pre += self.states[group_idx].size();
396                    let values_to_accumulate = match slice_and_maybe_filter(
397                        &values,
398                        opt_filter.as_ref().map(|f| f.as_boolean()),
399                        offsets,
400                    ) {
401                        Ok(values) => values,
402                        Err(error) => {
403                            sizes_post += self.states[group_idx].size();
404                            return Err(error);
405                        }
406                    };
407                    let update_result = f(
408                        self.states[group_idx].accumulator.as_mut(),
409                        &values_to_accumulate,
410                    );
411                    let state = &mut self.states[group_idx];
412                    if update_result.is_ok() {
413                        state.indices.clear();
414                    }
415                    sizes_post += state.size();
416                    update_result?;
417                }
418                return Ok(());
419            }
420
421            // Keep preparation bounded to avoid retaining one filtered array per
422            // group. Time only accumulator invocation: slicing and filtering
423            // are adapter work, not aggregate-owned subphase work.
424            for (chunk_index, groups) in groups_with_rows
425                .chunks(GROUPED_METRIC_PREPARATION_CHUNK_SIZE)
426                .enumerate()
427            {
428                let first_offset = chunk_index * GROUPED_METRIC_PREPARATION_CHUNK_SIZE;
429                let values_to_accumulate = groups
430                    .iter()
431                    .enumerate()
432                    .map(|(index, &group_idx)| {
433                        let values = slice_and_maybe_filter(
434                            &values,
435                            opt_filter.as_ref().map(|f| f.as_boolean()),
436                            &offsets[first_offset + index..first_offset + index + 2],
437                        )?;
438                        Ok((group_idx, values))
439                    })
440                    .collect::<Result<Vec<_>>>()?;
441
442                // Size accounting is adapter work: keep it out of the timer.
443                for (group_idx, _) in &values_to_accumulate {
444                    sizes_pre += self.states[*group_idx].size();
445                }
446
447                let (successful_groups, chunk_result) = {
448                    let _timer = metric_recorder.timer();
449                    let mut successful_groups = 0;
450                    let mut chunk_result = Ok(());
451                    for (group_idx, values) in &values_to_accumulate {
452                        chunk_result =
453                            f(self.states[*group_idx].accumulator.as_mut(), values);
454                        if chunk_result.is_err() {
455                            break;
456                        }
457                        successful_groups += 1;
458                    }
459                    (successful_groups, chunk_result)
460                };
461                for (index, (group_idx, _)) in values_to_accumulate.iter().enumerate() {
462                    let state = &mut self.states[*group_idx];
463                    if index < successful_groups {
464                        // Clear every successfully applied group before
465                        // propagating an error from a later group.
466                        state.indices.clear();
467                    }
468                    sizes_post += state.size();
469                }
470                chunk_result?;
471            }
472            Ok(())
473        })();
474
475        self.adjust_allocation(sizes_pre, sizes_post);
476        result
477    }
478
479    /// Increment the allocation by `n`
480    ///
481    /// See [`Self::allocation_bytes`] for rationale.
482    fn add_allocation(&mut self, size: usize) {
483        self.allocation_bytes += size;
484    }
485
486    /// Decrease the allocation by `n`
487    ///
488    /// See [`Self::allocation_bytes`] for rationale.
489    fn free_allocation(&mut self, size: usize) {
490        // use saturating sub to avoid errors if the accumulators
491        // report erroneous sizes
492        self.allocation_bytes = self.allocation_bytes.saturating_sub(size)
493    }
494
495    /// Release the scratch buffers when no group is left, so that an adapter
496    /// that has emitted every group holds no memory
497    fn free_scratch_if_empty(&mut self) {
498        if self.states.is_empty() {
499            self.free_scratch();
500        }
501    }
502
503    /// Release the scratch buffers. The next batch allocates them again.
504    fn free_scratch(&mut self) {
505        let scratch = std::mem::take(&mut self.scratch);
506        self.free_allocation(scratch.allocated_size());
507    }
508
509    /// Release the allocation held by a state that is being emitted.
510    fn free_state_allocation(&mut self, state: &AccumulatorState) {
511        self.free_allocation(state.size());
512    }
513
514    /// Adjusts the allocation for something that started with
515    /// start_size and now has new_size avoiding overflow
516    ///
517    /// See [`Self::allocation_bytes`] for rationale.
518    fn adjust_allocation(&mut self, old_size: usize, new_size: usize) {
519        if new_size > old_size {
520            self.add_allocation(new_size - old_size)
521        } else {
522            self.free_allocation(old_size - new_size)
523        }
524    }
525}
526
527impl GroupsAccumulator for GroupsAccumulatorAdapter {
528    fn set_metrics(&mut self, metrics: Arc<dyn AggregateMetrics>) {
529        self.metrics = Some(metrics);
530    }
531
532    fn update_batch(
533        &mut self,
534        values: &[ArrayRef],
535        group_indices: &[usize],
536        opt_filter: Option<&BooleanArray>,
537        total_num_groups: usize,
538    ) -> Result<()> {
539        self.invoke_per_accumulator(
540            values,
541            group_indices,
542            opt_filter,
543            total_num_groups,
544            |accumulator, values_to_accumulate| {
545                accumulator.update_batch_grouped(values_to_accumulate)
546            },
547        )?;
548        Ok(())
549    }
550
551    fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef> {
552        let vec_size_pre = self.states.allocated_size();
553
554        let states = emit_to.take_needed(&mut self.states);
555
556        let results: Vec<ScalarValue> = states
557            .into_iter()
558            .map(|mut state| {
559                self.free_state_allocation(&state);
560                state.accumulator.evaluate()
561            })
562            .collect::<Result<_>>()?;
563
564        let result = ScalarValue::iter_to_array(results);
565
566        self.adjust_allocation(vec_size_pre, self.states.allocated_size());
567        self.free_scratch_if_empty();
568
569        result
570    }
571
572    fn evaluate_preserving(&mut self, selection: GroupSelection<'_>) -> Result<ArrayRef> {
573        selection.validate_num_groups(self.states.len())?;
574        let selected_len = selection.len();
575        if selected_len == 0 {
576            // ScalarValue::iter_to_array needs at least one value to infer the
577            // output type, so evaluate a temporary empty accumulator.
578            let mut accumulator = self.create_accumulator()?;
579            return Ok(ScalarValue::iter_to_array([accumulator.evaluate()?])?.slice(0, 0));
580        }
581
582        let mut results = Vec::with_capacity(selected_len);
583        for group_index in selection.iter() {
584            let (result, size_pre, size_post) = {
585                let state = &mut self.states[group_index];
586                let size_pre = state.size();
587                let result = state.accumulator.evaluate()?;
588                (result, size_pre, state.size())
589            };
590            self.adjust_allocation(size_pre, size_post);
591            results.push(result);
592        }
593        ScalarValue::iter_to_array(results)
594    }
595
596    fn supports_evaluate_preserving(&self) -> bool {
597        true
598    }
599
600    // filtered_null_mask(opt_filter, &values);
601    fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>> {
602        let vec_size_pre = self.states.allocated_size();
603        let states = emit_to.take_needed(&mut self.states);
604        let num_states = states.len();
605
606        // each accumulator produces a potential vector of values
607        // which we need to form into columns
608        let mut results: Vec<Vec<ScalarValue>> = vec![];
609
610        for mut state in states {
611            self.free_state_allocation(&state);
612            let accumulator_state = state.accumulator.state()?;
613            results
614                .resize_with(accumulator_state.len(), || Vec::with_capacity(num_states));
615            for (idx, state_val) in accumulator_state.into_iter().enumerate() {
616                results[idx].push(state_val);
617            }
618        }
619
620        // create an array for each intermediate column
621        let arrays = results
622            .into_iter()
623            .map(ScalarValue::iter_to_array)
624            .collect::<Result<Vec<_>>>()?;
625
626        // double check each array has the same length (aka the
627        // accumulator was implemented correctly
628        if let Some(first_col) = arrays.first() {
629            for arr in &arrays {
630                assert_eq!(arr.len(), first_col.len())
631            }
632        }
633        self.adjust_allocation(vec_size_pre, self.states.allocated_size());
634        self.free_scratch_if_empty();
635
636        Ok(arrays)
637    }
638
639    fn merge_batch(
640        &mut self,
641        values: &[ArrayRef],
642        group_indices: &[usize],
643        total_num_groups: usize,
644    ) -> Result<()> {
645        self.invoke_per_accumulator(
646            values,
647            group_indices,
648            None,
649            total_num_groups,
650            |accumulator, values_to_accumulate| {
651                accumulator.merge_batch_grouped(values_to_accumulate)
652            },
653        )?;
654        Ok(())
655    }
656
657    fn size(&self) -> usize {
658        self.allocation_bytes
659    }
660
661    fn shrink_to_fit(&mut self) {
662        self.free_scratch();
663        // Each group keeps the capacity of its row indices after a batch, so
664        // a group that had many rows in the last batch still holds them
665        let mut freed = 0;
666        for state in &mut self.states {
667            if state.indices.is_empty() {
668                freed += std::mem::take(&mut state.indices).allocated_size();
669            }
670        }
671        self.free_allocation(freed);
672    }
673
674    fn convert_to_state(
675        &self,
676        values: &[ArrayRef],
677        opt_filter: Option<&BooleanArray>,
678    ) -> Result<Vec<ArrayRef>> {
679        let num_rows = values[0].len();
680
681        // If there are no rows, return empty arrays
682        if num_rows == 0 {
683            // create empty accumulator to get the state types
684            let empty_state = self.create_accumulator()?.state()?;
685            let empty_arrays = empty_state
686                .into_iter()
687                .map(|state_val| new_empty_array(&state_val.data_type()))
688                .collect::<Vec<_>>();
689
690            return Ok(empty_arrays);
691        }
692
693        // Each row has its respective group
694        let mut results = vec![];
695        let mut metric_recorder = None;
696        let mut prepared =
697            Vec::with_capacity(GROUPED_METRIC_PREPARATION_CHUNK_SIZE.min(num_rows));
698        for chunk_start in (0..num_rows).step_by(GROUPED_METRIC_PREPARATION_CHUNK_SIZE) {
699            let chunk_end =
700                (chunk_start + GROUPED_METRIC_PREPARATION_CHUNK_SIZE).min(num_rows);
701            prepared.clear();
702
703            for row_idx in chunk_start..chunk_end {
704                // Create the empty accumulator and prepare adapter-owned input
705                // outside the aggregate submetric.
706                let accumulator = self.create_accumulator()?;
707                // `create_accumulator` resolves the metric, so the recorder can
708                // only be built once the first accumulator exists.
709                metric_recorder.get_or_insert_with(|| {
710                    AggregateMetricRecorder::new(self.grouped_metric())
711                });
712                let values_to_accumulate =
713                    slice_and_maybe_filter(values, opt_filter, &[row_idx, row_idx + 1])?;
714                prepared.push((accumulator, values_to_accumulate));
715            }
716
717            // Time only aggregate-owned deduplication, once per bounded chunk.
718            let update_result: Result<()> = {
719                let _timer = metric_recorder
720                    .as_mut()
721                    .and_then(AggregateMetricRecorder::timer);
722                prepared
723                    .iter_mut()
724                    .try_for_each(|(accumulator, values_to_accumulate)| {
725                        accumulator.update_batch_grouped(values_to_accumulate)
726                    })
727            };
728            update_result?;
729
730            for (mut accumulator, _) in prepared.drain(..) {
731                let states = accumulator.state()?;
732
733                // Resize results to have enough columns according to the converted states
734                results.resize_with(states.len(), || Vec::with_capacity(num_rows));
735
736                // Add the states to results
737                for (idx, state_val) in states.into_iter().enumerate() {
738                    results[idx].push(state_val);
739                }
740            }
741        }
742
743        let arrays = results
744            .into_iter()
745            .map(ScalarValue::iter_to_array)
746            .collect::<Result<Vec<_>>>()?;
747
748        Ok(arrays)
749    }
750}
751
752/// Extension trait for [`Vec`] to account for allocations.
753pub trait VecAllocExt {
754    /// Item type.
755    type T;
756    /// Return the amount of memory allocated by this Vec (not
757    /// recursively counting any heap allocations contained within the
758    /// structure). Does not include the size of `self`
759    fn allocated_size(&self) -> usize;
760}
761
762impl<T> VecAllocExt for Vec<T> {
763    type T = T;
764    fn allocated_size(&self) -> usize {
765        size_of::<T>() * self.capacity()
766    }
767}
768
769fn get_filter_at_indices(
770    opt_filter: Option<&BooleanArray>,
771    indices: &PrimitiveArray<UInt32Type>,
772) -> Result<Option<ArrayRef>> {
773    opt_filter
774        .map(|filter| {
775            compute::take(
776                &filter, indices, None, // None: no index check
777            )
778        })
779        .transpose()
780        .map_err(|e| arrow_datafusion_err!(e))
781}
782
783// Copied from physical-plan
784pub(crate) fn slice_and_maybe_filter(
785    aggr_array: &[ArrayRef],
786    filter_opt: Option<&BooleanArray>,
787    offsets: &[usize],
788) -> Result<Vec<ArrayRef>> {
789    let (offset, length) = (offsets[0], offsets[1] - offsets[0]);
790    let sliced_arrays: Vec<ArrayRef> = aggr_array
791        .iter()
792        .map(|array| array.slice(offset, length))
793        .collect();
794
795    if let Some(f) = filter_opt {
796        let filter = f.slice(offset, length);
797
798        sliced_arrays
799            .iter()
800            .map(|array| {
801                compute::filter(&array, &filter).map_err(|e| arrow_datafusion_err!(e))
802            })
803            .collect()
804    } else {
805        Ok(sliced_arrays)
806    }
807}
808
809#[cfg(test)]
810mod tests {
811    use std::sync::Arc;
812    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
813    use std::time::Duration;
814
815    use super::*;
816    use crate::min_max::MaxAccumulator;
817    use arrow::array::{AsArray, BooleanArray, Int64Array};
818    use arrow::datatypes::{DataType, Int64Type};
819
820    #[derive(Debug)]
821    struct CountingMetric(Arc<AtomicUsize>);
822
823    impl AggregateMetric for CountingMetric {
824        fn add_duration(&self, _duration: Duration) {
825            self.0.fetch_add(1, Ordering::Relaxed);
826        }
827    }
828
829    #[derive(Debug)]
830    struct CountingMetrics(Arc<AtomicUsize>);
831
832    impl AggregateMetrics for CountingMetrics {
833        fn metric(&self, _subphase: &'static str) -> Arc<dyn AggregateMetric> {
834            Arc::new(CountingMetric(Arc::clone(&self.0)))
835        }
836    }
837
838    #[derive(Debug)]
839    struct DurationMetric(Arc<AtomicU64>);
840
841    impl AggregateMetric for DurationMetric {
842        fn add_duration(&self, duration: Duration) {
843            self.0
844                .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed);
845        }
846    }
847
848    #[derive(Debug)]
849    struct TimedAccumulator {
850        metric: Arc<dyn AggregateMetric>,
851    }
852
853    impl Accumulator for TimedAccumulator {
854        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
855            self.metric.add_duration(Duration::ZERO);
856            Ok(())
857        }
858
859        fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
860            Some(Arc::clone(&self.metric))
861        }
862
863        fn update_batch_grouped(&mut self, _values: &[ArrayRef]) -> Result<()> {
864            Ok(())
865        }
866
867        fn evaluate(&mut self) -> Result<ScalarValue> {
868            Ok(ScalarValue::Int64(None))
869        }
870
871        fn size(&self) -> usize {
872            size_of_val(self)
873        }
874
875        fn state(&mut self) -> Result<Vec<ScalarValue>> {
876            Ok(vec![ScalarValue::Int64(None)])
877        }
878
879        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
880            Ok(())
881        }
882    }
883
884    #[derive(Debug)]
885    struct MetricsAwareAccumulator {
886        metric: Option<Arc<dyn AggregateMetric>>,
887    }
888
889    impl Accumulator for MetricsAwareAccumulator {
890        fn set_metrics(&mut self, metrics: Arc<dyn AggregateMetrics>) {
891            self.metric = Some(metrics.metric("update"));
892        }
893
894        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
895            self.metric
896                .as_ref()
897                .expect("adapter must supply metrics to every group")
898                .add_duration(Duration::ZERO);
899            Ok(())
900        }
901
902        fn evaluate(&mut self) -> Result<ScalarValue> {
903            Ok(ScalarValue::Int64(None))
904        }
905
906        fn size(&self) -> usize {
907            size_of_val(self)
908        }
909
910        fn state(&mut self) -> Result<Vec<ScalarValue>> {
911            Ok(vec![ScalarValue::Int64(None)])
912        }
913
914        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
915            Ok(())
916        }
917    }
918
919    #[test]
920    fn adapter_supplies_metrics_to_every_group() -> Result<()> {
921        let metric_updates = Arc::new(AtomicUsize::new(0));
922        let mut adapter = GroupsAccumulatorAdapter::new(|| {
923            Ok(Box::new(MetricsAwareAccumulator { metric: None })
924                as Box<dyn Accumulator>)
925        });
926        adapter.set_metrics(Arc::new(CountingMetrics(Arc::clone(&metric_updates))));
927
928        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
929        adapter.update_batch(&[values], &[0, 1], None, 2)?;
930
931        assert_eq!(metric_updates.load(Ordering::Relaxed), 2);
932        Ok(())
933    }
934
935    #[test]
936    fn adapter_charges_retained_indices_once_and_releases_them() -> Result<()> {
937        let mut adapter = GroupsAccumulatorAdapter::new(|| {
938            Ok(Box::new(TimedAccumulator {
939                metric: Arc::new(CountingMetric(Arc::new(AtomicUsize::new(0)))),
940            }) as Box<dyn Accumulator>)
941        });
942        adapter.make_accumulators_if_needed(1)?;
943        let allocation_before_update = adapter.size();
944        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3, 4]));
945
946        adapter.update_batch(&[Arc::clone(&values)], &[0, 0, 0, 0], None, 1)?;
947        let retained_indices = adapter.states[0].indices.allocated_size();
948        assert!(retained_indices > 0);
949        assert!(adapter.states[0].indices.is_empty());
950        // The indices buffer comes back from the take kernels without a copy
951        assert!(adapter.scratch.batch_indices.capacity() >= 4);
952        let retained_scratch = adapter.scratch.allocated_size();
953        assert!(retained_scratch > 0);
954        assert_eq!(
955            adapter.size(),
956            allocation_before_update + retained_indices + retained_scratch
957        );
958
959        let allocation_after_first_update = adapter.size();
960        adapter.update_batch(&[values], &[0, 0, 0, 0], None, 1)?;
961        assert_eq!(adapter.size(), allocation_after_first_update);
962
963        adapter.evaluate(EmitTo::All)?;
964        assert_eq!(adapter.size(), 0);
965        Ok(())
966    }
967
968    #[test]
969    fn adapter_grouped_update_records_one_metric_after_filtering() -> Result<()> {
970        let metric_updates = Arc::new(AtomicUsize::new(0));
971        let mut accumulator = GroupsAccumulatorAdapter::new({
972            let metric_updates = Arc::clone(&metric_updates);
973            move || {
974                Ok(Box::new(TimedAccumulator {
975                    metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),
976                }) as Box<dyn Accumulator>)
977            }
978        });
979
980        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3, 4]));
981        let filter = BooleanArray::from(vec![true, false, true, false]);
982        accumulator.update_batch(&[values], &[0, 0, 1, 1], Some(&filter), 2)?;
983
984        assert_eq!(metric_updates.load(Ordering::Relaxed), 1);
985        Ok(())
986    }
987
988    #[test]
989    fn adapter_grouped_update_records_zero_duration_for_empty_batch() -> Result<()> {
990        let metric_updates = Arc::new(AtomicUsize::new(0));
991        let mut accumulator = GroupsAccumulatorAdapter::new({
992            let metric_updates = Arc::clone(&metric_updates);
993            move || {
994                Ok(Box::new(TimedAccumulator {
995                    metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),
996                }) as Box<dyn Accumulator>)
997            }
998        });
999
1000        let values: ArrayRef = Arc::new(Int64Array::from(vec![1]));
1001        accumulator.update_batch(&[values], &[0], None, 1)?;
1002        metric_updates.store(0, Ordering::Relaxed);
1003
1004        let empty_values: ArrayRef = Arc::new(Int64Array::from(Vec::<i64>::new()));
1005        accumulator.update_batch(&[empty_values], &[], None, 1)?;
1006
1007        assert_eq!(metric_updates.load(Ordering::Relaxed), 1);
1008        Ok(())
1009    }
1010
1011    #[test]
1012    fn adapter_convert_to_state_records_metric_once() -> Result<()> {
1013        let metric_updates = Arc::new(AtomicUsize::new(0));
1014        let accumulator = GroupsAccumulatorAdapter::new({
1015            let metric_updates = Arc::clone(&metric_updates);
1016            move || {
1017                Ok(Box::new(TimedAccumulator {
1018                    metric: Arc::new(CountingMetric(Arc::clone(&metric_updates))),
1019                }) as Box<dyn Accumulator>)
1020            }
1021        });
1022
1023        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 3]));
1024        accumulator.convert_to_state(&[values], None)?;
1025
1026        assert_eq!(metric_updates.load(Ordering::Relaxed), 1);
1027        Ok(())
1028    }
1029
1030    #[derive(Debug)]
1031    struct SlowStateAccumulator {
1032        metric: Arc<dyn AggregateMetric>,
1033    }
1034
1035    impl Accumulator for SlowStateAccumulator {
1036        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
1037            Ok(())
1038        }
1039
1040        fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
1041            Some(Arc::clone(&self.metric))
1042        }
1043
1044        fn evaluate(&mut self) -> Result<ScalarValue> {
1045            Ok(ScalarValue::Int64(None))
1046        }
1047
1048        fn size(&self) -> usize {
1049            size_of_val(self)
1050        }
1051
1052        fn state(&mut self) -> Result<Vec<ScalarValue>> {
1053            std::thread::sleep(Duration::from_millis(50));
1054            Ok(vec![ScalarValue::Int64(None)])
1055        }
1056
1057        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
1058            Ok(())
1059        }
1060    }
1061
1062    #[test]
1063    fn adapter_convert_to_state_excludes_state_materialization_from_metric() -> Result<()>
1064    {
1065        let recorded_nanos = Arc::new(AtomicU64::new(0));
1066        let accumulator = GroupsAccumulatorAdapter::new({
1067            let recorded_nanos = Arc::clone(&recorded_nanos);
1068            move || {
1069                Ok(Box::new(SlowStateAccumulator {
1070                    metric: Arc::new(DurationMetric(Arc::clone(&recorded_nanos))),
1071                }) as Box<dyn Accumulator>)
1072            }
1073        });
1074
1075        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
1076        let filter = BooleanArray::from(vec![true, false]);
1077        accumulator.convert_to_state(&[values], Some(&filter))?;
1078
1079        assert!(
1080            recorded_nanos.load(Ordering::Relaxed)
1081                < Duration::from_millis(25).as_nanos() as u64,
1082            "internal metric must exclude state materialization"
1083        );
1084        Ok(())
1085    }
1086
1087    #[derive(Debug)]
1088    struct SlowSizeAccumulator {
1089        metric: Arc<dyn AggregateMetric>,
1090    }
1091
1092    impl Accumulator for SlowSizeAccumulator {
1093        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
1094            Ok(())
1095        }
1096
1097        fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
1098            Some(Arc::clone(&self.metric))
1099        }
1100
1101        fn update_batch_grouped(&mut self, _values: &[ArrayRef]) -> Result<()> {
1102            Ok(())
1103        }
1104
1105        fn evaluate(&mut self) -> Result<ScalarValue> {
1106            Ok(ScalarValue::Int64(None))
1107        }
1108
1109        fn size(&self) -> usize {
1110            std::thread::sleep(Duration::from_millis(50));
1111            size_of_val(self)
1112        }
1113
1114        fn state(&mut self) -> Result<Vec<ScalarValue>> {
1115            Ok(vec![ScalarValue::Int64(None)])
1116        }
1117
1118        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
1119            Ok(())
1120        }
1121    }
1122
1123    #[test]
1124    fn adapter_grouped_update_excludes_size_accounting_from_metric() -> Result<()> {
1125        let recorded_nanos = Arc::new(AtomicU64::new(0));
1126        let mut accumulator = GroupsAccumulatorAdapter::new({
1127            let recorded_nanos = Arc::clone(&recorded_nanos);
1128            move || {
1129                Ok(Box::new(SlowSizeAccumulator {
1130                    metric: Arc::new(DurationMetric(Arc::clone(&recorded_nanos))),
1131                }) as Box<dyn Accumulator>)
1132            }
1133        });
1134
1135        let values: ArrayRef = Arc::new(Int64Array::from(vec![1]));
1136        accumulator.update_batch(&[values], &[0], None, 1)?;
1137
1138        assert!(
1139            recorded_nanos.load(Ordering::Relaxed)
1140                < Duration::from_millis(25).as_nanos() as u64,
1141            "grouped-update metric must exclude size accounting"
1142        );
1143        Ok(())
1144    }
1145
1146    #[derive(Debug)]
1147    struct FailOnceAccumulator {
1148        fail_first_update: bool,
1149        successful_group_rows: Option<Arc<AtomicUsize>>,
1150        allocation_bytes: usize,
1151        metric: Option<Arc<dyn AggregateMetric>>,
1152    }
1153
1154    impl Accumulator for FailOnceAccumulator {
1155        fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
1156            if self.fail_first_update {
1157                self.fail_first_update = false;
1158                return datafusion_common::internal_err!("injected update failure");
1159            }
1160            if let Some(rows) = &self.successful_group_rows {
1161                rows.fetch_add(values[0].len(), Ordering::Relaxed);
1162                self.allocation_bytes = 1024;
1163            }
1164            Ok(())
1165        }
1166
1167        fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
1168            self.metric.clone()
1169        }
1170
1171        fn evaluate(&mut self) -> Result<ScalarValue> {
1172            Ok(ScalarValue::Int64(None))
1173        }
1174
1175        fn size(&self) -> usize {
1176            size_of_val(self) + self.allocation_bytes
1177        }
1178
1179        fn state(&mut self) -> Result<Vec<ScalarValue>> {
1180            Ok(vec![ScalarValue::Int64(None)])
1181        }
1182
1183        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
1184            Ok(())
1185        }
1186    }
1187
1188    #[test]
1189    fn adapter_clears_successful_group_indices_after_later_error() -> Result<()> {
1190        let created = Arc::new(AtomicUsize::new(0));
1191        let successful_group_rows = Arc::new(AtomicUsize::new(0));
1192        let mut accumulator = GroupsAccumulatorAdapter::new({
1193            let created = Arc::clone(&created);
1194            let successful_group_rows = Arc::clone(&successful_group_rows);
1195            move || {
1196                let group = created.fetch_add(1, Ordering::Relaxed);
1197                Ok(Box::new(FailOnceAccumulator {
1198                    fail_first_update: group == 1,
1199                    successful_group_rows: (group == 0)
1200                        .then(|| Arc::clone(&successful_group_rows)),
1201                    allocation_bytes: 0,
1202                    metric: None,
1203                }) as Box<dyn Accumulator>)
1204            }
1205        });
1206
1207        accumulator.make_accumulators_if_needed(2)?;
1208        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
1209        assert!(
1210            accumulator
1211                .update_batch(&[Arc::clone(&values)], &[0, 1], None, 2)
1212                .is_err()
1213        );
1214        assert_eq!(
1215            accumulator.size(),
1216            accumulator.states.allocated_size()
1217                + accumulator
1218                    .states
1219                    .iter()
1220                    .map(AccumulatorState::size)
1221                    .sum::<usize>()
1222                + accumulator.scratch.allocated_size()
1223        );
1224        accumulator.update_batch(&[values], &[0, 1], None, 2)?;
1225
1226        assert_eq!(successful_group_rows.load(Ordering::Relaxed), 2);
1227        Ok(())
1228    }
1229
1230    #[test]
1231    fn adapter_reconciles_allocation_after_later_error_with_grouped_metric() -> Result<()>
1232    {
1233        let created = Arc::new(AtomicUsize::new(0));
1234        let successful_group_rows = Arc::new(AtomicUsize::new(0));
1235        let metric: Arc<dyn AggregateMetric> =
1236            Arc::new(CountingMetric(Arc::new(AtomicUsize::new(0))));
1237        let mut accumulator = GroupsAccumulatorAdapter::new({
1238            let created = Arc::clone(&created);
1239            let successful_group_rows = Arc::clone(&successful_group_rows);
1240            move || {
1241                let group = created.fetch_add(1, Ordering::Relaxed);
1242                Ok(Box::new(FailOnceAccumulator {
1243                    fail_first_update: group == 1,
1244                    successful_group_rows: (group == 0)
1245                        .then(|| Arc::clone(&successful_group_rows)),
1246                    allocation_bytes: 0,
1247                    metric: Some(Arc::clone(&metric)),
1248                }) as Box<dyn Accumulator>)
1249            }
1250        });
1251
1252        accumulator.make_accumulators_if_needed(2)?;
1253        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
1254        assert!(
1255            accumulator
1256                .update_batch(&[values], &[0, 1], None, 2)
1257                .is_err()
1258        );
1259        assert_eq!(
1260            accumulator.size(),
1261            accumulator.states.allocated_size()
1262                + accumulator
1263                    .states
1264                    .iter()
1265                    .map(AccumulatorState::size)
1266                    .sum::<usize>()
1267                + accumulator.scratch.allocated_size()
1268        );
1269        Ok(())
1270    }
1271
1272    #[test]
1273    fn adapter_convert_to_state_records_metric_on_update_error() -> Result<()> {
1274        let created = Arc::new(AtomicUsize::new(0));
1275        let metric_updates = Arc::new(AtomicUsize::new(0));
1276        let metric: Arc<dyn AggregateMetric> =
1277            Arc::new(CountingMetric(Arc::clone(&metric_updates)));
1278        let accumulator = GroupsAccumulatorAdapter::new({
1279            let created = Arc::clone(&created);
1280            move || {
1281                let group = created.fetch_add(1, Ordering::Relaxed);
1282                Ok(Box::new(FailOnceAccumulator {
1283                    fail_first_update: group == 1,
1284                    successful_group_rows: None,
1285                    allocation_bytes: 0,
1286                    metric: Some(Arc::clone(&metric)),
1287                }) as Box<dyn Accumulator>)
1288            }
1289        });
1290
1291        let values: ArrayRef = Arc::new(Int64Array::from(vec![1, 2]));
1292        assert!(accumulator.convert_to_state(&[values], None).is_err());
1293        assert_eq!(metric_updates.load(Ordering::Relaxed), 1);
1294        Ok(())
1295    }
1296
1297    /// One large batch must not make the adapter keep its scratch capacity
1298    /// for the smaller batches after it.
1299    #[test]
1300    fn adapter_releases_oversized_scratch() -> Result<()> {
1301        const NUM_GROUPS: usize = 2 * MAX_RETAINED_SCRATCH_ENTRIES;
1302        let mut adapter = GroupsAccumulatorAdapter::new(|| {
1303            Ok(Box::new(MaxAccumulator::try_new(&DataType::Int64)?)
1304                as Box<dyn Accumulator>)
1305        });
1306
1307        // every row is a different group, so the scratch buffers need one
1308        // entry for each row
1309        let group_indices: Vec<usize> = (0..NUM_GROUPS).collect();
1310        let values: ArrayRef =
1311            Arc::new(Int64Array::from_iter_values(0..NUM_GROUPS as i64));
1312        adapter.update_batch(&[values], &group_indices, None, NUM_GROUPS)?;
1313        let large_scratch = adapter.scratch.allocated_size();
1314        assert!(large_scratch >= NUM_GROUPS * size_of::<usize>());
1315        let size_after_large_batch = adapter.size();
1316
1317        // a batch with one row shrinks each large buffer to
1318        // SCRATCH_RETAIN_RATIO times what it used: one group, two offsets and
1319        // one row index
1320        let values: ArrayRef = Arc::new(Int64Array::from(vec![1]));
1321        adapter.update_batch(&[values], &[0], None, NUM_GROUPS)?;
1322        let small_scratch = adapter.scratch.allocated_size();
1323        assert!(small_scratch < large_scratch);
1324        assert_eq!(
1325            adapter.scratch.groups_with_rows.capacity(),
1326            SCRATCH_RETAIN_RATIO
1327        );
1328        assert_eq!(adapter.scratch.offsets.capacity(), 2 * SCRATCH_RETAIN_RATIO);
1329        assert_eq!(
1330            adapter.scratch.batch_indices.capacity(),
1331            SCRATCH_RETAIN_RATIO
1332        );
1333        assert_eq!(
1334            adapter.size(),
1335            size_after_large_batch - large_scratch + small_scratch
1336        );
1337        Ok(())
1338    }
1339
1340    #[test]
1341    fn adapter_preserving_evaluation_uses_accumulator_contract() -> Result<()> {
1342        let mut accumulator = GroupsAccumulatorAdapter::new(|| {
1343            Ok(Box::new(MaxAccumulator::try_new(&DataType::Int64)?)
1344                as Box<dyn Accumulator>)
1345        });
1346        let values = Arc::new(Int64Array::from(vec![Some(1), Some(5), Some(2), None]));
1347        accumulator.update_batch(&[values], &[0, 0, 1, 2], None, 4)?;
1348
1349        let selection = GroupSelection::try_from_indices(&[1, 0, 3, 1], 4)?;
1350        let expected = Int64Array::from(vec![Some(2), Some(5), None, Some(2)]);
1351        for _ in 0..2 {
1352            assert_eq!(
1353                accumulator
1354                    .evaluate_preserving(selection)?
1355                    .as_primitive::<Int64Type>(),
1356                &expected
1357            );
1358        }
1359
1360        let empty =
1361            accumulator.evaluate_preserving(GroupSelection::try_from_indices(&[], 4)?)?;
1362        assert_eq!(empty.data_type(), &DataType::Int64);
1363        assert!(empty.is_empty());
1364
1365        let values = Arc::new(Int64Array::from(vec![7, 4, 9]));
1366        accumulator.update_batch(&[values], &[0, 2, 3], None, 4)?;
1367        assert_eq!(
1368            accumulator
1369                .evaluate_preserving(GroupSelection::all(4))?
1370                .as_primitive::<Int64Type>(),
1371            &Int64Array::from(vec![Some(7), Some(2), Some(4), Some(9)])
1372        );
1373        assert!(accumulator.supports_evaluate_preserving());
1374        assert!(!accumulator.supports_state_preserving());
1375        Ok(())
1376    }
1377}