Skip to main content

risingwave_expr/window_function/
state.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeSet;
16
17use itertools::Itertools;
18use risingwave_common::row::OwnedRow;
19use risingwave_common::types::{Datum, DefaultOrdered};
20use risingwave_common::util::memcmp_encoding::MemcmpEncoded;
21use risingwave_common_estimate_size::EstimateSize;
22use smallvec::SmallVec;
23
24use super::WindowFuncCall;
25use crate::{ExprError, Result};
26
27/// Unique and ordered identifier for a row in internal states.
28#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, EstimateSize)]
29pub struct StateKey {
30    pub order_key: MemcmpEncoded,
31    pub pk: DefaultOrdered<OwnedRow>,
32}
33
34/// The watermark of the order key that closes a window, i.e., no future row can fall into it.
35/// A watermark `w` promises that no row with order value `< w` arrives afterwards.
36#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, EstimateSize)]
37pub struct WatermarkBound {
38    /// The order value, memcmp-encoded in the same way as [`StateKey::order_key`].
39    pub value: MemcmpEncoded,
40    /// Whether the watermark must be greater than `value`, rather than greater than or equal to.
41    pub exclusive: bool,
42}
43
44impl WatermarkBound {
45    pub fn is_satisfied_by(&self, watermark: &MemcmpEncoded) -> bool {
46        if self.exclusive {
47            watermark > &self.value
48        } else {
49            watermark >= &self.value
50        }
51    }
52}
53
54/// Whether the current window is closed, i.e., no future row can fall into it.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum Readiness {
57    Ready,
58    /// The window is closed once the watermark of the order key satisfies the bound.
59    OnWatermark(WatermarkBound),
60    /// Only future rows can close the window.
61    WaitForInput,
62}
63
64impl Readiness {
65    /// The readiness of windows that must all be closed.
66    pub fn and(self, other: Self) -> Self {
67        use Readiness::*;
68        match (self, other) {
69            (WaitForInput, _) | (_, WaitForInput) => WaitForInput,
70            (Ready, r) | (r, Ready) => r,
71            // At the same value, the exclusive bound is the stricter one.
72            (OnWatermark(a), OnWatermark(b)) => OnWatermark(std::cmp::max(a, b)),
73        }
74    }
75
76    pub fn is_ready(&self, watermark: Option<&MemcmpEncoded>) -> bool {
77        match self {
78            Readiness::Ready => true,
79            Readiness::OnWatermark(bound) => watermark.is_some_and(|w| bound.is_satisfied_by(w)),
80            Readiness::WaitForInput => false,
81        }
82    }
83}
84
85#[derive(Debug)]
86pub struct StatePos<'a> {
87    /// Only 2 cases in which the `key` is `None`:
88    /// 1. The state is empty.
89    /// 2. All rows in the state are output, and some are retained for the windows of future rows.
90    pub key: Option<&'a StateKey>,
91    pub is_ready: bool,
92}
93
94#[derive(Debug)]
95pub enum StateEvictHint {
96    /// Use a set instead of a single key to avoid state table iter or too many range delete.
97    /// Shouldn't be empty set.
98    CanEvict(BTreeSet<StateKey>),
99    /// State keys from the specified key are still required, so must be kept in the state table.
100    CannotEvict(StateKey),
101}
102
103impl StateEvictHint {
104    pub fn merge(self, other: StateEvictHint) -> StateEvictHint {
105        use StateEvictHint::*;
106        match (self, other) {
107            (CanEvict(a), CanEvict(b)) => {
108                // Example:
109                // a = CanEvict({1, 2, 3})
110                // b = CanEvict({2, 3, 4})
111                // a.merge(b) = CanEvict({1, 2, 3})
112                let a_last = a.last().unwrap();
113                let b_last = b.last().unwrap();
114                let last = std::cmp::min(a_last, b_last).clone();
115                CanEvict(
116                    a.into_iter()
117                        .take_while(|k| k <= &last)
118                        .chain(b.into_iter().take_while(|k| k <= &last))
119                        .collect(),
120                )
121            }
122            (CannotEvict(a), CannotEvict(b)) => {
123                // Example:
124                // a = CannotEvict(2), meaning keys < 2 can be evicted
125                // b = CannotEvict(3), meaning keys < 3 can be evicted
126                // a.merge(b) = CannotEvict(2)
127                CannotEvict(std::cmp::min(a, b))
128            }
129            (CanEvict(mut keys), CannotEvict(still_required))
130            | (CannotEvict(still_required), CanEvict(mut keys)) => {
131                // Example:
132                // a = CanEvict({1, 2, 3})
133                // b = CannotEvict(3)
134                // a.merge(b) = CanEvict({1, 2})
135                keys.split_off(&still_required);
136                if keys.is_empty() {
137                    CannotEvict(still_required)
138                } else {
139                    CanEvict(keys)
140                }
141            }
142        }
143    }
144}
145
146/// Snapshot of a window state for persistence and recovery.
147#[derive(Debug, Clone)]
148pub struct WindowStateSnapshot {
149    /// The key of the last output row.
150    pub last_output_key: Option<StateKey>,
151    /// Function-specific state. The variant must match the window function type;
152    /// a mismatch is detected at restore time and returned as an error.
153    pub function_state: risingwave_pb::window_function::window_state_snapshot::FunctionState,
154}
155
156pub trait WindowState: EstimateSize {
157    // TODO(rc): may append rows in batch like in `hash_agg`.
158    /// Append a new input row to the state. The `key` is expected to be increasing.
159    fn append(&mut self, key: StateKey, args: SmallVec<[Datum; 2]>);
160
161    /// Get the current window frame position.
162    fn curr_window(&self) -> StatePos<'_>;
163
164    /// Get the readiness of the current window, given that the rows are appended in the order of
165    /// the order key, so no future row is less than the last one. Unlike [`StatePos::is_ready`],
166    /// which is conservative and must not change for the recovery of existing jobs, this is exact.
167    fn readiness(&self) -> Readiness {
168        if self.curr_window().is_ready {
169            Readiness::Ready
170        } else {
171            Readiness::WaitForInput
172        }
173    }
174
175    /// Whether no row is retained in the state.
176    fn is_empty(&self) -> bool;
177
178    /// Slide the window frame forward and collect the output and evict hint. Similar to `Iterator::next`.
179    fn slide(&mut self) -> Result<(Datum, StateEvictHint)>;
180
181    /// Slide the window frame forward and collect the evict hint. Don't calculate the output if possible.
182    fn slide_no_output(&mut self) -> Result<StateEvictHint>;
183
184    /// Enable persistence for this window state. When enabled, the state may return
185    /// `CanEvict` hints and should support snapshot/restore.
186    fn enable_persistence(&mut self) {}
187
188    /// Create a snapshot of the current state for persistence.
189    /// Returns `None` if the state doesn't support persistence.
190    fn snapshot(&self) -> Option<WindowStateSnapshot> {
191        None
192    }
193
194    /// Restore the state from a snapshot. Called during recovery before replaying rows.
195    fn restore(&mut self, _snapshot: WindowStateSnapshot) -> Result<()> {
196        Ok(())
197    }
198}
199
200pub type BoxedWindowState = Box<dyn WindowState + Send + Sync>;
201
202#[linkme::distributed_slice]
203pub static WINDOW_STATE_BUILDERS: [fn(&WindowFuncCall) -> Result<BoxedWindowState>];
204
205pub fn create_window_state(call: &WindowFuncCall) -> Result<BoxedWindowState> {
206    // we expect only one builder function in `expr_impl/window_function/mod.rs`
207    let builder = WINDOW_STATE_BUILDERS.iter().next();
208    builder.map_or_else(
209        || {
210            Err(ExprError::UnsupportedFunction(format!(
211                "{}({}) -> {}",
212                call.kind,
213                call.args.arg_types().iter().format(", "),
214                call.return_type,
215            )))
216        },
217        |f| f(call),
218    )
219}
220
221/// Test that merging evict hints from mixed persistent-numbering and non-numbering window
222/// functions does not panic. This reproduces the scenario where e.g. `row_number()`, `lag()`,
223/// `rank()` are used together in an EOWC query:
224///
225///   1. `row_number` (persistent) -> `CanEvict({key})`
226///   2. `lag` (non-persistent)    -> `CannotEvict(key)`
227///      merge(1, 2) = `CanEvict({})` -- empty set, violates the "shouldn't be empty" invariant
228///   3. `rank` (persistent)       -> `CanEvict({key})`
229///      merge(empty, 3) panics on `.last().unwrap()`
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn make_state_key(order: i64, pk: i64) -> StateKey {
235        use risingwave_common::row::OwnedRow;
236        use risingwave_common::types::ScalarImpl;
237        StateKey {
238            order_key: MemcmpEncoded::from(order.to_be_bytes().to_vec()),
239            pk: OwnedRow::new(vec![Some(ScalarImpl::Int64(pk))]).into(),
240        }
241    }
242
243    /// Simulates `row_number()` -> `CanEvict({K})`, `lag()` -> `CannotEvict(K)`,
244    /// `rank()` -> `CanEvict({K})`.
245    /// The two-way merge must fall back to `CannotEvict` (not an empty `CanEvict`),
246    /// so the three-way merge doesn't panic on `.last().unwrap()`.
247    #[test]
248    fn test_merge_mixed_persistent_and_non_persistent() {
249        let key = make_state_key(1, 100);
250
251        // Two-way: CanEvict({K}) + CannotEvict(K) -> CannotEvict(K)
252        let merged = StateEvictHint::CanEvict(BTreeSet::from([key.clone()]))
253            .merge(StateEvictHint::CannotEvict(key.clone()));
254        assert!(matches!(&merged, StateEvictHint::CannotEvict(k) if k == &key));
255
256        // Three-way: CannotEvict(K) + CanEvict({K}) -> CannotEvict(K)
257        let merged = merged.merge(StateEvictHint::CanEvict(BTreeSet::from([key.clone()])));
258        assert!(matches!(&merged, StateEvictHint::CannotEvict(k) if k == &key));
259    }
260
261    #[test]
262    fn test_readiness_and() {
263        use Readiness::*;
264        let encode = |value: i64| MemcmpEncoded::from(value.to_be_bytes().to_vec());
265        let bound = |value: i64, exclusive: bool| WatermarkBound {
266            value: encode(value),
267            exclusive,
268        };
269
270        assert_eq!(
271            Ready.and(OnWatermark(bound(1, false))),
272            OnWatermark(bound(1, false))
273        );
274        assert_eq!(OnWatermark(bound(1, false)).and(WaitForInput), WaitForInput);
275        assert_eq!(
276            OnWatermark(bound(2, false)).and(OnWatermark(bound(1, true))),
277            OnWatermark(bound(2, false))
278        );
279        assert_eq!(
280            OnWatermark(bound(1, false)).and(OnWatermark(bound(1, true))),
281            OnWatermark(bound(1, true))
282        );
283
284        assert!(bound(1, false).is_satisfied_by(&encode(1)));
285        assert!(!bound(1, true).is_satisfied_by(&encode(1)));
286        assert!(bound(1, true).is_satisfied_by(&encode(2)));
287        assert!(!OnWatermark(bound(1, false)).is_ready(None));
288    }
289}