fv-streams-ops 0.2.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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
//! COLUMNAR event-time windowed aggregation: the batch-native counterpart of [`WindowAgg`](crate::WindowAgg).
//!
//! Rows arrive as an Arrow `RecordBatch` with their event times; keys are interned through
//! `arrow::row::RowConverter` (one comparable byte row per distinct group key, a dense id each);
//! every open window (a *pane*) holds one DataFusion `GroupsAccumulator` per aggregate with the
//! key id as the group index, so an event costs one vectorised `update_batch` per pane it lands
//! in. A pane fires when its end is at or below the watermark: each accumulator evaluates over all
//! ids, the ids the pane actually saw are selected, and one output batch is emitted with
//! `windowStart`, `windowEnd`, the group columns and the aggregates. Semantics match the row
//! operator exactly (tests pin them): `count` counts rows, `sum`/`avg` of no values are 0, `min`/
//! `max` of no numeric values are null, bool folds need a boolean column, bit folds whole numbers,
//! variance `samp` needs two values.
//!
//! Snapshots are versioned Arrow IPC (the accumulators' own `state` arrays plus the interned keys
//! and the watermark timers); a restored operator continues byte-identically.
//!
//! Emission order is (window start, key row-order): deterministic, and the key row-order is the
//! sort order of the group values themselves.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use arrow::array::{Array, ArrayRef, BinaryArray, BooleanArray, Float64Array, Int64Array, RecordBatch, UInt32Array};
use arrow::compute::{cast, take};
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use arrow::ipc::reader::StreamReader;
use arrow::ipc::writer::StreamWriter;
use arrow::row::{OwnedRow, RowConverter, SortField};
use datafusion::functions_aggregate::average::avg_udaf;
use datafusion::functions_aggregate::bit_and_or_xor::{bit_and_udaf, bit_or_udaf, bit_xor_udaf};
use datafusion::functions_aggregate::bool_and_or::{bool_and_udaf, bool_or_udaf};
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::functions_aggregate::min_max::{max_udaf, min_udaf};
use datafusion::functions_aggregate::stddev::{stddev_pop_udaf, stddev_udaf};
use datafusion::functions_aggregate::sum::sum_udaf;
use datafusion::functions_aggregate::variance::{var_pop_udaf, var_samp_udaf};
use datafusion::logical_expr::function::AccumulatorArgs;
use datafusion::logical_expr::{AggregateUDF, EmitTo, GroupsAccumulator};
use datafusion::physical_expr::expressions::col;
use datafusion::physical_expr::PhysicalExpr;

use crate::watermark::Watermark;
use crate::{Agg, AggOp, Trigger, WindowKind};

/// The batch-native operator seam the engine drives: feed a partition's batch with its event
/// times, drain fired panes after each batch, flush on shutdown, snapshot and restore.
pub trait BatchOperator {
    /// 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 partition's batch; `event_ms[i]` is row `i`'s event time. Returns how many rows
    /// were genuinely late (every window they belonged to had already fired).
    fn push_batch(&mut self, partition: i32, batch: &RecordBatch, event_ms: &[i64]) -> usize;
    /// Fire every pane the watermark has closed at processing time `now_ms`.
    fn advance(&mut self, now_ms: i64) -> Option<RecordBatch>;
    /// Fire every pane closed by a watermark delivered from upstream (less the allowed lateness);
    /// the rows' own event times do not move time.
    fn advance_to(&mut self, watermark_ms: i64) -> Option<RecordBatch>;
    /// Fire every remaining pane (clean shutdown).
    fn flush(&mut self) -> Option<RecordBatch>;
    /// The output schema (stable for the operator's life).
    fn output_schema(&self) -> SchemaRef;
    fn snapshot(&mut self) -> Vec<u8>;
    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String>;
}

pub const SNAPSHOT_VERSION: i64 = 4; // 3c-iii-b: per-pane-local key ids (to_global replaces seen)
pub const WINDOW_START: &str = "windowStart";
pub const WINDOW_END: &str = "windowEnd";

/// What one aggregate compiles to: the DataFusion function (or our own exact-distinct set), the
/// input column, and the output type.
enum AggKind {
    /// A DataFusion aggregate over `input`-typed values; `skip` when the column's type is one the
    /// row operator ignored (every value is fed as null, so the result is the empty-input result).
    Df {
        udaf: Arc<AggregateUDF>,
        input: DataType,
        skip: bool,
    },
    /// Exact distinct count: a per-group value set (DataFusion's distinct count has no
    /// `GroupsAccumulator`).
    Distinct,
}

struct AggPlan {
    op: AggOp,
    column: String,
    alias: String,
    kind: AggKind,
    /// The output type the row operator produced for this op (Float64 for every number).
    out: DataType,
}

/// One exact-distinct value set per group (the value as its comparable byte row).
type DistinctSets = Vec<HashMap<Vec<u8>, ()>>;

/// Per-pane state: one accumulator per aggregate, plus which key ids this pane saw.
struct Pane {
    accs: Vec<Box<dyn GroupsAccumulator>>,
    distinct: Vec<Option<DistinctSets>>,
    /// local id -> global key id: the keys THIS pane saw, in first-seen order. The accumulators and
    /// distinct sets are sized to this (the active keys), not the operator's global key count — so
    /// memory is bounded by the window, not by total distinct keys (Phase 3c-iii-b).
    to_global: Vec<u32>,
    /// global key id -> this pane's local id.
    local: HashMap<u32, u32>,
    /// Updating aggregate (5a): the LOCAL ids whose value changed since the last early fire. Only
    /// populated when a [`Trigger`] early-fires; an early fire emits exactly these (emission ∝ churn,
    /// not open-key count) and clears the set. Empty and untouched on the on-watermark path.
    dirty: HashSet<u32>,
}

pub struct WindowAggBatch {
    kind: WindowKind,
    group_by: Vec<String>,
    aggs: Vec<Agg>,
    plans: Vec<AggPlan>,
    /// Key interning: the row converter over the group columns, the byte row → id map, and the
    /// owned rows by id (for emission).
    converter: Option<RowConverter>,
    key_ids: HashMap<Vec<u8>, u32>,
    keys: Vec<OwnedRow>,
    key_types: Vec<DataType>,
    panes: BTreeMap<i64, Pane>,
    wm: Watermark,
    fired_through: i64,
    late_dropped: u64,
    input_schema: Option<SchemaRef>,
    /// Updating aggregate (5a): the early-firing trigger. [`Trigger::OnWatermark`] (the default)
    /// keeps every path below byte-identical to a plain windowed aggregate.
    trigger: Trigger,
    /// Rows ingested since the last fire — the [`Trigger::EveryRows`] cadence counter.
    rows_since_early: u64,
    /// Processing time of the last early fire — the [`Trigger::EveryMs`] anchor (`i64::MIN` = unset).
    last_early_ms: i64,
}

impl WindowAggBatch {
    pub fn tumbling(size_ms: i64, allowed_lateness_ms: i64, group_by: Vec<String>, aggs: Vec<Agg>) -> Self {
        Self::new(WindowKind::Tumbling { size_ms }, allowed_lateness_ms, group_by, aggs)
    }

    pub fn sliding(
        size_ms: i64,
        slide_ms: i64,
        allowed_lateness_ms: i64,
        group_by: Vec<String>,
        aggs: Vec<Agg>,
    ) -> Self {
        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 {
        WindowAggBatch {
            kind,
            group_by,
            aggs,
            plans: Vec::new(),
            converter: None,
            key_ids: HashMap::new(),
            keys: Vec::new(),
            key_types: Vec::new(),
            panes: BTreeMap::new(),
            wm: Watermark::new(allowed_lateness_ms),
            fired_through: i64::MIN,
            late_dropped: 0,
            input_schema: None,
            trigger: Trigger::OnWatermark,
            rows_since_early: 0,
            last_early_ms: i64::MIN,
        }
    }

    pub fn with_idle_timeout(mut self, idle_timeout_ms: i64) -> Self {
        self.wm = self.wm.with_idle_timeout(idle_timeout_ms);
        self
    }

    /// Make this an **updating** windowed aggregate: `trigger` early-fires the current partial value
    /// of open windows as upserts (see [`Trigger`]). [`Trigger::OnWatermark`] leaves it a plain
    /// windowed aggregate (the default) — passing it is a harmless no-op.
    pub fn with_trigger(mut self, trigger: Trigger) -> Self {
        self.trigger = trigger;
        self
    }

    pub fn watermark(&self, now_ms: i64) -> i64 {
        self.wm.current(now_ms)
    }

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

    pub fn open_panes(&self) -> usize {
        self.panes.len()
    }

    /// Bytes of resident dynamic state: the open panes' accumulators AND the key-interning table
    /// (the interning persists after panes fire — it is the unbounded cost 3c evicts a cold shard
    /// to free).
    pub fn state_bytes(&self) -> usize {
        let panes: usize = self
            .panes
            .values()
            .map(|p| p.accs.iter().map(|a| a.size()).sum::<usize>() + p.to_global.len())
            .sum();
        let interning: usize = self.keys.iter().map(|r| r.as_ref().len()).sum::<usize>() + self.key_ids.len() * 24; // HashMap entry overhead (key ptr + id + hash)
        panes + interning
    }

    fn cfg_fingerprint(&self) -> String {
        // `trigger.fingerprint()` is EMPTY for the on-watermark default, so an existing windowed
        // aggregate's fingerprint (and its checkpoints) are byte-identical; a non-default trigger
        // makes the fingerprint distinct, so a snapshot only restores into a same-trigger operator.
        format!(
            "v3;kind={:?};group_by={:?};aggs={:?};{}{}",
            self.kind,
            self.group_by,
            self.aggs,
            self.wm.cfg_fingerprint(),
            self.trigger.fingerprint(),
        )
    }

    /// Resolve the aggregates against the first batch's schema (column types decide the plan).
    fn plan_for(&mut self, schema: &SchemaRef) -> Result<(), String> {
        let mut plans = Vec::with_capacity(self.aggs.len());
        for a in &self.aggs {
            let input = schema
                .field_with_name(&a.column)
                .map(|f| f.data_type().clone())
                .unwrap_or(DataType::Null);
            let numeric = matches!(
                input,
                DataType::Float64
                    | DataType::Float32
                    | DataType::Int64
                    | DataType::Int32
                    | DataType::Int16
                    | DataType::Int8
                    | DataType::UInt64
                    | DataType::UInt32
                    | DataType::UInt16
                    | DataType::UInt8
            );
            let (kind, out) = match a.op {
                AggOp::Count => (
                    AggKind::Df {
                        udaf: count_udaf(),
                        input: DataType::Int64,
                        skip: false,
                    },
                    DataType::Float64,
                ),
                AggOp::CountDistinct => (AggKind::Distinct, DataType::Float64),
                AggOp::Sum | AggOp::Avg | AggOp::Min | AggOp::Max => {
                    let udaf = match a.op {
                        AggOp::Sum => sum_udaf(),
                        AggOp::Avg => avg_udaf(),
                        AggOp::Min => min_udaf(),
                        _ => max_udaf(),
                    };
                    (
                        AggKind::Df {
                            udaf,
                            input: DataType::Float64,
                            skip: !numeric,
                        },
                        DataType::Float64,
                    )
                }
                AggOp::VarPop | AggOp::VarSamp | AggOp::StddevPop | AggOp::StddevSamp => {
                    let udaf = match a.op {
                        AggOp::VarPop => var_pop_udaf(),
                        AggOp::VarSamp => var_samp_udaf(),
                        AggOp::StddevPop => stddev_pop_udaf(),
                        _ => stddev_udaf(),
                    };
                    (
                        AggKind::Df {
                            udaf,
                            input: DataType::Float64,
                            skip: !numeric,
                        },
                        DataType::Float64,
                    )
                }
                AggOp::BoolAnd | AggOp::BoolOr => (
                    AggKind::Df {
                        udaf: if a.op == AggOp::BoolAnd {
                            bool_and_udaf()
                        } else {
                            bool_or_udaf()
                        },
                        input: DataType::Boolean,
                        skip: input != DataType::Boolean,
                    },
                    DataType::Boolean,
                ),
                AggOp::BitAnd | AggOp::BitOr | AggOp::BitXor => (
                    AggKind::Df {
                        udaf: match a.op {
                            AggOp::BitAnd => bit_and_udaf(),
                            AggOp::BitOr => bit_or_udaf(),
                            _ => bit_xor_udaf(),
                        },
                        input: DataType::Int64,
                        skip: !numeric,
                    },
                    DataType::Float64,
                ),
            };
            plans.push(AggPlan {
                op: a.op,
                column: a.column.clone(),
                alias: a.alias.clone(),
                kind,
                out,
            });
        }
        self.plans = plans;
        // the key converter over the group columns (missing column → Null type).
        let types: Vec<DataType> = self
            .group_by
            .iter()
            .map(|g| {
                schema
                    .field_with_name(g)
                    .map(|f| f.data_type().clone())
                    .unwrap_or(DataType::Null)
            })
            .collect();
        self.converter = Some(
            RowConverter::new(types.iter().map(|t| SortField::new(t.clone())).collect()).map_err(|e| e.to_string())?,
        );
        self.key_types = types;
        self.input_schema = Some(Arc::clone(schema));
        Ok(())
    }

    fn new_pane(&self) -> Pane {
        let accs = self
            .plans
            .iter()
            .map(|p| match &p.kind {
                AggKind::Df { udaf, input, .. } => create_acc(udaf, input),
                AggKind::Distinct => create_acc(&count_udaf(), &DataType::Int64), // placeholder, unused
            })
            .collect();
        let distinct = self
            .plans
            .iter()
            .map(|p| match p.kind {
                AggKind::Distinct => Some(Vec::new()),
                _ => None,
            })
            .collect();
        Pane {
            accs,
            distinct,
            to_global: Vec::new(),
            local: HashMap::new(),
            dirty: HashSet::new(),
        }
    }

    /// The per-row key ids for a batch (interning new keys).
    fn intern_keys(&mut self, batch: &RecordBatch) -> Vec<u32> {
        if self.group_by.is_empty() {
            return vec![0; batch.num_rows()];
        }
        let cols: Vec<ArrayRef> = self
            .group_by
            .iter()
            .map(|g| match batch.column_by_name(g) {
                Some(c) => Arc::clone(c),
                None => arrow::array::new_null_array(&DataType::Null, batch.num_rows()),
            })
            .collect();
        let rows = self
            .converter
            .as_mut()
            .expect("planned")
            .convert_columns(&cols)
            .expect("group columns convert");
        let mut ids = Vec::with_capacity(batch.num_rows());
        for i in 0..batch.num_rows() {
            let r = rows.row(i);
            let bytes: &[u8] = r.as_ref();
            let id = match self.key_ids.get(bytes) {
                Some(&id) => id,
                None => {
                    let id = self.keys.len() as u32;
                    self.key_ids.insert(bytes.to_vec(), id);
                    self.keys.push(r.owned());
                    id
                }
            };
            ids.push(id);
        }
        ids
    }

    /// The input array for one aggregate over the selected rows, cast to the plan's input type
    /// (values the row operator would have skipped become null here, which the accumulators skip).
    fn agg_input(&self, plan: &AggPlan, batch: &RecordBatch, idx: &UInt32Array, event_ms: &[i64]) -> ArrayRef {
        let n = idx.len();
        let AggKind::Df { input, skip, .. } = &plan.kind else {
            unreachable!("distinct handled separately")
        };
        if plan.op == AggOp::Count {
            // count rows: any non-null column of the right length.
            let ones: Int64Array = idx
                .values()
                .iter()
                .map(|&i| event_ms[i as usize])
                .collect::<Vec<_>>()
                .into();
            return Arc::new(ones);
        }
        let colv = if *skip {
            None
        } else {
            batch.column_by_name(&plan.column)
        };
        let Some(colv) = colv else {
            return arrow::array::new_null_array(input, n);
        };
        let taken = take(colv.as_ref(), idx, None).expect("take");
        match input {
            DataType::Int64 => {
                // bit folds: whole numbers only; a fractional value is skipped (null).
                let f = cast(&taken, &DataType::Float64).expect("cast");
                let f = f.as_any().downcast_ref::<Float64Array>().expect("f64");
                let ints: Int64Array = (0..n)
                    .map(|i| {
                        if f.is_null(i) || f.value(i).fract() != 0.0 {
                            None
                        } else {
                            Some(f.value(i) as i64)
                        }
                    })
                    .collect();
                Arc::new(ints)
            }
            t => cast(&taken, t).expect("cast"),
        }
    }

    /// Fire (emit + EVICT) every pane the `ready` predicate closes, destructively — the pane is
    /// removed and its accumulators drained. This is the only firing on the on-watermark path.
    fn fire(&mut self, ready: impl Fn(i64, i64) -> bool, set_fired_through: Option<i64>) -> Option<RecordBatch> {
        let size = self.kind.size();
        let starts: Vec<i64> = self.panes.keys().filter(|s| ready(**s, size)).copied().collect();
        if let Some(wm) = set_fired_through {
            self.fired_through = self.fired_through.max(wm);
        }
        if starts.is_empty() {
            return None;
        }
        let out_schema = self.output_schema();
        let mut batches = Vec::with_capacity(starts.len());
        for start in starts {
            let mut pane = self.panes.remove(&start).expect("present");
            let ids = self.sorted_ids(&pane); // every key in the pane
            if let Some(b) = self.emit_pane(start, &mut pane, &ids, true, &out_schema) {
                batches.push(b);
            }
        }
        if batches.is_empty() {
            return None;
        }
        Some(arrow::compute::concat_batches(&out_schema, &batches).expect("concat fired"))
    }

    /// EARLY fire (5a): emit the current partial value of each open window's DIRTY groups as upserts,
    /// **non-destructively** — the panes stay open and their accumulators keep accumulating — then
    /// clear the dirty sets. The window/group columns are identical to a closing fire, so the
    /// emission keys collide (`w|start|end|group`) and downstream last-write-wins converges to the
    /// exact closing value. Emission is proportional to CHANGED groups, not open-key count.
    fn fire_open(&mut self) -> Option<RecordBatch> {
        let out_schema = self.output_schema();
        let starts: Vec<i64> = self.panes.keys().copied().collect();
        let mut batches = Vec::new();
        for start in starts {
            // own the pane so `emit_pane` (which borrows `&self`) can also read its accumulators.
            let mut pane = self.panes.remove(&start).expect("present");
            let ids = self.sorted_dirty_ids(&pane);
            if let Some(b) = self.emit_pane(start, &mut pane, &ids, false, &out_schema) {
                batches.push(b);
            }
            pane.dirty.clear();
            self.panes.insert(start, pane); // re-open: an early fire never evicts.
        }
        if batches.is_empty() {
            return None;
        }
        Some(arrow::compute::concat_batches(&out_schema, &batches).expect("concat early"))
    }

    /// Assemble one fired batch for pane `start` over the given LOCAL `ids` (already sorted in key
    /// row-order). `destructive` reads each Df accumulator with `evaluate(EmitTo::All)` — for a
    /// closing pane about to be dropped; otherwise a non-destructive read that leaves the live
    /// accumulator intact — for an early fire of a still-open pane. `None` when `ids` is empty.
    fn emit_pane(
        &self,
        start: i64,
        pane: &mut Pane,
        ids: &[u32],
        destructive: bool,
        out_schema: &SchemaRef,
    ) -> Option<RecordBatch> {
        if ids.is_empty() {
            return None;
        }
        let size = self.kind.size();
        let n = ids.len();
        let idx = UInt32Array::from(ids.to_vec());
        let mut cols: Vec<ArrayRef> = Vec::with_capacity(2 + self.group_by.len() + self.plans.len());
        cols.push(Arc::new(Int64Array::from(vec![start; n])));
        cols.push(Arc::new(Int64Array::from(vec![start + size; n])));
        // group columns from the interned rows (none without a groupBy).
        if !self.group_by.is_empty() {
            let rows: Vec<_> = ids
                .iter()
                .map(|i| self.keys[pane.to_global[*i as usize] as usize].row())
                .collect();
            let key_cols = self
                .converter
                .as_ref()
                .expect("planned")
                .convert_rows(rows)
                .expect("rows convert back");
            cols.extend(key_cols);
        }
        for (pi, plan) in self.plans.iter().enumerate() {
            let arr: ArrayRef = match &plan.kind {
                AggKind::Distinct => {
                    let sets = pane.distinct[pi].as_ref().expect("distinct sets");
                    let counts: Float64Array = ids
                        .iter()
                        .map(|i| sets.get(*i as usize).map(|s| s.len() as f64).unwrap_or(0.0))
                        .collect::<Vec<_>>()
                        .into();
                    Arc::new(counts)
                }
                AggKind::Df { .. } => {
                    let all = if destructive {
                        pane.accs[pi].evaluate(EmitTo::All).expect("evaluate")
                    } else {
                        self.eval_open(pane, pi)
                    };
                    let picked = if all.len() >= pane.to_global.len() {
                        take(all.as_ref(), &idx, None).expect("take")
                    } else {
                        // an accumulator never fed (no group reached it): all null.
                        arrow::array::new_null_array(all.data_type(), n)
                    };
                    finalize(plan, picked)
                }
            };
            cols.push(arr);
        }
        Some(RecordBatch::try_new(Arc::clone(out_schema), cols).expect("fired batch"))
    }

    /// The current value of pane accumulator `pi`, read WITHOUT disturbing the live accumulator:
    /// snapshot its `state` (which resets it), re-merge that back so the live one is unchanged, and
    /// evaluate a scratch accumulator built from the same state to get the finals. This is exactly
    /// the snapshot-then-remerge pattern the checkpoint path already relies on (`state` resets).
    fn eval_open(&self, pane: &mut Pane, pi: usize) -> ArrayRef {
        let n = pane.to_global.len();
        let state = pane.accs[pi].state(EmitTo::All).expect("state"); // resets the live accumulator
        let idx: Vec<usize> = (0..n).collect();
        let restored: Vec<ArrayRef> = state.iter().map(|a| a.slice(0, n.min(a.len()))).collect();
        let ok = !restored.is_empty() && restored[0].len() == n;
        if ok {
            // put the live accumulator back exactly as it was.
            pane.accs[pi].merge_batch(&restored, &idx, None, n).expect("re-merge live");
        }
        let mut scratch = match &self.plans[pi].kind {
            AggKind::Df { udaf, input, .. } => create_acc(udaf, input),
            AggKind::Distinct => unreachable!("eval_open is only called for Df aggregates"),
        };
        if ok {
            scratch.merge_batch(&restored, &idx, None, n).expect("scratch merge");
        }
        scratch.evaluate(EmitTo::All).expect("evaluate")
    }

    /// A pane's LOCAL ids (0..keys-in-pane), sorted in key row-order for deterministic emission.
    fn sorted_ids(&self, pane: &Pane) -> Vec<u32> {
        let mut ids: Vec<u32> = (0..pane.to_global.len() as u32).collect();
        self.sort_by_key_row(&mut ids, pane);
        ids
    }

    /// A pane's DIRTY local ids, sorted in key row-order (the early-fire emission set).
    fn sorted_dirty_ids(&self, pane: &Pane) -> Vec<u32> {
        let mut ids: Vec<u32> = pane.dirty.iter().copied().collect();
        self.sort_by_key_row(&mut ids, pane);
        ids
    }

    fn sort_by_key_row(&self, ids: &mut [u32], pane: &Pane) {
        if !self.group_by.is_empty() {
            ids.sort_by(|a, b| {
                self.keys[pane.to_global[*a as usize] as usize]
                    .row()
                    .cmp(&self.keys[pane.to_global[*b as usize] as usize].row())
            });
        }
    }

    /// Append an early fire to a closing-fire result when the trigger is due. `now_ms` is `None` on
    /// the watermark path, where a processing-time trigger ([`Trigger::EveryMs`]) does not apply.
    fn with_early(&mut self, closed: Option<RecordBatch>, now_ms: Option<i64>) -> Option<RecordBatch> {
        if !self.early_due(now_ms) {
            return closed;
        }
        match (closed, self.fire_open()) {
            (None, early) => early,
            (closed, None) => closed,
            (Some(c), Some(e)) => {
                let schema = c.schema();
                Some(arrow::compute::concat_batches(&schema, &[c, e]).expect("concat closed+early"))
            }
        }
    }

    /// Whether an early fire is due now, consuming the cadence counter/anchor when it fires.
    fn early_due(&mut self, now_ms: Option<i64>) -> bool {
        match self.trigger {
            Trigger::OnWatermark => false,
            Trigger::EveryRows(n) => {
                if n > 0 && self.rows_since_early >= n {
                    self.rows_since_early = 0;
                    true
                } else {
                    false
                }
            }
            Trigger::EveryMs(ms) => match now_ms {
                Some(t) if ms > 0 => {
                    if self.last_early_ms == i64::MIN {
                        self.last_early_ms = t; // anchor on the first processing tick, don't fire yet
                        false
                    } else if t - self.last_early_ms >= ms {
                        self.last_early_ms = t;
                        true
                    } else {
                        false
                    }
                }
                _ => false,
            },
        }
    }
}

/// The row operator's finalize rules on a column of raw aggregate results.
fn finalize(plan: &AggPlan, arr: ArrayRef) -> ArrayRef {
    match plan.op {
        // sum/avg of no values are 0.0; count is a number.
        AggOp::Sum | AggOp::Avg | AggOp::Count => {
            let f = cast(&arr, &DataType::Float64).expect("cast");
            let f = f.as_any().downcast_ref::<Float64Array>().expect("f64");
            Arc::new(Float64Array::from(
                (0..f.len())
                    .map(|i| if f.is_null(i) { 0.0 } else { f.value(i) })
                    .collect::<Vec<_>>(),
            ))
        }
        AggOp::BoolAnd | AggOp::BoolOr => arr,
        _ => cast(&arr, &plan.out).expect("cast"),
    }
}

fn create_acc(udaf: &AggregateUDF, input: &DataType) -> Box<dyn GroupsAccumulator> {
    let dt = input.clone();
    let schema = Schema::new(vec![Field::new("v", dt.clone(), true)]);
    let expr: Arc<dyn PhysicalExpr> = col("v", &schema).expect("col");
    let exprs = [expr];
    let field: Arc<Field> = Arc::new(Field::new("v", dt.clone(), true));
    let expr_fields = [field];
    let return_field = Arc::new(Field::new("out", udaf.return_type(&[dt]).expect("return type"), true));
    let args = AccumulatorArgs {
        return_field,
        schema: &schema,
        ignore_nulls: false,
        order_bys: &[],
        is_reversed: false,
        name: udaf.name(),
        is_distinct: false,
        exprs: &exprs,
        expr_fields: &expr_fields,
    };
    udaf.create_groups_accumulator(args).expect("groups accumulator")
}

impl BatchOperator for WindowAggBatch {
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        self.wm.expect(partitions, now_ms);
    }

    fn push_batch(&mut self, partition: i32, batch: &RecordBatch, event_ms: &[i64]) -> usize {
        if batch.num_rows() == 0 {
            return 0;
        }
        if self.trigger.early_fires() {
            self.rows_since_early += batch.num_rows() as u64;
        }
        if self.converter.is_none() {
            self.plan_for(&batch.schema())
                .expect("aggregates plan against the schema");
        }
        for &t in event_ms {
            self.wm.observe(partition, t);
        }
        let size = self.kind.size();
        let ids = self.intern_keys(batch);
        // rows per pane start (arrival order kept within a pane).
        let mut by_pane: BTreeMap<i64, Vec<u32>> = BTreeMap::new();
        let mut late = 0usize;
        for (i, &t) in event_ms.iter().enumerate() {
            let mut added = false;
            for start in self.kind.starts_for(t) {
                if start + size <= self.fired_through {
                    continue;
                }
                added = true;
                by_pane.entry(start).or_default().push(i as u32);
            }
            if !added {
                late += 1;
            }
        }
        self.late_dropped += late as u64;
        for (start, rows) in by_pane {
            if !self.panes.contains_key(&start) {
                let p = self.new_pane();
                self.panes.insert(start, p);
            }
            let idx = UInt32Array::from(rows.clone());
            let group_indices: Vec<usize> = rows.iter().map(|r| ids[*r as usize] as usize).collect();
            // the accumulator inputs for this pane's rows, computed before the pane is borrowed.
            let inputs: Vec<Option<ArrayRef>> = self
                .plans
                .iter()
                .map(|plan| match &plan.kind {
                    AggKind::Df { .. } => Some(self.agg_input(plan, batch, &idx, event_ms)),
                    AggKind::Distinct => None,
                })
                .collect();
            // map this batch's global key ids to the pane's LOCAL id space (assign on first sight),
            // so the accumulators size to the keys IN this pane, not the operator's global key count.
            let pane = self.panes.get_mut(&start).expect("inserted");
            let local_indices: Vec<usize> = group_indices
                .iter()
                .map(|&g| {
                    let g = g as u32;
                    match pane.local.get(&g) {
                        Some(&l) => l as usize,
                        None => {
                            let l = pane.to_global.len();
                            pane.local.insert(g, l as u32);
                            pane.to_global.push(g);
                            l
                        }
                    }
                })
                .collect();
            let n_local = pane.to_global.len();
            for (pi, plan) in self.plans.iter().enumerate() {
                match &plan.kind {
                    AggKind::Distinct => {
                        let Some(colv) = batch.column_by_name(&plan.column) else {
                            continue;
                        };
                        let taken = take(colv.as_ref(), &idx, None).expect("take");
                        let sets = pane.distinct[pi].as_mut().expect("sets");
                        if sets.len() < n_local {
                            sets.resize_with(n_local, HashMap::new);
                        }
                        // one byte row per value: null skipped.
                        let conv = RowConverter::new(vec![SortField::new(taken.data_type().clone())]).expect("conv");
                        let vrows = conv.convert_columns(&[Arc::clone(&taken)]).expect("convert");
                        for (r, l) in local_indices.iter().enumerate() {
                            if taken.is_null(r) {
                                continue;
                            }
                            sets[*l].insert(vrows.row(r).as_ref().to_vec(), ());
                        }
                    }
                    AggKind::Df { .. } => {
                        let values = inputs[pi].clone().expect("input computed");
                        pane.accs[pi]
                            .update_batch(&[values], &local_indices, None, n_local)
                            .expect("update_batch");
                    }
                }
            }
            // Updating aggregate (5a): every group this batch touched is now dirty for the next
            // early fire. Only tracked when a trigger early-fires — the on-watermark path never
            // allocates into `dirty`.
            if self.trigger.early_fires() {
                for &l in &local_indices {
                    pane.dirty.insert(l as u32);
                }
            }
        }
        late
    }

    fn advance(&mut self, now_ms: i64) -> Option<RecordBatch> {
        self.wm.tick(now_ms);
        let wm = self.wm.current(now_ms);
        let closed = if wm == i64::MIN {
            None
        } else {
            self.fire(|start, size| start + size <= wm, Some(wm))
        };
        self.with_early(closed, Some(now_ms))
    }

    fn advance_to(&mut self, watermark_ms: i64) -> Option<RecordBatch> {
        let wm = self.wm.after_lateness(watermark_ms);
        let closed = if wm == i64::MIN {
            None
        } else {
            self.fire(|start, size| start + size <= wm, Some(wm))
        };
        self.with_early(closed, None)
    }

    fn flush(&mut self) -> Option<RecordBatch> {
        self.fired_through = i64::MAX;
        self.fire(|_, _| true, None)
    }

    fn output_schema(&self) -> SchemaRef {
        let mut fields = vec![
            Field::new(WINDOW_START, DataType::Int64, false),
            Field::new(WINDOW_END, DataType::Int64, false),
        ];
        for (g, t) in self.group_by.iter().zip(self.key_types.iter()) {
            fields.push(Field::new(g, t.clone(), true));
        }
        for p in &self.plans {
            fields.push(Field::new(&p.alias, p.out.clone(), true));
        }
        Arc::new(Schema::new(fields))
    }

    /// Snapshot layout (one IPC stream): batch 0 = header (`v`, `cfg`, `fired_through`,
    /// `late_dropped`, watermark json, key rows as Binary); then per pane one batch per aggregate
    /// with the accumulator's `state` arrays (and the distinct sets as Binary lists), tagged in
    /// the schema metadata with the pane start and the aggregate index and the seen bitmap.
    fn snapshot(&mut self) -> Vec<u8> {
        // Framing: `[u32 len][IPC stream]` for the header, then one per pane — the reader never
        // has to know where a stream ends.
        let mut bytes = Vec::new();
        let frame = |bytes: &mut Vec<u8>, stream: Vec<u8>| {
            bytes.extend_from_slice(&(stream.len() as u32).to_le_bytes());
            bytes.extend_from_slice(&stream);
        };
        {
            let mut header_bytes = Vec::new();
            // header
            let owned: Vec<Vec<u8>> = self.keys.iter().map(|k| k.row().as_ref().to_vec()).collect();
            let keys = BinaryArray::from(owned.iter().map(|v| v.as_slice()).collect::<Vec<&[u8]>>());
            let header_schema = Arc::new(
                Schema::new(vec![Field::new("key", DataType::Binary, true)]).with_metadata(
                    [
                        ("v".to_string(), SNAPSHOT_VERSION.to_string()),
                        ("cfg".to_string(), self.cfg_fingerprint()),
                        ("fired_through".to_string(), self.fired_through.to_string()),
                        ("late_dropped".to_string(), self.late_dropped.to_string()),
                        ("wm".to_string(), self.wm.state_to_json().to_string()),
                        ("panes".to_string(), self.panes.len().to_string()),
                    ]
                    .into_iter()
                    .collect(),
                ),
            );
            let header = RecordBatch::try_new(Arc::clone(&header_schema), vec![Arc::new(keys)]).expect("header");
            let mut w = StreamWriter::try_new(&mut header_bytes, &header_schema).expect("writer");
            w.write(&header).expect("write header");
            w.finish().expect("finish");
            drop(w);
            frame(&mut bytes, header_bytes);
        }
        {
            // the input schema the plan was built against, so a restore into a fresh operator (no
            // batch seen yet) can plan first; empty when nothing has been planned.
            let schema = self.input_schema.clone().unwrap_or_else(|| Arc::new(Schema::empty()));
            let mut schema_bytes = Vec::new();
            let mut w = StreamWriter::try_new(&mut schema_bytes, &schema).expect("writer");
            w.finish().expect("finish");
            drop(w);
            frame(&mut bytes, schema_bytes);
        }
        // panes: each as its own IPC stream appended (a snapshot is a sequence of streams).
        for (start, pane) in self.panes.iter_mut() {
            let to_global: UInt32Array = pane.to_global.clone().into();
            let n = pane.to_global.len();
            // nullable: a distinct set can hold more (group, value) pairs than the pane has keys, and
            // every column is padded to the longest — a padded `seen` slot reads as "not seen".
            let mut fields = vec![Field::new("to_global", DataType::UInt32, true)];
            let mut cols: Vec<ArrayRef> = vec![Arc::new(to_global)];
            for (pi, plan) in self.plans.iter().enumerate() {
                match &plan.kind {
                    AggKind::Distinct => {
                        let sets = pane.distinct[pi].as_ref().expect("sets");
                        // every (group, value) pair as a Binary list flattened with a group index.
                        let mut groups: Vec<u32> = Vec::new();
                        let mut vals: Vec<Vec<u8>> = Vec::new();
                        for (g, s) in sets.iter().enumerate() {
                            for v in s.keys() {
                                groups.push(g as u32);
                                vals.push(v.clone());
                            }
                        }
                        // stored as separate batches would complicate; encode as one Binary column
                        // of `group(4 bytes LE) ++ value`.
                        let owned: Vec<Vec<u8>> = groups
                            .iter()
                            .zip(vals.iter())
                            .map(|(g, v)| {
                                let mut b = g.to_le_bytes().to_vec();
                                b.extend_from_slice(v);
                                b
                            })
                            .collect();
                        let enc = BinaryArray::from(owned.iter().map(|v| v.as_slice()).collect::<Vec<&[u8]>>());
                        // pad to n rows with nulls so all columns share a length.
                        let padded = pad_to(Arc::new(enc), n.max(groups.len()));
                        fields.push(Field::new(format!("d{pi}"), DataType::Binary, true));
                        cols.push(padded);
                    }
                    AggKind::Df { .. } => {
                        // `state` resets the accumulator; re-merge so the live operator continues.
                        let state = pane.accs[pi].state(EmitTo::All).expect("state");
                        let all: Vec<usize> = (0..n).collect();
                        let restored: Vec<ArrayRef> = state.iter().map(|a| a.slice(0, n.min(a.len()))).collect();
                        if !restored.is_empty() && restored[0].len() == n {
                            pane.accs[pi].merge_batch(&restored, &all, None, n).expect("re-merge");
                        }
                        for (si, s) in state.iter().enumerate() {
                            fields.push(Field::new(format!("a{pi}_{si}"), s.data_type().clone(), true));
                            cols.push(pad_to(Arc::clone(s), n));
                        }
                    }
                }
            }
            let len = cols.iter().map(|c| c.len()).max().unwrap_or(0);
            let cols: Vec<ArrayRef> = cols.into_iter().map(|c| pad_to(c, len)).collect();
            let schema = Arc::new(
                Schema::new(fields).with_metadata([("start".to_string(), start.to_string())].into_iter().collect()),
            );
            let b = RecordBatch::try_new(Arc::clone(&schema), cols).expect("pane batch");
            let mut pane_bytes = Vec::new();
            let mut w = StreamWriter::try_new(&mut pane_bytes, &schema).expect("writer");
            w.write(&b).expect("write pane");
            w.finish().expect("finish");
            drop(w);
            frame(&mut bytes, pane_bytes);
        }
        bytes
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        // frames: `[u32 len][IPC stream]`…
        let mut frames: Vec<&[u8]> = Vec::new();
        let mut pos = 0usize;
        while pos + 4 <= bytes.len() {
            let len = u32::from_le_bytes(bytes[pos..pos + 4].try_into().map_err(|_| "snapshot: frame")?) as usize;
            pos += 4;
            if pos + len > bytes.len() {
                return Err("snapshot: truncated frame".into());
            }
            frames.push(&bytes[pos..pos + len]);
            pos += len;
        }
        let mut frames = frames.into_iter();
        let header_bytes = frames.next().ok_or("snapshot: empty")?;
        let mut r = StreamReader::try_new(header_bytes, None).map_err(|e| format!("snapshot: {e}"))?;
        let header = r.next().ok_or("snapshot: empty")?.map_err(|e| e.to_string())?;
        let md = header.schema().metadata().clone();
        let v: i64 = md
            .get("v")
            .and_then(|s| s.parse().ok())
            .ok_or("snapshot: missing version")?;
        if v != SNAPSHOT_VERSION {
            return Err(format!("snapshot: version {v} != supported {SNAPSHOT_VERSION}"));
        }
        let cfg = md.get("cfg").cloned().unwrap_or_default();
        if cfg != self.cfg_fingerprint() {
            return Err("snapshot: config mismatch (window kind/size, group_by, aggs or lateness differ)".into());
        }
        self.fired_through = md.get("fired_through").and_then(|s| s.parse().ok()).unwrap_or(i64::MIN);
        self.late_dropped = md.get("late_dropped").and_then(|s| s.parse().ok()).unwrap_or(0);
        if let Some(w) = md.get("wm") {
            let j: serde_json::Value = serde_json::from_str(w).map_err(|e| e.to_string())?;
            self.wm.load_state(&j)?;
        }
        let n_panes: usize = md.get("panes").and_then(|s| s.parse().ok()).unwrap_or(0);
        // keys are byte rows whose types come from the plan; the schema frame below supplies the
        // plan for a fresh operator.
        let keys = header
            .column(0)
            .as_any()
            .downcast_ref::<BinaryArray>()
            .ok_or("snapshot: keys")?;
        // the input schema frame: a fresh operator (no batch seen yet) plans against it first.
        let schema_bytes = frames.next().ok_or("snapshot: schema frame missing")?;
        let sr = StreamReader::try_new(schema_bytes, None).map_err(|e| format!("snapshot schema: {e}"))?;
        let input_schema = sr.schema();
        if self.converter.is_none() {
            if input_schema.fields().is_empty() {
                // nothing was ever planned or held: an empty operator restores to empty.
                return Ok(());
            }
            self.plan_for(&input_schema)?;
        }
        let converter = self.converter.as_ref().expect("planned above");
        // rebuild the interning from the byte rows.
        self.key_ids.clear();
        self.keys.clear();
        let parser = converter.parser();
        for i in 0..keys.len() {
            let b = keys.value(i).to_vec();
            let row = parser.parse(&b).owned();
            self.key_ids.insert(b, i as u32);
            self.keys.push(row);
        }
        drop(r);
        // panes: one frame each.
        self.panes.clear();
        for _ in 0..n_panes {
            let pane_bytes = frames.next().ok_or("snapshot: pane frame missing")?;
            let mut pr = StreamReader::try_new(pane_bytes, None).map_err(|e| format!("snapshot pane: {e}"))?;
            let b = pr.next().ok_or("snapshot: pane missing")?.map_err(|e| e.to_string())?;
            let start: i64 = b
                .schema()
                .metadata()
                .get("start")
                .and_then(|s| s.parse().ok())
                .ok_or("snapshot: pane start")?;
            let tg = b
                .column(0)
                .as_any()
                .downcast_ref::<UInt32Array>()
                .ok_or("snapshot: to_global")?;
            let mut pane = self.new_pane();
            for i in 0..tg.len() {
                if tg.is_valid(i) {
                    let g = tg.value(i);
                    pane.local.insert(g, pane.to_global.len() as u32);
                    pane.to_global.push(g);
                }
            }
            let n = pane.to_global.len();
            let all: Vec<usize> = (0..n).collect();
            for (pi, plan) in self.plans.iter().enumerate() {
                match &plan.kind {
                    AggKind::Distinct => {
                        let colv = b.column_by_name(&format!("d{pi}")).ok_or("snapshot: distinct column")?;
                        let enc = colv
                            .as_any()
                            .downcast_ref::<BinaryArray>()
                            .ok_or("snapshot: distinct bytes")?;
                        let sets = pane.distinct[pi].as_mut().expect("sets");
                        sets.resize_with(n, HashMap::new);
                        for i in 0..enc.len() {
                            if enc.is_null(i) {
                                continue;
                            }
                            let v = enc.value(i);
                            let g =
                                u32::from_le_bytes(v[..4].try_into().map_err(|_| "snapshot: distinct group")?) as usize;
                            sets[g].insert(v[4..].to_vec(), ());
                        }
                    }
                    AggKind::Df { .. } => {
                        let state: Vec<ArrayRef> = b
                            .schema()
                            .fields()
                            .iter()
                            .enumerate()
                            .filter(|(_, f)| f.name().starts_with(&format!("a{pi}_")))
                            .map(|(i, _)| b.column(i).slice(0, n))
                            .collect();
                        if !state.is_empty() && n > 0 {
                            pane.accs[pi]
                                .merge_batch(&state, &all, None, n)
                                .map_err(|e| format!("snapshot: merge: {e}"))?;
                        }
                    }
                }
            }
            self.panes.insert(start, pane);
        }
        // Updating aggregate (5a): a restore resets the early-fire cadence and re-marks every open
        // group dirty, so the first post-restore early fire RE-SYNCS the whole open view (no stale
        // intermediate value can survive a restore). The closing value is exact regardless. The
        // cadence counters are dynamic, not persisted — the config fingerprint already pins the
        // trigger, so a checkpoint only loads into a same-trigger operator.
        if self.trigger.early_fires() {
            self.rows_since_early = 0;
            self.last_early_ms = i64::MIN;
            for pane in self.panes.values_mut() {
                pane.dirty = (0..pane.to_global.len() as u32).collect();
            }
        }
        Ok(())
    }
}

/// The row seam, so the engine's existing per-partition plumbing (restore, checkpoint, flush)
/// drives the columnar operator unchanged: batches go in through `push_batch`, a lone row through
/// a one-row batch, and fired batches come out as `WindowRow`s until the engine emits columns.
impl crate::WindowOperator for WindowAggBatch {
    fn state_bytes(&self) -> usize {
        WindowAggBatch::state_bytes(self)
    }
    fn open_windows(&self) -> usize {
        self.open_panes()
    }
    fn expect_partitions(&mut self, partitions: &[i32], now_ms: i64) {
        BatchOperator::expect_partitions(self, partitions, now_ms);
    }

    fn push(&mut self, partition: i32, event_ms: i64, row: &[(String, fv_value::Value)]) -> bool {
        // the slow path: a one-row batch in the operator's input schema (planned on the first
        // batch); before any batch, the row's own value types define it.
        let schema = match &self.input_schema {
            Some(s) => Arc::clone(s),
            None => Arc::new(Schema::new(
                row.iter()
                    .map(|(k, v)| Field::new(k, value_type(v), true))
                    .collect::<Vec<_>>(),
            )),
        };
        let cols: Vec<ArrayRef> = schema
            .fields()
            .iter()
            .map(|f| {
                let v = row.iter().find(|(k, _)| k == f.name()).map(|(_, v)| v);
                value_array(v, f.data_type())
            })
            .collect();
        let b = RecordBatch::try_new(schema, cols).expect("one-row batch");
        BatchOperator::push_batch(self, partition, &b, &[event_ms]) == 0
    }

    fn push_batch(&mut self, partition: i32, batch: &RecordBatch, event_ms: &[i64]) -> Option<usize> {
        Some(BatchOperator::push_batch(self, partition, batch, event_ms))
    }

    fn advance_batch(&mut self, now_ms: i64) -> Option<Option<RecordBatch>> {
        Some(BatchOperator::advance(self, now_ms))
    }

    fn advance_batch_to(&mut self, watermark_ms: i64) -> Option<Option<RecordBatch>> {
        Some(BatchOperator::advance_to(self, watermark_ms))
    }

    fn flush_batch(&mut self) -> Option<Option<RecordBatch>> {
        Some(BatchOperator::flush(self))
    }

    fn advance(&mut self, now_ms: i64) -> Vec<crate::WindowRow> {
        BatchOperator::advance(self, now_ms)
            .map(|b| self.batch_to_window_rows(&b))
            .unwrap_or_default()
    }

    fn advance_to(&mut self, watermark_ms: i64) -> Vec<crate::WindowRow> {
        BatchOperator::advance_to(self, watermark_ms)
            .map(|b| self.batch_to_window_rows(&b))
            .unwrap_or_default()
    }

    fn flush(&mut self) -> Vec<crate::WindowRow> {
        BatchOperator::flush(self)
            .map(|b| self.batch_to_window_rows(&b))
            .unwrap_or_default()
    }

    fn snapshot(&mut self) -> Vec<u8> {
        BatchOperator::snapshot(self)
    }

    fn load_snapshot(&mut self, bytes: &[u8]) -> Result<(), String> {
        BatchOperator::load_snapshot(self, bytes)
    }
}

impl WindowAggBatch {
    /// Fired rows as the row seam's `WindowRow`s (group values in `group_by` order).
    fn batch_to_window_rows(&self, b: &RecordBatch) -> Vec<crate::WindowRow> {
        let start = b.column(0).as_any().downcast_ref::<Int64Array>().expect("windowStart");
        let end = b.column(1).as_any().downcast_ref::<Int64Array>().expect("windowEnd");
        let ng = self.group_by.len();
        (0..b.num_rows())
            .map(|i| crate::WindowRow {
                window_start: start.value(i),
                window_end: end.value(i),
                key: (0..ng).map(|g| cell_value(b.column(2 + g), i)).collect(),
                aggs: self
                    .plans
                    .iter()
                    .enumerate()
                    .map(|(pi, p)| (p.alias.clone(), cell_value(b.column(2 + ng + pi), i)))
                    .collect(),
            })
            .collect()
    }
}

/// The Arrow type a dialect value lands in.
fn value_type(v: &fv_value::Value) -> DataType {
    match v {
        fv_value::Value::Num(_) => DataType::Float64,
        fv_value::Value::Str(_) => DataType::Utf8,
        fv_value::Value::Bool(_) => DataType::Boolean,
        _ => DataType::Null,
    }
}

/// A one-element array of `v` as `t` (null when absent or of another type).
fn value_array(v: Option<&fv_value::Value>, t: &DataType) -> ArrayRef {
    match (t, v) {
        (DataType::Float64, Some(fv_value::Value::Num(n))) => Arc::new(Float64Array::from(vec![*n])),
        (DataType::Int64, Some(fv_value::Value::Num(n))) => Arc::new(Int64Array::from(vec![*n as i64])),
        (DataType::Utf8, Some(fv_value::Value::Str(s))) => Arc::new(arrow::array::StringArray::from(vec![s.as_str()])),
        (DataType::Boolean, Some(fv_value::Value::Bool(b))) => Arc::new(BooleanArray::from(vec![*b])),
        _ => arrow::array::new_null_array(t, 1),
    }
}

/// One cell as a dialect value (the few types the operator emits).
fn cell_value(a: &ArrayRef, i: usize) -> fv_value::Value {
    if a.is_null(i) {
        return fv_value::Value::Null;
    }
    match a.data_type() {
        DataType::Float64 => fv_value::Value::Num(a.as_any().downcast_ref::<Float64Array>().unwrap().value(i)),
        DataType::Int64 => fv_value::Value::Num(a.as_any().downcast_ref::<Int64Array>().unwrap().value(i) as f64),
        DataType::Utf8 => fv_value::Value::Str(
            a.as_any()
                .downcast_ref::<arrow::array::StringArray>()
                .unwrap()
                .value(i)
                .to_string(),
        ),
        DataType::Boolean => fv_value::Value::Bool(a.as_any().downcast_ref::<BooleanArray>().unwrap().value(i)),
        _ => fv_value::Value::Null,
    }
}

fn pad_to(a: ArrayRef, n: usize) -> ArrayRef {
    if a.len() >= n {
        return a;
    }
    let nulls = arrow::array::new_null_array(a.data_type(), n - a.len());
    arrow::compute::concat(&[a.as_ref(), nulls.as_ref()]).expect("pad")
}

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

    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)
    }

    fn aggs() -> Vec<Agg> {
        vec![
            Agg::count("n"),
            Agg::of(AggOp::Sum, "v", "s"),
            Agg::of(AggOp::Avg, "v", "a"),
            Agg::of(AggOp::Min, "v", "mn"),
            Agg::of(AggOp::Max, "v", "mx"),
        ]
    }

    fn f64s(b: &RecordBatch, name: &str) -> Vec<f64> {
        let a = b.column_by_name(name).unwrap();
        let a = a.as_any().downcast_ref::<Float64Array>().unwrap();
        (0..a.len()).map(|i| a.value(i)).collect()
    }

    fn i64s(b: &RecordBatch, name: &str) -> Vec<i64> {
        let a = b.column_by_name(name).unwrap();
        let a = a.as_any().downcast_ref::<Int64Array>().unwrap();
        (0..a.len()).map(|i| a.value(i)).collect()
    }

    fn strs(b: &RecordBatch, name: &str) -> Vec<String> {
        let a = b.column_by_name(name).unwrap();
        let a = a.as_any().downcast_ref::<StringArray>().unwrap();
        (0..a.len()).map(|i| a.value(i).to_string()).collect()
    }

    #[test]
    fn tumbling_windows_fire_on_the_watermark_with_exact_aggregates() {
        let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("b", 5.0, 200), ("a", 3.0, 900), ("a", 10.0, 1500)]);
        assert_eq!(op.push_batch(0, &b, &t), 0);
        assert_eq!(op.open_panes(), 2);
        let fired = op.advance(0).unwrap();
        // watermark = 1500 → the [0,1000) pane fires; [1000,2000) stays open.
        assert_eq!(fired.num_rows(), 2);
        assert_eq!(strs(&fired, "k"), vec!["a", "b"]);
        assert_eq!(f64s(&fired, "n"), vec![2.0, 1.0]);
        assert_eq!(f64s(&fired, "s"), vec![4.0, 5.0]);
        assert_eq!(f64s(&fired, "a"), vec![2.0, 5.0]);
        assert_eq!(f64s(&fired, "mn"), vec![1.0, 5.0]);
        assert_eq!(f64s(&fired, "mx"), vec![3.0, 5.0]);
        assert_eq!(i64s(&fired, WINDOW_END), vec![1000, 1000]);
        assert_eq!(op.open_panes(), 1);
        let rest = op.flush().unwrap();
        assert_eq!(f64s(&rest, "s"), vec![10.0]);
    }

    #[test]
    fn advance_to_fires_by_the_delivered_watermark_less_lateness_never_by_the_rows() {
        // in-band time: rows at 9900 do not close anything; the caller's watermark does, and
        // the operator's allowed lateness still applies to it.
        let mut op = WindowAggBatch::tumbling(1000, 500, vec!["k".into()], vec![Agg::count("n")]);
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("b", 1.0, 9_900)]);
        assert_eq!(op.push_batch(0, &b, &t), 0);
        assert!(
            BatchOperator::advance_to(&mut op, 1_400).is_none(),
            "1400 − 500 < 1000: holds"
        );
        assert!(
            BatchOperator::advance_to(&mut op, i64::MIN).is_none(),
            "no time at all: holds"
        );
        let fired = BatchOperator::advance_to(&mut op, 1_500).unwrap();
        assert_eq!(strs(&fired, "k"), vec!["a"]);
        assert_eq!(i64s(&fired, WINDOW_END), vec![1000]);
        // a row for the fired window is now late by the same rule.
        let (late, t) = batch(&[("c", 1.0, 200)]);
        assert_eq!(op.push_batch(0, &late, &t), 1);
        assert_eq!(op.late_dropped(), 1);
        let rest = BatchOperator::advance_to(&mut op, 20_000).unwrap();
        assert_eq!(strs(&rest, "k"), vec!["b"]);
    }

    #[test]
    fn a_distinct_set_larger_than_the_key_count_snapshots_and_restores() {
        // REGRESSION (Nexmark q15): a global countDistinct — one key, thousands of distinct
        // values — padded the pane's non-nullable `seen` column with nulls and the snapshot
        // panicked at the first barrier.
        let mut op = WindowAggBatch::tumbling(1000, 0, vec![], vec![Agg::of(AggOp::CountDistinct, "k", "d")]);
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("b", 1.0, 200), ("c", 1.0, 300), ("a", 1.0, 400)]);
        assert_eq!(op.push_batch(0, &b, &t), 0);
        let snap = op.snapshot();
        let mut restored = WindowAggBatch::tumbling(1000, 0, vec![], vec![Agg::of(AggOp::CountDistinct, "k", "d")]);
        restored.expect_partitions(&[0], 0);
        restored.load_snapshot(&snap).unwrap();
        let (b2, t2) = batch(&[("d", 1.0, 1500)]);
        restored.push_batch(0, &b2, &t2);
        let fired = BatchOperator::advance(&mut restored, 0).unwrap();
        assert_eq!(f64s(&fired, "d"), vec![3.0], "a, b, c — the restored set counts three");
        // the live operator continues too (its snapshot did not disturb the set).
        op.push_batch(0, &b2, &t2);
        let fired = BatchOperator::advance(&mut op, 0).unwrap();
        assert_eq!(f64s(&fired, "d"), vec![3.0]);
    }

    #[test]
    fn sliding_windows_land_an_event_in_every_overlapping_pane() {
        let mut op = WindowAggBatch::sliding(1000, 500, 0, vec![], vec![Agg::count("n")]);
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("x", 1.0, 700)]);
        op.push_batch(0, &b, &t);
        assert_eq!(op.open_panes(), 2, "starts 500 and 0");
        let out = op.flush().unwrap();
        assert_eq!(i64s(&out, WINDOW_START), vec![0, 500]);
        assert_eq!(f64s(&out, "n"), vec![1.0, 1.0]);
    }

    #[test]
    fn late_events_are_dropped_and_counted_after_the_pane_fired() {
        let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")]);
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("a", 1.0, 2500)]);
        op.push_batch(0, &b, &t);
        assert!(op.advance(0).is_some()); // fires [0,1000) and [1000,2000)? only panes seen: [0,1000)
        let (late, tl) = batch(&[("a", 1.0, 150)]);
        assert_eq!(op.push_batch(0, &late, &tl), 1);
        assert_eq!(op.late_dropped(), 1);
    }

    #[test]
    fn allowed_lateness_holds_the_pane_open() {
        let mut op = WindowAggBatch::tumbling(1000, 500, vec![], vec![Agg::count("n")]);
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("a", 1.0, 1200)]);
        op.push_batch(0, &b, &t);
        assert!(op.advance(0).is_none(), "watermark 700 < end 1000");
        let (b2, t2) = batch(&[("a", 1.0, 1600)]);
        op.push_batch(0, &b2, &t2);
        let fired = op.advance(0).unwrap();
        assert_eq!(f64s(&fired, "n"), vec![1.0]);
    }

    #[test]
    fn a_lagging_partition_holds_firing() {
        let mut op = WindowAggBatch::tumbling(1000, 0, vec![], vec![Agg::count("n")]);
        op.expect_partitions(&[0, 1], 0);
        let (b, t) = batch(&[("a", 1.0, 5000)]);
        op.push_batch(0, &b, &t);
        assert!(op.advance(0).is_none(), "partition 1 has not reported");
        let (b1, t1) = batch(&[("a", 1.0, 2500)]);
        op.push_batch(1, &b1, &t1);
        // watermark = min(5000, 2500) = 2500: [2000,3000) is still open, [5000,6000) too — and the
        // pane partition 0 opened at 5000 must wait for partition 1 to pass 6000.
        assert!(op.advance(0).is_none());
        let (b2, t2) = batch(&[("a", 1.0, 6500)]);
        op.push_batch(1, &b2, &t2);
        // watermark = min(5000, 6500) = 5000: [2000,3000) fires; [5000,6000) (partition 0) and
        // [6000,7000) (the 6500 event) still wait for partition 0 to advance.
        let fired = op.advance(0).unwrap();
        assert_eq!(i64s(&fired, WINDOW_START), vec![2000]);
        assert_eq!(i64s(&op.flush().unwrap(), WINDOW_START), vec![5000, 6000]);
    }

    #[test]
    fn the_whole_op_family_matches_the_row_operator_rules() {
        let schema = Arc::new(Schema::new(vec![
            Field::new("v", DataType::Float64, true),
            Field::new("b", DataType::Boolean, true),
            Field::new("s", DataType::Utf8, true),
        ]));
        let v: Float64Array = vec![Some(2.0), Some(4.0), None, Some(2.5)].into();
        let bb: BooleanArray = vec![Some(true), Some(false), None, Some(true)].into();
        let s: StringArray = vec!["x", "y", "x", "x"].into();
        let b = RecordBatch::try_new(schema, vec![Arc::new(v), Arc::new(bb), Arc::new(s)]).unwrap();
        let aggs = vec![
            Agg::count("n"),
            Agg::of(AggOp::CountDistinct, "s", "ds"),
            Agg::of(AggOp::Sum, "v", "sum"),
            Agg::of(AggOp::Min, "s", "min_s"), // strings are not numeric: null
            Agg::of(AggOp::VarSamp, "v", "vs"),
            Agg::of(AggOp::StddevPop, "v", "sp"),
            Agg::of(AggOp::BoolAnd, "b", "ba"),
            Agg::of(AggOp::BoolOr, "b", "bo"),
            Agg::of(AggOp::BitOr, "v", "bor"), // 2 | 4 (2.5 skipped) = 6
        ];
        let mut op = WindowAggBatch::tumbling(1000, 0, vec![], aggs);
        op.expect_partitions(&[0], 0);
        op.push_batch(0, &b, &[1, 2, 3, 4]);
        let out = op.flush().unwrap();
        assert_eq!(f64s(&out, "n"), vec![4.0]);
        assert_eq!(f64s(&out, "ds"), vec![2.0]);
        assert_eq!(f64s(&out, "sum"), vec![8.5]);
        assert!(out.column_by_name("min_s").unwrap().is_null(0));
        let vs = f64s(&out, "vs")[0];
        assert!((vs - 1.0833333333).abs() < 1e-6, "var_samp of 2,4,2.5 = {vs}");
        let sp = f64s(&out, "sp")[0];
        assert!((sp - 0.8498365855).abs() < 1e-6, "stddev_pop = {sp}");
        let ba = out.column_by_name("ba").unwrap();
        let ba = ba.as_any().downcast_ref::<BooleanArray>().unwrap();
        assert!(!ba.value(0));
        let bo = out.column_by_name("bo").unwrap();
        assert!(bo.as_any().downcast_ref::<BooleanArray>().unwrap().value(0));
        assert_eq!(f64s(&out, "bor"), vec![6.0]);
    }

    #[test]
    fn snapshot_restore_fires_identically_to_the_uninterrupted_run() {
        let (b1, t1) = batch(&[("a", 1.0, 100), ("b", 2.0, 300), ("a", 3.0, 1100)]);
        let (b2, t2) = batch(&[("a", 4.0, 1200), ("c", 5.0, 2500)]);
        let run = |restore: bool| -> Vec<(f64, String, f64)> {
            let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
            op.expect_partitions(&[0], 0);
            op.push_batch(0, &b1, &t1);
            let mut op = if restore {
                let snap = op.snapshot();
                let mut fresh = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
                fresh.expect_partitions(&[0], 0);
                fresh.load_snapshot(&snap).unwrap();
                fresh
            } else {
                op
            };
            op.push_batch(0, &b2, &t2);
            let mut out = Vec::new();
            for fired in [op.advance(0), op.flush()].into_iter().flatten() {
                let starts = i64s(&fired, WINDOW_START);
                let ks = strs(&fired, "k");
                let sums = f64s(&fired, "s");
                for i in 0..fired.num_rows() {
                    out.push((starts[i] as f64, ks[i].clone(), sums[i]));
                }
            }
            out
        };
        let plain = run(false);
        let restored = run(true);
        assert_eq!(plain, restored);
        // [0,1000): a, b · [1000,2000): a (1100 + 1200) · [2000,3000): c
        assert_eq!(plain.len(), 4);
    }

    #[test]
    fn snapshot_refuses_a_config_mismatch() {
        let (b1, t1) = batch(&[("a", 1.0, 100)]);
        let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
        op.push_batch(0, &b1, &t1);
        let snap = op.snapshot();
        let mut other = WindowAggBatch::tumbling(2000, 0, vec!["k".into()], aggs());
        assert!(other.load_snapshot(&snap).is_err());
    }

    // ── 5a: the updating windowed aggregate (early firing / upsert emission) ──────────────────────

    #[test]
    fn on_watermark_trigger_matches_the_default_exactly() {
        // an explicit OnWatermark is byte-identical to no trigger at all: no early rows, same close.
        let feed = |op: &mut WindowAggBatch| {
            op.expect_partitions(&[0], 0);
            let (b, t) = batch(&[("a", 1.0, 100), ("b", 1.0, 200), ("a", 1.0, 900)]);
            op.push_batch(0, &b, &t);
            BatchOperator::advance_to(&mut *op, 1000).unwrap()
        };
        let mut explicit = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")])
            .with_trigger(Trigger::OnWatermark);
        let mut plain = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")]);
        let e = feed(&mut explicit);
        let p = feed(&mut plain);
        assert_eq!(strs(&e, "k"), strs(&p, "k"));
        assert_eq!(f64s(&e, "n"), f64s(&p, "n"));
        assert_eq!(f64s(&e, "n"), vec![2.0, 1.0]);
        // and the config fingerprint is unchanged, so old checkpoints still load.
        assert_eq!(explicit.cfg_fingerprint(), plain.cfg_fingerprint());
    }

    #[test]
    fn every_rows_early_fires_are_partial_and_converge_to_the_exact_close() {
        let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")])
            .with_trigger(Trigger::EveryRows(2));
        op.expect_partitions(&[0], 0);
        // two rows in [0,1000): the trigger fires the OPEN pane's current partials (a=1, b=1),
        // under the window's real bounds — the same emission key the close will reuse.
        let (b, t) = batch(&[("a", 1.0, 100), ("b", 1.0, 200)]);
        op.push_batch(0, &b, &t);
        let early1 = BatchOperator::advance_to(&mut op, 500).expect("early fire");
        assert_eq!(strs(&early1, "k"), vec!["a", "b"]);
        assert_eq!(f64s(&early1, "n"), vec![1.0, 1.0]);
        assert_eq!(i64s(&early1, WINDOW_END), vec![1000, 1000]);
        assert_eq!(op.open_panes(), 1, "an early fire does NOT evict the window");
        // two more rows for `a` only → the next early fire re-emits ONLY the changed group (a=3).
        let (b, t) = batch(&[("a", 1.0, 300), ("a", 1.0, 400)]);
        op.push_batch(0, &b, &t);
        let early2 = BatchOperator::advance_to(&mut op, 500).expect("early fire");
        assert_eq!(strs(&early2, "k"), vec!["a"], "only the dirty group re-emits");
        assert_eq!(f64s(&early2, "n"), vec![3.0]);
        // the watermark closes the window → the FINAL, exact values (the last write per key).
        let close = BatchOperator::advance_to(&mut op, 1000).expect("close");
        assert_eq!(strs(&close, "k"), vec!["a", "b"]);
        assert_eq!(f64s(&close, "n"), vec![3.0, 1.0], "exact at close: a=3, b=1");
    }

    #[test]
    fn early_firing_is_non_destructive_the_close_equals_the_plain_run() {
        // avg/min/max exercise the state→re-merge→scratch read, where a destructive evaluate would
        // corrupt the live accumulator. An EveryRows(1) run must close identically to a plain run.
        let feed = |op: &mut WindowAggBatch| {
            op.expect_partitions(&[0], 0);
            for chunk in [
                &[("a", 2.0, 100), ("b", 5.0, 150)][..],
                &[("a", 4.0, 200), ("a", 6.0, 300)][..],
                &[("b", 1.0, 400)][..],
            ] {
                let (bb, tt) = batch(chunk);
                op.push_batch(0, &bb, &tt);
                let _ = BatchOperator::advance_to(&mut *op, 500); // an early fire between every batch
            }
            BatchOperator::advance_to(&mut *op, 1000).expect("close")
        };
        let mut early = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs())
            .with_trigger(Trigger::EveryRows(1));
        let mut plain = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], aggs());
        let e = feed(&mut early);
        let p = feed(&mut plain);
        assert_eq!(strs(&e, "k"), strs(&p, "k"));
        for col in ["n", "s", "a", "mn", "mx"] {
            assert_eq!(f64s(&e, col), f64s(&p, col), "column {col}: early firing corrupted the accumulator");
        }
        // sanity: a=(2,4,6)→n3 s12 a4 mn2 mx6 ; b=(5,1)→n2 s6 a3 mn1 mx5.
        assert_eq!(f64s(&e, "n"), vec![3.0, 2.0]);
        assert_eq!(f64s(&e, "mx"), vec![6.0, 5.0]);
    }

    #[test]
    fn every_rows_replays_identically() {
        let run = || {
            let mut op = WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n"), Agg::of(AggOp::Sum, "v", "s")])
                .with_trigger(Trigger::EveryRows(2));
            op.expect_partitions(&[0], 0);
            let mut seq: Vec<(Vec<String>, Vec<f64>)> = Vec::new();
            for chunk in [&[("a", 1.0, 100), ("b", 2.0, 150)][..], &[("a", 3.0, 200), ("c", 4.0, 250)][..]] {
                let (bb, tt) = batch(chunk);
                op.push_batch(0, &bb, &tt);
                if let Some(f) = BatchOperator::advance_to(&mut op, 500) {
                    seq.push((strs(&f, "k"), f64s(&f, "s")));
                }
            }
            if let Some(f) = BatchOperator::advance_to(&mut op, 1000) {
                seq.push((strs(&f, "k"), f64s(&f, "s")));
            }
            seq
        };
        assert_eq!(run(), run(), "same input → identical early-fire + close emission sequence");
    }

    #[test]
    fn a_restore_resyncs_every_open_group_as_dirty() {
        let mk = || {
            WindowAggBatch::tumbling(1000, 0, vec!["k".into()], vec![Agg::count("n")])
                .with_trigger(Trigger::EveryRows(1))
        };
        let mut op = mk();
        op.expect_partitions(&[0], 0);
        let (b, t) = batch(&[("a", 1.0, 100), ("b", 1.0, 200)]);
        op.push_batch(0, &b, &t);
        let _ = BatchOperator::advance_to(&mut op, 500); // early-fire a,b; the dirty set is now clear
        let snap = op.snapshot();
        let mut restored = mk();
        restored.expect_partitions(&[0], 0);
        restored.load_snapshot(&snap).unwrap();
        // one NEW row for c; the next early fire must re-emit a and b too — proving the restore
        // re-marked every open group dirty (a stale intermediate can't survive a restore).
        let (b2, t2) = batch(&[("c", 1.0, 300)]);
        restored.push_batch(0, &b2, &t2);
        let early = BatchOperator::advance_to(&mut restored, 500).expect("early fire");
        assert_eq!(strs(&early, "k"), vec!["a", "b", "c"]);
        assert_eq!(f64s(&early, "n"), vec![1.0, 1.0, 1.0]);
    }

    // Diagnostic (ignored): the 5a emission-volume-vs-trigger and state-growth ledger. Run:
    //   cargo test -p fv-streams-ops zz_emission_volume_vs_trigger -- --ignored --nocapture
    // A single open window (q17's day), G groups each updated U times: the on-watermark aggregate
    // emits G rows (once, at close); an early-firing trigger adds ~(input rows / n) fires, each of
    // the CHANGED groups — emission ∝ churn / cadence, not open-key count. Resident state is O(G),
    // bounded by the active keys and released at close (never grows without limit — the #984 guard).
    #[test]
    #[ignore]
    fn zz_emission_volume_vs_trigger() {
        let (g, u, b): (usize, usize, usize) = (2_000, 20, 500);
        let mk_batch = |ks: &[String], ts: 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 karr: StringArray = ks.iter().map(|s| s.as_str()).collect::<Vec<_>>().into();
            let varr: Float64Array = ks.iter().map(|_| 1.0).collect::<Vec<_>>().into();
            let tarr: Int64Array = ks.iter().map(|_| ts).collect::<Vec<_>>().into();
            let bb = RecordBatch::try_new(schema, vec![Arc::new(karr), Arc::new(varr), Arc::new(tarr)]).unwrap();
            (bb, vec![ts; ks.len()])
        };
        let keys: Vec<String> = (0..g).map(|i| format!("k{i:06}")).collect();
        eprintln!("EMISSION VOLUME — {g} groups × {u} updates = {} input rows, one open window:", g * u);
        for trig in [None, Some(1_000u64), Some(5_000), Some(20_000)] {
            let mut op = WindowAggBatch::tumbling(1_000_000, 0, vec!["k".into()], vec![Agg::count("n"), Agg::of(AggOp::Sum, "v", "s")]);
            if let Some(n) = trig {
                op = op.with_trigger(Trigger::EveryRows(n));
            }
            op.expect_partitions(&[0], 0);
            let mut early_rows = 0usize;
            let mut ts = 0i64;
            for _ in 0..u {
                let mut i = 0;
                while i < g {
                    let end = (i + b).min(g);
                    let (bb, tt) = mk_batch(&keys[i..end], ts);
                    op.push_batch(0, &bb, &tt);
                    // watermark far below the window end: nothing CLOSES, so any output is early.
                    if let Some(f) = BatchOperator::advance_to(&mut op, ts) {
                        early_rows += f.num_rows();
                    }
                    ts += 1;
                    i = end;
                }
            }
            let resident = op.state_bytes();
            let close_rows = op.flush().map(|f| f.num_rows()).unwrap_or(0);
            let label = trig.map(|n| format!("everyRows({n})")).unwrap_or_else(|| "onWatermark".into());
            eprintln!(
                "  {label:>16}: early={early_rows:>7}  close={close_rows}  total={:>7}  ({:.1}× the {g}-row close)  resident_state={resident} bytes",
                early_rows + close_rows,
                (early_rows + close_rows) as f64 / g as f64,
            );
        }
    }

    // Diagnostic (ignored): does load_snapshot scale linearly in the key count? Run explicitly:
    //   cargo test -p fv-streams-ops zz_load_snapshot_scaling -- --ignored --nocapture
    #[test]
    #[ignore]
    fn zz_load_snapshot_scaling() {
        use std::time::Instant;
        for &m in &[100_000usize, 400_000] {
            // one sliding window (10s/800ms) so a key lands in ~12 overlapping open panes, like q5.
            let mk = || WindowAggBatch::sliding(10_000, 800, 5_000_000, vec!["k".into()], vec![Agg::count("n")]);
            let mut op = mk();
            op.expect_partitions(&[0], 0);
            let keys: Vec<String> = (0..m).map(|i| format!("auction-{i}")).collect();
            let ks: StringArray = keys.iter().map(|s| s.as_str()).collect::<Vec<_>>().into();
            let vs: Float64Array = (0..m).map(|_| 1.0).collect::<Vec<_>>().into();
            let ts: Int64Array = (0..m).map(|_| 5000i64).collect::<Vec<_>>().into();
            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 b = RecordBatch::try_new(schema, vec![Arc::new(ks), Arc::new(vs), Arc::new(ts)]).unwrap();
            let t = vec![5000i64; m];
            op.push_batch(0, &b, &t);
            let t_snap = Instant::now();
            let snap = op.snapshot();
            let snap_ms = t_snap.elapsed().as_millis();
            let mut fresh = mk();
            fresh.expect_partitions(&[0], 0);
            let t_load = Instant::now();
            fresh.load_snapshot(&snap).unwrap();
            let load_ms = t_load.elapsed().as_millis();
            eprintln!(
                "SCALING m={m} keys, {} panes, snap {} MB in {snap_ms} ms, load {load_ms} ms",
                fresh.panes.len(),
                snap.len() / 1_000_000,
            );
        }
    }
}