Skip to main content

risingwave_expr_impl/window_function/
rank.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;
16use std::marker::PhantomData;
17
18use risingwave_common::types::Datum;
19use risingwave_common::util::memcmp_encoding::MemcmpEncoded;
20use risingwave_common_estimate_size::EstimateSize;
21use risingwave_common_estimate_size::collections::EstimatedVecDeque;
22use risingwave_expr::window_function::{
23    StateEvictHint, StateKey, StatePos, WindowFuncCall, WindowState, WindowStateSnapshot,
24};
25use risingwave_expr::{ExprError, Result};
26use risingwave_pb::window_function::window_state_snapshot::FunctionState;
27use risingwave_pb::window_function::{DenseRankState, RankState as RankStateProto, RowNumberState};
28use smallvec::SmallVec;
29
30use self::private::RankFuncCount;
31
32mod private {
33    use super::*;
34
35    pub trait RankFuncCount: Default + EstimateSize {
36        /// Count and return the rank for the given key, updating internal state.
37        fn count(&mut self, curr_key: StateKey) -> i64;
38
39        /// Convert the function state to the proto oneof variant for persistence.
40        fn to_proto_state(&self) -> FunctionState;
41
42        /// Restore the function state from the proto oneof variant.
43        /// Returns an error if the variant does not match this function type.
44        fn from_proto_state(state: FunctionState) -> Result<Self>
45        where
46            Self: Sized;
47    }
48}
49
50#[derive(Default, EstimateSize)]
51pub(super) struct RowNumber {
52    prev_rank: i64,
53}
54
55impl RankFuncCount for RowNumber {
56    fn count(&mut self, _curr_key: StateKey) -> i64 {
57        let curr_rank = self.prev_rank + 1;
58        self.prev_rank = curr_rank;
59        curr_rank
60    }
61
62    fn to_proto_state(&self) -> FunctionState {
63        FunctionState::RowNumberState(RowNumberState {
64            prev_rank: self.prev_rank,
65        })
66    }
67
68    fn from_proto_state(state: FunctionState) -> Result<Self> {
69        match state {
70            FunctionState::RowNumberState(s) => Ok(Self {
71                prev_rank: s.prev_rank,
72            }),
73            other => Err(ExprError::Internal(anyhow::anyhow!(
74                "expected RowNumberState, got {other:?}"
75            ))),
76        }
77    }
78}
79
80#[derive(EstimateSize)]
81pub(super) struct Rank {
82    prev_order_key: Option<MemcmpEncoded>,
83    prev_rank: i64,
84    // 1-based position of the previously output row within its peer group.
85    // Used to advance the rank by the peer-group size when a new group starts.
86    prev_pos_in_peer_group: i64,
87}
88
89impl Default for Rank {
90    fn default() -> Self {
91        Self {
92            prev_order_key: None,
93            prev_rank: 0,
94            prev_pos_in_peer_group: 1, // first position in the fake starting peer group
95        }
96    }
97}
98
99impl RankFuncCount for Rank {
100    fn count(&mut self, curr_key: StateKey) -> i64 {
101        let (curr_rank, curr_pos_in_group) = if let Some(prev_order_key) =
102            self.prev_order_key.as_ref()
103            && prev_order_key == &curr_key.order_key
104        {
105            // current key is in the same peer group as the previous one
106            (self.prev_rank, self.prev_pos_in_peer_group + 1)
107        } else {
108            // starting a new peer group
109            (self.prev_rank + self.prev_pos_in_peer_group, 1)
110        };
111        self.prev_order_key = Some(curr_key.order_key);
112        self.prev_rank = curr_rank;
113        self.prev_pos_in_peer_group = curr_pos_in_group;
114        curr_rank
115    }
116
117    fn to_proto_state(&self) -> FunctionState {
118        FunctionState::RankState(RankStateProto {
119            prev_order_key: self.prev_order_key.as_ref().map(|k| k.to_vec()),
120            prev_rank: self.prev_rank,
121            prev_pos_in_peer_group: self.prev_pos_in_peer_group,
122        })
123    }
124
125    fn from_proto_state(state: FunctionState) -> Result<Self> {
126        match state {
127            FunctionState::RankState(s) => Ok(Self {
128                prev_order_key: s.prev_order_key.map(Into::into),
129                prev_rank: s.prev_rank,
130                prev_pos_in_peer_group: s.prev_pos_in_peer_group,
131            }),
132            other => Err(ExprError::Internal(anyhow::anyhow!(
133                "expected RankState, got {other:?}"
134            ))),
135        }
136    }
137}
138
139#[derive(Default, EstimateSize)]
140pub(super) struct DenseRank {
141    prev_order_key: Option<MemcmpEncoded>,
142    prev_rank: i64,
143}
144
145impl RankFuncCount for DenseRank {
146    fn count(&mut self, curr_key: StateKey) -> i64 {
147        let curr_rank = if let Some(prev_order_key) = self.prev_order_key.as_ref()
148            && prev_order_key == &curr_key.order_key
149        {
150            // current key is in the same peer group as the previous one
151            self.prev_rank
152        } else {
153            // starting a new peer group
154            self.prev_rank + 1
155        };
156        self.prev_order_key = Some(curr_key.order_key);
157        self.prev_rank = curr_rank;
158        curr_rank
159    }
160
161    fn to_proto_state(&self) -> FunctionState {
162        FunctionState::DenseRankState(DenseRankState {
163            prev_order_key: self.prev_order_key.as_ref().map(|k| k.to_vec()),
164            prev_rank: self.prev_rank,
165        })
166    }
167
168    fn from_proto_state(state: FunctionState) -> Result<Self> {
169        match state {
170            FunctionState::DenseRankState(s) => Ok(Self {
171                prev_order_key: s.prev_order_key.map(Into::into),
172                prev_rank: s.prev_rank,
173            }),
174            other => Err(ExprError::Internal(anyhow::anyhow!(
175                "expected DenseRankState, got {other:?}"
176            ))),
177        }
178    }
179}
180
181/// Generic state for rank window functions including `row_number`, `rank` and `dense_rank`.
182#[derive(EstimateSize)]
183pub(super) struct RankState<RF: RankFuncCount> {
184    /// First state key of the partition.
185    first_key: Option<StateKey>,
186    /// State keys that are waiting to be outputted.
187    buffer: EstimatedVecDeque<StateKey>,
188    /// Function-specific state.
189    func_state: RF,
190    /// Whether persistence is enabled for this state.
191    persistence_enabled: bool,
192    /// The key of the last output row (for snapshot).
193    last_output_key: Option<StateKey>,
194    /// During recovery, skip updating `func_state` for rows up to and including this key.
195    recover_skip_until: Option<StateKey>,
196    _phantom: PhantomData<RF>,
197}
198
199impl<RF: RankFuncCount> RankState<RF> {
200    pub fn new(_call: &WindowFuncCall) -> Self {
201        Self {
202            first_key: None,
203            buffer: Default::default(),
204            func_state: Default::default(),
205            persistence_enabled: false,
206            last_output_key: None,
207            recover_skip_until: None,
208            _phantom: PhantomData,
209        }
210    }
211
212    fn slide_inner(&mut self) -> (i64, StateEvictHint) {
213        let curr_key = self
214            .buffer
215            .pop_front()
216            .expect("should not slide forward when the current window is not ready");
217        let rank = self.func_state.count(curr_key.clone());
218
219        // Track last output key for persistence
220        self.last_output_key = Some(curr_key.clone());
221
222        let evict_hint = if self.persistence_enabled {
223            // When persistence is enabled, we can evict the just-output key
224            let mut evict_set = BTreeSet::new();
225            evict_set.insert(curr_key);
226            StateEvictHint::CanEvict(evict_set)
227        } else {
228            // Can't evict any state key in EOWC mode without persistence,
229            // because we can't recover from previous output
230            StateEvictHint::CannotEvict(
231                self.first_key
232                    .clone()
233                    .expect("should have appended some rows"),
234            )
235        };
236        (rank, evict_hint)
237    }
238
239    fn slide_no_output_inner(&mut self) -> StateEvictHint {
240        let curr_key = self
241            .buffer
242            .pop_front()
243            .expect("should not slide forward when the current window is not ready");
244
245        // Check if we should skip counting (during recovery)
246        let should_skip = self
247            .recover_skip_until
248            .as_ref()
249            .is_some_and(|skip_key| &curr_key <= skip_key);
250
251        if !should_skip {
252            // Normal counting
253            self.func_state.count(curr_key.clone());
254        }
255
256        // Clear recover_skip_until when we've processed the target key
257        if self
258            .recover_skip_until
259            .as_ref()
260            .is_some_and(|skip_key| &curr_key == skip_key)
261        {
262            self.recover_skip_until = None;
263        }
264
265        // Track last output key for persistence
266        self.last_output_key = Some(curr_key.clone());
267
268        if self.persistence_enabled {
269            let mut evict_set = BTreeSet::new();
270            evict_set.insert(curr_key);
271            StateEvictHint::CanEvict(evict_set)
272        } else {
273            StateEvictHint::CannotEvict(
274                self.first_key
275                    .clone()
276                    .expect("should have appended some rows"),
277            )
278        }
279    }
280}
281
282impl<RF: RankFuncCount> WindowState for RankState<RF> {
283    fn append(&mut self, key: StateKey, _args: SmallVec<[Datum; 2]>) {
284        if self.first_key.is_none() {
285            self.first_key = Some(key.clone());
286        }
287        self.buffer.push_back(key);
288    }
289
290    fn curr_window(&self) -> StatePos<'_> {
291        let curr_key = self.buffer.front();
292        StatePos {
293            key: curr_key,
294            is_ready: curr_key.is_some(),
295        }
296    }
297
298    fn is_empty(&self) -> bool {
299        self.buffer.is_empty()
300    }
301
302    fn slide(&mut self) -> Result<(Datum, StateEvictHint)> {
303        let (rank, evict_hint) = self.slide_inner();
304        Ok((Some(rank.into()), evict_hint))
305    }
306
307    fn slide_no_output(&mut self) -> Result<StateEvictHint> {
308        let evict_hint = self.slide_no_output_inner();
309        Ok(evict_hint)
310    }
311
312    fn enable_persistence(&mut self) {
313        self.persistence_enabled = true;
314    }
315
316    fn snapshot(&self) -> Option<WindowStateSnapshot> {
317        if !self.persistence_enabled {
318            return None;
319        }
320        Some(WindowStateSnapshot {
321            last_output_key: self.last_output_key.clone(),
322            function_state: self.func_state.to_proto_state(),
323        })
324    }
325
326    fn restore(&mut self, snapshot: WindowStateSnapshot) -> Result<()> {
327        self.func_state = RF::from_proto_state(snapshot.function_state)?;
328        // Set recover_skip_until so that slide_no_output skips counting for rows
329        // that have already been counted before the snapshot was taken.
330        self.recover_skip_until = snapshot.last_output_key;
331        Ok(())
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use risingwave_common::row::OwnedRow;
338    use risingwave_common::types::{DataType, ScalarImpl};
339    use risingwave_common::util::memcmp_encoding;
340    use risingwave_common::util::sort_util::OrderType;
341    use risingwave_expr::aggregate::AggArgs;
342    use risingwave_expr::window_function::{Frame, FrameBound, WindowFuncKind};
343
344    use super::*;
345
346    fn create_state_key(order: i64, pk: i64) -> StateKey {
347        StateKey {
348            order_key: memcmp_encoding::encode_value(
349                Some(ScalarImpl::from(order)),
350                OrderType::ascending(),
351            )
352            .unwrap(),
353            pk: OwnedRow::new(vec![Some(pk.into())]).into(),
354        }
355    }
356
357    #[test]
358    #[should_panic(expected = "should not slide forward when the current window is not ready")]
359    fn test_rank_state_bad_use() {
360        let call = WindowFuncCall {
361            kind: WindowFuncKind::RowNumber,
362            return_type: DataType::Int64,
363            args: AggArgs::default(),
364            ignore_nulls: false,
365            frame: Frame::rows(
366                FrameBound::UnboundedPreceding,
367                FrameBound::UnboundedFollowing,
368            ),
369        };
370        let mut state = RankState::<RowNumber>::new(&call);
371        assert!(state.curr_window().key.is_none());
372        assert!(!state.curr_window().is_ready);
373        _ = state.slide()
374    }
375
376    #[test]
377    fn test_row_number_state() {
378        let call = WindowFuncCall {
379            kind: WindowFuncKind::RowNumber,
380            return_type: DataType::Int64,
381            args: AggArgs::default(),
382            ignore_nulls: false,
383            frame: Frame::rows(
384                FrameBound::UnboundedPreceding,
385                FrameBound::UnboundedFollowing,
386            ),
387        };
388        let mut state = RankState::<RowNumber>::new(&call);
389        assert!(state.curr_window().key.is_none());
390        assert!(!state.curr_window().is_ready);
391        state.append(create_state_key(1, 100), SmallVec::new());
392        assert_eq!(state.curr_window().key.unwrap(), &create_state_key(1, 100));
393        assert!(state.curr_window().is_ready);
394        let (output, evict_hint) = state.slide().unwrap();
395        assert_eq!(output.unwrap(), 1i64.into());
396        match evict_hint {
397            StateEvictHint::CannotEvict(state_key) => {
398                assert_eq!(state_key, create_state_key(1, 100));
399            }
400            _ => unreachable!(),
401        }
402        assert!(!state.curr_window().is_ready);
403        state.append(create_state_key(2, 103), SmallVec::new());
404        state.append(create_state_key(2, 102), SmallVec::new());
405        assert_eq!(state.curr_window().key.unwrap(), &create_state_key(2, 103));
406        let (output, evict_hint) = state.slide().unwrap();
407        assert_eq!(output.unwrap(), 2i64.into());
408        match evict_hint {
409            StateEvictHint::CannotEvict(state_key) => {
410                assert_eq!(state_key, create_state_key(1, 100));
411            }
412            _ => unreachable!(),
413        }
414        assert_eq!(state.curr_window().key.unwrap(), &create_state_key(2, 102));
415        let (output, _) = state.slide().unwrap();
416        assert_eq!(output.unwrap(), 3i64.into());
417    }
418
419    #[test]
420    fn test_rank_state() {
421        let call = WindowFuncCall {
422            kind: WindowFuncKind::Rank,
423            return_type: DataType::Int64,
424            args: AggArgs::default(),
425            ignore_nulls: false,
426            frame: Frame::rows(
427                FrameBound::UnboundedPreceding,
428                FrameBound::UnboundedFollowing,
429            ),
430        };
431        let mut state = RankState::<Rank>::new(&call);
432        assert!(state.curr_window().key.is_none());
433        assert!(!state.curr_window().is_ready);
434        state.append(create_state_key(1, 100), SmallVec::new());
435        state.append(create_state_key(2, 103), SmallVec::new());
436        state.append(create_state_key(2, 102), SmallVec::new());
437        state.append(create_state_key(3, 106), SmallVec::new());
438        state.append(create_state_key(3, 105), SmallVec::new());
439        state.append(create_state_key(3, 104), SmallVec::new());
440        state.append(create_state_key(8, 108), SmallVec::new());
441
442        let mut outputs = vec![];
443        while state.curr_window().is_ready {
444            outputs.push(state.slide().unwrap().0)
445        }
446
447        assert_eq!(
448            outputs,
449            vec![
450                Some(1i64.into()),
451                Some(2i64.into()),
452                Some(2i64.into()),
453                Some(4i64.into()),
454                Some(4i64.into()),
455                Some(4i64.into()),
456                Some(7i64.into())
457            ]
458        );
459    }
460
461    #[test]
462    fn test_dense_rank_state() {
463        let call = WindowFuncCall {
464            kind: WindowFuncKind::DenseRank,
465            return_type: DataType::Int64,
466            args: AggArgs::default(),
467            ignore_nulls: false,
468            frame: Frame::rows(
469                FrameBound::UnboundedPreceding,
470                FrameBound::UnboundedFollowing,
471            ),
472        };
473        let mut state = RankState::<DenseRank>::new(&call);
474        assert!(state.curr_window().key.is_none());
475        assert!(!state.curr_window().is_ready);
476        state.append(create_state_key(1, 100), SmallVec::new());
477        state.append(create_state_key(2, 103), SmallVec::new());
478        state.append(create_state_key(2, 102), SmallVec::new());
479        state.append(create_state_key(3, 106), SmallVec::new());
480        state.append(create_state_key(3, 105), SmallVec::new());
481        state.append(create_state_key(3, 104), SmallVec::new());
482        state.append(create_state_key(8, 108), SmallVec::new());
483
484        let mut outputs = vec![];
485        while state.curr_window().is_ready {
486            outputs.push(state.slide().unwrap().0)
487        }
488
489        assert_eq!(
490            outputs,
491            vec![
492                Some(1i64.into()),
493                Some(2i64.into()),
494                Some(2i64.into()),
495                Some(3i64.into()),
496                Some(3i64.into()),
497                Some(3i64.into()),
498                Some(4i64.into())
499            ]
500        );
501    }
502
503    fn create_call(kind: WindowFuncKind) -> WindowFuncCall {
504        WindowFuncCall {
505            kind,
506            return_type: DataType::Int64,
507            args: AggArgs::default(),
508            ignore_nulls: false,
509            frame: Frame::rows(
510                FrameBound::UnboundedPreceding,
511                FrameBound::UnboundedFollowing,
512            ),
513        }
514    }
515
516    #[test]
517    fn test_row_number_snapshot_restore_roundtrip() {
518        let call = create_call(WindowFuncKind::RowNumber);
519        let mut state = RankState::<RowNumber>::new(&call);
520        state.enable_persistence();
521
522        // Process some rows
523        state.append(create_state_key(1, 100), SmallVec::new());
524        state.append(create_state_key(2, 101), SmallVec::new());
525        state.append(create_state_key(3, 102), SmallVec::new());
526
527        // Output first two rows
528        let (output1, _) = state.slide().unwrap();
529        assert_eq!(output1.unwrap(), 1i64.into());
530        let (output2, _) = state.slide().unwrap();
531        assert_eq!(output2.unwrap(), 2i64.into());
532
533        // Take snapshot
534        let snapshot = state.snapshot().unwrap();
535        assert!(snapshot.last_output_key.is_some());
536        assert_eq!(
537            snapshot.last_output_key.as_ref().unwrap(),
538            &create_state_key(2, 101)
539        );
540
541        // Create new state and restore
542        let mut new_state = RankState::<RowNumber>::new(&call);
543        new_state.enable_persistence();
544        new_state.restore(snapshot).unwrap();
545
546        // Continue from where we left off (row 3)
547        new_state.append(create_state_key(3, 102), SmallVec::new());
548        new_state.append(create_state_key(4, 103), SmallVec::new());
549
550        // Output should continue from rank 3
551        let (output3, _) = new_state.slide().unwrap();
552        assert_eq!(output3.unwrap(), 3i64.into());
553        let (output4, _) = new_state.slide().unwrap();
554        assert_eq!(output4.unwrap(), 4i64.into());
555    }
556
557    #[test]
558    fn test_rank_snapshot_restore_roundtrip() {
559        let call = create_call(WindowFuncKind::Rank);
560        let mut state = RankState::<Rank>::new(&call);
561        state.enable_persistence();
562
563        // Add rows with ties
564        state.append(create_state_key(1, 100), SmallVec::new());
565        state.append(create_state_key(2, 101), SmallVec::new());
566        state.append(create_state_key(2, 102), SmallVec::new()); // tie
567
568        // Output rows
569        let (output1, _) = state.slide().unwrap();
570        assert_eq!(output1.unwrap(), 1i64.into());
571        let (output2, _) = state.slide().unwrap();
572        assert_eq!(output2.unwrap(), 2i64.into()); // first in tie group
573        let (output3, _) = state.slide().unwrap();
574        assert_eq!(output3.unwrap(), 2i64.into()); // second in tie group
575
576        // Take snapshot
577        let snapshot = state.snapshot().unwrap();
578
579        // Create new state and restore
580        let mut new_state = RankState::<Rank>::new(&call);
581        new_state.enable_persistence();
582        new_state.restore(snapshot).unwrap();
583
584        // Add more rows
585        new_state.append(create_state_key(3, 103), SmallVec::new());
586
587        // Output should be rank 4 (since 2 items tied at rank 2)
588        let (output4, _) = new_state.slide().unwrap();
589        assert_eq!(output4.unwrap(), 4i64.into());
590    }
591
592    #[test]
593    fn test_dense_rank_snapshot_restore_roundtrip() {
594        let call = create_call(WindowFuncKind::DenseRank);
595        let mut state = RankState::<DenseRank>::new(&call);
596        state.enable_persistence();
597
598        // Add rows with ties
599        state.append(create_state_key(1, 100), SmallVec::new());
600        state.append(create_state_key(2, 101), SmallVec::new());
601        state.append(create_state_key(2, 102), SmallVec::new()); // tie
602
603        // Output rows
604        let (output1, _) = state.slide().unwrap();
605        assert_eq!(output1.unwrap(), 1i64.into());
606        let (output2, _) = state.slide().unwrap();
607        assert_eq!(output2.unwrap(), 2i64.into());
608        let (output3, _) = state.slide().unwrap();
609        assert_eq!(output3.unwrap(), 2i64.into()); // same rank due to tie
610
611        // Take snapshot
612        let snapshot = state.snapshot().unwrap();
613
614        // Create new state and restore
615        let mut new_state = RankState::<DenseRank>::new(&call);
616        new_state.enable_persistence();
617        new_state.restore(snapshot).unwrap();
618
619        // Add more rows
620        new_state.append(create_state_key(3, 103), SmallVec::new());
621
622        // Output should be rank 3 (dense rank increments by 1)
623        let (output4, _) = new_state.slide().unwrap();
624        assert_eq!(output4.unwrap(), 3i64.into());
625    }
626
627    #[test]
628    fn test_recovery_skip_logic() {
629        // Test that slide_no_output correctly skips counting for recovered rows
630        let call = create_call(WindowFuncKind::RowNumber);
631        let mut state = RankState::<RowNumber>::new(&call);
632        state.enable_persistence();
633
634        // Process initial rows
635        state.append(create_state_key(1, 100), SmallVec::new());
636        state.append(create_state_key(2, 101), SmallVec::new());
637        state.append(create_state_key(3, 102), SmallVec::new());
638
639        let (_, _) = state.slide().unwrap();
640        let (_, _) = state.slide().unwrap();
641
642        // Take snapshot after row 2
643        let snapshot = state.snapshot().unwrap();
644        assert_eq!(
645            snapshot.last_output_key.as_ref().unwrap(),
646            &create_state_key(2, 101)
647        );
648
649        // Create new state and restore
650        let mut new_state = RankState::<RowNumber>::new(&call);
651        new_state.enable_persistence();
652        new_state.restore(snapshot).unwrap();
653
654        // Simulate recovery: replay rows from state table
655        // First two rows should be skipped in slide_no_output
656        new_state.append(create_state_key(1, 100), SmallVec::new());
657        new_state.append(create_state_key(2, 101), SmallVec::new());
658        new_state.append(create_state_key(3, 102), SmallVec::new());
659        new_state.append(create_state_key(4, 103), SmallVec::new());
660
661        // Use slide_no_output for recovery (skips counting for rows <= snapshot key)
662        let _ = new_state.slide_no_output().unwrap();
663        let _ = new_state.slide_no_output().unwrap();
664
665        // Now output the remaining rows - should continue correctly
666        let (output3, _) = new_state.slide().unwrap();
667        assert_eq!(output3.unwrap(), 3i64.into());
668        let (output4, _) = new_state.slide().unwrap();
669        assert_eq!(output4.unwrap(), 4i64.into());
670    }
671
672    #[test]
673    fn test_eviction_hint_with_persistence() {
674        let call = create_call(WindowFuncKind::RowNumber);
675
676        // Test without persistence - should return CannotEvict
677        let mut state_no_persist = RankState::<RowNumber>::new(&call);
678        state_no_persist.append(create_state_key(1, 100), SmallVec::new());
679        let (_, evict_hint) = state_no_persist.slide().unwrap();
680        match evict_hint {
681            StateEvictHint::CannotEvict(_) => {}
682            StateEvictHint::CanEvict(_) => panic!("expected CannotEvict without persistence"),
683        }
684
685        // Test with persistence - should return CanEvict
686        let mut state_persist = RankState::<RowNumber>::new(&call);
687        state_persist.enable_persistence();
688        state_persist.append(create_state_key(1, 100), SmallVec::new());
689        let (_, evict_hint) = state_persist.slide().unwrap();
690        match evict_hint {
691            StateEvictHint::CanEvict(keys) => {
692                assert_eq!(keys.len(), 1);
693                assert!(keys.contains(&create_state_key(1, 100)));
694            }
695            StateEvictHint::CannotEvict(_) => panic!("expected CanEvict with persistence"),
696        }
697    }
698
699    #[test]
700    fn test_snapshot_returns_none_without_persistence() {
701        let call = create_call(WindowFuncKind::RowNumber);
702        let mut state = RankState::<RowNumber>::new(&call);
703        // Don't enable persistence
704        state.append(create_state_key(1, 100), SmallVec::new());
705        let (_, _) = state.slide().unwrap();
706
707        // Snapshot should return None
708        assert!(state.snapshot().is_none());
709    }
710
711    #[test]
712    fn test_restore_from_empty_starts_fresh() {
713        // Test that restoring with default state works correctly
714        let call = create_call(WindowFuncKind::RowNumber);
715        let mut state = RankState::<RowNumber>::new(&call);
716        state.enable_persistence();
717
718        // Create a snapshot with default func_state (prev_rank = 0)
719        let snapshot = WindowStateSnapshot {
720            last_output_key: None,
721            function_state: RowNumber::default().to_proto_state(),
722        };
723
724        state.restore(snapshot).unwrap();
725
726        // Add rows and verify output starts from 1
727        state.append(create_state_key(1, 100), SmallVec::new());
728        let (output, _) = state.slide().unwrap();
729        assert_eq!(output.unwrap(), 1i64.into());
730    }
731
732    #[test]
733    fn test_wrong_function_state_type_is_rejected() {
734        // Restoring a RowNumber state with a RankState payload should fail fast.
735        let call = create_call(WindowFuncKind::RowNumber);
736        let mut state = RankState::<RowNumber>::new(&call);
737        state.enable_persistence();
738
739        // Snapshot contains a RankState variant instead of RowNumberState.
740        let snapshot = WindowStateSnapshot {
741            last_output_key: None,
742            function_state: Rank::default().to_proto_state(),
743        };
744
745        assert!(state.restore(snapshot).is_err());
746    }
747}