Skip to main content

datafusion_expr/
window_state.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//! Structures used to hold window function state (for implementing WindowUDFs)
6
7use std::{collections::VecDeque, ops::Range, sync::Arc};
8
9use crate::{WindowFrame, WindowFrameBound, WindowFrameUnits};
10
11use arrow::compute::kernels::sort::{LexicographicalComparator, SortColumn};
12use arrow::{
13    array::ArrayRef,
14    compute::{SortOptions, concat, concat_batches},
15    datatypes::{DataType, SchemaRef},
16    record_batch::RecordBatch,
17};
18use datafusion_common::{
19    Result, ScalarValue, internal_datafusion_err, internal_err,
20    utils::{compare_rows, get_row_at_idx, search_in_slice},
21};
22
23/// Holds the state of evaluating a window function
24#[derive(Debug, Clone)]
25pub struct WindowAggState {
26    /// The range that we calculate the window function
27    pub window_frame_range: Range<usize>,
28    pub window_frame_ctx: Option<WindowFrameContext>,
29    /// The index of the first row in the partition's buffered record batch
30    /// whose result has not been calculated yet; equivalently, the number
31    /// of buffered rows with calculated results. The next evaluation pass
32    /// resumes from this index.
33    pub last_calculated_index: usize,
34    /// The offset of the deleted row number
35    pub offset_pruned_rows: usize,
36    /// Stores the results calculated by window frame
37    pub out_col: ArrayRef,
38    /// Keeps track of how many rows should be generated to be in sync with input record_batch
39    // (For each row in the input record batch we need to generate a window result).
40    pub n_row_result_missing: usize,
41    /// Snapshot of [`PartitionBatchState::n_rows_received`] as of this
42    /// partition's last evaluation pass
43    pub n_rows_received: usize,
44    /// Snapshot of [`PartitionBatchState::is_end`] as of this partition's
45    /// last evaluation pass
46    pub is_end: bool,
47}
48
49impl WindowAggState {
50    pub fn prune_state(&mut self, n_prune: usize) {
51        self.window_frame_range = Range {
52            start: self.window_frame_range.start - n_prune,
53            end: self.window_frame_range.end - n_prune,
54        };
55        self.last_calculated_index -= n_prune;
56        self.offset_pruned_rows += n_prune;
57
58        match self.window_frame_ctx.as_mut() {
59            // Rows have no state do nothing
60            Some(WindowFrameContext::Rows(_)) => {}
61            Some(WindowFrameContext::Range { state, .. }) => {
62                // Release the old ORDER BY arrays early. Replacement arrays would
63                // also invalidate the cache by identity when it is next used.
64                state.peer_comparator = None;
65            }
66            Some(WindowFrameContext::Groups { state, .. }) => {
67                let mut n_group_to_del = 0;
68                for (_, end_idx) in &state.group_end_indices {
69                    if n_prune < *end_idx {
70                        break;
71                    }
72                    n_group_to_del += 1;
73                }
74                state.group_end_indices.drain(0..n_group_to_del);
75                state
76                    .group_end_indices
77                    .iter_mut()
78                    .for_each(|(_, start_idx)| *start_idx -= n_prune);
79                state.current_group_idx -= n_group_to_del;
80            }
81            None => {}
82        }
83    }
84
85    pub fn update(
86        &mut self,
87        out_col: &ArrayRef,
88        partition_batch_state: &PartitionBatchState,
89    ) -> Result<()> {
90        self.last_calculated_index += out_col.len();
91        // no need to use concat if the current `out_col` is empty
92        if self.out_col.is_empty() {
93            self.out_col = Arc::clone(out_col);
94        } else {
95            self.out_col = concat(&[&self.out_col, &out_col])?;
96        }
97        self.n_row_result_missing =
98            partition_batch_state.record_batch.num_rows() - self.last_calculated_index;
99        self.n_rows_received = partition_batch_state.n_rows_received;
100        self.is_end = partition_batch_state.is_end;
101        Ok(())
102    }
103
104    /// Returns true when this state is fully up to date with the partition's
105    /// buffered batch, meaning another evaluation pass over the partition could
106    /// not produce any new results or change any state:
107    ///
108    /// - `last_calculated_index` has reached the end of the partition's
109    ///   buffered batch, so every row of this partition that has arrived so
110    ///   far already has a result.
111    /// - When a partition ends, a final evaluation pass is needed to bring
112    ///   derived state up to date.
113    #[inline]
114    pub fn is_up_to_date_with(
115        &self,
116        partition_batch_state: &PartitionBatchState,
117    ) -> bool {
118        let all_rows_have_results =
119            self.last_calculated_index == partition_batch_state.record_batch.num_rows();
120        if all_rows_have_results {
121            debug_assert_eq!(self.n_row_result_missing, 0);
122        }
123
124        // `self.is_end` holds the flag as of the previous evaluation pass.
125        let partition_just_ended = !self.is_end && partition_batch_state.is_end;
126        all_rows_have_results && !partition_just_ended
127    }
128
129    /// Returns true when the partition's input is unchanged since the last
130    /// evaluation pass: no new rows have arrived and the end flag has not
131    /// changed.
132    ///
133    /// Standard (non-aggregate) window functions read nothing outside their
134    /// partition, so we can skip re-evaluating them when their input hasn't
135    /// changed. Aggregate window functions cannot use this test to skip
136    /// evaluation, because they also consult the ORDER BY values of the most
137    /// recent input row across *all* partitions.
138    #[inline]
139    pub fn is_input_unchanged(
140        &self,
141        partition_batch_state: &PartitionBatchState,
142    ) -> bool {
143        self.n_rows_received == partition_batch_state.n_rows_received
144            && self.is_end == partition_batch_state.is_end
145    }
146
147    pub fn new(out_type: &DataType) -> Result<Self> {
148        let empty_out_col = ScalarValue::try_from(out_type)?.to_array_of_size(0)?;
149        Ok(Self {
150            window_frame_range: Range { start: 0, end: 0 },
151            window_frame_ctx: None,
152            last_calculated_index: 0,
153            offset_pruned_rows: 0,
154            out_col: empty_out_col,
155            n_row_result_missing: 0,
156            n_rows_received: 0,
157            is_end: false,
158        })
159    }
160}
161
162/// This object stores the window frame state for use in incremental calculations.
163#[derive(Debug, Clone)]
164pub enum WindowFrameContext {
165    /// ROWS frames are inherently stateless.
166    Rows(Arc<WindowFrame>),
167    /// RANGE frames are stateful, they store indices specifying where the
168    /// previous search left off. This amortizes the overall cost to O(n)
169    /// where n denotes the row count.
170    Range {
171        window_frame: Arc<WindowFrame>,
172        state: WindowFrameStateRange,
173    },
174    /// GROUPS frames are stateful, they store group boundaries and indices
175    /// specifying where the previous search left off. This amortizes the
176    /// overall cost to O(n) where n denotes the row count.
177    Groups {
178        window_frame: Arc<WindowFrame>,
179        state: WindowFrameStateGroups,
180    },
181}
182
183impl WindowFrameContext {
184    /// Create a new state object for the given window frame.
185    pub fn new(window_frame: Arc<WindowFrame>, sort_options: Vec<SortOptions>) -> Self {
186        match window_frame.units {
187            WindowFrameUnits::Rows => WindowFrameContext::Rows(window_frame),
188            WindowFrameUnits::Range => WindowFrameContext::Range {
189                window_frame,
190                state: WindowFrameStateRange::new(sort_options),
191            },
192            WindowFrameUnits::Groups => WindowFrameContext::Groups {
193                window_frame,
194                state: WindowFrameStateGroups::default(),
195            },
196        }
197    }
198
199    /// This function calculates beginning/ending indices for the frame of the current row.
200    pub fn calculate_range(
201        &mut self,
202        range_columns: &[ArrayRef],
203        last_range: &Range<usize>,
204        length: usize,
205        idx: usize,
206    ) -> Result<Range<usize>> {
207        match self {
208            WindowFrameContext::Rows(window_frame) => {
209                Self::calculate_range_rows(window_frame, length, idx)
210            }
211            // Sort options is used in RANGE mode calculations because the
212            // ordering or position of NULLs impact range calculations and
213            // comparison of rows.
214            WindowFrameContext::Range {
215                window_frame,
216                state,
217            } => state.calculate_range(
218                window_frame,
219                last_range,
220                range_columns,
221                length,
222                idx,
223            ),
224            // Sort options is not used in GROUPS mode calculations as the
225            // inequality of two rows indicates a group change, and ordering
226            // or position of NULLs do not impact inequality.
227            WindowFrameContext::Groups {
228                window_frame,
229                state,
230            } => state.calculate_range(window_frame, range_columns, length, idx),
231        }
232    }
233
234    /// This function calculates beginning/ending indices for the frame of the current row.
235    fn calculate_range_rows(
236        window_frame: &Arc<WindowFrame>,
237        length: usize,
238        idx: usize,
239    ) -> Result<Range<usize>> {
240        let start = match window_frame.start_bound {
241            // UNBOUNDED PRECEDING
242            WindowFrameBound::Preceding(ScalarValue::UInt64(None)) => 0,
243            WindowFrameBound::Preceding(ScalarValue::UInt64(Some(n))) => {
244                idx.saturating_sub(n as usize)
245            }
246            WindowFrameBound::CurrentRow => idx,
247            // UNBOUNDED FOLLOWING
248            WindowFrameBound::Following(ScalarValue::UInt64(None)) => {
249                return internal_err!(
250                    "Frame start cannot be UNBOUNDED FOLLOWING '{window_frame:?}'"
251                );
252            }
253            // `n` comes from the query and can be as large as `u64::MAX`
254            WindowFrameBound::Following(ScalarValue::UInt64(Some(n))) => {
255                std::cmp::min(idx.saturating_add(n as usize), length)
256            }
257            // ERRONEOUS FRAMES
258            WindowFrameBound::Preceding(_) | WindowFrameBound::Following(_) => {
259                return internal_err!("Rows should be UInt64");
260            }
261        };
262        let end = match window_frame.end_bound {
263            // UNBOUNDED PRECEDING
264            WindowFrameBound::Preceding(ScalarValue::UInt64(None)) => {
265                return internal_err!(
266                    "Frame end cannot be UNBOUNDED PRECEDING '{window_frame:?}'"
267                );
268            }
269            WindowFrameBound::Preceding(ScalarValue::UInt64(Some(n))) => {
270                if idx >= n as usize {
271                    idx - n as usize + 1
272                } else {
273                    0
274                }
275            }
276            WindowFrameBound::CurrentRow => idx + 1,
277            // UNBOUNDED FOLLOWING
278            WindowFrameBound::Following(ScalarValue::UInt64(None)) => length,
279            WindowFrameBound::Following(ScalarValue::UInt64(Some(n))) => {
280                std::cmp::min(idx.saturating_add(n as usize).saturating_add(1), length)
281            }
282            // ERRONEOUS FRAMES
283            WindowFrameBound::Preceding(_) | WindowFrameBound::Following(_) => {
284                return internal_err!("Rows should be UInt64");
285            }
286        };
287        Ok(Range { start, end })
288    }
289}
290
291/// State for each unique partition determined according to PARTITION BY column(s)
292#[derive(Debug, Clone, PartialEq)]
293pub struct PartitionBatchState {
294    /// The record batch belonging to current partition
295    pub record_batch: RecordBatch,
296    /// Total number of rows this partition has ever received
297    pub n_rows_received: usize,
298    /// Flag indicating whether we have received all data for this partition
299    pub is_end: bool,
300    /// Number of rows emitted for this partition since the last pruning pass
301    pub n_out_row: usize,
302}
303
304impl PartitionBatchState {
305    pub fn new(schema: SchemaRef) -> Self {
306        Self {
307            record_batch: RecordBatch::new_empty(schema),
308            n_rows_received: 0,
309            is_end: false,
310            n_out_row: 0,
311        }
312    }
313
314    pub fn new_with_batch(batch: RecordBatch) -> Self {
315        let n_rows_received = batch.num_rows();
316        Self {
317            record_batch: batch,
318            n_rows_received,
319            is_end: false,
320            n_out_row: 0,
321        }
322    }
323
324    pub fn extend(&mut self, batch: &RecordBatch) -> Result<()> {
325        self.record_batch =
326            concat_batches(&self.record_batch.schema(), [&self.record_batch, batch])?;
327        self.n_rows_received += batch.num_rows();
328        Ok(())
329    }
330}
331
332/// This structure encapsulates all the state information we require as we scan
333/// ranges of data while processing RANGE frames.
334/// Attribute `sort_options` stores the column ordering specified by the ORDER
335/// BY clause. This information is used to calculate the range.
336#[derive(Debug, Default)]
337pub struct WindowFrameStateRange {
338    sort_options: Vec<SortOptions>,
339    peer_comparator: Option<RangePeerComparator>,
340}
341
342/// Reuse comparators to avoid per-row setup work, including logical-null masks
343/// that can take O(n) to build for dictionary arrays.
344struct RangePeerComparator {
345    columns: Vec<ArrayRef>,
346    comparator: LexicographicalComparator,
347}
348
349impl RangePeerComparator {
350    fn matches_columns(&self, columns: &[ArrayRef]) -> bool {
351        // Sliced arrays have different row indices even when they share buffers.
352        self.columns.len() == columns.len()
353            && self
354                .columns
355                .iter()
356                .zip(columns)
357                .all(|(old, new)| Arc::ptr_eq(old, new))
358    }
359}
360
361impl Clone for WindowFrameStateRange {
362    fn clone(&self) -> Self {
363        // A clone builds its own comparator when it first sees nested keys.
364        Self::new(self.sort_options.clone())
365    }
366}
367
368// Preserve the public WindowFrameStateRange type's existing unwind-safety traits.
369// The cached Arrow arrays and comparison closures are immutable, so a comparison
370// that unwinds cannot leave this cache partially updated.
371impl std::panic::UnwindSafe for RangePeerComparator {}
372impl std::panic::RefUnwindSafe for RangePeerComparator {}
373
374impl std::fmt::Debug for RangePeerComparator {
375    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
376        f.debug_struct("RangePeerComparator")
377            .field("num_columns", &self.columns.len())
378            .finish_non_exhaustive()
379    }
380}
381
382impl WindowFrameStateRange {
383    /// Create a new object to store the search state.
384    fn new(sort_options: Vec<SortOptions>) -> Self {
385        Self {
386            sort_options,
387            peer_comparator: None,
388        }
389    }
390
391    fn peer_boundary<const START: bool>(
392        &mut self,
393        range_columns: &[ArrayRef],
394        idx: usize,
395        mut boundary: usize,
396        length: usize,
397    ) -> Result<usize> {
398        let cached = match &self.peer_comparator {
399            Some(cached) if cached.matches_columns(range_columns) => cached,
400            _ => {
401                let sort_columns = range_columns
402                    .iter()
403                    .zip(&self.sort_options)
404                    .map(|(values, options)| SortColumn {
405                        values: Arc::clone(values),
406                        options: Some(*options),
407                    })
408                    .collect::<Vec<_>>();
409                self.peer_comparator.insert(RangePeerComparator {
410                    columns: range_columns.to_vec(),
411                    comparator: LexicographicalComparator::try_new(&sort_columns)?,
412                })
413            }
414        };
415        // ScalarValue equality can distinguish encodings of the same nested value:
416        // a list with a null dictionary key and one with a key referencing null.
417        while boundary < length {
418            let is_peer = cached.comparator.compare(boundary, idx).is_eq();
419            if is_peer == START {
420                break;
421            }
422            boundary += 1;
423        }
424        Ok(boundary)
425    }
426
427    /// This function calculates beginning/ending indices for the frame of the current row.
428    // Argument `last_range` stores the resulting indices from the previous search. Since the indices only
429    // advance forward, we start from `last_range` subsequently. Thus, the overall
430    // time complexity of linear search amortizes to O(n) where n denotes the total
431    // row count.
432    fn calculate_range(
433        &mut self,
434        window_frame: &Arc<WindowFrame>,
435        last_range: &Range<usize>,
436        range_columns: &[ArrayRef],
437        length: usize,
438        idx: usize,
439    ) -> Result<Range<usize>> {
440        let has_current_row = window_frame.start_bound == WindowFrameBound::CurrentRow
441            || window_frame.end_bound == WindowFrameBound::CurrentRow;
442        let nested_current_row = has_current_row
443            && range_columns
444                .iter()
445                .any(|column| column.data_type().is_nested());
446        let start = match window_frame.start_bound {
447            WindowFrameBound::Preceding(ref n) => {
448                if n.is_null() {
449                    // UNBOUNDED PRECEDING
450                    0
451                } else {
452                    self.calculate_index_of_row::<true, true>(
453                        range_columns,
454                        last_range,
455                        idx,
456                        Some(n),
457                        length,
458                    )?
459                }
460            }
461            WindowFrameBound::CurrentRow if nested_current_row => {
462                self.peer_boundary::<true>(range_columns, idx, last_range.start, length)?
463            }
464            WindowFrameBound::CurrentRow => self.calculate_index_of_row::<true, true>(
465                range_columns,
466                last_range,
467                idx,
468                None,
469                length,
470            )?,
471            WindowFrameBound::Following(ref n) => self
472                .calculate_index_of_row::<true, false>(
473                    range_columns,
474                    last_range,
475                    idx,
476                    Some(n),
477                    length,
478                )?,
479        };
480        let end = match window_frame.end_bound {
481            WindowFrameBound::Preceding(ref n) => self
482                .calculate_index_of_row::<false, true>(
483                    range_columns,
484                    last_range,
485                    idx,
486                    Some(n),
487                    length,
488                )?,
489            WindowFrameBound::CurrentRow if nested_current_row => {
490                // An equality scan cannot skip preceding non-peers if evaluation
491                // starts partway through a partition.
492                self.peer_boundary::<false>(
493                    range_columns,
494                    idx,
495                    last_range.end.max(idx),
496                    length,
497                )?
498            }
499            WindowFrameBound::CurrentRow => self.calculate_index_of_row::<false, false>(
500                range_columns,
501                last_range,
502                idx,
503                None,
504                length,
505            )?,
506            WindowFrameBound::Following(ref n) => {
507                if n.is_null() {
508                    // UNBOUNDED FOLLOWING
509                    length
510                } else {
511                    self.calculate_index_of_row::<false, false>(
512                        range_columns,
513                        last_range,
514                        idx,
515                        Some(n),
516                        length,
517                    )?
518                }
519            }
520        };
521        Ok(Range { start, end })
522    }
523
524    /// This function does the heavy lifting when finding range boundaries. It is meant to be
525    /// called twice, in succession, to get window frame start and end indices (with `SIDE`
526    /// supplied as true and false, respectively).
527    fn calculate_index_of_row<const SIDE: bool, const SEARCH_SIDE: bool>(
528        &self,
529        range_columns: &[ArrayRef],
530        last_range: &Range<usize>,
531        idx: usize,
532        delta: Option<&ScalarValue>,
533        length: usize,
534    ) -> Result<usize> {
535        let mut end_range = get_row_at_idx(range_columns, idx)?;
536        let search_start = if SIDE {
537            last_range.start
538        } else {
539            last_range.end
540        };
541        if let Some(delta) = delta {
542            let is_descending: bool = self
543                .sort_options
544                .first()
545                .ok_or_else(|| {
546                    internal_datafusion_err!(
547                        "Sort options unexpectedly absent in a window frame"
548                    )
549                })?
550                .descending;
551
552            // On overflow the boundary exceeds the type's range and is
553            // effectively unbounded within the partition. Collapse to the
554            // partition edge rather than feeding `search_in_slice` a
555            // wrapped-around target: PRECEDING searches reach `search_start`,
556            // FOLLOWING searches reach `length`.
557            let unbounded_edge = if SEARCH_SIDE { search_start } else { length };
558            // Turn the current row values into search targets in place
559            for value in &mut end_range {
560                if value.is_null() {
561                    continue;
562                }
563                let target = if SEARCH_SIDE == is_descending {
564                    match value.add_checked(delta) {
565                        Ok(v) => v,
566                        Err(_) => return Ok(unbounded_edge),
567                    }
568                } else if value.is_unsigned() && *value < *delta {
569                    // NOTE: This gets a polymorphic zero without having long coercion code for ScalarValue.
570                    //       If we decide to implement a "default" construction mechanism for ScalarValue,
571                    //       change the following statement to use that.
572                    value.sub(&*value)?
573                } else {
574                    match value.sub_checked(delta) {
575                        Ok(v) => v,
576                        Err(_) => return Ok(unbounded_edge),
577                    }
578                };
579                *value = target;
580            }
581        }
582        let compare_fn = |current: &[ScalarValue], target: &[ScalarValue]| {
583            let cmp = compare_rows(current, target, &self.sort_options)?;
584            Ok(if SIDE { cmp.is_lt() } else { cmp.is_le() })
585        };
586        search_in_slice(range_columns, &end_range, compare_fn, search_start, length)
587    }
588}
589
590// In GROUPS mode, rows with duplicate sorting values are grouped together.
591// Therefore, there must be an ORDER BY clause in the window definition to use GROUPS mode.
592// The syntax is as follows:
593//     GROUPS frame_start [ frame_exclusion ]
594//     GROUPS BETWEEN frame_start AND frame_end [ frame_exclusion ]
595// The optional frame_exclusion specifier is not yet supported.
596// The frame_start and frame_end parameters allow us to specify which rows the window
597// frame starts and ends with. They accept the following values:
598//    - UNBOUNDED PRECEDING: Start with the first row of the partition. Possible only in frame_start.
599//    - offset PRECEDING: When used in frame_start, it refers to the first row of the group
600//                        that comes "offset" groups before the current group (i.e. the group
601//                        containing the current row). When used in frame_end, it refers to the
602//                        last row of the group that comes "offset" groups before the current group.
603//    - CURRENT ROW: When used in frame_start, it refers to the first row of the group containing
604//                   the current row. When used in frame_end, it refers to the last row of the group
605//                   containing the current row.
606//    - offset FOLLOWING: When used in frame_start, it refers to the first row of the group
607//                        that comes "offset" groups after the current group (i.e. the group
608//                        containing the current row). When used in frame_end, it refers to the
609//                        last row of the group that comes "offset" groups after the current group.
610//    - UNBOUNDED FOLLOWING: End with the last row of the partition. Possible only in frame_end.
611
612/// This structure encapsulates all the state information we require as we
613/// scan groups of data while processing window frames.
614#[derive(Debug, Default, Clone)]
615pub struct WindowFrameStateGroups {
616    /// A tuple containing group values and the row index where the group ends.
617    /// Example: [[1, 1], [1, 1], [2, 1], [2, 1], ...] would correspond to
618    ///          [([1, 1], 2), ([2, 1], 4), ...].
619    pub group_end_indices: VecDeque<(Vec<ScalarValue>, usize)>,
620    /// The group index to which the row index belongs.
621    pub current_group_idx: usize,
622}
623
624impl WindowFrameStateGroups {
625    fn calculate_range(
626        &mut self,
627        window_frame: &Arc<WindowFrame>,
628        range_columns: &[ArrayRef],
629        length: usize,
630        idx: usize,
631    ) -> Result<Range<usize>> {
632        let start = match window_frame.start_bound {
633            WindowFrameBound::Preceding(ref n) => {
634                if n.is_null() {
635                    // UNBOUNDED PRECEDING
636                    0
637                } else {
638                    self.calculate_index_of_row::<true, true>(
639                        range_columns,
640                        idx,
641                        Some(n),
642                        length,
643                    )?
644                }
645            }
646            WindowFrameBound::CurrentRow => self.calculate_index_of_row::<true, true>(
647                range_columns,
648                idx,
649                None,
650                length,
651            )?,
652            WindowFrameBound::Following(ref n) => self
653                .calculate_index_of_row::<true, false>(
654                    range_columns,
655                    idx,
656                    Some(n),
657                    length,
658                )?,
659        };
660        let end = match window_frame.end_bound {
661            WindowFrameBound::Preceding(ref n) => self
662                .calculate_index_of_row::<false, true>(
663                    range_columns,
664                    idx,
665                    Some(n),
666                    length,
667                )?,
668            WindowFrameBound::CurrentRow => self.calculate_index_of_row::<false, false>(
669                range_columns,
670                idx,
671                None,
672                length,
673            )?,
674            WindowFrameBound::Following(ref n) => {
675                if n.is_null() {
676                    // UNBOUNDED FOLLOWING
677                    length
678                } else {
679                    self.calculate_index_of_row::<false, false>(
680                        range_columns,
681                        idx,
682                        Some(n),
683                        length,
684                    )?
685                }
686            }
687        };
688        Ok(Range { start, end })
689    }
690
691    /// This function does the heavy lifting when finding range boundaries. It is meant to be
692    /// called twice, in succession, to get window frame start and end indices (with `SIDE`
693    /// supplied as true and false, respectively). Generic argument `SEARCH_SIDE` determines
694    /// the sign of `delta` (where true/false represents negative/positive respectively).
695    fn calculate_index_of_row<const SIDE: bool, const SEARCH_SIDE: bool>(
696        &mut self,
697        range_columns: &[ArrayRef],
698        idx: usize,
699        delta: Option<&ScalarValue>,
700        length: usize,
701    ) -> Result<usize> {
702        let delta = if let Some(delta) = delta {
703            if let ScalarValue::UInt64(Some(value)) = delta {
704                *value as usize
705            } else {
706                return internal_err!(
707                    "Unexpectedly got a non-UInt64 value in a GROUPS mode window frame"
708                );
709            }
710        } else {
711            0
712        };
713        let mut group_start = 0;
714        let last_group = self.group_end_indices.back_mut();
715        if let Some((group_row, group_end)) = last_group {
716            if *group_end < length {
717                let new_group_row = get_row_at_idx(range_columns, *group_end)?;
718                // If last/current group keys are the same, we extend the last group:
719                if new_group_row.eq(group_row) {
720                    // Update the end boundary of the group (search right boundary):
721                    *group_end = search_in_slice(
722                        range_columns,
723                        group_row,
724                        check_equality,
725                        *group_end,
726                        length,
727                    )?;
728                }
729            }
730            // Start searching from the last group boundary:
731            group_start = *group_end;
732        }
733
734        // Advance groups until `idx` is inside a group:
735        while idx >= group_start {
736            let group_row = get_row_at_idx(range_columns, group_start)?;
737            // Find end boundary of the group (search right boundary):
738            let group_end = search_in_slice(
739                range_columns,
740                &group_row,
741                check_equality,
742                group_start,
743                length,
744            )?;
745            self.group_end_indices.push_back((group_row, group_end));
746            group_start = group_end;
747        }
748
749        // Update the group index `idx` belongs to:
750        while self.current_group_idx < self.group_end_indices.len()
751            && idx >= self.group_end_indices[self.current_group_idx].1
752        {
753            self.current_group_idx += 1;
754        }
755
756        // Find the group index of the frame boundary:
757        let group_idx = if SEARCH_SIDE {
758            self.current_group_idx.saturating_sub(delta)
759        } else {
760            self.current_group_idx + delta
761        };
762
763        // Extend `group_start_indices` until it includes at least `group_idx`:
764        while self.group_end_indices.len() <= group_idx && group_start < length {
765            let group_row = get_row_at_idx(range_columns, group_start)?;
766            // Find end boundary of the group (search right boundary):
767            let group_end = search_in_slice(
768                range_columns,
769                &group_row,
770                check_equality,
771                group_start,
772                length,
773            )?;
774            self.group_end_indices.push_back((group_row, group_end));
775            group_start = group_end;
776        }
777
778        // Calculate index of the group boundary:
779        Ok(match (SIDE, SEARCH_SIDE) {
780            // Window frame start:
781            (true, _) => {
782                let group_idx = std::cmp::min(group_idx, self.group_end_indices.len());
783                if group_idx > 0 {
784                    // Normally, start at the boundary of the previous group.
785                    self.group_end_indices[group_idx - 1].1
786                } else {
787                    // If previous group is out of the table, start at zero.
788                    0
789                }
790            }
791            // Window frame end, PRECEDING n
792            (false, true) => {
793                if self.current_group_idx >= delta {
794                    let group_idx = self.current_group_idx - delta;
795                    self.group_end_indices[group_idx].1
796                } else {
797                    // Group is out of the table, therefore end at zero.
798                    0
799                }
800            }
801            // Window frame end, FOLLOWING n
802            (false, false) => {
803                let group_idx = std::cmp::min(
804                    self.current_group_idx + delta,
805                    self.group_end_indices.len() - 1,
806                );
807                self.group_end_indices[group_idx].1
808            }
809        })
810    }
811}
812
813fn check_equality(current: &[ScalarValue], target: &[ScalarValue]) -> Result<bool> {
814    Ok(current == target)
815}
816
817#[cfg(test)]
818mod tests {
819    use super::*;
820
821    use arrow::array::{Float64Array, UInt64Array};
822    use arrow::datatypes::{Field, Schema};
823
824    #[test]
825    fn nested_range_peers_across_cloning_and_pruning() -> Result<()> {
826        use arrow::array::ListArray;
827        use arrow::datatypes::Int64Type;
828
829        fn assert_unwind_safe<T: std::panic::UnwindSafe + std::panic::RefUnwindSafe>() {}
830        assert_unwind_safe::<WindowFrameStateRange>();
831
832        let frame = Arc::new(WindowFrame::new_bounds(
833            WindowFrameUnits::Range,
834            WindowFrameBound::CurrentRow,
835            WindowFrameBound::CurrentRow,
836        ));
837        let columns: [ArrayRef; 1] =
838            [Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(
839                [1, 1, 2, 2].into_iter().map(|v| Some(vec![Some(v)])),
840            ))];
841        let mut range = WindowFrameStateRange::new(vec![SortOptions::default()]);
842        assert_eq!(
843            range.calculate_range(&frame, &(0..0), &columns, 4, 0)?,
844            0..2
845        );
846        assert_eq!(
847            range
848                .clone()
849                .calculate_range(&frame, &(0..2), &columns, 4, 1)?,
850            0..2
851        );
852
853        let columns = [columns[0].slice(1, 3)];
854        assert_eq!(
855            range.calculate_range(&frame, &(0..0), &columns, 3, 0)?,
856            0..1
857        );
858        let retained = Arc::downgrade(&columns[0]);
859        let mut state = WindowAggState::new(&DataType::Int64)?;
860        state.window_frame_range =
861            range.calculate_range(&frame, &(0..1), &columns, 3, 1)?;
862        assert_eq!(state.window_frame_range, 1..3);
863        state.last_calculated_index = 1;
864        state.window_frame_ctx = Some(WindowFrameContext::Range {
865            window_frame: frame,
866            state: range,
867        });
868        let pruned = [columns[0].slice(1, 2)];
869        drop(columns);
870        assert!(retained.upgrade().is_some());
871        state.prune_state(1);
872        assert!(retained.upgrade().is_none());
873        assert_eq!(
874            state.window_frame_ctx.as_mut().unwrap().calculate_range(
875                &pruned,
876                &state.window_frame_range,
877                2,
878                0,
879            )?,
880            0..2
881        );
882        Ok(())
883    }
884
885    #[test]
886    fn range_peers_compare_nested_dictionary_nulls_logically() -> Result<()> {
887        use arrow::array::{DictionaryArray, Int8Array, Int32Array, ListArray};
888        use arrow::buffer::OffsetBuffer;
889        use arrow::datatypes::Int8Type;
890
891        // Both lists contain NULL: one dictionary key is null, the other
892        // references a null value. ScalarValue equality distinguishes them.
893        let values: ArrayRef = Arc::new(DictionaryArray::<Int8Type>::try_new(
894            Int8Array::from(vec![None, Some(0)]),
895            Arc::new(Int32Array::from(vec![None])),
896        )?);
897        let columns: [ArrayRef; 1] = [Arc::new(ListArray::new(
898            Arc::new(Field::new("item", values.data_type().clone(), true)),
899            OffsetBuffer::from_lengths([1, 1]),
900            values,
901            None,
902        ))];
903        let frame = Arc::new(WindowFrame::new_bounds(
904            WindowFrameUnits::Range,
905            WindowFrameBound::CurrentRow,
906            WindowFrameBound::CurrentRow,
907        ));
908        let mut state = WindowFrameContext::new(frame, vec![SortOptions::default()]);
909        let mut range = 0..0;
910        for idx in 0..2 {
911            range = state.calculate_range(&columns, &range, 2, idx)?;
912            assert_eq!(range, 0..2);
913        }
914        Ok(())
915    }
916
917    fn get_test_data() -> (Vec<ArrayRef>, Vec<SortOptions>) {
918        let range_columns: Vec<ArrayRef> = vec![Arc::new(Float64Array::from(vec![
919            5.0, 7.0, 8.0, 8.0, 9., 10., 10., 10., 11.,
920        ]))];
921        let sort_options = vec![SortOptions {
922            descending: false,
923            nulls_first: false,
924        }];
925
926        (range_columns, sort_options)
927    }
928
929    #[test]
930    fn test_is_input_unchanged() -> Result<()> {
931        let schema =
932            Arc::new(Schema::new(vec![Field::new("ts", DataType::UInt64, false)]));
933        let batch = |values: &[u64]| -> Result<RecordBatch> {
934            Ok(RecordBatch::try_new(
935                Arc::clone(&schema),
936                vec![Arc::new(UInt64Array::from(values.to_vec()))],
937            )?)
938        };
939        let results = |n: usize| ScalarValue::UInt64(Some(0)).to_array_of_size(n);
940
941        let mut partition = PartitionBatchState::new_with_batch(batch(&[1, 2, 3])?);
942        assert_eq!(partition.n_rows_received, 3);
943
944        // A freshly created state has seen none of the partition's rows, so
945        // it must not report the input as unchanged.
946        let mut state = WindowAggState::new(&DataType::UInt64)?;
947        assert!(!state.is_input_unchanged(&partition));
948
949        // After an evaluation pass (here producing results for two of the
950        // three rows), the state has seen the partition's current input.
951        state.update(&results(2)?, &partition)?;
952        assert!(state.is_input_unchanged(&partition));
953
954        // New rows must be detected...
955        partition.extend(&batch(&[4])?)?;
956        assert_eq!(partition.n_rows_received, 4);
957        assert!(!state.is_input_unchanged(&partition));
958        // ...until the next evaluation pass catches up again.
959        state.update(&results(2)?, &partition)?;
960        assert!(state.is_input_unchanged(&partition));
961
962        // Pruning rows whose results are already calculated shrinks the
963        // buffer but not the received-row count, so it must not make the
964        // input appear changed.
965        let n_prune = 2;
966        let batch_ref = &partition.record_batch;
967        partition.record_batch = batch_ref.slice(n_prune, batch_ref.num_rows() - n_prune);
968        // An evaluator would have advanced the frame at least past the
969        // pruned rows; prune_state requires this.
970        state.window_frame_range = n_prune..n_prune;
971        state.prune_state(n_prune);
972        assert_eq!(partition.n_rows_received, 4);
973        assert!(state.is_input_unchanged(&partition));
974
975        // The end-of-partition transition must trigger one final pass, even
976        // though no rows arrived.
977        partition.is_end = true;
978        assert!(!state.is_input_unchanged(&partition));
979        state.update(&results(0)?, &partition)?;
980        assert!(state.is_input_unchanged(&partition));
981
982        Ok(())
983    }
984
985    fn assert_group_ranges(
986        window_frame: &Arc<WindowFrame>,
987        expected_results: Vec<(Range<usize>, usize)>,
988    ) -> Result<()> {
989        let mut window_frame_groups = WindowFrameStateGroups::default();
990        let (range_columns, _) = get_test_data();
991        let n_row = range_columns[0].len();
992        for (idx, (expected_range, expected_group_idx)) in
993            expected_results.into_iter().enumerate()
994        {
995            let range = window_frame_groups.calculate_range(
996                window_frame,
997                &range_columns,
998                n_row,
999                idx,
1000            )?;
1001            assert_eq!(range, expected_range);
1002            assert_eq!(window_frame_groups.current_group_idx, expected_group_idx);
1003        }
1004        Ok(())
1005    }
1006
1007    fn assert_frame_ranges(
1008        window_frame: &Arc<WindowFrame>,
1009        expected_results: Vec<Range<usize>>,
1010    ) -> Result<()> {
1011        let mut window_frame_context =
1012            WindowFrameContext::new(Arc::clone(window_frame), vec![]);
1013        let (range_columns, _) = get_test_data();
1014        let n_row = range_columns[0].len();
1015        let mut last_range = Range { start: 0, end: 0 };
1016        for (idx, expected_range) in expected_results.into_iter().enumerate() {
1017            let range = window_frame_context.calculate_range(
1018                &range_columns,
1019                &last_range,
1020                n_row,
1021                idx,
1022            )?;
1023            assert_eq!(range, expected_range);
1024            last_range = range;
1025        }
1026        Ok(())
1027    }
1028
1029    #[test]
1030    fn test_default_window_frame_group_boundaries() -> Result<()> {
1031        let window_frame = Arc::new(WindowFrame::new(None));
1032        assert_group_ranges(
1033            &window_frame,
1034            vec![
1035                (Range { start: 0, end: 9 }, 0),
1036                (Range { start: 0, end: 9 }, 0),
1037                (Range { start: 0, end: 9 }, 0),
1038                (Range { start: 0, end: 9 }, 0),
1039                (Range { start: 0, end: 9 }, 0),
1040                (Range { start: 0, end: 9 }, 0),
1041                (Range { start: 0, end: 9 }, 0),
1042                (Range { start: 0, end: 9 }, 0),
1043                (Range { start: 0, end: 9 }, 0),
1044            ],
1045        )?;
1046
1047        assert_frame_ranges(
1048            &window_frame,
1049            vec![
1050                Range { start: 0, end: 9 },
1051                Range { start: 0, end: 9 },
1052                Range { start: 0, end: 9 },
1053                Range { start: 0, end: 9 },
1054                Range { start: 0, end: 9 },
1055                Range { start: 0, end: 9 },
1056                Range { start: 0, end: 9 },
1057                Range { start: 0, end: 9 },
1058                Range { start: 0, end: 9 },
1059            ],
1060        )?;
1061
1062        Ok(())
1063    }
1064
1065    #[test]
1066    fn test_unordered_window_frame_group_boundaries() -> Result<()> {
1067        let window_frame = Arc::new(WindowFrame::new(Some(false)));
1068        assert_group_ranges(
1069            &window_frame,
1070            vec![
1071                (Range { start: 0, end: 1 }, 0),
1072                (Range { start: 0, end: 2 }, 1),
1073                (Range { start: 0, end: 4 }, 2),
1074                (Range { start: 0, end: 4 }, 2),
1075                (Range { start: 0, end: 5 }, 3),
1076                (Range { start: 0, end: 8 }, 4),
1077                (Range { start: 0, end: 8 }, 4),
1078                (Range { start: 0, end: 8 }, 4),
1079                (Range { start: 0, end: 9 }, 5),
1080            ],
1081        )?;
1082
1083        assert_frame_ranges(
1084            &window_frame,
1085            vec![
1086                Range { start: 0, end: 9 },
1087                Range { start: 0, end: 9 },
1088                Range { start: 0, end: 9 },
1089                Range { start: 0, end: 9 },
1090                Range { start: 0, end: 9 },
1091                Range { start: 0, end: 9 },
1092                Range { start: 0, end: 9 },
1093                Range { start: 0, end: 9 },
1094                Range { start: 0, end: 9 },
1095            ],
1096        )?;
1097
1098        Ok(())
1099    }
1100
1101    #[test]
1102    fn test_ordered_window_frame_group_boundaries() -> Result<()> {
1103        let window_frame = Arc::new(WindowFrame::new(Some(true)));
1104        assert_group_ranges(
1105            &window_frame,
1106            vec![
1107                (Range { start: 0, end: 1 }, 0),
1108                (Range { start: 0, end: 2 }, 1),
1109                (Range { start: 0, end: 4 }, 2),
1110                (Range { start: 0, end: 4 }, 2),
1111                (Range { start: 0, end: 5 }, 3),
1112                (Range { start: 0, end: 8 }, 4),
1113                (Range { start: 0, end: 8 }, 4),
1114                (Range { start: 0, end: 8 }, 4),
1115                (Range { start: 0, end: 9 }, 5),
1116            ],
1117        )?;
1118
1119        assert_frame_ranges(
1120            &window_frame,
1121            vec![
1122                Range { start: 0, end: 1 },
1123                Range { start: 0, end: 2 },
1124                Range { start: 0, end: 3 },
1125                Range { start: 0, end: 4 },
1126                Range { start: 0, end: 5 },
1127                Range { start: 0, end: 6 },
1128                Range { start: 0, end: 7 },
1129                Range { start: 0, end: 8 },
1130                Range { start: 0, end: 9 },
1131            ],
1132        )?;
1133
1134        Ok(())
1135    }
1136
1137    #[test]
1138    fn test_window_frame_group_boundaries() -> Result<()> {
1139        let window_frame = Arc::new(WindowFrame::new_bounds(
1140            WindowFrameUnits::Groups,
1141            WindowFrameBound::Preceding(ScalarValue::UInt64(Some(1))),
1142            WindowFrameBound::Following(ScalarValue::UInt64(Some(1))),
1143        ));
1144        assert_group_ranges(
1145            &window_frame,
1146            vec![
1147                (Range { start: 0, end: 2 }, 0),
1148                (Range { start: 0, end: 4 }, 1),
1149                (Range { start: 1, end: 5 }, 2),
1150                (Range { start: 1, end: 5 }, 2),
1151                (Range { start: 2, end: 8 }, 3),
1152                (Range { start: 4, end: 9 }, 4),
1153                (Range { start: 4, end: 9 }, 4),
1154                (Range { start: 4, end: 9 }, 4),
1155                (Range { start: 5, end: 9 }, 5),
1156            ],
1157        )
1158    }
1159
1160    #[test]
1161    fn test_window_frame_group_boundaries_both_following() -> Result<()> {
1162        let window_frame = Arc::new(WindowFrame::new_bounds(
1163            WindowFrameUnits::Groups,
1164            WindowFrameBound::Following(ScalarValue::UInt64(Some(1))),
1165            WindowFrameBound::Following(ScalarValue::UInt64(Some(2))),
1166        ));
1167        assert_group_ranges(
1168            &window_frame,
1169            vec![
1170                (Range::<usize> { start: 1, end: 4 }, 0),
1171                (Range::<usize> { start: 2, end: 5 }, 1),
1172                (Range::<usize> { start: 4, end: 8 }, 2),
1173                (Range::<usize> { start: 4, end: 8 }, 2),
1174                (Range::<usize> { start: 5, end: 9 }, 3),
1175                (Range::<usize> { start: 8, end: 9 }, 4),
1176                (Range::<usize> { start: 8, end: 9 }, 4),
1177                (Range::<usize> { start: 8, end: 9 }, 4),
1178                (Range::<usize> { start: 9, end: 9 }, 5),
1179            ],
1180        )
1181    }
1182
1183    #[test]
1184    fn test_window_frame_group_boundaries_both_preceding() -> Result<()> {
1185        let window_frame = Arc::new(WindowFrame::new_bounds(
1186            WindowFrameUnits::Groups,
1187            WindowFrameBound::Preceding(ScalarValue::UInt64(Some(2))),
1188            WindowFrameBound::Preceding(ScalarValue::UInt64(Some(1))),
1189        ));
1190        assert_group_ranges(
1191            &window_frame,
1192            vec![
1193                (Range::<usize> { start: 0, end: 0 }, 0),
1194                (Range::<usize> { start: 0, end: 1 }, 1),
1195                (Range::<usize> { start: 0, end: 2 }, 2),
1196                (Range::<usize> { start: 0, end: 2 }, 2),
1197                (Range::<usize> { start: 1, end: 4 }, 3),
1198                (Range::<usize> { start: 2, end: 5 }, 4),
1199                (Range::<usize> { start: 2, end: 5 }, 4),
1200                (Range::<usize> { start: 2, end: 5 }, 4),
1201                (Range::<usize> { start: 4, end: 8 }, 5),
1202            ],
1203        )
1204    }
1205}