Skip to main content

datafusion_physical_expr/window/
sliding_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::aggregate::reverse_aggregate_window_expr;
13use crate::window::window_expr::{
14    AggregateWindowExpr, WindowEvalContext, WindowFn, filter_array,
15};
16use crate::window::{PartitionBatches, PartitionWindowAggStates, WindowExpr};
17use crate::{PhysicalExpr, expressions::PhysicalSortExpr};
18
19use arrow::array::{ArrayRef, BooleanArray};
20use arrow::datatypes::FieldRef;
21use arrow::record_batch::RecordBatch;
22use datafusion_common::{Result, ScalarValue};
23use datafusion_expr::{Accumulator, WindowFrame};
24
25/// A window expr that takes the form of an aggregate function that
26/// can be incrementally computed over sliding windows.
27///
28/// See comments on [`WindowExpr`] for more details.
29#[derive(Debug)]
30pub struct SlidingAggregateWindowExpr {
31    aggregate: Arc<AggregateFunctionExpr>,
32    partition_by: Vec<Arc<dyn PhysicalExpr>>,
33    order_by: Vec<PhysicalSortExpr>,
34    window_frame: Arc<WindowFrame>,
35    filter: Option<Arc<dyn PhysicalExpr>>,
36}
37
38impl SlidingAggregateWindowExpr {
39    /// Create a new (sliding) aggregate window function expression.
40    pub fn new(
41        aggregate: Arc<AggregateFunctionExpr>,
42        partition_by: &[Arc<dyn PhysicalExpr>],
43        order_by: &[PhysicalSortExpr],
44        window_frame: Arc<WindowFrame>,
45        filter: Option<Arc<dyn PhysicalExpr>>,
46    ) -> Self {
47        Self {
48            aggregate,
49            partition_by: partition_by.to_vec(),
50            order_by: order_by.to_vec(),
51            window_frame,
52            filter,
53        }
54    }
55
56    /// Get the [AggregateFunctionExpr] of this object.
57    pub fn get_aggregate_expr(&self) -> &AggregateFunctionExpr {
58        &self.aggregate
59    }
60}
61
62/// Incrementally update window function using the fact that batch is
63/// pre-sorted given the sort columns and then per partition point.
64///
65/// Evaluates the peer group (e.g. `SUM` or `MAX` gives the same results
66/// for peers) and concatenate the results.
67impl WindowExpr for SlidingAggregateWindowExpr {
68    /// Return a reference to Any that can be used for downcasting
69    fn as_any(&self) -> &dyn Any {
70        self
71    }
72
73    fn field(&self) -> Result<FieldRef> {
74        Ok(self.aggregate.field())
75    }
76
77    fn name(&self) -> &str {
78        self.aggregate.name()
79    }
80
81    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>> {
82        self.aggregate.expressions()
83    }
84
85    fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
86        self.aggregate_evaluate(batch)
87    }
88
89    fn evaluate_stateful(
90        &self,
91        partition_batches: &PartitionBatches,
92        window_agg_state: &mut PartitionWindowAggStates,
93        eval_ctx: &WindowEvalContext<'_>,
94    ) -> Result<()> {
95        self.aggregate_evaluate_stateful(partition_batches, window_agg_state, eval_ctx)
96    }
97
98    fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>] {
99        &self.partition_by
100    }
101
102    fn order_by(&self) -> &[PhysicalSortExpr] {
103        &self.order_by
104    }
105
106    fn get_window_frame(&self) -> &Arc<WindowFrame> {
107        &self.window_frame
108    }
109
110    fn get_reverse_expr(&self) -> Option<Arc<dyn WindowExpr>> {
111        reverse_aggregate_window_expr(
112            &self.aggregate,
113            &self.partition_by,
114            &self.order_by,
115            &self.window_frame,
116            self.filter.as_ref(),
117        )
118    }
119
120    fn uses_bounded_memory(&self) -> bool {
121        !self.window_frame.end_bound.is_unbounded()
122    }
123
124    fn with_new_expressions(
125        &self,
126        args: Vec<Arc<dyn PhysicalExpr>>,
127        partition_bys: Vec<Arc<dyn PhysicalExpr>>,
128        order_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
129    ) -> Option<Arc<dyn WindowExpr>> {
130        debug_assert_eq!(self.order_by.len(), order_by_exprs.len());
131
132        let new_order_by = self
133            .order_by
134            .iter()
135            .zip(order_by_exprs)
136            .map(|(req, new_expr)| PhysicalSortExpr {
137                expr: new_expr,
138                options: req.options,
139            })
140            .collect();
141        Some(Arc::new(SlidingAggregateWindowExpr {
142            aggregate: self
143                .aggregate
144                .with_new_expressions(args, vec![])
145                .map(Arc::new)?,
146            partition_by: partition_bys,
147            order_by: new_order_by,
148            window_frame: Arc::clone(&self.window_frame),
149            filter: self.filter.clone(),
150        }))
151    }
152
153    fn create_window_fn(&self) -> Result<WindowFn> {
154        Ok(WindowFn::Aggregate(self.get_accumulator()?))
155    }
156}
157
158impl AggregateWindowExpr for SlidingAggregateWindowExpr {
159    fn get_accumulator(&self) -> Result<Box<dyn Accumulator>> {
160        self.aggregate.create_sliding_accumulator()
161    }
162
163    fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
164        self.filter.as_ref()
165    }
166
167    /// Given current range and the last range, calculates the accumulator
168    /// result for the range of interest.
169    fn get_aggregate_result_inside_range(
170        &self,
171        last_range: &Range<usize>,
172        cur_range: &Range<usize>,
173        value_slice: &[ArrayRef],
174        accumulator: &mut Box<dyn Accumulator>,
175        filter_mask: Option<&BooleanArray>,
176    ) -> Result<ScalarValue> {
177        if cur_range.start == cur_range.end {
178            // Keep the accumulator synchronized with `last_range`. RANGE frames
179            // can become empty between two non-empty frames when the ORDER BY
180            // values contain gaps.
181            let retract_bound = last_range.end - last_range.start;
182            if retract_bound > 0 {
183                let slice_mask =
184                    filter_mask.map(|m| m.slice(last_range.start, retract_bound));
185                let retract: Vec<ArrayRef> = value_slice
186                    .iter()
187                    .map(|v| v.slice(last_range.start, retract_bound))
188                    .map(|arr| match &slice_mask {
189                        Some(m) => filter_array(&arr, m),
190                        None => Ok(arr),
191                    })
192                    .collect::<Result<Vec<_>>>()?;
193                accumulator.retract_batch(&retract)?
194            }
195            self.aggregate
196                .default_value(self.aggregate.field().data_type())
197        } else {
198            // Accumulate any new rows that have entered the window:
199            let update_bound = cur_range.end - last_range.end;
200            if update_bound > 0 {
201                let slice_mask =
202                    filter_mask.map(|m| m.slice(last_range.end, update_bound));
203                let update: Vec<ArrayRef> = value_slice
204                    .iter()
205                    .map(|v| v.slice(last_range.end, update_bound))
206                    .map(|arr| match &slice_mask {
207                        Some(m) => filter_array(&arr, m),
208                        None => Ok(arr),
209                    })
210                    .collect::<Result<Vec<_>>>()?;
211                accumulator.update_batch(&update)?
212            }
213
214            // Remove rows that have now left the window:
215            let retract_bound = cur_range.start - last_range.start;
216            if retract_bound > 0 {
217                let slice_mask =
218                    filter_mask.map(|m| m.slice(last_range.start, retract_bound));
219                let retract: Vec<ArrayRef> = value_slice
220                    .iter()
221                    .map(|v| v.slice(last_range.start, retract_bound))
222                    .map(|arr| match &slice_mask {
223                        Some(m) => filter_array(&arr, m),
224                        None => Ok(arr),
225                    })
226                    .collect::<Result<Vec<_>>>()?;
227                accumulator.retract_batch(&retract)?
228            }
229            accumulator.evaluate()
230        }
231    }
232
233    fn is_constant_in_partition(&self) -> bool {
234        false
235    }
236}