Skip to main content

datafusion_expr_common/
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//! Vectorized [`GroupsAccumulator`]
6
7use arrow::array::{ArrayRef, BooleanArray};
8use datafusion_common::{Result, exec_err, not_impl_err, utils::split_vec_min_alloc};
9use std::sync::Arc;
10
11use crate::accumulator::AggregateMetrics;
12
13/// Describes how many rows should be emitted during grouping.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum EmitTo {
16    /// Emit all groups
17    All,
18    /// Emit only the first `n` groups and shift all existing group
19    /// indexes down by `n`.
20    ///
21    /// For example, if `n=10`, group_index `0, 1, ... 9` are emitted
22    /// and group indexes `10, 11, 12, ...` become `0, 1, 2, ...`.
23    First(usize),
24}
25
26impl EmitTo {
27    /// Removes the number of rows from `v` required to emit the right
28    /// number of rows, returning a `Vec` with elements taken, and the
29    /// remaining values in `v`.
30    ///
31    /// This avoids copying if Self::All
32    pub fn take_needed<T>(&self, v: &mut Vec<T>) -> Vec<T> {
33        match self {
34            Self::All => {
35                // Take the entire vector, leave new (empty) vector
36                std::mem::take(v)
37            }
38            Self::First(n) => split_vec_min_alloc(v, *n),
39        }
40    }
41}
42
43/// Selects groups for a non-destructive grouped aggregation read.
44///
45/// Unlike [`EmitTo`], this selection does not remove groups or change their
46/// indices. Selections created by [`Self::try_from_indices`] preserve the
47/// requested order and support duplicate indices.
48///
49/// A selection is validated once when it is constructed and can then be reused
50/// for the group values and accumulators participating in the same snapshot.
51/// Construct a new selection if the number or indexing of those groups changes.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct GroupSelection<'a> {
54    total_num_groups: usize,
55    indices: Option<&'a [usize]>,
56}
57
58impl<'a> GroupSelection<'a> {
59    /// Selects all `total_num_groups` groups in group-index order.
60    pub fn all(total_num_groups: usize) -> Self {
61        Self {
62            total_num_groups,
63            indices: None,
64        }
65    }
66
67    /// Selects groups in the order specified by `indices`.
68    ///
69    /// Returns an error if an index is not less than `total_num_groups`. Empty
70    /// selections are valid, and duplicate indices are preserved.
71    pub fn try_from_indices(
72        indices: &'a [usize],
73        total_num_groups: usize,
74    ) -> Result<Self> {
75        if let Some(index) = indices.iter().find(|&&index| index >= total_num_groups) {
76            return exec_err!(
77                "Group index {index} is out of bounds for {total_num_groups} groups"
78            );
79        }
80        Ok(Self {
81            total_num_groups,
82            indices: Some(indices),
83        })
84    }
85
86    /// Returns the group count against which this selection was constructed.
87    pub fn total_num_groups(self) -> usize {
88        self.total_num_groups
89    }
90
91    /// Ensures this selection is being applied to the same number of groups
92    /// against which it was constructed.
93    ///
94    /// Preserving-read implementations should call this method with their
95    /// stored group count before using [`Self::iter`]. This check is `O(1)`;
96    /// the selected indices were already checked by [`Self::try_from_indices`].
97    pub fn validate_num_groups(self, actual_num_groups: usize) -> Result<()> {
98        if actual_num_groups != self.total_num_groups {
99            return exec_err!(
100                "Group selection was constructed for {} groups but applied to {actual_num_groups} groups",
101                self.total_num_groups
102            );
103        }
104        Ok(())
105    }
106
107    /// Returns the number of selected groups.
108    pub fn len(self) -> usize {
109        self.indices
110            .map_or(self.total_num_groups, |indices| indices.len())
111    }
112
113    /// Returns `true` if no groups are selected.
114    pub fn is_empty(self) -> bool {
115        self.len() == 0
116    }
117
118    /// Returns the selected group indices in output order.
119    pub fn iter(self) -> impl Iterator<Item = usize> + 'a {
120        let (all, indices): (_, &'a [usize]) = match self.indices {
121            None => (0..self.total_num_groups, &[]),
122            Some(indices) => (0..0, indices),
123        };
124        all.chain(indices.iter().copied())
125    }
126}
127
128/// `GroupsAccumulator` implements a single aggregate (e.g. AVG) and
129/// stores the state for *all* groups internally.
130///
131/// Logically, a [`GroupsAccumulator`] stores a mapping from each group index to
132/// the state of the aggregate for that group. For example an implementation for
133/// `min` might look like
134///
135/// ```text
136///    ┌─────┐
137///    │  0  │───────────▶   100
138///    ├─────┤
139///    │  1  │───────────▶   200
140///    └─────┘
141///      ...                 ...
142///    ┌─────┐
143///    │ N-2 │───────────▶    50
144///    ├─────┤
145///    │ N-1 │───────────▶   200
146///    └─────┘
147///
148///
149///  Logical group      Current Min
150///     number          value for that
151///                     group
152/// ```
153///
154/// # Notes on Implementing `GroupsAccumulator`
155///
156/// All aggregates must first implement the simpler [`Accumulator`] trait, which
157/// handles state for a single group. Implementing `GroupsAccumulator` is
158/// optional and is harder to implement than `Accumulator`, but can be much
159/// faster for queries with many group values.  See the [Aggregating Millions of
160/// Groups Fast blog] for more background.
161/// For more background, please also see the [Aggregating Millions of Groups Fast in Apache Arrow DataFusion 28.0.0 blog]
162///
163/// [Aggregating Millions of Groups Fast in Apache Arrow DataFusion 28.0.0 blog]: https://datafusion.apache.org/blog/2023/08/05/datafusion_fast_grouping
164///
165/// [`NullState`] can help keep the state for groups that have not seen any
166/// values and produce the correct output for those groups.
167///
168/// [`NullState`]: https://docs.rs/datafusion/latest/datafusion/physical_expr/struct.NullState.html
169///
170/// # Details
171/// Each group is assigned a `group_index` by the hash table and each
172/// accumulator manages the specific state, one per `group_index`.
173///
174/// `group_index`es are contiguous (there aren't gaps), and thus it is
175/// expected that each `GroupsAccumulator` will use something like `Vec<..>`
176/// to store the group states.
177///
178/// [`Accumulator`]: crate::accumulator::Accumulator
179/// [Aggregating Millions of Groups Fast blog]: https://arrow.apache.org/blog/2023/08/05/datafusion_fast_grouping/
180pub trait GroupsAccumulator: Send + std::any::Any {
181    /// Supplies optional metrics owned by this aggregate expression.
182    ///
183    /// Call this immediately after construction and before the accumulator is
184    /// used; replacing metrics after use is unsupported. The default preserves
185    /// compatibility for accumulators without internal submetrics.
186    fn set_metrics(&mut self, _metrics: Arc<dyn AggregateMetrics>) {}
187
188    /// Updates the accumulator's state from its arguments, encoded as
189    /// a vector of [`ArrayRef`]s.
190    ///
191    /// * `values`: the input arguments to the accumulator
192    ///
193    /// * `group_indices`: The group indices to which each row in `values` belongs.
194    ///
195    /// * `opt_filter`: if present, only update aggregate state using
196    ///   `values[i]` if `opt_filter[i]` is true
197    ///
198    /// * `total_num_groups`: the number of groups (the largest
199    ///   group_index is thus `total_num_groups - 1`).
200    ///
201    /// Note that subsequent calls to update_batch may have larger
202    /// total_num_groups as new groups are seen.
203    ///
204    /// See [`NullState`] to help keep the state for groups that have not seen any
205    /// values and produce the correct output for those groups.
206    ///
207    /// [`NullState`]: https://docs.rs/datafusion/latest/datafusion/physical_expr/struct.NullState.html
208    fn update_batch(
209        &mut self,
210        values: &[ArrayRef],
211        group_indices: &[usize],
212        opt_filter: Option<&BooleanArray>,
213        total_num_groups: usize,
214    ) -> Result<()>;
215
216    /// Returns the final aggregate value for each group as a single
217    /// `RecordBatch`, resetting the internal state.
218    ///
219    /// The rows returned *must* be in group_index order: The value
220    /// for group_index 0, followed by 1, etc.  Any group_index that
221    /// did not have values, should be null.
222    ///
223    /// For example, a `SUM` accumulator maintains a running sum for
224    /// each group, and `evaluate` will produce that running sum as
225    /// its output for all groups, in group_index order
226    ///
227    /// If `emit_to` is [`EmitTo::All`], the accumulator should
228    /// return all groups and release / reset its internal state
229    /// equivalent to when it was first created.
230    ///
231    /// If `emit_to` is [`EmitTo::First`], only the first `n` groups
232    /// should be emitted and the state for those first groups
233    /// removed. State for the remaining groups must be retained for
234    /// future use. The group_indices on subsequent calls to
235    /// `update_batch` or `merge_batch` will be shifted down by
236    /// `n`. See [`EmitTo::First`] for more details.
237    fn evaluate(&mut self, emit_to: EmitTo) -> Result<ArrayRef>;
238
239    /// Returns final aggregate values without changing the logical state or
240    /// group indices.
241    ///
242    /// Rows are returned in the order specified by `selection`. An empty
243    /// selection returns a correctly typed array with no rows.
244    ///
245    /// This method requires exclusive access because implementations may mutate
246    /// internal caches or builders. However, repeated calls and later updates
247    /// must observe the same logical accumulator state.
248    fn evaluate_preserving(
249        &mut self,
250        _selection: GroupSelection<'_>,
251    ) -> Result<ArrayRef> {
252        not_impl_err!("Preserving grouped evaluation is not implemented")
253    }
254
255    /// Returns `true` if [`Self::evaluate_preserving`] is implemented.
256    fn supports_evaluate_preserving(&self) -> bool {
257        false
258    }
259
260    /// Returns the intermediate aggregate state for this accumulator,
261    /// used for multi-phase grouping, resetting its internal state.
262    ///
263    /// See [`Accumulator::state`] for more information on multi-phase
264    /// aggregation.
265    ///
266    /// For example, `AVG` might return two arrays: `SUM` and `COUNT`
267    /// but the `MIN` aggregate would just return a single array.
268    ///
269    /// Note more sophisticated internal state can be passed as
270    /// single `StructArray` rather than multiple arrays.
271    ///
272    /// See [`Self::evaluate`] for details on the required output
273    /// order and `emit_to`.
274    ///
275    /// [`Accumulator::state`]: crate::accumulator::Accumulator::state
276    fn state(&mut self, emit_to: EmitTo) -> Result<Vec<ArrayRef>>;
277
278    /// Returns intermediate aggregate state without changing the logical state
279    /// or group indices.
280    ///
281    /// Each returned array has one row per selected group, in the order
282    /// specified by `selection`. An empty selection returns the normal number
283    /// of correctly typed state arrays, each with no rows.
284    ///
285    /// This method requires exclusive access because implementations may mutate
286    /// internal caches or builders. However, repeated calls and later updates
287    /// must observe the same logical accumulator state.
288    fn state_preserving(
289        &mut self,
290        _selection: GroupSelection<'_>,
291    ) -> Result<Vec<ArrayRef>> {
292        not_impl_err!("Preserving grouped state is not implemented")
293    }
294
295    /// Returns `true` if [`Self::state_preserving`] is implemented.
296    fn supports_state_preserving(&self) -> bool {
297        false
298    }
299
300    /// Merges intermediate state (the output from [`Self::state`])
301    /// into this accumulator's current state.
302    ///
303    /// For some aggregates (such as `SUM`), `merge_batch` is the same
304    /// as `update_batch`, but for some aggregates (such as `COUNT`,
305    /// where the partial counts must be summed) the operations
306    /// differ. See [`Self::state`] for more details on how state is
307    /// used and merged.
308    ///
309    /// * `values`: arrays produced from previously calling `state` on other accumulators.
310    ///
311    /// Other arguments are the same as for [`Self::update_batch`], except that
312    /// there is no `opt_filter` — aggregate filters are applied during the
313    /// partial (update) phase, so by the time intermediate states are merged
314    /// no per-row filtering is needed.
315    fn merge_batch(
316        &mut self,
317        values: &[ArrayRef],
318        group_indices: &[usize],
319        total_num_groups: usize,
320    ) -> Result<()>;
321
322    /// Converts an input batch directly to the intermediate aggregate state.
323    ///
324    /// This is the equivalent of treating each input row as its own group. It
325    /// is invoked when the Partial phase of a multi-phase aggregation is not
326    /// reducing the cardinality enough to warrant spending more effort on
327    /// pre-aggregation (see `Background` section below), and switches to
328    /// passing intermediate state directly on to the next aggregation phase.
329    ///
330    /// Examples:
331    /// * `COUNT`: an array of 1s for each row in the input batch.
332    /// * `SUM/MIN/MAX`: the input values themselves.
333    ///
334    /// # Arguments
335    /// * `values`: the input arguments to the accumulator
336    /// * `opt_filter`: if present, any row where `opt_filter[i]` is false should be ignored
337    ///
338    /// # Background
339    ///
340    /// In a multi-phase aggregation (see [`Accumulator::state`]), the initial
341    /// Partial phase reduces the cardinality of the input data as soon as
342    /// possible in the plan.
343    ///
344    /// This strategy is very effective for queries with a small number of
345    /// groups, as most of the data is aggregated immediately and only a small
346    /// amount of data must be repartitioned (see [`Accumulator::state`] for
347    /// background)
348    ///
349    /// However, for queries with a large number of groups, the Partial phase
350    /// often does not reduce the cardinality enough to warrant the memory and
351    /// CPU cost of actually performing the aggregation. For such cases, the
352    /// HashAggregate operator will dynamically switch to passing intermediate
353    /// state directly to the next aggregation phase with minimal processing
354    /// using this method.
355    ///
356    /// [`Accumulator::state`]: crate::accumulator::Accumulator::state
357    fn convert_to_state(
358        &self,
359        values: &[ArrayRef],
360        opt_filter: Option<&BooleanArray>,
361    ) -> Result<Vec<ArrayRef>>;
362
363    /// Amount of memory used to store the state of this accumulator,
364    /// in bytes.
365    ///
366    /// This function is called once per batch, so it should be `O(n)` to
367    /// compute, not `O(num_groups)`
368    ///
369    /// May be expensive; check the implementation before calling on hot paths.
370    fn size(&self) -> usize;
371
372    /// Keeps the stored groups but releases capacity they do not need, such as
373    /// per-batch scratch buffers, so that [`Self::size`] reflects the stored
374    /// groups. For example, after [`EmitTo::First`] removes most groups, an
375    /// accumulator may keep a buffer it sized for the last input batch.
376    ///
377    /// The default does nothing.
378    fn shrink_to_fit(&mut self) {}
379}
380
381#[cfg(test)]
382mod tests {
383    use super::{EmitTo, GroupSelection};
384
385    /// When `n` is small relative to `len`, the old `split_off(n) + swap` pattern had
386    /// two allocation problems:
387    ///
388    /// 1. The returned Vec kept the original large backing allocation even though it
389    ///    only contains `n` elements (wasted capacity on a short-lived value).
390    /// 2. `split_off` allocated a fresh Vec for the `len - n` remaining elements,
391    ///    even though that side is much larger than `n` — the expensive side to
392    ///    allocate.
393    ///
394    /// `split_vec_min_alloc` fixes both: when `n * 2 <= len` it uses
395    /// `drain(0..n).collect()`, allocating only `n` elements for the emitted prefix
396    /// and keeping the original large backing in the remaining accumulator.
397    #[test]
398    fn take_needed_first_small_n_allocates_minimally() {
399        let mut v: Vec<i32> = Vec::with_capacity(128);
400        v.extend(0..20i32);
401        let original_capacity = v.capacity(); // 128
402
403        // n=4, n*2=8 <= len=20 -> drain branch in split_vec_min_alloc
404        let emitted = EmitTo::First(4).take_needed(&mut v);
405
406        assert_eq!(emitted, vec![0, 1, 2, 3]);
407        assert_eq!(v, (4..20i32).collect::<Vec<_>>());
408
409        // The emitted prefix must NOT carry the original large allocation.
410        // Old split_off+swap returned a Vec with capacity=128 for only 4 elements.
411        assert!(
412            emitted.capacity() <= 4,
413            "emitted prefix capacity {} should be ~n=4, not the original {}",
414            emitted.capacity(),
415            original_capacity,
416        );
417
418        // The remaining accumulator must retain the original large allocation so
419        // that incoming groups don't immediately force a realloc.
420        // Old split_off+swap left the remaining vec with a small fresh allocation.
421        assert_eq!(
422            v.capacity(),
423            original_capacity,
424            "remaining vec capacity {} should equal original {}",
425            v.capacity(),
426            original_capacity,
427        );
428    }
429
430    #[test]
431    fn group_selection_is_validated_once_and_reusable() {
432        let values = [10, 20, 30, 40];
433        let selected =
434            GroupSelection::try_from_indices(&[3, 1, 3], values.len()).unwrap();
435        assert_eq!(selected.total_num_groups(), values.len());
436        assert_eq!(selected.len(), 3);
437        assert_eq!(
438            selected
439                .iter()
440                .map(|index| values[index])
441                .collect::<Vec<_>>(),
442            vec![40, 20, 40]
443        );
444        selected.validate_num_groups(values.len()).unwrap();
445        let error = selected.validate_num_groups(values.len() - 1).unwrap_err();
446        assert!(error.to_string().contains("constructed for 4 groups"));
447
448        let all = GroupSelection::all(values.len());
449        assert_eq!(
450            all.iter().map(|index| values[index]).collect::<Vec<_>>(),
451            values
452        );
453
454        let empty = GroupSelection::try_from_indices(&[], values.len()).unwrap();
455        assert!(empty.is_empty());
456        assert!(empty.iter().next().is_none());
457
458        let error = GroupSelection::try_from_indices(&[4], values.len()).unwrap_err();
459        assert!(error.to_string().contains("out of bounds"));
460    }
461}