fv-streams-ops 0.3.0

Stateful streaming operators for FusionVault Streams: event-time tumbling and sliding windows with keyed incremental aggregation, session windows, stream joins, top-N and last-N, watermarks and snapshots. Pure and synchronous — no I/O, no runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! # fv-streams-ops — stateful streaming operators
//!
//! The line between "fast stateless ETL" and "a streaming engine" is stateful, event-time operators:
//! windows, keyed state, watermarks, timers, and stream joins. DataFusion 54 has none of these
//! natively (an aggregate over an unbounded source refuses to plan or runs as batch-in-disguise —
//! proven by an earlier spike), so we build them.
//!
//! ## Event-time windows with keyed incremental aggregation
//!
//! - **event time** — each event carries a timestamp; windows are assigned by event time, not arrival.
//! - **window kinds** — **tumbling** (fixed, non-overlapping `[start, start+size)`) and **sliding**
//!   (overlapping: an event belongs to every window of width `size` stepping by `slide`, so `ceil(size/
//!   slide)` windows). Session windows (dynamic bounds + merging) are a separate operator.
//! - **keyed incremental aggregation** — one running accumulator per `(window, group-key)`, updated
//!   O(1) per event per window it lands in. (We evaluated reusing `fv_plan::reshape::aggregate` — batch
//!   GROUP-BY on DataFusion per closed window — but incremental accumulators are the right streaming
//!   shape: O(1)/event and O(keys × live-windows) memory instead of buffering every row, with no
//!   per-window query spin-up. The batch-reuse path stays for future *arbitrary-SQL* windowed transforms.)
//! - **watermark-driven firing** — the watermark is `max-event-time − allowed-lateness`; a window fires
//!   (emits + evicts) once its end is `≤` the watermark, so late-but-in-lateness events still land and
//!   genuinely late events (their window already fired) are dropped and counted.
//!
//! The core is pure and synchronous — no I/O, no runtime — so it unit-tests in isolation and the stream
//! worker drives it (feed `push`, drain `advance` after each batch, `flush` on shutdown).

/// Every Rust code block in the README is compiled and run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

use std::collections::HashMap;

use fv_value::Value;

mod acc;
pub mod batch_join;
pub mod batch_window;
mod join;
pub mod lookup_join;
mod rank;
mod session;
pub mod sharded_window;
mod snapshot;
mod watermark;
use acc::Acc;
pub use batch_join::{FrozenFile, StreamJoinBatch};
pub use batch_window::{BatchOperator, WindowAggBatch};
pub use join::{Side, StreamJoin};
pub use lookup_join::LookupJoinBatch;
pub use rank::{LastN, TopN};
pub use session::SessionAgg;
pub use sharded_window::ShardedWindow;
pub mod error;
pub use error::{state_fault, StateError};
use watermark::Watermark;

/// The common interface a windowing operator exposes to the stream worker: feed events with `push`,
/// drain the windows the advancing watermark has closed with `advance`, `flush` everything on shutdown,
/// and register the read partitions so the (min-across-partitions) watermark holds until all report.
/// Implemented by [`WindowAgg`] (tumbling/sliding) and [`SessionAgg`] (session) so the worker drives
/// either through one path.
pub trait WindowOperator {
    /// Register the read partitions at processing time `now_ms` (drives bounded-idleness timers).
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64);
    /// Ingest one event from `partition`; returns `false` if it was dropped as genuinely late.
    fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, Value)]) -> bool;
    /// Ingest a whole batch from `partition` (`event_ms[i]` is row `i`'s event time). Returns the
    /// number of genuinely late rows, or `None` when this operator has no batch path (the engine
    /// then pushes row by row). The columnar operators answer this; the row operators do not.
    fn push_batch(&mut self, _partition: i32, _batch: &arrow::array::RecordBatch, _event_ms: &[i64]) -> Option<usize> {
        None
    }
    /// Fire the closed windows as a batch, or `None` when this operator has no batch path (the
    /// engine then takes the `WindowRow`s from `advance`). Columnar operators answer this.
    fn advance_batch(&mut self, _now_ms: i64) -> Option<Option<arrow::array::RecordBatch>> {
        None
    }
    /// Fire every remaining window as a batch on shutdown, or `None` when there is no batch path.
    fn flush_batch(&mut self) -> Option<Option<arrow::array::RecordBatch>> {
        None
    }
    /// Fire (emit + evict) every window the current watermark has closed, at processing time `now_ms`.
    fn advance(&mut self, now_ms: i64) -> Vec<WindowRow>;
    /// Fire every window closed by a watermark delivered from upstream (`watermark_ms`, already the
    /// minimum across the operator's inputs), less this operator's allowed lateness. The rows'
    /// own event times do not move time here — the caller's watermark does — so a fast input can
    /// never fire a window ahead of a slow one.
    fn advance_to(&mut self, watermark_ms: i64) -> Vec<WindowRow>;
    /// `advance_to` as a batch, or `None` when there is no batch path.
    fn advance_batch_to(&mut self, _watermark_ms: i64) -> Option<Option<arrow::array::RecordBatch>> {
        None
    }
    /// Fire ALL remaining windows regardless of watermark (clean shutdown).
    fn flush(&mut self) -> Vec<WindowRow>;
    /// Bytes of resident dynamic state (accumulators, interning) — for a memory budget. `0` if the
    /// operator does not account it (it then never triggers eviction).
    fn state_bytes(&self) -> usize {
        0
    }
    /// How many windows are still open (unfired). A shard with none is pure interning: it can be
    /// frozen and skipped by firing until a late key reopens it. `0` by default.
    fn open_windows(&self) -> usize {
        0
    }
    /// serialize the operator's DYNAMIC state (versioned envelope, config-fingerprinted). An `Err`
    /// is a state-tier fault (a frozen shard's file could not be read); the engine fails the
    /// checkpoint — and the build — with it, naming the task.
    fn snapshot(&mut self) -> Result<Vec<u8>, StateError>;
    /// restore dynamic state into this freshly-configured operator. Refuses (loudly) a snapshot
    /// from a different operator kind, snapshot version, or operator configuration.
    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String>;

    /// `true` when this operator checkpoints as one file per shard ([`snapshot_shard_files`]), so
    /// the barrier never materialises the whole state as a single object. `false` by default (the
    /// caller serialises the whole [`snapshot`] instead).
    ///
    /// [`snapshot_shard_files`]: WindowOperator::snapshot_shard_files
    /// [`snapshot`]: WindowOperator::snapshot
    fn shard_files_supported(&self) -> bool {
        false
    }
    /// Write this operator's state as ONE FILE PER SHARD into `dir`, each named `<tag>-<shard>.arrow`,
    /// returning `(shard_index, path)` for every shard. The whole state is never held in memory at
    /// once — a single shard's bytes are the peak. Only meaningful when [`shard_files_supported`];
    /// the default panics (the caller must gate on that flag).
    ///
    /// [`shard_files_supported`]: WindowOperator::shard_files_supported
    fn snapshot_shard_files(
        &mut self,
        _dir: &std::path::Path,
        _tag: &str,
    ) -> Result<Vec<(usize, std::path::PathBuf)>, StateError> {
        unreachable!("snapshot_shard_files without shard_files_supported")
    }
    /// Rebuild from the files [`snapshot_shard_files`] produced — `(shard_index, local_path)`, each
    /// already placed on disk by the caller. Bounded to one shard's bytes at a time.
    ///
    /// [`snapshot_shard_files`]: WindowOperator::snapshot_shard_files
    fn load_shard_files(&mut self, _files: &[(usize, std::path::PathBuf)]) -> Result<(), String> {
        Err("this operator does not support file-backed restore".into())
    }
}

impl WindowOperator for WindowAgg {
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        WindowAgg::expect_partitions(self, partitions, now_ms)
    }
    fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, Value)]) -> bool {
        WindowAgg::push(self, partition, event_ms, row)
    }
    fn advance(&mut self, now_ms: i64) -> Vec<WindowRow> {
        WindowAgg::advance(self, now_ms)
    }
    fn advance_to(&mut self, watermark_ms: i64) -> Vec<WindowRow> {
        WindowAgg::advance_to(self, watermark_ms)
    }
    fn flush(&mut self) -> Vec<WindowRow> {
        WindowAgg::flush(self)
    }
    fn snapshot(&mut self) -> Result<Vec<u8>, StateError> {
        Ok(WindowAgg::snapshot(self))
    }
    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        WindowAgg::load_snapshot(self, bytes)
    }
}

/// The aggregation op applied to a column within each window+key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggOp {
    Count,
    Sum,
    Avg,
    Min,
    Max,
    /// Exact distinct count of a column's non-null values per (window, group) — a per-accumulator
    /// value-set (unlocks Nexmark q15-style reports). Memory bound: distinct values per group
    /// per open window — document the cardinality when using it.
    CountDistinct,
    // FUNC-2: incremental aggregates, all O(1)/event and mergeable (session bridging).
    /// Population / sample variance + standard deviation over a numeric column, via Welford's
    /// online algorithm (numerically stable, parallel-mergeable). Samp needs ≥2 values (else null).
    VarPop,
    VarSamp,
    StddevPop,
    StddevSamp,
    /// Boolean AND / OR fold over a boolean column (`true` until a `false` for And; mirror for Or).
    BoolAnd,
    BoolOr,
    /// Bitwise AND / OR / XOR fold over an integer column (values must be whole numbers).
    BitAnd,
    BitOr,
    BitXor,
}

impl AggOp {
    /// The variance/stddev family — the ops that need Welford side-state.
    pub(crate) fn is_variance(self) -> bool {
        matches!(
            self,
            AggOp::VarPop | AggOp::VarSamp | AggOp::StddevPop | AggOp::StddevSamp
        )
    }
}

/// One named aggregation: `op` over `column` (ignored for `Count`), output under `alias`.
#[derive(Debug, Clone)]
pub struct Agg {
    pub op: AggOp,
    pub column: String,
    pub alias: String,
}

impl Agg {
    pub fn count(alias: impl Into<String>) -> Self {
        Self {
            op: AggOp::Count,
            column: String::new(),
            alias: alias.into(),
        }
    }
    pub fn of(op: AggOp, column: impl Into<String>, alias: impl Into<String>) -> Self {
        Self {
            op,
            column: column.into(),
            alias: alias.into(),
        }
    }
}

/// How an event time maps to windows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowKind {
    /// Fixed, non-overlapping `[start, start+size)`.
    Tumbling { size_ms: i64 },
    /// Overlapping: windows of width `size` stepping by `slide` (`slide ≤ size`; `slide == size` is
    /// tumbling).
    Sliding { size_ms: i64, slide_ms: i64 },
}

impl WindowKind {
    pub(crate) fn size(&self) -> i64 {
        match self {
            WindowKind::Tumbling { size_ms } | WindowKind::Sliding { size_ms, .. } => *size_ms,
        }
    }

    /// The starts of every window an event time belongs to (one for tumbling; `ceil(size/slide)` for
    /// sliding — the slide-aligned starts `s` with `s ≤ t < s+size`).
    pub fn starts_for(&self, t: i64) -> Vec<i64> {
        match self {
            WindowKind::Tumbling { size_ms } => vec![t.div_euclid(*size_ms) * size_ms],
            WindowKind::Sliding { size_ms, slide_ms } => {
                let mut starts = Vec::new();
                let mut s = t.div_euclid(*slide_ms) * slide_ms; // latest slide-aligned start ≤ t
                while s > t - size_ms {
                    starts.push(s);
                    s -= slide_ms;
                }
                starts
            }
        }
    }
}

/// When an **updating** windowed aggregate EARLY-FIRES: emits the current (partial) value of its
/// still-open windows as upserts, before the watermark closes them. An early emission carries the
/// same `window_start`/`window_end`/group as the eventual closing fire, so its emission key
/// (`w|start|end|group`) is identical and downstream last-write-wins converges to the exact closing
/// value. The contract is therefore **eventual correctness between fires, exact at close** — the
/// closing fire is always the last write for a `(window, group)`.
///
/// `OnWatermark` (the default) never early-fires: the operator is byte-identical to a plain windowed
/// aggregate, so an existing pipeline (and its checkpoints) are untouched.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Trigger {
    /// No early firing — windows emit once, when the watermark closes them (today's behaviour).
    #[default]
    OnWatermark,
    /// Early-fire after every `n` ingested rows since the last fire. DATA-DRIVEN: the final value is
    /// exact and the emission sequence replays identically whenever batch boundaries are stable (the
    /// partition's row order is its log order). The cheap, deterministic default for early firing.
    EveryRows(u64),
    /// Early-fire once `ms` of PROCESSING time have passed since the last fire. Wall-clock, so the
    /// *intermediate* emissions are not byte-replayable (only the closing value is), exactly like an
    /// ingest-time window. Fires on a processing-time advance/tick, so it is best-effort under an
    /// in-band (watermark-driven) task.
    EveryMs(i64),
}

impl Trigger {
    /// A stable fingerprint fragment for the operator config. **Empty for [`OnWatermark`]** so an
    /// existing (on-watermark) checkpoint's fingerprint is byte-identical — a restore never regresses.
    ///
    /// [`OnWatermark`]: Trigger::OnWatermark
    pub(crate) fn fingerprint(&self) -> String {
        match self {
            Trigger::OnWatermark => String::new(),
            Trigger::EveryRows(n) => format!(";trigger=rows({n})"),
            Trigger::EveryMs(ms) => format!(";trigger=ms({ms})"),
        }
    }
    /// Whether this trigger ever emits before a window closes (drives the zero-cost fast path: when
    /// `false`, no dirty-key tracking and no early-fire pass run at all).
    pub(crate) fn early_fires(&self) -> bool {
        !matches!(self, Trigger::OnWatermark)
    }
}

/// One fired window's aggregated output for one group key.
#[derive(Debug, Clone, PartialEq)]
pub struct WindowRow {
    /// Window bounds (epoch-ms), half-open `[start, end)`.
    pub window_start: i64,
    pub window_end: i64,
    /// The group-by column values, in `group_by` order.
    pub key: Vec<Value>,
    /// The aggregated outputs: `(alias, value)`, in `aggs` order.
    pub aggs: Vec<(String, Value)>,
}

/// An event-time windowed aggregator. Feed events with [`push`](Self::push); after a batch, drain the
/// windows the advancing watermark has closed with [`advance`](Self::advance); [`flush`](Self::flush)
/// fires everything on shutdown.
pub struct WindowAgg {
    kind: WindowKind,
    group_by: Vec<String>,
    aggs: Vec<Agg>,
    /// T2 (memory diet): group keys are INTERNED — `key_ids` maps a composite key string to a dense
    /// id; `key_data` stores the composite + emission values ONCE per distinct key. Open windows
    /// reference keys by id, so per-(window, key) state is a slim `Acc` under an `(i64, u32)` map
    /// key instead of duplicated string/value vectors. The intern table grows with DISTINCT keys
    /// ever seen (~100B each), not with open windows.
    key_ids: HashMap<String, u32>,
    key_data: Vec<(String, Vec<Value>)>,
    state: HashMap<(i64, u32), Acc>,
    /// Precomputed `needs_sets(&aggs)` so per-event accumulator creation never rescans the agg list.
    with_sets: bool,
    with_welford: bool,
    /// Per-partition event-time watermark (min-across-partitions − lateness); see `Watermark`.
    wm: Watermark,
    /// Watermark of the last fire — a window whose end `≤` this has already fired.
    fired_through: i64,
    /// Events wholly dropped because every window they'd land in had already fired (genuinely late).
    late_dropped: u64,
}

impl WindowAgg {
    /// A tumbling aggregator: `size_ms` window width, `allowed_lateness_ms` grace before a window fires.
    pub fn tumbling(size_ms: i64, allowed_lateness_ms: i64, group_by: Vec<String>, aggs: Vec<Agg>) -> Self {
        assert!(size_ms > 0, "window size must be > 0");
        Self::new(WindowKind::Tumbling { size_ms }, allowed_lateness_ms, group_by, aggs)
    }

    /// A sliding aggregator: `size_ms` width stepping by `slide_ms` (`0 < slide ≤ size`).
    pub fn sliding(
        size_ms: i64,
        slide_ms: i64,
        allowed_lateness_ms: i64,
        group_by: Vec<String>,
        aggs: Vec<Agg>,
    ) -> Self {
        assert!(
            size_ms > 0 && slide_ms > 0 && slide_ms <= size_ms,
            "sliding needs 0 < slide ≤ size"
        );
        Self::new(
            WindowKind::Sliding { size_ms, slide_ms },
            allowed_lateness_ms,
            group_by,
            aggs,
        )
    }

    fn new(kind: WindowKind, allowed_lateness_ms: i64, group_by: Vec<String>, aggs: Vec<Agg>) -> Self {
        let with_sets = acc::needs_sets(&aggs);
        let with_welford = acc::needs_welford(&aggs);
        Self {
            kind,
            group_by,
            aggs,
            key_ids: HashMap::new(),
            key_data: Vec::new(),
            state: HashMap::new(),
            with_sets,
            with_welford,
            wm: Watermark::new(allowed_lateness_ms),
            fired_through: i64::MIN,
            late_dropped: 0,
        }
    }

    /// Enable bounded idleness: a partition silent longer than `idle_timeout_ms` (processing time)
    /// stops holding the watermark back. `<= 0` leaves it disabled. See `Watermark`.
    pub fn with_idle_timeout(mut self, idle_timeout_ms: i64) -> Self {
        self.wm = self.wm.with_idle_timeout(idle_timeout_ms);
        self
    }

    /// The current watermark at processing time `now_ms` (min across ACTIVE partitions − lateness);
    /// `i64::MIN` until every seen/assigned partition has produced an event, or when all are idle. See
    /// `Watermark`.
    pub fn watermark(&self, now_ms: i64) -> i64 {
        self.wm.current(now_ms)
    }

    pub fn late_dropped(&self) -> u64 {
        self.late_dropped
    }

    /// Register the partitions this operator will read at processing time `now_ms` so the watermark
    /// holds until each has reported (see `Watermark::expect`). Call it as the assignment is learned.
    pub fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        self.wm.expect(partitions, now_ms);
    }

    /// Ingest one event from `partition` at `event_ms` with a row (`&[(column, value)]` — a
    /// `fv_plan::Row`'s `.0`). Adds it to every not-yet-fired window it belongs to. Returns `false` if
    /// it was wholly late (all of its windows had already fired). The `partition` drives per-partition
    /// watermark tracking — a consumer reading several partitions won't fire ahead of its slowest one.
    pub fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, Value)]) -> bool {
        self.wm.observe(partition, event_ms);
        let size = self.kind.size();
        // ONE composite-string build per event (the hot path's only allocation on the hit path);
        // the emission values are built only the first time a key is seen.
        let composite = acc::composite_of(row, &self.group_by);
        let id = match self.key_ids.get(&composite) {
            Some(&id) => id,
            None => {
                let id = self.key_data.len() as u32;
                self.key_data
                    .push((composite.clone(), acc::vals_of(row, &self.group_by)));
                self.key_ids.insert(composite, id);
                id
            }
        };
        let (n_aggs, with_sets, with_welford) = (self.aggs.len(), self.with_sets, self.with_welford);

        let mut added = false;
        for start in self.kind.starts_for(event_ms) {
            if start + size <= self.fired_through {
                continue; // this window already fired — skip it (late for this window)
            }
            added = true;
            self.state
                .entry((start, id))
                .or_insert_with(|| Acc::new(n_aggs, with_sets, with_welford))
                .add(&self.aggs, row);
        }
        if !added {
            self.late_dropped += 1;
        }
        added
    }

    /// Fire every window whose end is `≤` the watermark at processing time `now_ms`: emit one
    /// [`WindowRow`] per `(window, key)`, evict them, record the watermark as fired-through. Ordered by
    /// `(start, key)`. `now_ms` advances the bounded-idleness timers before the watermark is read.
    pub fn advance(&mut self, now_ms: i64) -> Vec<WindowRow> {
        self.wm.tick(now_ms);
        let wm = self.wm.current(now_ms);
        self.fire_through(wm)
    }

    /// Fire every window whose end is `≤` a watermark delivered from upstream, less the allowed
    /// lateness; the rows' own times play no part.
    pub fn advance_to(&mut self, watermark_ms: i64) -> Vec<WindowRow> {
        let wm = self.wm.after_lateness(watermark_ms);
        self.fire_through(wm)
    }

    fn fire_through(&mut self, wm: i64) -> Vec<WindowRow> {
        if wm == i64::MIN {
            return Vec::new();
        }
        self.fire(|start, size| start + size <= wm, Some(wm))
    }

    /// Fire ALL remaining windows regardless of watermark — a clean shutdown/flush so no buffered
    /// window is lost when the stream ends.
    pub fn flush(&mut self) -> Vec<WindowRow> {
        self.fired_through = i64::MAX;
        self.fire(|_, _| true, None)
    }

    fn fire(&mut self, ready: impl Fn(i64, i64) -> bool, set_fired_through: Option<i64>) -> Vec<WindowRow> {
        let size = self.kind.size();
        let keys: Vec<(i64, u32)> = self
            .state
            .keys()
            .filter(|(start, _)| ready(*start, size))
            .copied()
            .collect();
        let mut fired: Vec<((i64, u32), Acc)> = Vec::with_capacity(keys.len());
        for k in keys {
            if let Some(acc) = self.state.remove(&k) {
                fired.push((k, acc));
            }
        }
        if let Some(wm) = set_fired_through {
            self.fired_through = self.fired_through.max(wm);
        }
        // Deterministic emission order: (start, composite key string) — same ordering rule as before
        // interning (the composite IS the old per-column key vector, joined).
        fired.sort_by(|a, b| {
            a.0 .0
                .cmp(&b.0 .0)
                .then_with(|| self.key_data[a.0 .1 as usize].0.cmp(&self.key_data[b.0 .1 as usize].0))
        });
        fired
            .into_iter()
            .map(|((start, id), acc)| WindowRow {
                window_start: start,
                window_end: start + size,
                aggs: acc.finalize_aggs(&self.aggs),
                key: self.key_data[id as usize].1.clone(),
            })
            .collect()
    }

    // ── snapshot/restore (see `snapshot` module). ──

    fn cfg_fingerprint(&self) -> String {
        format!(
            "kind={:?};group_by={:?};aggs={:?};{}",
            self.kind,
            self.group_by,
            self.aggs,
            self.wm.cfg_fingerprint()
        )
    }

    /// Serialize the DYNAMIC state: open windows, watermark timers, fired-through, late count.
    /// FORMAT 2 (T2): keys referenced by open state are written ONCE (`keys`), accumulators as
    /// compact tuples referencing them by index — smaller and faster than the v1 per-acc objects.
    pub fn snapshot(&self) -> Vec<u8> {
        use serde_json::json;
        // Dense re-index: only keys with open state travel (the intern table itself does not).
        let mut snap_idx: HashMap<u32, usize> = HashMap::new();
        let mut keys: Vec<serde_json::Value> = Vec::new();
        let mut state: Vec<serde_json::Value> = Vec::with_capacity(self.state.len());
        for ((start, id), acc) in &self.state {
            let idx = *snap_idx.entry(*id).or_insert_with(|| {
                let (composite, vals) = &self.key_data[*id as usize];
                keys.push(json!([
                    composite,
                    vals.iter().map(fv_value::value_to_json).collect::<Vec<_>>()
                ]));
                keys.len() - 1
            });
            state.push(json!([start, idx, snapshot::acc_to_json_v2(acc)]));
        }
        snapshot::envelope(
            "window",
            &self.cfg_fingerprint(),
            json!({
                "format": 2,
                "keys": keys,
                "state": state,
                "wm": self.wm.state_to_json(),
                "fired_through": self.fired_through,
                "late_dropped": self.late_dropped,
            }),
        )
    }

    /// Intern a composite key with known emission values, returning its id (load path + tests).
    fn intern(&mut self, composite: String, vals: Vec<Value>) -> u32 {
        match self.key_ids.get(&composite) {
            Some(&id) => id,
            None => {
                let id = self.key_data.len() as u32;
                self.key_data.push((composite.clone(), vals));
                self.key_ids.insert(composite, id);
                id
            }
        }
    }

    /// Restore dynamic state into this freshly-configured aggregator (config mismatch refused).
    /// DUAL-READ: format 2 (interned, current) and the pre-T2 format 1 (per-acc objects with the
    /// group key embedded) — old checkpoints MUST load correctly across the upgrade; refusing them
    /// would silently lose consumed-but-unfired rows.
    pub fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        let s = snapshot::open_envelope("window", &self.cfg_fingerprint(), bytes)?;
        let mut map = HashMap::new();
        if s["format"].as_i64() == Some(2) {
            let key_entries = s["keys"].as_array().ok_or("window snapshot v2: keys not an array")?;
            let mut ids = Vec::with_capacity(key_entries.len());
            for e in key_entries {
                let t = e
                    .as_array()
                    .filter(|a| a.len() == 2)
                    .ok_or("window snapshot v2: bad key entry")?;
                let composite = t[0].as_str().ok_or("window snapshot v2: bad composite")?.to_string();
                let vals: Vec<Value> = t[1]
                    .as_array()
                    .ok_or("window snapshot v2: bad key vals")?
                    .iter()
                    .map(fv_value::json_to_value)
                    .collect();
                ids.push(self.intern(composite, vals));
            }
            for e in s["state"].as_array().ok_or("window snapshot v2: state not an array")? {
                let a = e
                    .as_array()
                    .filter(|a| a.len() == 3)
                    .ok_or("window snapshot v2: bad state entry")?;
                let start = a[0].as_i64().ok_or("window snapshot v2: bad window start")?;
                let idx = a[1].as_u64().ok_or("window snapshot v2: bad key index")? as usize;
                let id = *ids.get(idx).ok_or("window snapshot v2: key index out of range")?;
                map.insert((start, id), snapshot::acc_from_json_v2(&a[2])?);
            }
        } else {
            for e in s["state"].as_array().ok_or("window snapshot: state not an array")? {
                let a = e
                    .as_array()
                    .filter(|a| a.len() == 3)
                    .ok_or("window snapshot: bad state entry")?;
                let start = a[0].as_i64().ok_or("window snapshot: bad window start")?;
                let gk: Vec<String> = a[1]
                    .as_array()
                    .ok_or("window snapshot: bad group key")?
                    .iter()
                    .map(|s| {
                        s.as_str()
                            .map(String::from)
                            .ok_or_else(|| "window snapshot: bad group key part".to_string())
                    })
                    .collect::<Result<_, _>>()?;
                let (vals, acc) = snapshot::acc_from_json_v1(&a[2])?;
                let id = self.intern(gk.join("\u{1}"), vals);
                map.insert((start, id), acc);
            }
        }
        self.state = map;
        self.wm.load_state(&s["wm"])?;
        self.fired_through = s["fired_through"]
            .as_i64()
            .ok_or("window snapshot: missing fired_through")?;
        self.late_dropped = s["late_dropped"]
            .as_u64()
            .ok_or("window snapshot: missing late_dropped")?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn row(pairs: &[(&str, Value)]) -> Vec<(String, Value)> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }
    fn num(w: &WindowRow, alias: &str) -> f64 {
        match &w.aggs.iter().find(|(a, _)| a == alias).unwrap().1 {
            Value::Num(n) => *n,
            other => panic!("expected num for {alias}, got {other:?}"),
        }
    }

    #[test]
    fn v1_snapshot_loads_and_fires_identically_after_the_t2_upgrade() {
        // THE UPGRADE CONTRACT: a pre-T2 checkpoint (per-acc objects, embedded keys) must restore
        // into the interned layout and fire the same windows — refusing or misreading it would
        // silently lose consumed-but-unfired rows across a deploy.
        let mk = || {
            WindowAgg::tumbling(
                1000,
                0,
                vec!["k".into()],
                vec![Agg::count("n"), Agg::of(AggOp::Sum, "amount", "total")],
            )
        };
        let op = mk();
        // A v1 snapshot as the pre-T2 code wrote it (envelope v1, no "format", gk = value_key parts).
        let v1 = serde_json::json!({
            "v": 1,
            "kind": "window",
            "cfg": op.cfg_fingerprint(),
            "state": {
                "state": [
                    [0i64, ["sa"], {"key": ["a"], "count": 2, "slots": [null, 7.0]}],
                    [0i64, ["sb"], {"key": ["b"], "count": 1, "slots": [null, 3.0]}],
                    [1000i64, ["sa"], {"key": ["a"], "count": 5, "slots": [null, 50.0]}],
                ],
                "wm": {"part_max": {"0": 1500}, "last_activity": {"0": 0}, "last_seen_max": {"0": 1500}},
                "fired_through": i64::MIN,
                "late_dropped": 0,
            },
        });
        let mut restored = mk();
        restored
            .load_snapshot(&serde_json::to_vec(&v1).unwrap())
            .expect("a v1 snapshot must load");
        let fired = restored.flush();
        assert_eq!(fired.len(), 3);
        let w0a = fired
            .iter()
            .find(|w| w.window_start == 0 && w.key == vec![Value::Str("a".into())])
            .unwrap();
        assert_eq!(num(w0a, "n"), 2.0);
        assert_eq!(num(w0a, "total"), 7.0);
        let w1a = fired
            .iter()
            .find(|w| w.window_start == 1000 && w.key == vec![Value::Str("a".into())])
            .unwrap();
        assert_eq!(num(w1a, "n"), 5.0);
        assert_eq!(num(w1a, "total"), 50.0);
    }

    #[test]
    fn v2_snapshot_stores_each_key_once_across_windows() {
        // The T2 point, asserted structurally: many open windows for one key must serialize the key
        // ONCE (v1 embedded it per window — the measured 3.4KB/acc pathology).
        let mut op = WindowAgg::tumbling(1000, 1_000_000, vec!["k".into()], vec![Agg::count("n")]);
        op.expect_partitions(&[0], 0);
        for w in 0..100i64 {
            op.push(
                0,
                w * 1000,
                &row(&[
                    ("k", Value::Str("the-only-key-string".into())),
                    ("amount", Value::Num(1.0)),
                ]),
            );
        }
        let snap = op.snapshot();
        let text = String::from_utf8(snap).unwrap();
        assert_eq!(
            text.matches("the-only-key-string").count(),
            2,
            "once in the composite, once in the vals — never per window"
        );
        // And the accumulator side stays set-free for scalar aggs (the lazy-sets guarantee).
        assert!(!text.contains("\"sets\""), "v2 tuples carry null, not a sets field");
    }

    #[test]
    fn tumbling_window_assignment_is_by_event_time() {
        let k = WindowKind::Tumbling { size_ms: 1000 };
        assert_eq!(k.starts_for(0), vec![0]);
        assert_eq!(k.starts_for(999), vec![0]);
        assert_eq!(k.starts_for(1000), vec![1000]);
        assert_eq!(k.starts_for(2500), vec![2000]);
    }

    #[test]
    fn sliding_window_assignment_covers_overlapping_windows() {
        let k = WindowKind::Sliding {
            size_ms: 1000,
            slide_ms: 500,
        };
        // t=750 → windows [500,1500) and [0,1000).
        assert_eq!(k.starts_for(750), vec![500, 0]);
        // t=1200 → [1000,2000) and [500,1500).
        assert_eq!(k.starts_for(1200), vec![1000, 500]);
        // t=0 → [0,1000) and [-500,500) both contain 0.
        assert_eq!(k.starts_for(0), vec![0, -500]);
    }

    #[test]
    fn aggregates_count_sum_avg_min_max_within_a_tumbling_window() {
        let aggs = vec![
            Agg::count("n"),
            Agg::of(AggOp::Sum, "amount", "total"),
            Agg::of(AggOp::Avg, "amount", "mean"),
            Agg::of(AggOp::Min, "amount", "lo"),
            Agg::of(AggOp::Max, "amount", "hi"),
        ];
        let mut w = WindowAgg::tumbling(1000, 0, vec![], aggs);
        for (t, a) in [(10, 2.0), (20, 4.0), (30, 6.0)] {
            w.push(0, t, &row(&[("amount", Value::Num(a))]));
        }
        w.push(0, 1500, &row(&[("amount", Value::Num(99.0))])); // advance watermark past window 0
        let out = w.advance(0);
        assert_eq!(out.len(), 1);
        let r = &out[0];
        assert_eq!((r.window_start, r.window_end), (0, 1000));
        assert_eq!(num(r, "n"), 3.0);
        assert_eq!(num(r, "total"), 12.0);
        assert_eq!(num(r, "mean"), 4.0);
        assert_eq!(num(r, "lo"), 2.0);
        assert_eq!(num(r, "hi"), 6.0);
    }

    #[test]
    fn sliding_event_lands_in_every_overlapping_window() {
        // size 1000, slide 500. Events at 100, 300, 700 → window [0,1000) has all 3; [500,1500) has 700.
        let mut w = WindowAgg::sliding(1000, 500, 0, vec![], vec![Agg::count("n")]);
        for t in [100, 300, 700] {
            w.push(0, t, &row(&[]));
        }
        w.push(0, 2200, &row(&[])); // watermark 2200 → windows ending ≤ 2200 fire: [0,1000),[500,1500),[1000,2000),[1500,2500)? end 2500>2200 no
        let mut out = w.advance(0);
        out.sort_by_key(|r| r.window_start);
        let w0 = out.iter().find(|r| r.window_start == 0).unwrap();
        let w500 = out.iter().find(|r| r.window_start == 500).unwrap();
        assert_eq!(num(w0, "n"), 3.0, "[0,1000) saw 100,300,700");
        assert_eq!(num(w500, "n"), 1.0, "[500,1500) saw only 700");
    }

    #[test]
    fn separate_windows_and_keys_do_not_mix() {
        let mut w = WindowAgg::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[("k", Value::Str("a".into()))]));
        w.push(0, 200, &row(&[("k", Value::Str("b".into()))]));
        w.push(0, 300, &row(&[("k", Value::Str("a".into()))]));
        w.push(0, 1100, &row(&[("k", Value::Str("a".into()))]));
        let out = w.advance(0);
        assert_eq!(out.len(), 2);
        let a = out.iter().find(|r| r.key == vec![Value::Str("a".into())]).unwrap();
        let b = out.iter().find(|r| r.key == vec![Value::Str("b".into())]).unwrap();
        assert_eq!(num(a, "n"), 2.0);
        assert_eq!(num(b, "n"), 1.0);
    }

    #[test]
    fn allowed_lateness_holds_a_window_open() {
        let mut w = WindowAgg::tumbling(1000, 500, vec![], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[]));
        w.push(0, 1200, &row(&[])); // watermark 700 < 1000 → not fired
        assert!(w.advance(0).is_empty());
        w.push(0, 1600, &row(&[])); // watermark 1100 ≥ 1000 → fires
        assert_eq!(w.advance(0).len(), 1);
    }

    #[test]
    fn genuinely_late_events_are_dropped_and_counted() {
        let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[]));
        w.push(0, 1500, &row(&[]));
        assert_eq!(w.advance(0).len(), 1);
        assert!(!w.push(0, 200, &row(&[])), "late event rejected");
        assert_eq!(w.late_dropped(), 1);
        assert!(w.push(0, 1600, &row(&[])));
    }

    #[test]
    fn sliding_streaming_scenario_counts_every_window_exactly() {
        // The real streaming pattern: monotonic ts, 1 event/ts, advance after each batch. Every full
        // window [s, s+1000) must see exactly 1000 events (ts s..s+999) — no half-counts, none missing.
        let mut w = WindowAgg::sliding(1000, 500, 0, vec![], vec![Agg::count("n")]);
        let mut fired: std::collections::HashMap<i64, f64> = std::collections::HashMap::new();
        let mut t = 0i64;
        for _batch in 0..16 {
            for _ in 0..250 {
                w.push(0, t, &[]);
                t += 1;
            }
            for r in w.advance(0) {
                fired.insert(r.window_start, num(&r, "n"));
            }
        }
        for r in w.flush() {
            fired.insert(r.window_start, num(&r, "n"));
        }
        // Full windows in the interior must each have exactly 1000 events.
        for s in [1000_i64, 1500, 2000, 2500, 3000] {
            assert_eq!(
                fired.get(&s),
                Some(&1000.0),
                "window [{s},{}) should have 1000 events",
                s + 1000
            );
        }
    }

    #[test]
    fn multi_partition_watermark_is_the_min_so_a_lagging_partition_holds_firing() {
        // The bug this guards against: a consumer reading several partitions must NOT fire a window
        // ahead of its slowest partition, or the lagging partition's events get dropped as late.
        let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[]));
        w.push(0, 5000, &row(&[])); // partition 0 races ahead…
        w.push(1, 100, &row(&[])); // …partition 1 lags at 100.
                                   // watermark = min(5000, 100) = 100 → window 0 must NOT fire (else p1's later events are lost).
        assert!(w.advance(0).is_empty(), "the lagging partition holds the watermark");
        w.push(1, 1500, &row(&[])); // p1 catches up past window 0.
        let out = w.advance(0); // watermark = min(5000, 1500) = 1500 → window 0 fires with BOTH events.
        assert_eq!(out.len(), 1);
        assert_eq!(
            num(&out[0], "n"),
            2.0,
            "both partitions' ts-100 events counted, none dropped"
        );
    }

    #[test]
    fn expected_but_unseen_partition_holds_the_watermark() {
        // A consumer that drains one partition before polling another must not fire on the first alone.
        let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        w.expect_partitions(&[0, 1], 0);
        w.push(0, 100, &row(&[])); // an event in window [0,1000) on partition 0
        w.push(0, 5000, &row(&[])); // partition 0 races ahead; partition 1 has no events yet
        assert!(
            w.advance(0).is_empty(),
            "unseen assigned partition 1 pins the watermark → nothing fires"
        );
        w.push(1, 5000, &row(&[])); // partition 1 finally reports → min watermark = 5000
        let out = w.advance(0);
        assert_eq!(out.len(), 1, "now both seen → window [0,1000) fires");
        assert_eq!(num(&out[0], "n"), 1.0, "with its one event, not dropped");
    }

    #[test]
    fn flush_fires_all_remaining_windows() {
        let mut w = WindowAgg::tumbling(1000, 10_000, vec![], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[]));
        w.push(0, 5000, &row(&[]));
        assert!(w.advance(0).is_empty());
        assert_eq!(w.flush().len(), 2);
    }

    #[test]
    fn snapshot_restore_fires_identically_to_the_uninterrupted_run() {
        // The checkpoint contract: restore + replay of the tail must fire BYTE-IDENTICALLY to a run that was
        // never interrupted — including mid-stream firing, fired_through, late drops, and watermarks.
        let mk = || {
            let mut w = WindowAgg::tumbling(
                1000,
                100,
                vec!["k".into()],
                vec![Agg::count("n"), Agg::of(AggOp::Sum, "amount", "total")],
            );
            w.expect_partitions(&[0, 1], 0);
            w
        };
        let ev = |i: i64| {
            (
                (i % 2) as i32,
                i * 7, // event time strides windows
                row(&[
                    ("k", Value::Str(format!("g{}", i % 5))),
                    ("amount", Value::Num(i as f64)),
                ]),
            )
        };
        let head: Vec<_> = (0..500).map(ev).collect();
        let tail: Vec<_> = (500..1000).map(ev).collect();

        // Uninterrupted: push head, advance (mid-stream firing), push tail, advance + flush.
        let mut a = mk();
        let mut fired_a = Vec::new();
        for (p, t, r) in &head {
            a.push(*p, *t, r);
        }
        fired_a.extend(a.advance(0));
        for (p, t, r) in &tail {
            a.push(*p, *t, r);
        }
        assert!(
            !a.push(0, 0, &row(&[("k", Value::Str("g0".into()))])),
            "late event dropped"
        );
        fired_a.extend(a.advance(0));
        fired_a.extend(a.flush());

        // Interrupted at the same point: head + advance, SNAPSHOT, "crash", restore into a fresh
        // operator, replay the tail.
        let mut b1 = mk();
        let mut fired_b = Vec::new();
        for (p, t, r) in &head {
            b1.push(*p, *t, r);
        }
        fired_b.extend(b1.advance(0));
        let snap = b1.snapshot();
        drop(b1); // the crash
        let mut b2 = mk();
        b2.load_snapshot(&snap).expect("restore");
        for (p, t, r) in &tail {
            b2.push(*p, *t, r);
        }
        assert!(
            !b2.push(0, 0, &row(&[("k", Value::Str("g0".into()))])),
            "late event still dropped after restore"
        );
        fired_b.extend(b2.advance(0));
        fired_b.extend(b2.flush());

        assert_eq!(fired_a, fired_b, "restored run must fire byte-identically");
        assert_eq!(a.late_dropped(), b2.late_dropped(), "late counts preserved");
    }

    #[test]
    fn snapshot_refuses_config_and_kind_mismatch() {
        let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        w.push(0, 100, &row(&[]));
        let snap = w.snapshot();
        // Different window size → config changed → refused.
        let mut other = WindowAgg::tumbling(2000, 0, vec![], vec![Agg::count("n")]);
        assert!(other.load_snapshot(&snap).unwrap_err().contains("config changed"));
        // A session snapshot into a window operator → kind mismatch → refused.
        let mut s = SessionAgg::new(1000, 0, vec![], vec![Agg::count("n")]);
        let mut w2 = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        assert!(w2
            .load_snapshot(&WindowOperator::snapshot(&mut s).unwrap())
            .unwrap_err()
            .contains("kind"));
    }

    #[test]
    fn snapshot_preserves_bounded_idleness_timers() {
        // A restored operator must remember partition activity: partition 1 silent since t=0 goes idle
        // at the same processing time it would have in the original.
        let mk = || {
            let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]).with_idle_timeout(1000);
            w.expect_partitions(&[0, 1], 0);
            w.push(0, 100, &row(&[]));
            w.push(1, 200, &row(&[]));
            w.advance(0); // stamp activity at t=0
            w.push(0, 1500, &row(&[]));
            w
        };
        let mut orig = mk();
        let mut restored = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]).with_idle_timeout(1000);
        restored.load_snapshot(&mk().snapshot()).expect("restore");
        let a = orig.advance(5000); // partition 1 idle → window [0,1000) fires
        let b = restored.advance(5000);
        assert_eq!(a, b, "idle-release behavior identical after restore");
        assert!(a.iter().any(|r| r.window_start == 0));
    }

    #[test]
    fn bounded_idleness_releases_windows_held_by_a_silent_partition() {
        // Partition 1 produces once then goes silent; partition 0 keeps advancing. Without an idle
        // timeout, partition 1's stale max pins the watermark and window [0,1000) never fires until
        // flush. With one, partition 1 goes idle (processing time) and partition 0 drives firing.
        let mk = |idle_ms: i64| {
            let mut w = WindowAgg::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
            if idle_ms > 0 {
                w = w.with_idle_timeout(idle_ms);
            }
            w.expect_partitions(&[0, 1], 0);
            w.push(0, 100, &row(&[]));
            w.push(1, 200, &row(&[])); // partition 1's only event
            w.advance(0); // stamp both partitions active at processing-time 0
            w.push(0, 1500, &row(&[])); // partition 0 keeps producing; partition 1 stays silent
            w
        };
        let mut no_idle = mk(0);
        assert!(
            no_idle.advance(5000).is_empty(),
            "no idle timeout → the silent partition holds forever"
        );
        let mut idle = mk(1000);
        let out = idle.advance(5000); // now=5000: partition 1 idle since t=0 → partition 0 (max 1500) drives
        assert!(
            out.iter().any(|r| r.window_start == 0),
            "idle partition released → window [0,1000) fires"
        );
    }
}