Skip to main content

datafusion_physical_expr/window/
window_expr.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
5use std::any::Any;
6use std::fmt::Debug;
7use std::ops::Range;
8use std::sync::Arc;
9
10use crate::PhysicalExpr;
11
12use arrow::array::BooleanArray;
13use arrow::array::{Array, ArrayRef, make_comparator, new_empty_array};
14use arrow::compute::SortOptions;
15use arrow::compute::filter as arrow_filter;
16use arrow::compute::kernels::sort::SortColumn;
17use arrow::datatypes::FieldRef;
18use arrow::record_batch::RecordBatch;
19use datafusion_common::cast::as_boolean_array;
20use datafusion_common::hash_utils::RandomState;
21use datafusion_common::{
22    Result, ScalarValue, arrow_datafusion_err, exec_datafusion_err, exec_err,
23    internal_err,
24};
25use datafusion_expr::window_state::{
26    PartitionBatchState, WindowAggState, WindowFrameContext, WindowFrameStateGroups,
27};
28use datafusion_expr::{Accumulator, PartitionEvaluator, WindowFrame, WindowFrameBound};
29use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
30
31use datafusion_physical_expr_common::utils::evaluate_expressions_to_arrays;
32use indexmap::IndexMap;
33
34/// Common trait for [window function] implementations
35///
36/// # Aggregate Window Expressions
37///
38/// These expressions take the form
39///
40/// ```text
41/// OVER({ROWS | RANGE| GROUPS} BETWEEN UNBOUNDED PRECEDING AND ...)
42/// ```
43///
44/// For example, cumulative window frames uses `PlainAggregateWindowExpr`.
45///
46/// # Non Aggregate Window Expressions
47///
48/// The expressions have the form
49///
50/// ```text
51/// OVER({ROWS | RANGE| GROUPS} BETWEEN M {PRECEDING| FOLLOWING} AND ...)
52/// ```
53///
54/// For example, sliding window frames use [`SlidingAggregateWindowExpr`].
55///
56/// [window function]: https://en.wikipedia.org/wiki/Window_function_(SQL)
57/// [`PlainAggregateWindowExpr`]: crate::window::PlainAggregateWindowExpr
58/// [`SlidingAggregateWindowExpr`]: crate::window::SlidingAggregateWindowExpr
59pub trait WindowExpr: Send + Sync + Debug {
60    /// Returns the window expression as [`Any`] so that it can be
61    /// downcast to a specific implementation.
62    fn as_any(&self) -> &dyn Any;
63
64    /// The field of the final result of this window function.
65    fn field(&self) -> Result<FieldRef>;
66
67    /// Human readable name such as `"MIN(c2)"` or `"RANK()"`. The default
68    /// implementation returns placeholder text.
69    fn name(&self) -> &str {
70        "WindowExpr: default name"
71    }
72
73    /// Expressions that are passed to the WindowAccumulator.
74    /// Functions which take a single input argument, such as `sum`, return a single [`datafusion_expr::expr::Expr`],
75    /// others (e.g. `cov`) return many.
76    fn expressions(&self) -> Vec<Arc<dyn PhysicalExpr>>;
77
78    /// Evaluate the window function arguments against the batch and return
79    /// array ref, normally the resulting `Vec` is a single element one.
80    fn evaluate_args(&self, batch: &RecordBatch) -> Result<Vec<ArrayRef>> {
81        evaluate_expressions_to_arrays(&self.expressions(), batch)
82    }
83
84    /// Evaluate the window function values against the batch
85    fn evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef>;
86
87    /// Evaluate the window function against the batch. This function facilitates
88    /// stateful, bounded-memory implementations.
89    ///
90    /// `eval_ctx` carries stream-level (cross-partition) information; see
91    /// [`WindowEvalContext`].
92    fn evaluate_stateful(
93        &self,
94        _partition_batches: &PartitionBatches,
95        _window_agg_state: &mut PartitionWindowAggStates,
96        _eval_ctx: &WindowEvalContext<'_>,
97    ) -> Result<()> {
98        internal_err!("evaluate_stateful is not implemented for {}", self.name())
99    }
100
101    /// Expressions that's from the window function's partition by clause, empty if absent
102    fn partition_by(&self) -> &[Arc<dyn PhysicalExpr>];
103
104    /// Expressions that's from the window function's order by clause, empty if absent
105    fn order_by(&self) -> &[PhysicalSortExpr];
106
107    /// Get order by columns, empty if absent
108    fn order_by_columns(&self, batch: &RecordBatch) -> Result<Vec<SortColumn>> {
109        self.order_by()
110            .iter()
111            .map(|e| e.evaluate_to_sort_column(batch))
112            .collect()
113    }
114
115    /// Get the window frame of this [WindowExpr].
116    fn get_window_frame(&self) -> &Arc<WindowFrame>;
117
118    /// Return a flag indicating whether this [WindowExpr] can run with
119    /// bounded memory.
120    fn uses_bounded_memory(&self) -> bool;
121
122    /// Get the reverse expression of this [WindowExpr].
123    fn get_reverse_expr(&self) -> Option<Arc<dyn WindowExpr>>;
124
125    /// Creates a new instance of the window function evaluator.
126    ///
127    /// Returns `WindowFn::Builtin` for built-in window functions (e.g., ROW_NUMBER, RANK)
128    /// or `WindowFn::Aggregate` for aggregate window functions (e.g., SUM, AVG).
129    fn create_window_fn(&self) -> Result<WindowFn>;
130
131    /// Returns all expressions used in the [`WindowExpr`].
132    /// These expressions are (1) function arguments, (2) partition by expressions, (3) order by expressions.
133    fn all_expressions(&self) -> WindowPhysicalExpressions {
134        let args = self.expressions();
135        let partition_by_exprs = self.partition_by().to_vec();
136        let order_by_exprs = self
137            .order_by()
138            .iter()
139            .map(|sort_expr| Arc::clone(&sort_expr.expr))
140            .collect();
141        WindowPhysicalExpressions {
142            args,
143            partition_by_exprs,
144            order_by_exprs,
145        }
146    }
147
148    /// Rewrites [`WindowExpr`], with new expressions given. The argument should be consistent
149    /// with the return value of the [`WindowExpr::all_expressions`] method.
150    /// Returns `Some(Arc<dyn WindowExpr>)` if re-write is supported, otherwise returns `None`.
151    fn with_new_expressions(
152        &self,
153        _args: Vec<Arc<dyn PhysicalExpr>>,
154        _partition_bys: Vec<Arc<dyn PhysicalExpr>>,
155        _order_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
156    ) -> Option<Arc<dyn WindowExpr>> {
157        None
158    }
159}
160
161/// Stores the physical expressions used inside the `WindowExpr`.
162pub struct WindowPhysicalExpressions {
163    /// Window function arguments
164    pub args: Vec<Arc<dyn PhysicalExpr>>,
165    /// PARTITION BY expressions
166    pub partition_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
167    /// ORDER BY expressions
168    pub order_by_exprs: Vec<Arc<dyn PhysicalExpr>>,
169}
170
171/// Extension trait that adds common functionality to [`AggregateWindowExpr`]s
172pub trait AggregateWindowExpr: WindowExpr {
173    /// Get the accumulator for the window expression. Note that distinct
174    /// window expressions may return distinct accumulators; e.g. sliding
175    /// (non-sliding) expressions will return sliding (normal) accumulators.
176    fn get_accumulator(&self) -> Result<Box<dyn Accumulator>>;
177
178    /// Optional FILTER (WHERE ...) predicate for this window aggregate.
179    fn filter_expr(&self) -> Option<&Arc<dyn PhysicalExpr>>;
180
181    /// Given current range and the last range, calculates the accumulator
182    /// result for the range of interest.
183    fn get_aggregate_result_inside_range(
184        &self,
185        last_range: &Range<usize>,
186        cur_range: &Range<usize>,
187        value_slice: &[ArrayRef],
188        accumulator: &mut Box<dyn Accumulator>,
189        filter_mask: Option<&BooleanArray>,
190    ) -> Result<ScalarValue>;
191
192    /// Indicates whether this window function always produces the same result
193    /// for all rows in the partition.
194    fn is_constant_in_partition(&self) -> bool;
195
196    /// Evaluates the window function against the batch.
197    fn aggregate_evaluate(&self, batch: &RecordBatch) -> Result<ArrayRef> {
198        let mut accumulator = self.get_accumulator()?;
199        let mut last_range = Range { start: 0, end: 0 };
200        let sort_options = self.order_by().iter().map(|o| o.options).collect();
201        let mut window_frame_ctx =
202            WindowFrameContext::new(Arc::clone(self.get_window_frame()), sort_options);
203        self.get_result_column(
204            &mut accumulator,
205            batch,
206            None,
207            &mut last_range,
208            &mut window_frame_ctx,
209            0,
210            false,
211        )
212    }
213
214    /// Statefully evaluates the window function against the batch. Maintains
215    /// state so that it can work incrementally over multiple chunks.
216    fn aggregate_evaluate_stateful(
217        &self,
218        partition_batches: &PartitionBatches,
219        window_agg_state: &mut PartitionWindowAggStates,
220        eval_ctx: &WindowEvalContext<'_>,
221    ) -> Result<()> {
222        let field = self.field()?;
223        let out_type = field.data_type();
224        // Every partition consults the same most recent input row, so its
225        // ORDER BY values can be evaluated once, outside the per-partition
226        // loop.
227        let most_recent_row_order_bys = eval_ctx
228            .most_recent_row
229            .map(|batch| self.order_by_columns(batch))
230            .transpose()?
231            .map(get_orderby_values);
232        for (partition_row, partition_batch_state) in partition_batches.iter() {
233            if !window_agg_state.contains_key(partition_row) {
234                let accumulator = self.get_accumulator()?;
235                window_agg_state.insert(
236                    partition_row.clone(),
237                    WindowState {
238                        state: WindowAggState::new(out_type)?,
239                        window_fn: WindowFn::Aggregate(accumulator),
240                        published: false,
241                    },
242                );
243            }
244            let window_state = window_agg_state
245                .get_mut(partition_row)
246                .ok_or_else(|| exec_datafusion_err!("Cannot find state"))?;
247            let WindowFn::Aggregate(accumulator) = &mut window_state.window_fn else {
248                unreachable!()
249            };
250            let state = &mut window_state.state;
251            let record_batch = &partition_batch_state.record_batch;
252
253            // Skip partitions that cannot produce anything new until they
254            // either receive rows or reach their end.
255            if state.is_up_to_date_with(partition_batch_state) {
256                continue;
257            }
258
259            // If there is no window state context, initialize it.
260            let window_frame_ctx = state.window_frame_ctx.get_or_insert_with(|| {
261                let sort_options = self.order_by().iter().map(|o| o.options).collect();
262                WindowFrameContext::new(Arc::clone(self.get_window_frame()), sort_options)
263            });
264            let out_col = self.get_result_column(
265                accumulator,
266                record_batch,
267                most_recent_row_order_bys.as_deref(),
268                // Start search from the last range
269                &mut state.window_frame_range,
270                window_frame_ctx,
271                state.last_calculated_index,
272                !partition_batch_state.is_end,
273            )?;
274            state.update(&out_col, partition_batch_state)?;
275        }
276        Ok(())
277    }
278
279    /// Calculates the window expression result for the given record batch.
280    /// Assumes that `record_batch` belongs to a single partition.
281    ///
282    /// # Arguments
283    /// * `accumulator`: The accumulator to use for the calculation.
284    /// * `record_batch`: batch belonging to the current partition (see [`PartitionBatchState`]).
285    /// * `most_recent_row_order_bys`: ORDER BY values of the most recent input
286    ///   row, if available (see [`WindowExpr::evaluate_stateful`]).
287    /// * `last_range`: The last range of rows that were processed (see [`WindowAggState`]).
288    /// * `window_frame_ctx`: Details about the window frame (see [`WindowFrameContext`]).
289    /// * `idx`: The index of the current row in the record batch.
290    /// * `not_end`: is the current row not the end of the partition (see [`PartitionBatchState`]).
291    #[expect(clippy::too_many_arguments)]
292    fn get_result_column(
293        &self,
294        accumulator: &mut Box<dyn Accumulator>,
295        record_batch: &RecordBatch,
296        most_recent_row_order_bys: Option<&[ArrayRef]>,
297        last_range: &mut Range<usize>,
298        window_frame_ctx: &mut WindowFrameContext,
299        mut idx: usize,
300        not_end: bool,
301    ) -> Result<ArrayRef> {
302        let values = self.evaluate_args(record_batch)?;
303
304        // Evaluate filter mask once per record batch if present
305        let filter_mask_arr: Option<ArrayRef> = match self.filter_expr() {
306            Some(expr) => {
307                let value = expr.evaluate(record_batch)?;
308                Some(value.into_array(record_batch.num_rows())?)
309            }
310            None => None,
311        };
312
313        // Borrow boolean view from the owned array
314        let filter_mask: Option<&BooleanArray> = match filter_mask_arr.as_deref() {
315            Some(arr) => Some(as_boolean_array(arr)?),
316            None => None,
317        };
318
319        if self.is_constant_in_partition() {
320            if not_end {
321                let field = self.field()?;
322                let out_type = field.data_type();
323                return Ok(new_empty_array(out_type));
324            }
325            let values = if let Some(mask) = filter_mask {
326                // Apply mask to all argument arrays before a single update
327                filter_arrays(&values, mask)?
328            } else {
329                values
330            };
331            accumulator.update_batch(&values)?;
332            let value = accumulator.evaluate()?;
333            return value.to_array_of_size(record_batch.num_rows());
334        }
335        let order_bys = get_orderby_values(self.order_by_columns(record_batch)?);
336
337        // We iterate on each row to perform a running calculation.
338        let length = values[0].len();
339        let mut row_wise_results: Vec<ScalarValue> =
340            Vec::with_capacity(length.saturating_sub(idx));
341        let is_causal = self.get_window_frame().is_causal();
342        // These ordering arrays do not change during this evaluation. Compare
343        // their last/most-recent rows lazily once, since comparator setup can
344        // scan entire dictionary arrays to compute logical nulls.
345        let mut row_ahead = None;
346        while idx < length {
347            // Start search from the last_range. This squeezes searched range.
348            let cur_range =
349                window_frame_ctx.calculate_range(&order_bys, last_range, length, idx)?;
350            // Exit if the range is non-causal and extends all the way:
351            if cur_range.end == length
352                && !is_causal
353                && not_end
354                && !is_end_bound_safe(
355                    window_frame_ctx,
356                    &order_bys,
357                    most_recent_row_order_bys,
358                    self.order_by(),
359                    idx,
360                    &mut row_ahead,
361                )?
362            {
363                break;
364            }
365            let value = self.get_aggregate_result_inside_range(
366                last_range,
367                &cur_range,
368                &values,
369                accumulator,
370                filter_mask,
371            )?;
372            // Update last range
373            *last_range = cur_range;
374            row_wise_results.push(value);
375            idx += 1;
376        }
377
378        if row_wise_results.is_empty() {
379            let field = self.field()?;
380            let out_type = field.data_type();
381            Ok(new_empty_array(out_type))
382        } else {
383            ScalarValue::iter_to_array(row_wise_results)
384        }
385    }
386}
387
388/// Filters a single array with the provided boolean mask.
389pub(crate) fn filter_array(array: &ArrayRef, mask: &BooleanArray) -> Result<ArrayRef> {
390    arrow_filter(array.as_ref(), mask)
391        .map(|a| a as ArrayRef)
392        .map_err(|e| arrow_datafusion_err!(e))
393}
394
395/// Filters a list of arrays with the provided boolean mask.
396pub(crate) fn filter_arrays(
397    arrays: &[ArrayRef],
398    mask: &BooleanArray,
399) -> Result<Vec<ArrayRef>> {
400    arrays.iter().map(|arr| filter_array(arr, mask)).collect()
401}
402
403/// Determines whether the end bound calculation for a window frame context is
404/// safe, meaning that the end bound stays the same, regardless of future data,
405/// based on the current sort expressions and ORDER BY columns. This function
406/// delegates work to specific functions for each frame type.
407///
408/// # Parameters
409///
410/// * `window_frame_ctx`: The context of the window frame being evaluated.
411/// * `order_bys`: A slice of `ArrayRef` representing the ORDER BY columns.
412/// * `most_recent_order_bys`: An optional reference to the most recent ORDER BY
413///   columns.
414/// * `sort_exprs`: Defines the lexicographical ordering in question.
415/// * `idx`: The current index in the window frame.
416/// * `row_ahead`: The last/most-recent row comparison, reused within one evaluation.
417///
418/// # Returns
419///
420/// A `Result` which is `Ok(true)` if the end bound is safe, `Ok(false)` otherwise.
421pub(crate) fn is_end_bound_safe(
422    window_frame_ctx: &WindowFrameContext,
423    order_bys: &[ArrayRef],
424    most_recent_order_bys: Option<&[ArrayRef]>,
425    sort_exprs: &[PhysicalSortExpr],
426    idx: usize,
427    row_ahead: &mut Option<bool>,
428) -> Result<bool> {
429    if sort_exprs.is_empty() {
430        // Early return if no sort expressions are present:
431        return Ok(false);
432    }
433
434    match window_frame_ctx {
435        WindowFrameContext::Rows(window_frame) => {
436            is_end_bound_safe_for_rows(&window_frame.end_bound)
437        }
438        WindowFrameContext::Range { window_frame, .. } => is_end_bound_safe_for_range(
439            &window_frame.end_bound,
440            &order_bys[0],
441            most_recent_order_bys.map(|items| &items[0]),
442            &sort_exprs[0].options,
443            idx,
444            row_ahead,
445        ),
446        WindowFrameContext::Groups {
447            window_frame,
448            state,
449        } => is_end_bound_safe_for_groups(
450            &window_frame.end_bound,
451            state,
452            &order_bys[0],
453            most_recent_order_bys.map(|items| &items[0]),
454            &sort_exprs[0].options,
455            row_ahead,
456        ),
457    }
458}
459
460/// For row-based window frames, determines whether the end bound calculation
461/// is safe, which is trivially the case for `Preceding` and `CurrentRow` bounds.
462/// For 'Following' bounds, it compares the bound value to zero to ensure that
463/// it doesn't extend beyond the current row.
464///
465/// # Parameters
466///
467/// * `end_bound`: Reference to the window frame bound in question.
468///
469/// # Returns
470///
471/// A `Result` indicating whether the end bound is safe for row-based window frames.
472fn is_end_bound_safe_for_rows(end_bound: &WindowFrameBound) -> Result<bool> {
473    if let WindowFrameBound::Following(value) = end_bound {
474        let zero = ScalarValue::new_zero(&value.data_type());
475        Ok(zero.map(|zero| value.eq(&zero)).unwrap_or(false))
476    } else {
477        Ok(true)
478    }
479}
480
481/// For row-based window frames, determines whether the end bound calculation
482/// is safe by comparing it against specific values (zero, current row). It uses
483/// the `is_row_ahead` helper function to determine if the current row is ahead
484/// of the most recent row based on the ORDER BY column and sorting options.
485///
486/// # Parameters
487///
488/// * `end_bound`: Reference to the window frame bound in question.
489/// * `orderby_col`: Reference to the column used for ordering.
490/// * `most_recent_ob_col`: Optional reference to the most recent order-by column.
491/// * `sort_options`: The sorting options used in the window frame.
492/// * `idx`: The current index in the window frame.
493///
494/// # Returns
495///
496/// A `Result` indicating whether the end bound is safe for range-based window frames.
497fn is_end_bound_safe_for_range(
498    end_bound: &WindowFrameBound,
499    orderby_col: &ArrayRef,
500    most_recent_ob_col: Option<&ArrayRef>,
501    sort_options: &SortOptions,
502    idx: usize,
503    row_ahead: &mut Option<bool>,
504) -> Result<bool> {
505    match end_bound {
506        // A frame ending in `N PRECEDING` can only reach the end of the buffer
507        // when the current row's frame ends at its last peer, as for a NULL or
508        // NaN ORDER BY value, so it is safe once a row past its peers arrives.
509        WindowFrameBound::Preceding(_) | WindowFrameBound::CurrentRow => {
510            is_row_ahead(orderby_col, most_recent_ob_col, sort_options, row_ahead)
511        }
512        WindowFrameBound::Following(delta) => {
513            let Some(most_recent_ob_col) = most_recent_ob_col else {
514                return Ok(false);
515            };
516            let most_recent_row_value =
517                ScalarValue::try_from_array(most_recent_ob_col, 0)?;
518            let current_row_value = ScalarValue::try_from_array(orderby_col, idx)?;
519
520            if sort_options.descending {
521                current_row_value
522                    .sub(delta)
523                    .map(|value| value > most_recent_row_value)
524            } else {
525                current_row_value
526                    .add(delta)
527                    .map(|value| most_recent_row_value > value)
528            }
529        }
530    }
531}
532
533/// For group-based window frames, determines whether the end bound calculation
534/// is safe by considering the group offset and whether the current row is ahead
535/// of the most recent row in terms of sorting. It checks if the end bound is
536/// within the bounds of the current group based on group end indices.
537///
538/// # Parameters
539///
540/// * `end_bound`: Reference to the window frame bound in question.
541/// * `state`: The state of the window frame for group calculations.
542/// * `orderby_col`: Reference to the column used for ordering.
543/// * `most_recent_ob_col`: Optional reference to the most recent order-by column.
544/// * `sort_options`: The sorting options used in the window frame.
545///
546/// # Returns
547///
548/// A `Result` indicating whether the end bound is safe for group-based window frames.
549fn is_end_bound_safe_for_groups(
550    end_bound: &WindowFrameBound,
551    state: &WindowFrameStateGroups,
552    orderby_col: &ArrayRef,
553    most_recent_ob_col: Option<&ArrayRef>,
554    sort_options: &SortOptions,
555    row_ahead: &mut Option<bool>,
556) -> Result<bool> {
557    match end_bound {
558        WindowFrameBound::Preceding(value) => {
559            let zero = ScalarValue::new_zero(&value.data_type())?;
560            if value.eq(&zero) {
561                is_row_ahead(orderby_col, most_recent_ob_col, sort_options, row_ahead)
562            } else {
563                Ok(true)
564            }
565        }
566        WindowFrameBound::CurrentRow => {
567            is_row_ahead(orderby_col, most_recent_ob_col, sort_options, row_ahead)
568        }
569        WindowFrameBound::Following(ScalarValue::UInt64(Some(offset))) => {
570            let delta = state.group_end_indices.len() - state.current_group_idx;
571            if delta == (*offset as usize) + 1 {
572                is_row_ahead(orderby_col, most_recent_ob_col, sort_options, row_ahead)
573            } else {
574                Ok(false)
575            }
576        }
577        _ => Ok(false),
578    }
579}
580
581/// Checks whether the most recent input row is ahead of the partition's last row.
582/// Both arrays stay unchanged during one evaluation, so reuse the comparison.
583fn is_row_ahead(
584    old_col: &ArrayRef,
585    current_col: Option<&ArrayRef>,
586    sort_options: &SortOptions,
587    row_ahead: &mut Option<bool>,
588) -> Result<bool> {
589    if let Some(ahead) = *row_ahead {
590        return Ok(ahead);
591    }
592    let Some(current_col) = current_col else {
593        return Ok(false);
594    };
595    if old_col.is_empty() || current_col.is_empty() {
596        return Ok(false);
597    }
598    let cmp = make_comparator(old_col.as_ref(), current_col.as_ref(), *sort_options)?;
599    let ahead = cmp(old_col.len() - 1, 0).is_lt();
600    *row_ahead = Some(ahead);
601    Ok(ahead)
602}
603
604/// Get order by expression results inside `order_by_columns`.
605pub(crate) fn get_orderby_values(order_by_columns: Vec<SortColumn>) -> Vec<ArrayRef> {
606    order_by_columns.into_iter().map(|s| s.values).collect()
607}
608
609/// State for incrementally evaluating a window function
610/// within a partition, created by [`WindowExpr::create_window_fn`].
611#[derive(Debug)]
612pub enum WindowFn {
613    /// A "normal" window function, such as `lead` or `lag`, evaluated via a
614    /// [`PartitionEvaluator`]. Despite the name, it is used for all window
615    /// functions that are not aggregate functions.
616    Builtin(Box<dyn PartitionEvaluator>),
617    /// An aggregate function used as a window function, such as `avg` or
618    /// `sum`, which is evaluated via an [`Accumulator`].
619    Aggregate(Box<dyn Accumulator>),
620}
621
622/// Key for IndexMap for each unique partition
623///
624/// For instance, if window frame is `OVER(PARTITION BY a,b)`,
625/// PartitionKey would consist of unique `[a,b]` pairs
626pub type PartitionKey = Vec<ScalarValue>;
627
628/// Stream-level context passed to [`WindowExpr::evaluate_stateful`].
629///
630/// This carries information that spans all partitions of the input, as
631/// opposed to the per-partition state in [`PartitionBatches`] and
632/// [`PartitionWindowAggStates`]. It is `non_exhaustive` so that fields can
633/// be added without breaking implementors; construct it with
634/// [`Default::default`] and the `with_*` builder methods.
635#[derive(Debug, Clone, Copy, Default)]
636#[non_exhaustive]
637pub struct WindowEvalContext<'a> {
638    /// A single-row batch containing the most recent input row, whichever
639    /// partition that row belongs to. It is `Some` only when the input is
640    /// ordered by the first ORDER BY column across partitions (`Linear`
641    /// mode), in which case no future input row -- in any partition -- can
642    /// precede it in that column; implementations can use this bound to
643    /// decide whether pending window frames can be finalized before their
644    /// partition receives more data.
645    pub most_recent_row: Option<&'a RecordBatch>,
646}
647
648impl<'a> WindowEvalContext<'a> {
649    /// Sets the most recent input row (see [`Self::most_recent_row`]).
650    pub fn with_most_recent_row(mut self, batch: Option<&'a RecordBatch>) -> Self {
651        self.most_recent_row = batch;
652        self
653    }
654}
655
656#[derive(Debug)]
657pub struct WindowState {
658    pub state: WindowAggState,
659    pub window_fn: WindowFn,
660    /// True once [`Self::aggregate_state`] has been called on this entry.
661    /// Guards against a second destructive [`Accumulator::state`] read: the
662    /// method itself errors on second call, and the observer loop in
663    /// `BoundedWindowAggStream::publish_finalized_states` uses this as an
664    /// early-skip so it doesn't attempt one. Independent of `state.is_end`,
665    /// which is a group-closed signal that the pruning path also reads.
666    pub published: bool,
667}
668
669impl WindowState {
670    /// [`Accumulator::state`] if this window function is an aggregate, `None`
671    /// otherwise (built-in functions like `row_number`, `rank`, `lead`/`lag`
672    /// have no serializable accumulator state).
673    ///
674    /// [`Accumulator::state`] takes `&mut self` and its trait doc calls out
675    /// that "this function should not be called twice, otherwise it will
676    /// result in potentially non-deterministic behavior." Several built-in
677    /// impls (`median`, `percentile_cont`, `string_agg`,
678    /// `min_max_bytes`/`min_max_struct`) `std::mem::take` their internal
679    /// buffers on call — a second call returns *empty* state, not the same
680    /// state, so a downstream prefix-merge would silently lose every value
681    /// the accumulator had ingested.
682    ///
683    /// Enforced at this layer: on first call we set [`Self::published`] and
684    /// return the state; any later call errors rather than performing a
685    /// destructive re-read.
686    pub fn aggregate_state(&mut self) -> Result<Option<Vec<ScalarValue>>> {
687        if self.published {
688            return exec_err!(
689                "WindowState::aggregate_state called more than once; \
690                 Accumulator::state is a destructive read for several \
691                 built-in aggregates and a second call would silently lose data"
692            );
693        }
694        let state = match &mut self.window_fn {
695            WindowFn::Aggregate(accumulator) => Some(accumulator.state()?),
696            WindowFn::Builtin(_) => None,
697        };
698        self.published = true;
699        Ok(state)
700    }
701}
702
703pub type PartitionWindowAggStates = IndexMap<PartitionKey, WindowState, RandomState>;
704
705/// The IndexMap (i.e. an ordered HashMap) where record batches are separated for each partition.
706pub type PartitionBatches = IndexMap<PartitionKey, PartitionBatchState, RandomState>;
707
708#[cfg(test)]
709mod tests {
710    use std::sync::Arc;
711
712    use crate::window::window_expr::{WindowFn, WindowState, is_row_ahead};
713
714    use arrow::array::{ArrayRef, Float64Array};
715    use arrow::compute::SortOptions;
716    use arrow::datatypes::DataType;
717    use datafusion_common::{Result, ScalarValue};
718    use datafusion_expr::{Accumulator, window_state::WindowAggState};
719
720    /// Minimal [`Accumulator`] whose `state()` records how many times it was
721    /// called by returning the count as its single state element. Any second
722    /// call would surface (were it allowed to happen) as `[UInt64(2)]`
723    /// instead of `[UInt64(1)]`.
724    #[derive(Debug)]
725    struct CallCountingAccumulator {
726        calls: usize,
727    }
728
729    impl Accumulator for CallCountingAccumulator {
730        fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
731            Ok(())
732        }
733        fn evaluate(&mut self) -> Result<ScalarValue> {
734            Ok(ScalarValue::Null)
735        }
736        fn size(&self) -> usize {
737            size_of::<Self>()
738        }
739        fn state(&mut self) -> Result<Vec<ScalarValue>> {
740            self.calls += 1;
741            Ok(vec![ScalarValue::UInt64(Some(self.calls as u64))])
742        }
743        fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
744            Ok(())
745        }
746    }
747
748    #[test]
749    fn aggregate_state_errors_on_second_call() -> Result<()> {
750        // `Accumulator::state()` is a destructive read for several built-in
751        // aggregates (median, percentile_cont, string_agg, min_max_bytes/
752        // min_max_struct all `mem::take` their internal buffers). Its trait
753        // doc says "should not be called twice"; `WindowState::aggregate_state`
754        // enforces that at this layer by returning an error rather than
755        // performing the second read.
756        let acc: Box<dyn Accumulator> = Box::new(CallCountingAccumulator { calls: 0 });
757        let mut ws = WindowState {
758            state: WindowAggState::new(&DataType::UInt64)?,
759            window_fn: WindowFn::Aggregate(acc),
760            published: false,
761        };
762        let first = ws.aggregate_state()?;
763        assert_eq!(first, Some(vec![ScalarValue::UInt64(Some(1))]));
764        assert!(ws.published, "published must flip on successful publish");
765        let err = ws.aggregate_state().unwrap_err().to_string();
766        assert!(
767            err.contains("called more than once"),
768            "expected second-call error, got: {err}"
769        );
770        Ok(())
771    }
772
773    #[test]
774    fn test_is_row_ahead() -> Result<()> {
775        let old_values: ArrayRef =
776            Arc::new(Float64Array::from(vec![5.0, 7.0, 8.0, 9., 10.]));
777
778        let new_values1: ArrayRef = Arc::new(Float64Array::from(vec![11.0]));
779        let new_values2: ArrayRef = Arc::new(Float64Array::from(vec![10.0]));
780
781        assert!(is_row_ahead(
782            &old_values,
783            Some(&new_values1),
784            &SortOptions {
785                descending: false,
786                nulls_first: false
787            },
788            &mut None,
789        )?);
790        assert!(!is_row_ahead(
791            &old_values,
792            Some(&new_values2),
793            &SortOptions {
794                descending: false,
795                nulls_first: false
796            },
797            &mut None,
798        )?);
799
800        Ok(())
801    }
802}