Skip to main content

datafusion_expr_common/
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//! Accumulator module contains the trait definition for aggregation function's accumulators.
6
7use arrow::array::ArrayRef;
8use datafusion_common::{Result, ScalarValue, instant::Instant, internal_err};
9use std::fmt::Debug;
10use std::sync::Arc;
11use std::time::Duration;
12
13/// A metric owned by one aggregate implementation.
14///
15/// Aggregate implementations use this interface for optional internal
16/// subphases. The execution engine owns metric registration and aggregation.
17pub trait AggregateMetric: Debug + Send + Sync + std::panic::RefUnwindSafe {
18    /// Adds elapsed time to this metric.
19    fn add_duration(&self, duration: Duration);
20}
21
22/// Factory for optional metrics owned by one aggregate expression.
23///
24/// `subphase` must be a stable static identifier. Repeated requests for the
25/// same subphase must return handles that update the same metric identity. An
26/// implementation may request no metrics. The execution engine assigns the
27/// aggregate expression identity.
28pub trait AggregateMetrics: Debug + Send + Sync {
29    /// Returns the metric for an aggregate-owned internal subphase.
30    fn metric(&self, subphase: &'static str) -> Arc<dyn AggregateMetric>;
31}
32
33/// Publishes aggregate-owned timing when dropped.
34///
35/// Create this before the operation that may return an error, and scope each
36/// [`Self::timer`] to only the aggregate-owned work. All timed intervals are
37/// combined into one metric update when the recorder is dropped.
38pub struct AggregateMetricRecorder {
39    metric: Option<Arc<dyn AggregateMetric>>,
40    duration: Duration,
41}
42
43impl AggregateMetricRecorder {
44    /// Creates a recorder for an optional aggregate-owned metric.
45    pub fn new(metric: Option<Arc<dyn AggregateMetric>>) -> Self {
46        Self {
47            metric,
48            duration: Duration::ZERO,
49        }
50    }
51
52    /// Starts timing one aggregate-owned interval.
53    pub fn timer(&mut self) -> Option<AggregateMetricTimer<'_>> {
54        self.metric.as_ref()?;
55        Some(AggregateMetricTimer {
56            duration: &mut self.duration,
57            start: Instant::now(),
58        })
59    }
60}
61
62impl Drop for AggregateMetricRecorder {
63    fn drop(&mut self) {
64        if let Some(metric) = &self.metric {
65            metric.add_duration(self.duration);
66        }
67    }
68}
69
70/// One aggregate-owned interval recorded by [`AggregateMetricRecorder`].
71pub struct AggregateMetricTimer<'a> {
72    duration: &'a mut Duration,
73    start: Instant,
74}
75
76impl Drop for AggregateMetricTimer<'_> {
77    fn drop(&mut self) {
78        *self.duration += self.start.elapsed();
79    }
80}
81
82/// Tracks an aggregate function's state.
83///
84/// `Accumulator`s are stateful objects that implement a single group. They
85/// aggregate values from multiple rows together into a final output aggregate.
86///
87/// [`GroupsAccumulator`] is an additional more performant (but also complex) API
88/// that manages state for multiple groups at once.
89///
90/// An accumulator knows how to:
91/// * update its state from inputs via [`update_batch`]
92///
93/// * compute the final value from its internal state via [`evaluate`]
94///
95/// * retract an update to its state from given inputs via
96///   [`retract_batch`] (when used as a window aggregate [window
97///   function])
98///
99/// * convert its internal state to a vector of aggregate values via
100///   [`state`] and combine the state from multiple accumulators
101///   via [`merge_batch`], as part of efficient multi-phase grouping.
102///
103/// [`update_batch`]: Self::update_batch
104/// [`retract_batch`]: Self::retract_batch
105/// [`state`]: Self::state
106/// [`evaluate`]: Self::evaluate
107/// [`merge_batch`]: Self::merge_batch
108/// [`GroupsAccumulator`]: crate::groups_accumulator::GroupsAccumulator
109/// [window function]: https://en.wikipedia.org/wiki/Window_function_(SQL)
110pub trait Accumulator: Send + Sync + Debug + std::any::Any {
111    /// Supplies optional metrics owned by this aggregate expression.
112    ///
113    /// The grouped accumulator adapter supplies these metrics to every
114    /// accumulator it creates. Call this immediately after construction and
115    /// before the accumulator is used; replacing metrics after use is
116    /// unsupported. The default preserves compatibility for accumulators
117    /// without internal submetrics.
118    fn set_metrics(&mut self, _metrics: Arc<dyn AggregateMetrics>) {}
119
120    /// Updates the accumulator's state from its input.
121    ///
122    /// `values` contains the arguments to this aggregate function.
123    ///
124    /// For example, the `SUM` accumulator maintains a running sum,
125    /// and `update_batch` adds each of the input values to the
126    /// running sum.
127    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()>;
128
129    /// Returns an optional metric timed once per grouped adapter input batch.
130    ///
131    /// A grouped accumulator adapter uses this for aggregate-owned work it
132    /// dispatches to one accumulator per group. The default preserves the
133    /// usual per-accumulator update path.
134    fn grouped_update_batch_metric(&self) -> Option<Arc<dyn AggregateMetric>> {
135        None
136    }
137
138    /// Updates state when called by a grouped accumulator adapter.
139    ///
140    /// The default delegates to [`Self::update_batch`]. Implementations that
141    /// return a [`Self::grouped_update_batch_metric`] can avoid timing every
142    /// per-group call; the adapter records one interval for the full batch.
143    fn update_batch_grouped(&mut self, values: &[ArrayRef]) -> Result<()> {
144        self.update_batch(values)
145    }
146
147    /// Merges state when called by a grouped accumulator adapter.
148    ///
149    /// The default delegates to [`Self::merge_batch`]. Implementations that
150    /// return a [`Self::grouped_update_batch_metric`] can avoid timing every
151    /// per-group merge; the adapter records one interval for the full batch.
152    fn merge_batch_grouped(&mut self, states: &[ArrayRef]) -> Result<()> {
153        self.merge_batch(states)
154    }
155
156    /// Returns the final aggregate value.
157    ///
158    /// For example, the `SUM` accumulator maintains a running sum,
159    /// and `evaluate` will produce that running sum as its output.
160    ///
161    /// This function gets `&mut self` to allow for the accumulator to build
162    /// arrow-compatible internal state that can be returned without copying
163    /// when possible (for example distinct strings).
164    ///
165    /// ## Correctness
166    ///
167    /// This function must not consume the internal state, as it is also used in window
168    /// aggregate functions where it can be executed multiple times depending on the
169    /// current window frame. Consuming the internal state can cause the next invocation
170    /// to have incorrect results.
171    ///
172    /// - Even if this accumulator doesn't implement [`retract_batch`] it may still be used
173    ///   in window aggregate functions where the window frame is
174    ///   `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`
175    ///
176    /// It is fine to modify the state (e.g. re-order elements within internal state vec) so long
177    /// as this doesn't cause an incorrect computation on the next call of evaluate.
178    ///
179    /// [`retract_batch`]: Self::retract_batch
180    fn evaluate(&mut self) -> Result<ScalarValue>;
181
182    /// Returns the allocated size required for this accumulator, in
183    /// bytes, including `Self`.
184    ///
185    /// This value is used to calculate the memory used during
186    /// execution so DataFusion can stay within its allotted limit.
187    ///
188    /// "Allocated" means that for internal containers such as `Vec`,
189    /// the `capacity` should be used not the `len`.
190    ///
191    /// May be expensive; check the implementation before calling on hot paths.
192    fn size(&self) -> usize;
193
194    /// Returns the intermediate state of the accumulator, consuming the
195    /// intermediate state.
196    ///
197    /// This function should not be called twice, otherwise it will
198    /// result in potentially non-deterministic behavior.
199    ///
200    /// This function gets `&mut self` to allow for the accumulator to build
201    /// arrow-compatible internal state that can be returned without copying
202    /// when possible (for example distinct strings).
203    ///
204    /// Intermediate state is used for "multi-phase" grouping in
205    /// DataFusion, where an aggregate is computed in parallel with
206    /// multiple `Accumulator` instances, as described below:
207    ///
208    /// # Multi-Phase Grouping
209    ///
210    /// ```text
211    ///                               ▲
212    ///                               │                   evaluate() is called to
213    ///                               │                   produce the final aggregate
214    ///                               │                   value per group
215    ///                               │
216    ///                  ┌─────────────────────────┐
217    ///                  │GroupBy                  │
218    ///                  │(AggregateMode::Final)   │      state() is called for each
219    ///                  │                         │      group and the resulting
220    ///                  └─────────────────────────┘      RecordBatches passed to the
221    ///                                                   Final GroupBy via merge_batch()
222    ///                               ▲
223    ///                               │
224    ///              ┌────────────────┴───────────────┐
225    ///              │                                │
226    ///              │                                │
227    /// ┌─────────────────────────┐      ┌─────────────────────────┐
228    /// │        GroupBy          │      │        GroupBy          │
229    /// │(AggregateMode::Partial) │      │(AggregateMode::Partial) │
230    /// └─────────────────────────┘      └─────────────────────────┘
231    ///              ▲                                ▲
232    ///              │                                │    update_batch() is called for
233    ///              │                                │    each input RecordBatch
234    ///         .─────────.                      .─────────.
235    ///      ,─'           '─.                ,─'           '─.
236    ///     ;      Input      :              ;      Input      :
237    ///     :   Partition 0   ;              :   Partition 1   ;
238    ///      ╲               ╱                ╲               ╱
239    ///       '─.         ,─'                  '─.         ,─'
240    ///          `───────'                        `───────'
241    /// ```
242    ///
243    /// The partial state is serialized as `Arrays` and then combined
244    /// with other partial states from different instances of this
245    /// Accumulator (that ran on different partitions, for example).
246    ///
247    /// The state can be and often is a different type than the output
248    /// type of the [`Accumulator`] and needs different merge
249    /// operations (for example, the partial state for `COUNT` needs
250    /// to be summed together)
251    ///
252    /// Some accumulators can return multiple values for their
253    /// intermediate states. For example, the average accumulator
254    /// tracks `sum` and `n`, and this function should return a vector
255    /// of two values, sum and n.
256    ///
257    /// Note that [`ScalarValue::List`] can be used to pass multiple
258    /// values if the number of intermediate values is not known at
259    /// planning time (e.g. for `MEDIAN`)
260    ///
261    /// # Multi-phase repartitioned Grouping
262    ///
263    /// Many multi-phase grouping plans contain a Repartition operation
264    /// as well as shown below:
265    ///
266    /// ```text
267    ///                ▲                          ▲
268    ///                │                          │
269    ///                │                          │
270    ///                │                          │
271    ///                │                          │
272    ///                │                          │
273    ///    ┌───────────────────────┐  ┌───────────────────────┐       4. Each AggregateMode::Final
274    ///    │GroupBy                │  │GroupBy                │       GroupBy has an entry for its
275    ///    │(AggregateMode::Final) │  │(AggregateMode::Final) │       subset of groups (in this case
276    ///    │                       │  │                       │       that means half the entries)
277    ///    └───────────────────────┘  └───────────────────────┘
278    ///                ▲                          ▲
279    ///                │                          │
280    ///                └─────────────┬────────────┘
281    ///                              │
282    ///                              │
283    ///                              │
284    ///                 ┌─────────────────────────┐                   3. Repartitioning by hash(group
285    ///                 │       Repartition       │                   keys) ensures that each distinct
286    ///                 │         HASH(x)         │                   group key now appears in exactly
287    ///                 └─────────────────────────┘                   one partition
288    ///                              ▲
289    ///                              │
290    ///              ┌───────────────┴─────────────┐
291    ///              │                             │
292    ///              │                             │
293    /// ┌─────────────────────────┐  ┌──────────────────────────┐     2. Each AggregateMode::Partial
294    /// │        GroupBy          │  │       GroupBy            │     GroupBy has an entry for *all*
295    /// │(AggregateMode::Partial) │  │ (AggregateMode::Partial) │     the groups
296    /// └─────────────────────────┘  └──────────────────────────┘
297    ///              ▲                             ▲
298    ///              │                             │
299    ///              │                             │
300    ///         .─────────.                   .─────────.
301    ///      ,─'           '─.             ,─'           '─.
302    ///     ;      Input      :           ;      Input      :         1. Since input data is
303    ///     :   Partition 0   ;           :   Partition 1   ;         arbitrarily or RoundRobin
304    ///      ╲               ╱             ╲               ╱          distributed, each partition
305    ///       '─.         ,─'               '─.         ,─'           likely has all distinct
306    ///          `───────'                     `───────'
307    /// ```
308    ///
309    /// This structure is used so that the `AggregateMode::Partial` accumulators
310    /// reduces the cardinality of the input as soon as possible. Typically,
311    /// each partial accumulator sees all groups in the input as the group keys
312    /// are evenly distributed across the input.
313    ///
314    /// The final output is computed by repartitioning the result of
315    /// [`Self::state`] from each Partial aggregate and `hash(group keys)` so
316    /// that each distinct group key appears in exactly one of the
317    /// `AggregateMode::Final` GroupBy nodes. The outputs of the final nodes are
318    /// then unioned together to produce the overall final output.
319    ///
320    /// Here is an example that shows the distribution of groups in the
321    /// different phases
322    ///
323    /// ```text
324    ///               ┌─────┐                ┌─────┐
325    ///               │  1  │                │  3  │
326    ///               ├─────┤                ├─────┤
327    ///               │  2  │                │  4  │                After repartitioning by
328    ///               └─────┘                └─────┘                hash(group keys), each distinct
329    ///               ┌─────┐                ┌─────┐                group key now appears in exactly
330    ///               │  1  │                │  3  │                one partition
331    ///               ├─────┤                ├─────┤
332    ///               │  2  │                │  4  │
333    ///               └─────┘                └─────┘
334    ///
335    ///
336    /// ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─
337    ///
338    ///               ┌─────┐                ┌─────┐
339    ///               │  2  │                │  2  │
340    ///               ├─────┤                ├─────┤
341    ///               │  1  │                │  2  │
342    ///               ├─────┤                ├─────┤
343    ///               │  3  │                │  3  │
344    ///               ├─────┤                ├─────┤
345    ///               │  4  │                │  1  │
346    ///               └─────┘                └─────┘                Input data is arbitrarily or
347    ///                 ...                    ...                  RoundRobin distributed, each
348    ///               ┌─────┐                ┌─────┐                partition likely has all
349    ///               │  1  │                │  4  │                distinct group keys
350    ///               ├─────┤                ├─────┤
351    ///               │  4  │                │  3  │
352    ///               ├─────┤                ├─────┤
353    ///               │  1  │                │  1  │
354    ///               ├─────┤                ├─────┤
355    ///               │  4  │                │  3  │
356    ///               └─────┘                └─────┘
357    ///
358    ///           group values           group values
359    ///           in partition 0         in partition 1
360    /// ```
361    fn state(&mut self) -> Result<Vec<ScalarValue>>;
362
363    /// Updates the accumulator's state from an `Array` containing one
364    /// or more intermediate values.
365    ///
366    /// For some aggregates (such as `SUM`), merge_batch is the same
367    /// as `update_batch`, but for some aggregates (such as `COUNT`)
368    /// the operations differ. See [`Self::state`] for more details on how
369    /// state is used and merged.
370    ///
371    /// The `states` array passed was formed by concatenating the
372    /// results of calling [`Self::state`] on zero or more other
373    /// `Accumulator` instances.
374    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()>;
375
376    /// Retracts (removed) an update (caused by the given inputs) to
377    /// accumulator's state.
378    ///
379    /// This is the inverse operation of [`Self::update_batch`] and is used
380    /// to incrementally calculate window aggregates where the `OVER`
381    /// clause defines a bounded window.
382    ///
383    /// # Example
384    ///
385    /// For example, given the following input partition
386    ///
387    /// ```text
388    ///                     │      current      │
389    ///                            window
390    ///                     │                   │
391    ///                ┌────┬────┬────┬────┬────┬────┬────┬────┬────┐
392    ///     Input      │ A  │ B  │ C  │ D  │ E  │ F  │ G  │ H  │ I  │
393    ///   partition    └────┴────┴────┴────┼────┴────┴────┴────┼────┘
394    ///
395    ///                                    │         next      │
396    ///                                             window
397    /// ```
398    ///
399    /// First, [`Self::evaluate`] will be called to produce the output
400    /// for the current window.
401    ///
402    /// Then, to advance to the next window:
403    ///
404    /// First, [`Self::retract_batch`] will be called with the values
405    /// that are leaving the window, `[B, C, D]` and then
406    /// [`Self::update_batch`] will be called with the values that are
407    /// entering the window, `[F, G, H]`.
408    fn retract_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
409        // TODO add retract for all accumulators
410        internal_err!(
411            "Retract should be implemented for aggregate functions when used with custom window frame queries"
412        )
413    }
414
415    /// Does the accumulator support incrementally updating its value
416    /// by *removing* values.
417    ///
418    /// If this function returns true, [`Self::retract_batch`] will be
419    /// called for sliding window functions such as queries with an
420    /// `OVER (ROWS BETWEEN 1 PRECEDING AND 2 FOLLOWING)`
421    fn supports_retract_batch(&self) -> bool {
422        false
423    }
424}