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
//! `ShardedWindow` — a [`WindowOperator`] that splits a keyBy window into `k` key-range shards so
//! the coldest shards can be **frozen to files under memory pressure** (Phase 3c). Each shard is a
//! full window operator over its own key-range; a row routes to `hash(group key) % k`, so every
//! key's rows land in one shard and the shards aggregate independently. Firing is driven by the
//! engine's watermark (`advance_to`), which advances every shard's `fired_through` identically, so
//! lateness and results are identical to one unsharded operator.
//!
//! Eviction (3c-ii): a shard with no open windows is pure interning — its cold keys' state. When
//! resident state exceeds the budget (`STREAM_MEMORY_LIMIT_MB`) the coldest such shard is frozen to
//! a file (its `snapshot()`) and dropped from memory; firing skips it (nothing to fire) so it stays
//! evicted, and a later row for one of its keys thaws it (`load_snapshot`) — the read-merge-on-miss.

use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use arrow::array::{ArrayRef, RecordBatch, UInt32Array};
use arrow::datatypes::DataType;
use arrow::row::{RowConverter, SortField};

use crate::{state_fault, StateError, Value, WindowOperator, WindowRow};

type Mk = Box<dyn Fn() -> Box<dyn WindowOperator + Send> + Send>;

/// The `shard index` a checkpoint uses for its ONE combined hot-shard file (as opposed to a real
/// shard index for a frozen shard's own file). Fits a `u32` so it survives the engine's head
/// encoding, and cannot collide with a real index (shard counts are small).
const HOT_COMBINED: usize = u32::MAX as usize;

/// A shard is resident (hot) or frozen to a file (pure interning, no open windows).
enum ShardSlot {
    Hot(Box<dyn WindowOperator + Send>),
    Frozen { path: PathBuf },
}

/// One keyBy window split across `k` key-range shards, with optional cold-shard eviction.
pub struct ShardedWindow {
    shards: Vec<ShardSlot>,
    group_by: Vec<String>,
    converter: Option<RowConverter>,
    mk: Mk,
    /// Where cold shards freeze, and the resident-byte budget. `None`/`0` = never evict.
    dir: Option<PathBuf>,
    budget: usize,
    touch: Vec<u64>,
    clock: u64,
    frozen_seq: u64,
    /// Remembered so a thawed shard re-registers its read partitions.
    partitions: Vec<i32>,
    now_ms: i64,
}

impl ShardedWindow {
    /// `k` shards built from `mk`, routed by `group_by`. No eviction (see [`ShardedWindow::with_eviction`]).
    pub fn new(
        k: usize,
        mk: impl Fn() -> Box<dyn WindowOperator + Send> + Send + 'static,
        group_by: Vec<String>,
    ) -> Self {
        let k = k.max(1);
        let mk: Mk = Box::new(mk);
        ShardedWindow {
            shards: (0..k).map(|_| ShardSlot::Hot(mk())).collect(),
            group_by,
            converter: None,
            mk,
            dir: None,
            budget: 0,
            touch: vec![0; k],
            clock: 0,
            frozen_seq: 0,
            partitions: Vec::new(),
            now_ms: 0,
        }
    }

    /// Freeze cold (window-less) shards to `dir` when resident state exceeds `budget_bytes`.
    pub fn with_eviction(mut self, dir: PathBuf, budget_bytes: usize) -> Self {
        let _ = std::fs::create_dir_all(&dir);
        self.dir = Some(dir);
        self.budget = budget_bytes;
        self
    }

    /// How many shards this operator holds.
    pub fn shard_count(&self) -> usize {
        self.shards.len()
    }

    /// Shards currently resident in memory (the rest are frozen to disk).
    pub fn resident_shards(&self) -> usize {
        self.shards.iter().filter(|s| matches!(s, ShardSlot::Hot(_))).count()
    }

    fn bump(&mut self, i: usize) {
        self.clock += 1;
        self.touch[i] = self.clock;
    }

    /// Make shard `i` resident, thawing it from its file if frozen. Returns `&mut` to the operator.
    fn hot(&mut self, i: usize) -> &mut Box<dyn WindowOperator + Send> {
        if let ShardSlot::Frozen { path, .. } = &self.shards[i] {
            let path = path.clone();
            // The data path has no error channel (see `error`): a lost or unreadable frozen file
            // escalates through `state_fault`, which the task runtime turns into a FAILED build
            // carrying this diagnostic. The `Hot` arm above is untouched.
            let bytes = std::fs::read(&path)
                .unwrap_or_else(|e| state_fault(StateError::io(format!("thaw shard {i}"), &path, e)));
            let mut op = (self.mk)();
            op.load_snapshot(&bytes).unwrap_or_else(|e| {
                state_fault(StateError::corrupt(
                    format!("thaw shard {i} from {}", path.display()),
                    e,
                ))
            });
            op.expect_partitions(&self.partitions, self.now_ms);
            let _ = std::fs::remove_file(&path);
            self.shards[i] = ShardSlot::Hot(op);
        }
        self.bump(i);
        match &mut self.shards[i] {
            ShardSlot::Hot(op) => op,
            ShardSlot::Frozen { .. } => unreachable!("just thawed"),
        }
    }

    fn resident_bytes(&self) -> usize {
        self.shards
            .iter()
            .filter_map(|s| match s {
                ShardSlot::Hot(op) => Some(op.state_bytes()),
                ShardSlot::Frozen { .. } => None,
            })
            .sum()
    }

    /// Freeze shard `i` if it is resident and has no open windows (pure interning).
    fn freeze(&mut self, i: usize) -> bool {
        let Some(dir) = self.dir.clone() else { return false };
        let ShardSlot::Hot(op) = &mut self.shards[i] else {
            return false;
        };
        if op.open_windows() != 0 {
            return false;
        }
        // a hot shard's snapshot is in-memory work; an `Err` would be a state-tier fault below it,
        // escalated like a thaw (the data path has no error channel).
        let snap = op.snapshot().unwrap_or_else(|e| state_fault(e));
        self.frozen_seq += 1;
        let path = dir.join(format!("shard-{i}-{}.arrow", self.frozen_seq));
        if std::fs::write(&path, &snap).is_err() {
            return false;
        }
        self.shards[i] = ShardSlot::Frozen { path };
        true
    }

    /// While over budget, freeze the coldest window-less resident shard. Stops if none can be evicted.
    fn enforce_budget(&mut self) {
        if self.budget == 0 || self.dir.is_none() {
            return;
        }
        while self.resident_bytes() > self.budget {
            let victim = self
                .shards
                .iter()
                .enumerate()
                .filter(|(_, s)| matches!(s, ShardSlot::Hot(op) if op.open_windows() == 0))
                .min_by_key(|(i, _)| self.touch[*i])
                .map(|(i, _)| i);
            match victim {
                Some(i) if self.freeze(i) => {}
                _ => break, // nothing window-less to evict — hold anyway
            }
        }
    }

    fn shard_of_rows(&mut self, batch: &RecordBatch) -> Vec<usize> {
        let k = self.shards.len();
        if self.group_by.is_empty() || k == 1 {
            return vec![0; batch.num_rows()];
        }
        let cols: Vec<ArrayRef> = self
            .group_by
            .iter()
            .map(|g| match batch.column_by_name(g) {
                Some(c) => std::sync::Arc::clone(c),
                None => arrow::array::new_null_array(&DataType::Null, batch.num_rows()),
            })
            .collect();
        if self.converter.is_none() {
            let fields = cols.iter().map(|c| SortField::new(c.data_type().clone())).collect();
            self.converter = Some(RowConverter::new(fields).expect("row converter"));
        }
        let rows = self
            .converter
            .as_mut()
            .expect("converter")
            .convert_columns(&cols)
            .expect("group columns convert");
        (0..batch.num_rows())
            .map(|i| {
                let mut h = std::collections::hash_map::DefaultHasher::new();
                rows.row(i).as_ref().hash(&mut h);
                (h.finish() as usize) % k
            })
            .collect()
    }

    fn split(&mut self, batch: &RecordBatch, event_ms: &[i64]) -> Vec<Option<(RecordBatch, Vec<i64>)>> {
        let k = self.shards.len();
        let of = self.shard_of_rows(batch);
        let mut idx: Vec<Vec<u32>> = vec![Vec::new(); k];
        let mut times: Vec<Vec<i64>> = vec![Vec::new(); k];
        for (i, &s) in of.iter().enumerate() {
            idx[s].push(i as u32);
            times[s].push(event_ms[i]);
        }
        idx.into_iter()
            .zip(times)
            .map(|(rows, ts)| {
                if rows.is_empty() {
                    None
                } else {
                    let take = UInt32Array::from(rows);
                    let cols: Vec<ArrayRef> = batch
                        .columns()
                        .iter()
                        .map(|c| arrow::compute::take(c, &take, None).expect("take"))
                        .collect();
                    let sub = RecordBatch::try_new(batch.schema(), cols).expect("shard batch");
                    Some((sub, ts))
                }
            })
            .collect()
    }
}

/// Concatenate the shards' fired batches, if any answered the batch path.
fn concat(per_shard: &[Option<Option<RecordBatch>>]) -> Option<Option<RecordBatch>> {
    let mut batches: Vec<RecordBatch> = Vec::new();
    let mut any_batch_path = false;
    for inner in per_shard.iter().flatten() {
        any_batch_path = true;
        if let Some(b) = inner {
            if b.num_rows() > 0 {
                batches.push(b.clone());
            }
        }
    }
    if !any_batch_path {
        return None;
    }
    match batches.first() {
        None => Some(None),
        Some(first) => {
            let schema = first.schema();
            Some(Some(
                arrow::compute::concat_batches(&schema, &batches).expect("concat fired"),
            ))
        }
    }
}

impl WindowOperator for ShardedWindow {
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        self.partitions = partitions.to_vec();
        self.now_ms = now_ms;
        for s in &mut self.shards {
            if let ShardSlot::Hot(op) = s {
                op.expect_partitions(partitions, now_ms);
            }
        }
    }

    fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, Value)]) -> bool {
        let k = self.shards.len();
        let s = if self.group_by.is_empty() || k == 1 {
            0
        } else {
            let mut h = std::collections::hash_map::DefaultHasher::new();
            for g in &self.group_by {
                if let Some((_, v)) = row.iter().find(|(name, _)| name == g) {
                    format!("{v:?}").hash(&mut h);
                }
            }
            (h.finish() as usize) % k
        };
        let out = self.hot(s).push(partition, event_ms, row);
        self.enforce_budget();
        out
    }

    fn push_batch(&mut self, partition: i32, batch: &RecordBatch, event_ms: &[i64]) -> Option<usize> {
        let parts = self.split(batch, event_ms);
        let mut late = 0usize;
        let mut answered = false;
        for (s, part) in parts.into_iter().enumerate() {
            if let Some((sub, ts)) = part {
                if let Some(l) = self.hot(s).push_batch(partition, &sub, &ts) {
                    answered = true;
                    late += l;
                }
            }
        }
        self.enforce_budget();
        answered.then_some(late)
    }

    fn advance(&mut self, now_ms: i64) -> Vec<WindowRow> {
        let out: Vec<WindowRow> = self
            .shards
            .iter_mut()
            .filter_map(|s| match s {
                ShardSlot::Hot(op) => Some(op.advance(now_ms)),
                ShardSlot::Frozen { .. } => None, // no open windows
            })
            .flatten()
            .collect();
        self.enforce_budget();
        out
    }

    fn advance_to(&mut self, watermark_ms: i64) -> Vec<WindowRow> {
        let out: Vec<WindowRow> = self
            .shards
            .iter_mut()
            .filter_map(|s| match s {
                ShardSlot::Hot(op) => Some(op.advance_to(watermark_ms)),
                ShardSlot::Frozen { .. } => None,
            })
            .flatten()
            .collect();
        self.enforce_budget();
        out
    }

    fn advance_batch(&mut self, now_ms: i64) -> Option<Option<RecordBatch>> {
        let per: Vec<_> = self
            .shards
            .iter_mut()
            .map(|s| match s {
                ShardSlot::Hot(op) => op.advance_batch(now_ms),
                ShardSlot::Frozen { .. } => Some(None),
            })
            .collect();
        let out = concat(&per);
        self.enforce_budget();
        out
    }

    fn advance_batch_to(&mut self, watermark_ms: i64) -> Option<Option<RecordBatch>> {
        let per: Vec<_> = self
            .shards
            .iter_mut()
            .map(|s| match s {
                ShardSlot::Hot(op) => op.advance_batch_to(watermark_ms),
                ShardSlot::Frozen { .. } => Some(None),
            })
            .collect();
        let out = concat(&per);
        self.enforce_budget();
        out
    }

    fn flush(&mut self) -> Vec<WindowRow> {
        self.shards
            .iter_mut()
            .filter_map(|s| match s {
                ShardSlot::Hot(op) => Some(op.flush()),
                ShardSlot::Frozen { .. } => None,
            })
            .flatten()
            .collect()
    }

    fn flush_batch(&mut self) -> Option<Option<RecordBatch>> {
        let per: Vec<_> = self
            .shards
            .iter_mut()
            .map(|s| match s {
                ShardSlot::Hot(op) => op.flush_batch(),
                ShardSlot::Frozen { .. } => Some(None),
            })
            .collect();
        concat(&per)
    }

    fn state_bytes(&self) -> usize {
        self.resident_bytes()
    }

    fn open_windows(&self) -> usize {
        self.shards
            .iter()
            .map(|s| match s {
                ShardSlot::Hot(op) => op.open_windows(),
                ShardSlot::Frozen { .. } => 0,
            })
            .sum()
    }

    fn snapshot(&mut self) -> Result<Vec<u8>, StateError> {
        // self-contained: `[u32 k]` then per shard `[u32 len][bytes]` (a frozen shard's file bytes).
        let mut out = Vec::new();
        out.extend_from_slice(&(self.shards.len() as u32).to_le_bytes());
        for s in &mut self.shards {
            let snap = match s {
                ShardSlot::Hot(op) => op.snapshot()?,
                ShardSlot::Frozen { path, .. } => {
                    std::fs::read(&*path).map_err(|e| StateError::io("read frozen shard", &*path, e))?
                }
            };
            out.extend_from_slice(&(snap.len() as u32).to_le_bytes());
            out.extend_from_slice(&snap);
        }
        Ok(out)
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        let mut pos = 0usize;
        let read_u32 = |p: &mut usize| -> Result<usize, String> {
            let v = bytes
                .get(*p..*p + 4)
                .ok_or("sharded snapshot: truncated")?
                .try_into()
                .map_err(|_| "sharded snapshot: len")?;
            *p += 4;
            Ok(u32::from_le_bytes(v) as usize)
        };
        let k = read_u32(&mut pos)?;
        if k != self.shards.len() {
            return Err(format!(
                "sharded snapshot: {k} shards != this operator's {}",
                self.shards.len()
            ));
        }
        for i in 0..k {
            let len = read_u32(&mut pos)?;
            let frame = bytes.get(pos..pos + len).ok_or("sharded snapshot: truncated frame")?;
            pos += len;
            let mut op = (self.mk)();
            op.load_snapshot(frame)?;
            self.shards[i] = ShardSlot::Hot(op);
            self.touch[i] = 0;
        }
        self.enforce_budget();
        Ok(())
    }

    fn shard_files_supported(&self) -> bool {
        true
    }

    fn snapshot_shard_files(&mut self, dir: &Path, tag: &str) -> Result<Vec<(usize, PathBuf)>, StateError> {
        // Split by tier (D5): the HOT shards (open windows) go into ONE combined file, written one
        // shard at a time (bounded memory) as `[u32 n_hot]` then per shard `[u32 idx][u32 len][bytes]`
        // — one object put, and `load_shard_files` rebuilds them in parallel. Each FROZEN shard
        // (window-less pure interning, already an immutable file on disk) is HARDLINKED into staging,
        // not rebuilt: restore registers it lazily and thaws it only if a key for it arrives. So a
        // cold-dominated gigabyte restores by re-referencing files, not by a full heap rebuild. The
        // hardlink is cheap and immune to a later thaw removing the original (the join's own fix); the
        // barrier is synchronous, so nothing thaws under it.
        use std::io::Write;
        let mut out = Vec::new();
        let hot_path = dir.join(format!("{tag}-hot.arrow"));
        // A full disk or a lost staging dir is a checkpoint the barrier cannot take: returned, so the
        // engine fails the build with the path and the OS error — never a panic on the task.
        let io = |op: &str, e: std::io::Error| StateError::io(op, &hot_path, e);
        {
            let mut f =
                std::io::BufWriter::new(std::fs::File::create(&hot_path).map_err(|e| io("create checkpoint file", e))?);
            let hot: Vec<usize> = (0..self.shards.len())
                .filter(|&i| matches!(self.shards[i], ShardSlot::Hot(_)))
                .collect();
            f.write_all(&(hot.len() as u32).to_le_bytes())
                .map_err(|e| io("write checkpoint file", e))?;
            for i in hot {
                let snap = match &mut self.shards[i] {
                    ShardSlot::Hot(op) => op.snapshot()?,
                    ShardSlot::Frozen { .. } => unreachable!("filtered to hot"),
                };
                f.write_all(&(i as u32).to_le_bytes())
                    .map_err(|e| io("write checkpoint file", e))?;
                f.write_all(&(snap.len() as u32).to_le_bytes())
                    .map_err(|e| io("write checkpoint file", e))?;
                f.write_all(&snap).map_err(|e| io("write checkpoint file", e))?;
                // `snap` drops here — the peak is one shard's bytes, not the operator's whole state.
            }
            f.flush().map_err(|e| io("flush checkpoint file", e))?;
        }
        out.push((HOT_COMBINED, hot_path));
        for i in 0..self.shards.len() {
            if let ShardSlot::Frozen { path: frozen } = &self.shards[i] {
                let link = dir.join(format!("{tag}-frz{i}.arrow"));
                if std::fs::hard_link(frozen, &link).is_err() {
                    // cross-device or a stale link — fall back to a copy (still bounded, one shard).
                    std::fs::copy(frozen, &link)
                        .map_err(|e| StateError::io(format!("stage frozen shard {i}"), &link, e))?;
                }
                out.push((i, link));
            }
        }
        Ok(out)
    }

    fn load_shard_files(&mut self, files: &[(usize, PathBuf)]) -> Result<(), String> {
        // Frozen shards register LAZILY — a `Frozen { path }` slot, no rebuild; they are window-less
        // (only window-less shards freeze), so firing already skips them and a late key thaws one on
        // demand. Only the hot shards are rebuilt, and those in parallel.
        let hot_path = files
            .iter()
            .find(|(idx, _)| *idx == HOT_COMBINED)
            .map(|(_, p)| p.clone())
            .ok_or("sharded restore: no hot file")?;
        for (idx, path) in files {
            if *idx != HOT_COMBINED {
                if *idx >= self.shards.len() {
                    return Err(format!(
                        "sharded restore: frozen shard {idx} out of {}",
                        self.shards.len()
                    ));
                }
                self.shards[*idx] = ShardSlot::Frozen { path: path.clone() };
                self.touch[*idx] = 0;
            }
        }

        let bytes = std::fs::read(&hot_path).map_err(|e| format!("read hot file: {e}"))?;
        let mut pos = 0usize;
        let read_u32 = |b: &[u8], p: &mut usize| -> Result<usize, String> {
            let v = b.get(*p..*p + 4).ok_or("hot file: truncated")?;
            *p += 4;
            Ok(u32::from_le_bytes(v.try_into().unwrap()) as usize)
        };
        let n_hot = read_u32(&bytes, &mut pos)?;
        let mut idxs: Vec<usize> = Vec::with_capacity(n_hot);
        let mut frames: Vec<&[u8]> = Vec::with_capacity(n_hot);
        for _ in 0..n_hot {
            let idx = read_u32(&bytes, &mut pos)?;
            let len = read_u32(&bytes, &mut pos)?;
            let fr = bytes.get(pos..pos + len).ok_or("hot file: truncated frame")?;
            pos += len;
            if idx >= self.shards.len() {
                return Err(format!("hot file: shard {idx} out of {}", self.shards.len()));
            }
            idxs.push(idx);
            frames.push(fr);
        }
        // Rebuild the hot shards IN PARALLEL: they are independent operators, and the per-shard load
        // (key interning + accumulator merge) is the recovery bottleneck single-threaded. Chunk over
        // the available parallelism; each thread rebuilds its chunk from the byte frames.
        let mut ops: Vec<Box<dyn WindowOperator + Send>> = (0..n_hot).map(|_| (self.mk)()).collect();
        let ncpu = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4)
            .max(1);
        let chunk = n_hot.div_ceil(ncpu).max(1);
        let mut first_err: Option<String> = None;
        std::thread::scope(|s| {
            let mut handles = Vec::new();
            for (ops_chunk, frames_chunk) in ops.chunks_mut(chunk).zip(frames.chunks(chunk)) {
                handles.push(s.spawn(move || -> Result<(), String> {
                    for (op, fr) in ops_chunk.iter_mut().zip(frames_chunk) {
                        op.load_snapshot(fr)?;
                    }
                    Ok(())
                }));
            }
            for h in handles {
                match h.join() {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => {
                        first_err.get_or_insert(e);
                    }
                    Err(_) => {
                        // a rebuild thread panicked: reported as the restore's failure, not re-raised
                        first_err.get_or_insert("shard restore thread panicked".into());
                    }
                }
            }
        });
        if let Some(e) = first_err {
            return Err(e);
        }
        for (idx, op) in idxs.into_iter().zip(ops) {
            self.shards[idx] = ShardSlot::Hot(op);
            self.touch[idx] = 0;
        }
        Ok(())
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use crate::batch_window::WindowAggBatch;
    use crate::Agg;
    use arrow::array::{Float64Array, Int64Array, StringArray};
    use arrow::datatypes::{Field, Schema};
    use std::sync::Arc;

    pub(super) fn batch(rows: &[(&str, f64, i64)]) -> (RecordBatch, Vec<i64>) {
        let schema = Arc::new(Schema::new(vec![
            Field::new("k", DataType::Utf8, true),
            Field::new("v", DataType::Float64, true),
            Field::new("ts", DataType::Int64, true),
        ]));
        let k: StringArray = rows.iter().map(|r| r.0).collect::<Vec<_>>().into();
        let v: Float64Array = rows.iter().map(|r| r.1).collect::<Vec<_>>().into();
        let ts: Int64Array = rows.iter().map(|r| r.2).collect::<Vec<_>>().into();
        let b = RecordBatch::try_new(schema, vec![Arc::new(k), Arc::new(v), Arc::new(ts)]).unwrap();
        let t = rows.iter().map(|r| r.2).collect();
        (b, t)
    }

    // every fired row rendered to a string and sorted — an order-independent, column-generic
    // comparison of the two operators' output.
    pub(super) fn rows_of(b: &RecordBatch) -> Vec<String> {
        use arrow::util::display::{ArrayFormatter, FormatOptions};
        let opts = FormatOptions::default();
        let fmts: Vec<_> = b
            .columns()
            .iter()
            .map(|c| ArrayFormatter::try_new(c, &opts).unwrap())
            .collect();
        let mut out: Vec<String> = (0..b.num_rows())
            .map(|i| {
                fmts.iter()
                    .map(|f| f.value(i).to_string())
                    .collect::<Vec<_>>()
                    .join("|")
            })
            .collect();
        out.sort();
        out
    }

    pub(super) fn drain(op: &mut dyn WindowOperator, wm: i64) -> Vec<String> {
        match op.advance_batch_to(wm) {
            Some(Some(b)) => rows_of(&b),
            _ => Vec::new(),
        }
    }

    #[test]
    fn a_sharded_window_matches_one_unsharded_operator_row_for_row() {
        let aggs = || vec![Agg::count("n"), Agg::of(crate::AggOp::Sum, "v", "s")];
        let mut plain = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
        let mut sharded = ShardedWindow::new(
            4,
            move || Box::new(WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs())),
            vec!["k".into()],
        );
        plain.expect_partitions(&[0], 0);
        sharded.expect_partitions(&[0], 0);

        // many keys across several windows, out of order.
        let mut data = Vec::new();
        for w in 0..5i64 {
            for key in 0..40i64 {
                data.push((format!("k{key}"), (key + w) as f64, w * 1000 + key % 900));
            }
        }
        for chunk in data.chunks(37) {
            let rows: Vec<(&str, f64, i64)> = chunk.iter().map(|(k, v, t)| (k.as_str(), *v, *t)).collect();
            let (b, t) = batch(&rows);
            assert_eq!(plain.push_batch(0, &b, &t), sharded.push_batch(0, &b, &t));
        }
        // fire progressively; the two must agree at every watermark.
        for wm in [1500i64, 3500, 5500] {
            assert_eq!(drain(&mut plain, wm), drain(&mut sharded, wm), "mismatch at wm {wm}");
        }
        // a snapshot restores into a fresh sharded operator identically.
        let snap = sharded.snapshot().unwrap();
        let mut restored = ShardedWindow::new(
            4,
            || {
                Box::new(WindowAggBatch::tumbling(
                    1000,
                    0,
                    vec!["k".into()],
                    vec![Agg::count("n"), Agg::of(crate::AggOp::Sum, "v", "s")],
                ))
            },
            vec!["k".into()],
        );
        restored.load_snapshot(&snap).unwrap();
        assert_eq!(drain(&mut sharded, 100_000), drain(&mut restored, 100_000));
    }

    #[test]
    fn a_sharded_updating_window_early_fires_through_every_shard_and_closes_exactly() {
        use crate::Trigger;
        let aggs = || vec![Agg::count("n"), Agg::of(crate::AggOp::Sum, "v", "s")];
        // 4 shards; the updating one early-fires every 2 rows (per shard), the plain one never.
        let mut updating = ShardedWindow::new(
            4,
            move || {
                Box::new(
                    WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs()).with_trigger(Trigger::EveryRows(2)),
                )
            },
            vec!["k".into()],
        );
        let mut plain = ShardedWindow::new(
            4,
            move || Box::new(WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs())),
            vec!["k".into()],
        );
        updating.expect_partitions(&[0], 0);
        plain.expect_partitions(&[0], 0);
        let (b, t) = batch(&[
            ("a", 1.0, 100),
            ("b", 2.0, 200),
            ("c", 3.0, 300),
            ("a", 4.0, 400),
            ("b", 5.0, 500),
        ]);
        updating.push_batch(0, &b, &t);
        plain.push_batch(0, &b, &t);
        // the trigger reaches the shards: an early fire emits open-window partials at a
        // non-closing watermark; the plain operator emits nothing until the window closes.
        assert!(
            !drain(&mut updating, 500).is_empty(),
            "trigger early-fired through the shards"
        );
        assert!(drain(&mut plain, 500).is_empty(), "no trigger → no early emission");
        // both close identically and exactly — early firing did not disturb the sharded state.
        assert_eq!(drain(&mut updating, 1000), drain(&mut plain, 1000));
    }

    #[test]
    fn shard_files_checkpoint_restores_frozen_shards_lazily_and_exactly() {
        fn mk6() -> Box<dyn WindowOperator + Send> {
            Box::new(WindowAggBatch::tumbling(
                1000,
                0,
                vec!["k".into()],
                vec![Agg::count("n"), Agg::of(crate::AggOp::Sum, "v", "s")],
            ))
        }
        let build = || ShardedWindow::new(6, mk6, vec!["k".into()]);

        // Two identical operators; one evicts (budget 1) so window-less shards freeze to files.
        let mut whole = build();
        let evdir = tempfile::tempdir().unwrap();
        let mut byfile = build().with_eviction(evdir.path().to_path_buf(), 1);
        whole.expect_partitions(&[0], 0);
        byfile.expect_partitions(&[0], 0);

        // Windows 0..3 of keys 0..30, each FIRED fully as we go → the shards go window-less and
        // freeze under the 1-byte budget, so at the checkpoint they are files, not resident.
        for w in 0..3i64 {
            let rows: Vec<(String, f64, i64)> = (0..30i64)
                .map(|key| (format!("k{key}"), (key + w) as f64, w * 1000 + 10))
                .collect();
            let r: Vec<(&str, f64, i64)> = rows.iter().map(|(k, v, t)| (k.as_str(), *v, *t)).collect();
            let (b, t) = batch(&r);
            assert_eq!(whole.push_batch(0, &b, &t), byfile.push_batch(0, &b, &t));
            let wm = (w + 1) * 1000 + 5;
            assert_eq!(
                drain(&mut whole, wm),
                drain(&mut byfile, wm),
                "mismatch firing window {w}"
            );
        }

        // Checkpoint: window-less shards become their own files; restore registers them LAZILY.
        let ckpt = tempfile::tempdir().unwrap();
        let files = byfile.snapshot_shard_files(ckpt.path(), "s0-e7").unwrap();
        assert_eq!(
            files.iter().filter(|(i, _)| *i == HOT_COMBINED).count(),
            1,
            "one combined hot file"
        );
        let n_frozen = files.iter().filter(|(i, _)| *i != HOT_COMBINED).count();
        assert!(
            n_frozen >= 1,
            "fully-fired windows should leave window-less shards to freeze (got {n_frozen})"
        );

        let mut restored = build();
        restored.expect_partitions(&[0], 0);
        restored.load_shard_files(&files).unwrap();
        // LAZY: the frozen shards come back as files, NOT rebuilt into memory — this is what lets a
        // cold-dominated gigabyte recover in seconds (re-reference, don't heap-rebuild).
        assert!(
            restored.resident_shards() < 6,
            "frozen shards must restore lazily (resident {})",
            restored.resident_shards()
        );

        // A late key THAWS its lazily-restored frozen shard on demand and stays exact vs the whole op.
        let (lb, lt) = batch(&[("k5", 9.0, 5000), ("k17", 8.0, 5000)]);
        assert_eq!(whole.push_batch(0, &lb, &lt), restored.push_batch(0, &lb, &lt));
        assert_eq!(drain(&mut whole, 100_000), drain(&mut restored, 100_000));
    }
}

#[cfg(test)]
mod eviction_tests {
    use super::tests::*;
    use super::*;
    use crate::batch_window::WindowAggBatch;
    use crate::{Agg, AggOp};

    #[test]
    fn eviction_stays_exact_and_bounds_resident_shards() {
        let mk = || vec![Agg::count("n"), Agg::of(AggOp::Sum, "v", "s")];
        let mut plain = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], mk());
        let dir = tempfile::tempdir().unwrap();
        // a 1-byte budget: any resident state over budget frees the coldest window-less shard.
        let mut sharded = ShardedWindow::new(
            8,
            move || Box::new(WindowAggBatch::tumbling(1000, 0, vec!["k".into()], mk())),
            vec!["k".into()],
        )
        .with_eviction(dir.path().to_path_buf(), 1);
        plain.expect_partitions(&[0], 0);
        sharded.expect_partitions(&[0], 0);

        let mut min_resident = 8usize;
        // several windows of many keys; fire each window fully before the next, so shards go
        // window-less and become evictable.
        for w in 0..6i64 {
            let rows: Vec<(String, f64, i64)> = (0..60i64)
                .map(|key| (format!("k{key}"), (key + w) as f64, w * 1000 + 10))
                .collect();
            let r: Vec<(&str, f64, i64)> = rows.iter().map(|(k, v, t)| (k.as_str(), *v, *t)).collect();
            let (b, t) = batch(&r);
            assert_eq!(plain.push_batch(0, &b, &t), sharded.push_batch(0, &b, &t));
            // fire window w (its end is (w+1)*1000); the shards clear their panes and can freeze.
            let wm = (w + 1) * 1000 + 5;
            assert_eq!(
                drain(&mut plain, wm),
                drain(&mut sharded, wm),
                "mismatch firing window {w}"
            );
            min_resident = min_resident.min(sharded.resident_shards());
        }
        assert!(
            min_resident < 8,
            "eviction never froze a shard (resident stayed {min_resident})"
        );

        // a late row for an old key must thaw its shard and still be exact against the plain op.
        let (b, t) = batch(&[("k7", 1.0, 6100), ("k42", 2.0, 6100)]);
        assert_eq!(plain.push_batch(0, &b, &t), sharded.push_batch(0, &b, &t));
        assert_eq!(drain(&mut plain, 100_000), drain(&mut sharded, 100_000));
    }

    #[test]
    fn a_checkpoint_the_disk_refuses_is_returned_not_a_panic() {
        // The once-per-epoch path has an error channel: a staging "dir" that is a plain file makes
        // `create` fail, and the barrier gets the OS error with the file named — the engine fails
        // the build with it, naming the task.
        let mk = || vec![Agg::count("n")];
        let mut sharded = ShardedWindow::new(
            2,
            move || Box::new(WindowAggBatch::tumbling(1000, 0, vec!["k".into()], mk())),
            vec!["k".into()],
        );
        sharded.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100)]);
        sharded.push_batch(0, &b, &t);
        let dir = tempfile::tempdir().unwrap();
        let not_a_dir = dir.path().join("file");
        std::fs::write(&not_a_dir, b"x").unwrap();
        let msg = sharded.snapshot_shard_files(&not_a_dir, "t").unwrap_err().to_string();
        assert!(
            msg.contains("create checkpoint file") && msg.contains("t-hot.arrow"),
            "{msg}"
        );
    }

    #[test]
    fn a_frozen_shard_whose_file_is_gone_is_a_returned_error_at_the_barrier_and_a_typed_fault_on_the_data_path() {
        let mk = || vec![Agg::count("n"), Agg::of(AggOp::Sum, "v", "s")];
        let dir = tempfile::tempdir().unwrap();
        let mut sharded = ShardedWindow::new(
            2,
            move || Box::new(WindowAggBatch::tumbling(1000, 0, vec!["k".into()], mk())),
            vec!["k".into()],
        )
        .with_eviction(dir.path().to_path_buf(), 1);
        sharded.expect_partitions(&[0], 0);
        // one full window over many keys, fired: both shards go window-less (evictable).
        let rows: Vec<(String, f64, i64)> = (0..60i64).map(|key| (format!("k{key}"), key as f64, 10)).collect();
        let r: Vec<(&str, f64, i64)> = rows.iter().map(|(k, v, t)| (k.as_str(), *v, *t)).collect();
        let (b, t) = batch(&r);
        sharded.push_batch(0, &b, &t);
        drain(&mut sharded, 1005);
        // a new key opens a window in its shard; the 1-byte budget freezes the other, window-less one.
        let (b, t) = batch(&[("zz", 1.0, 1500)]);
        sharded.push_batch(0, &b, &t);
        assert_eq!(sharded.resident_shards(), 1, "the window-less shard should have frozen");
        // the spill directory is lost out from under the operator.
        for e in std::fs::read_dir(dir.path()).unwrap() {
            std::fs::remove_file(e.unwrap().path()).unwrap();
        }
        // once per epoch: the barrier's snapshot returns the fault, naming the operation and file.
        let msg = sharded.snapshot().unwrap_err().to_string();
        assert!(msg.contains("read frozen shard") && msg.contains("shard-"), "{msg}");
        // the data path has no error channel: the first late row that lands in the frozen shard
        // escalates through `state_fault` with the typed diagnostic — which the task runtime turns
        // into a FAILED build. (Keys hash to shards; with two shards one of these lands there.)
        let mut escalated = None;
        for key in 0..60i64 {
            let k = format!("k{key}");
            let (b, t) = batch(&[(k.as_str(), 1.0, 2100)]);
            let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sharded.push_batch(0, &b, &t)));
            if let Err(payload) = r {
                escalated = Some(payload.downcast_ref::<String>().cloned().unwrap_or_default());
                break;
            }
        }
        let msg = escalated.expect("a row for the frozen shard escalated");
        assert!(msg.contains("state io: thaw shard") && msg.contains("shard-"), "{msg}");
    }
}