Skip to main content

datafusion_physical_expr/window/
aggregate.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//! Physical exec for aggregate window function expressions.
6
7use std::any::Any;
8use std::ops::Range;
9use std::sync::Arc;
10
11use crate::aggregate::AggregateFunctionExpr;
12use crate::window::standard::add_new_ordering_expr_with_partition_by;
13use crate::window::window_expr::{
14    AggregateWindowExpr, WindowEvalContext, WindowFn, filter_array,
15};
16use crate::window::{
17    PartitionBatches, PartitionWindowAggStates, SlidingAggregateWindowExpr, WindowExpr,
18};
19use crate::{EquivalenceProperties, PhysicalExpr};
20
21use arrow::array::ArrayRef;
22use arrow::array::BooleanArray;
23use arrow::datatypes::FieldRef;
24use arrow::record_batch::RecordBatch;
25use datafusion_common::{Result, ScalarValue, exec_datafusion_err};
26use datafusion_expr::{Accumulator, WindowFrame, WindowFrameBound, WindowFrameUnits};
27use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
28
29/// Reverses an aggregate-backed window expression.
30///
31/// Shared by [`PlainAggregateWindowExpr::get_reverse_expr`] and
32/// [`SlidingAggregateWindowExpr::get_reverse_expr`], which are otherwise
33/// identical. The reversed frame decides which of the two variants is produced:
34/// an ever-expanding frame can be evaluated by the plain (accumulating) variant,
35/// anything else needs the sliding variant.
36///
37/// The aggregate is reversed with
38/// [`AggregateFunctionExpr::reverse_expr_preserving_name`] so that the window's
39/// output field name is unchanged -- the window exec's schema is derived from
40/// [`WindowExpr::field`], and parent plan nodes reference those columns by name.
41pub(crate) fn reverse_aggregate_window_expr(
42    aggregate: &AggregateFunctionExpr,
43    partition_by: &[Arc<dyn PhysicalExpr>],
44    order_by: &[PhysicalSortExpr],
45    window_frame: &WindowFrame,
46    filter: Option<&Arc<dyn PhysicalExpr>>,
47) -> Option<Arc<dyn WindowExpr>> {
48    aggregate
49        .reverse_expr_preserving_name()
50        .map(|reverse_expr| {
51            let reverse_expr = Arc::new(reverse_expr);
52            let reverse_order_by =
53                order_by.iter().map(|e| e.reverse()).collect::<Vec<_>>();
54            let reverse_window_frame = Arc::new(window_frame.reverse());
55            let filter = filter.cloned();
56            if reverse_window_frame.is_ever_expanding() {
57                Arc::new(PlainAggregateWindowExpr::new(
58                    reverse_expr,
59                    partition_by,
60                    &reverse_order_by,
61                    reverse_window_frame,
62                    filter,
63                )) as _
64            } else {
65                Arc::new(SlidingAggregateWindowExpr::new(
66                    reverse_expr,
67                    partition_by,
68                    &reverse_order_by,
69                    reverse_window_frame,
70                    filter,
71                )) as _
72            }
73        })
74}
75
76/// A window expr that takes the form of an aggregate function.
77///
78/// See comments on [`WindowExpr`] for more details.
79#[derive(Debug)]
80pub struct PlainAggregateWindowExpr {
81    aggregate: Arc<AggregateFunctionExpr>,
82    partition_by: Vec<Arc<dyn PhysicalExpr>>,
83    order_by: Vec<PhysicalSortExpr>,
84    window_frame: Arc<WindowFrame>,
85    is_constant_in_partition: bool,
86    filter: Option<Arc<dyn PhysicalExpr>>,
87}
88
89impl PlainAggregateWindowExpr {
90    /// Create a new aggregate window function expression
91    pub fn new(
92        aggregate: Arc<AggregateFunctionExpr>,
93        partition_by: &[Arc<dyn PhysicalExpr>],
94        order_by: &[PhysicalSortExpr],
95        window_frame: Arc<WindowFrame>,
96        filter: Option<Arc<dyn PhysicalExpr>>,
97    ) -> Self {
98        let is_constant_in_partition =
99            Self::is_window_constant_in_partition(order_by, &window_frame);
100        Self {
101            aggregate,
102            partition_by: partition_by.to_vec(),
103            order_by: order_by.to_vec(),
104            window_frame,
105            is_constant_in_partition,
106            filter,
107        }
108    }
109
110    /// Get aggregate expr of AggregateWindowExpr
111    pub fn get_aggregate_expr(&self) -> &AggregateFunctionExpr {
112        &self.aggregate
113    }
114
115    pub fn add_equal_orderings(
116        &self,
117        eq_properties: &mut EquivalenceProperties,
118        window_expr_index: usize,
119    ) -> Result<()> {
120        if let Some(expr) = self
121            .get_aggregate_expr()
122            .get_result_ordering(window_expr_index)
123        {
124            add_new_ordering_expr_with_partition_by(
125                eq_properties,
126                expr,
127                &self.partition_by,
128            )?;
129        }
130        Ok(())
131    }
132
133    // Returns true if every row in the partition has the same window frame. This allows
134    // for preventing bound + function calculation for every row due to the values being the
135    // same.
136    //
137    // This occurs when both bounds fall under either condition below:
138    //  1. Bound is unbounded (`Preceding` or `Following`)
139    //  2. Bound is `CurrentRow` while using `Range` units with no order by clause
140    //  This results in an invalid range specification. Following PostgreSQL’s convention,
141    //  we interpret this as the entire partition being used for the current window frame.
142    fn is_window_constant_in_partition(
143        order_by: &[PhysicalSortExpr],
144        window_frame: &WindowFrame,
145    ) -> bool {
146        let is_constant_bound = |bound: &WindowFrameBound| match bound {
147            WindowFrameBound::CurrentRow => {
148                window_frame.units == WindowFrameUnits::Range && order_by.is_empty()
149            }
150            _ => bound.is_unbounded(),
151        };
152
153        is_constant_bound(&window_frame.start_bound)
154            && is_constant_bound(&window_frame.end_bound)
155    }
156}
157
158/// peer based evaluation based on the fact that batch is pre-sorted given the sort columns
159/// and then per partition point we'll evaluate the peer group (e.g. SUM or MAX gives the same
160/// results for peers) and concatenate the results.
161impl WindowExpr for PlainAggregateWindowExpr {
162    /// Return a reference to Any that can be used for downcasting
163    fn as_any(&self) -> &dyn Any {
164        self
165    }
166
167    fn field(&self) -> Result<FieldRef> {
168        Ok(self.aggregate.field())
169    }
170
171    fn name(&self) -> &str {
172        self.aggregate.name()
173    }
174
175    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
176        self.aggregate.expressions()
177    }
178
179    fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
180        self.aggregate_evaluate(batch)
181    }
182
183    fn evaluate_stateful(
184        &self,
185        partition_batches: &PartitionBatches,
186        window_agg_state: &mut PartitionWindowAggStates,
187        eval_ctx: &WindowEvalContext<'_>,
188    ) -> Result<()> {
189        self.aggregate_evaluate_stateful(partition_batches, window_agg_state, eval_ctx)?;
190
191        // Update window frame range for each partition. As we know that
192        // non-sliding aggregations will never call `retract_batch`, this value
193        // can safely increase, and we can remove "old" parts of the state.
194        // This enables us to run queries involving UNBOUNDED PRECEDING frames
195        // using bounded memory for suitable aggregations.
196        for partition_row in partition_batches.keys() {
197            let window_state = window_agg_state
198                .get_mut(partition_row)
199                .ok_or_else(|| exec_datafusion_err!("Cannot find state"))?;
200            let state = &mut window_state.state;
201            if self.window_frame.start_bound.is_unbounded() {
202                state.window_frame_range.start =
203                    state.window_frame_range.end.saturating_sub(1);
204            }
205        }
206        Ok(())
207    }
208
209    fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>] {
210        &self.partition_by
211    }
212
213    fn order_by(&self) -> &[PhysicalSortExpr] {
214        &self.order_by
215    }
216
217    fn get_window_frame(&self) -> &Arc<WindowFrame> {
218        &self.window_frame
219    }
220
221    fn get_reverse_expr(&self) -> Option<Arc<dyn WindowExpr>> {
222        reverse_aggregate_window_expr(
223            &self.aggregate,
224            &self.partition_by,
225            &self.order_by,
226            &self.window_frame,
227            self.filter.as_ref(),
228        )
229    }
230
231    fn uses_bounded_memory(&self) -> bool {
232        !self.window_frame.end_bound.is_unbounded()
233    }
234
235    fn create_window_fn(&self) -> Result<WindowFn> {
236        Ok(WindowFn::Aggregate(self.get_accumulator()?))
237    }
238}
239
240impl AggregateWindowExpr for PlainAggregateWindowExpr {
241    fn get_accumulator(&self) -> Result<Box<dyn Accumulator>> {
242        self.aggregate.create_accumulator()
243    }
244
245    fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
246        self.filter.as_ref()
247    }
248
249    /// For a given range, calculate accumulation result inside the range on
250    /// `value_slice` and update accumulator state.
251    // We assume that `cur_range` contains `last_range` and their start points
252    // are same. In summary if `last_range` is `Range{start: a,end: b}` and
253    // `cur_range` is `Range{start: a1, end: b1}`, it is guaranteed that a1=a and b1>=b.
254    fn get_aggregate_result_inside_range(
255        &self,
256        last_range: &Range<usize>,
257        cur_range: &Range<usize>,
258        value_slice: &[ArrayRef],
259        accumulator: &mut Box<dyn Accumulator>,
260        filter_mask: Option<&BooleanArray>,
261    ) -> Result<ScalarValue> {
262        if cur_range.start == cur_range.end {
263            self.aggregate
264                .default_value(self.aggregate.field().data_type())
265        } else {
266            // Accumulate any new rows that have entered the window:
267            let update_bound = cur_range.end - last_range.end;
268            // A non-sliding aggregation only processes new data, it never
269            // deals with expiring data as its starting point is always the
270            // same point (i.e. the beginning of the table/frame). Hence, we
271            // do not call `retract_batch`.
272            if update_bound > 0 {
273                let slice_mask =
274                    filter_mask.map(|m| m.slice(last_range.end, update_bound));
275                let update: Vec<ArrayRef> = value_slice
276                    .iter()
277                    .map(|v| v.slice(last_range.end, update_bound))
278                    .map(|arr| match &slice_mask {
279                        Some(m) => filter_array(&arr, m),
280                        None => Ok(arr),
281                    })
282                    .collect::<Result<Vec<_>>>()?;
283                accumulator.update_batch(&update)?
284            }
285            accumulator.evaluate()
286        }
287    }
288
289    fn is_constant_in_partition(&self) -> bool {
290        self.is_constant_in_partition
291    }
292}