asap_sketchlib 0.2.1

A high-performance sketching library for approximate stream processing
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
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
//! Tumbling (non-overlapping, fixed-duration) window support for sketches.
//!
//! A tumbling window collects items for a fixed duration, then closes. Closed
//! windows are retained up to a configurable limit and can be merged for
//! aggregate queries. A [`SketchPool`] recycles sketch instances when windows
//! expire, avoiding allocation churn.
//!
//! # Supported sketch types
//!
//! Any type implementing [`TumblingWindowSketch`] can be used. Built-in
//! implementations are provided for [`FoldCMS`], [`FoldCS`], and [`KLL`].

use crate::DataInput;
use crate::fold_cms::FoldCMS;
use crate::fold_cs::FoldCS;
use crate::kll::KLL;

// ---------------------------------------------------------------------------
// TumblingWindowSketch trait
// ---------------------------------------------------------------------------

/// Trait unifying insert / merge / clear / construct for pool and tumbling
/// window manager use.
///
/// The `tumbling_` prefix avoids collision with existing method names on the
/// underlying sketch types.
pub trait TumblingWindowSketch: Clone + Sized {
    /// Configuration sufficient to construct a fresh instance.
    type Config: Clone;

    /// Create a new sketch from its configuration.
    fn from_config(config: &Self::Config) -> Self;

    /// Insert one observation.
    fn tumbling_insert(&mut self, key: &DataInput, value: i64);

    /// Merge `other` into `self`.
    fn tumbling_merge(&mut self, other: &Self);

    /// Reset to the empty state, preserving allocations where possible.
    fn tumbling_clear(&mut self);
}

// ---------------------------------------------------------------------------
// Config structs
// ---------------------------------------------------------------------------

/// Configuration for constructing a [`FoldCMS`] via [`TumblingWindowSketch`].
#[derive(Clone, Debug)]
pub struct FoldCMSConfig {
    /// Number of sketch rows.
    pub rows: usize,
    /// Full-width column count before folding.
    pub full_cols: usize,
    /// Folding depth applied to the sketch.
    pub fold_level: u32,
    /// Capacity of the heavy-hitter heap.
    pub top_k: usize,
}

/// Configuration for constructing a [`FoldCS`] via [`TumblingWindowSketch`].
#[derive(Clone, Debug)]
pub struct FoldCSConfig {
    /// Number of sketch rows.
    pub rows: usize,
    /// Full-width column count before folding.
    pub full_cols: usize,
    /// Folding depth applied to the sketch.
    pub fold_level: u32,
    /// Capacity of the heavy-hitter heap.
    pub top_k: usize,
}

/// Configuration for constructing a [`KLL`] via [`TumblingWindowSketch`].
#[derive(Clone, Debug)]
pub struct KLLConfig {
    /// Main KLL capacity parameter.
    pub k: usize,
    /// Minimum compactor size parameter.
    pub m: usize,
}

// ---------------------------------------------------------------------------
// TumblingWindowSketch impls
// ---------------------------------------------------------------------------

impl TumblingWindowSketch for FoldCMS {
    type Config = FoldCMSConfig;

    fn from_config(config: &Self::Config) -> Self {
        FoldCMS::new(
            config.rows,
            config.full_cols,
            config.fold_level,
            config.top_k,
        )
    }

    fn tumbling_insert(&mut self, key: &DataInput, value: i64) {
        self.insert(key, value);
    }

    fn tumbling_merge(&mut self, other: &Self) {
        self.merge_same_level(other);
    }

    fn tumbling_clear(&mut self) {
        self.clear();
    }
}

impl TumblingWindowSketch for FoldCS {
    type Config = FoldCSConfig;

    fn from_config(config: &Self::Config) -> Self {
        FoldCS::new(
            config.rows,
            config.full_cols,
            config.fold_level,
            config.top_k,
        )
    }

    fn tumbling_insert(&mut self, key: &DataInput, value: i64) {
        self.insert(key, value);
    }

    fn tumbling_merge(&mut self, other: &Self) {
        self.merge_same_level(other);
    }

    fn tumbling_clear(&mut self) {
        self.clear();
    }
}

impl TumblingWindowSketch for KLL {
    type Config = KLLConfig;

    fn from_config(config: &Self::Config) -> Self {
        KLL::init(config.k, config.m)
    }

    fn tumbling_insert(&mut self, key: &DataInput, _value: i64) {
        // KLL is a quantile sketch — each call is one observation.
        let _ = self.update_data_input(key);
    }

    fn tumbling_merge(&mut self, other: &Self) {
        self.merge(other);
    }

    fn tumbling_clear(&mut self) {
        self.clear();
    }
}

// ---------------------------------------------------------------------------
// SketchPool
// ---------------------------------------------------------------------------

/// Generic object pool that recycles sketch instances via [`TumblingWindowSketch::tumbling_clear`].
pub struct SketchPool<S: TumblingWindowSketch> {
    free_list: Vec<S>,
    total_allocated: usize,
    config: S::Config,
}

impl<S: TumblingWindowSketch> SketchPool<S> {
    /// Create a pool and pre-allocate `cap` sketches.
    pub fn new(cap: usize, config: S::Config) -> Self {
        let mut free_list = Vec::with_capacity(cap);
        for _ in 0..cap {
            free_list.push(S::from_config(&config));
        }
        SketchPool {
            free_list,
            total_allocated: cap,
            config,
        }
    }

    /// Take a sketch from the free-list, or allocate a fresh one.
    pub fn take(&mut self) -> S {
        if let Some(s) = self.free_list.pop() {
            s
        } else {
            self.total_allocated += 1;
            S::from_config(&self.config)
        }
    }

    /// Return a sketch to the pool after clearing it.
    pub fn put(&mut self, mut sketch: S) {
        sketch.tumbling_clear();
        self.free_list.push(sketch);
    }

    /// Number of sketches currently available in the free-list.
    pub fn available(&self) -> usize {
        self.free_list.len()
    }

    /// Total number of sketches ever allocated by this pool.
    pub fn total_allocated(&self) -> usize {
        self.total_allocated
    }
}

// ---------------------------------------------------------------------------
// ClosedWindow
// ---------------------------------------------------------------------------

/// A closed (immutable) tumbling window with its sketch and metadata.
struct ClosedWindow<S: TumblingWindowSketch> {
    sketch: S,
    _window_id: u64,
}

// ---------------------------------------------------------------------------
// TumblingWindow
// ---------------------------------------------------------------------------

/// Manages a sequence of tumbling (non-overlapping) windows over a sketch
/// type `S`. Each window collects items for `window_size` time units, then
/// closes. At most `max_windows` closed windows are retained; older ones
/// are evicted and their sketches returned to the pool.
pub struct TumblingWindow<S: TumblingWindowSketch> {
    /// Currently open window's sketch.
    active: S,
    /// Sequential counter for window IDs.
    active_window_id: u64,
    /// Timestamp when the active window opened.
    active_start: u64,
    /// Duration of each window.
    window_size: u64,
    /// Maximum number of closed windows to retain.
    max_windows: usize,
    /// Closed windows, ordered oldest-to-newest.
    closed: Vec<ClosedWindow<S>>,
    /// Pool for recycling sketch instances.
    pool: SketchPool<S>,
}

impl<S: TumblingWindowSketch> TumblingWindow<S> {
    /// Create a new tumbling window manager.
    ///
    /// * `window_size` — duration of each window in abstract time units.
    /// * `max_windows` — maximum number of closed windows to retain.
    /// * `config`      — sketch configuration for constructing fresh sketches.
    /// * `pool_cap`    — initial number of pre-allocated pool sketches.
    pub fn new(window_size: u64, max_windows: usize, config: S::Config, pool_cap: usize) -> Self {
        assert!(window_size > 0, "window_size must be > 0");
        let mut pool = SketchPool::new(pool_cap, config.clone());
        let active = pool.take();
        TumblingWindow {
            active,
            active_window_id: 0,
            active_start: 0,
            window_size,
            max_windows,
            closed: Vec::with_capacity(max_windows),
            pool,
        }
    }

    /// Insert an observation at the given timestamp.
    ///
    /// If `time` falls beyond the current window boundary, the active window
    /// is closed and new windows are opened as needed (empty intermediate
    /// windows are skipped).
    pub fn insert(&mut self, time: u64, key: &DataInput, value: i64) {
        // Advance windows as needed.
        while time >= self.active_start + self.window_size {
            self.close_active();
        }
        self.active.tumbling_insert(key, value);
    }

    /// Force-close the active window at `current_time` and open a fresh one.
    pub fn flush(&mut self, current_time: u64) {
        while current_time >= self.active_start + self.window_size {
            self.close_active();
        }
        // If the active window still contains the current_time, close it anyway.
        self.close_active();
    }

    /// Close the active window, push it to closed, evict if over limit.
    fn close_active(&mut self) {
        let old_active = std::mem::replace(&mut self.active, self.pool.take());
        self.closed.push(ClosedWindow {
            sketch: old_active,
            _window_id: self.active_window_id,
        });
        self.active_window_id += 1;
        self.active_start += self.window_size;

        // Evict oldest if over limit.
        while self.closed.len() > self.max_windows {
            let evicted = self.closed.remove(0);
            self.pool.put(evicted.sketch);
        }
    }

    /// Merge all closed windows + the active window into a single sketch.
    pub fn query_all(&self) -> S {
        let mut merged = self.active.clone();
        for cw in &self.closed {
            merged.tumbling_merge(&cw.sketch);
        }
        merged
    }

    /// Merge the `n` most recent closed windows + the active window.
    ///
    /// If `n >= closed_count()`, this is equivalent to `query_all()`.
    pub fn query_recent(&self, n: usize) -> S {
        let mut merged = self.active.clone();
        let start = self.closed.len().saturating_sub(n);
        for cw in &self.closed[start..] {
            merged.tumbling_merge(&cw.sketch);
        }
        merged
    }

    /// Reference to the active (currently open) sketch.
    pub fn active_sketch(&self) -> &S {
        &self.active
    }

    /// Number of closed windows currently retained.
    pub fn closed_count(&self) -> usize {
        self.closed.len()
    }

    /// Number of sketches available in the pool.
    pub fn pool_available(&self) -> usize {
        self.pool.available()
    }

    /// Total sketches ever allocated by the pool.
    pub fn pool_total_allocated(&self) -> usize {
        self.pool.total_allocated()
    }
}

// ---------------------------------------------------------------------------
// Specialized hierarchical merge queries for FoldCMS / FoldCS
// ---------------------------------------------------------------------------

impl TumblingWindow<FoldCMS> {
    /// Hierarchically merges all windows into one FoldCMS.
    ///
    /// This produces a progressively unfolded result — more accurate than
    /// repeated `merge_same_level` when the fold level is > 0.
    pub fn query_all_hierarchical(&self) -> FoldCMS {
        let sketches: Vec<FoldCMS> = self
            .closed
            .iter()
            .map(|cw| cw.sketch.clone())
            .chain(std::iter::once(self.active.clone()))
            .collect();
        FoldCMS::hierarchical_merge(&sketches)
    }
}

impl TumblingWindow<FoldCS> {
    /// Hierarchically merges all windows into one FoldCS.
    pub fn query_all_hierarchical(&self) -> FoldCS {
        let sketches: Vec<FoldCS> = self
            .closed
            .iter()
            .map(|cw| cw.sketch.clone())
            .chain(std::iter::once(self.active.clone()))
            .collect();
        FoldCS::hierarchical_merge(&sketches)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{sample_normal_f64, sample_uniform_f64, sample_zipf_u64};
    use std::collections::HashMap;

    // -- Pool tests ----------------------------------------------------------

    #[test]
    fn pool_take_returns_preallocated() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut pool = SketchPool::<FoldCMS>::new(4, config);
        assert_eq!(pool.available(), 4);
        assert_eq!(pool.total_allocated(), 4);

        let _s1 = pool.take();
        assert_eq!(pool.available(), 3);
        assert_eq!(pool.total_allocated(), 4);
    }

    #[test]
    fn pool_take_allocates_when_empty() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut pool = SketchPool::<FoldCMS>::new(0, config);
        assert_eq!(pool.available(), 0);
        assert_eq!(pool.total_allocated(), 0);

        let _s = pool.take();
        assert_eq!(pool.total_allocated(), 1);
    }

    #[test]
    fn pool_put_recycles() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut pool = SketchPool::<FoldCMS>::new(1, config);
        let s = pool.take();
        assert_eq!(pool.available(), 0);

        pool.put(s);
        assert_eq!(pool.available(), 1);
        assert_eq!(pool.total_allocated(), 1);
    }

    // -- Clear method tests --------------------------------------------------

    #[test]
    fn fold_cms_clear_resets_to_empty() {
        let mut sk: FoldCMS = FoldCMS::new(3, 1024, 3, 10);
        for i in 0..50u64 {
            sk.insert(&DataInput::U64(i), 1);
        }
        assert!(sk.query(&DataInput::U64(0)) > 0);

        sk.clear();

        for i in 0..50u64 {
            assert_eq!(
                sk.query(&DataInput::U64(i)),
                0,
                "key {i} should be 0 after clear"
            );
        }
        assert!(sk.heap().is_empty(), "heap should be empty after clear");
    }

    #[test]
    fn fold_cs_clear_resets_to_empty() {
        let mut sk: FoldCS = FoldCS::new(3, 1024, 3, 10);
        for i in 0..50u64 {
            sk.insert(&DataInput::U64(i), 1);
        }
        assert_ne!(sk.query(&DataInput::U64(0)), 0);

        sk.clear();

        for i in 0..50u64 {
            assert_eq!(
                sk.query(&DataInput::U64(i)),
                0,
                "key {i} should be 0 after clear"
            );
        }
        assert!(sk.heap().is_empty(), "heap should be empty after clear");
    }

    #[test]
    fn kll_clear_resets_to_empty() {
        let mut sk = KLL::init(200, 8);
        for i in 0..1000 {
            sk.update_data_input(&DataInput::F64(i as f64)).unwrap();
        }
        assert!(sk.count() > 0);

        sk.clear();

        assert_eq!(sk.count(), 0, "count should be 0 after clear");
        let cdf = sk.cdf();
        assert_eq!(cdf.query(0.5), 0.0, "empty sketch should return 0.0");
    }

    // -- Construction guard tests --------------------------------------------

    #[test]
    #[should_panic(expected = "window_size must be > 0")]
    fn zero_window_size_panics() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let _tw = TumblingWindow::<FoldCMS>::new(0, 5, config, 4);
    }

    // -- Window mechanics tests ----------------------------------------------

    #[test]
    fn window_closes_on_time_advance() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 10, config, 4);

        // Insert into window 0 (time 0..99).
        tw.insert(0, &DataInput::Str("a"), 1);
        tw.insert(50, &DataInput::Str("a"), 1);
        assert_eq!(tw.closed_count(), 0);

        // Time 100 → window 0 closes, window 1 opens.
        tw.insert(100, &DataInput::Str("b"), 1);
        assert_eq!(tw.closed_count(), 1);

        // Time 200 → window 1 closes.
        tw.insert(200, &DataInput::Str("c"), 1);
        assert_eq!(tw.closed_count(), 2);
    }

    #[test]
    fn window_evicts_oldest_beyond_max() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 3, config, 4);

        // Fill 4 windows (max_windows=3 closed + active).
        for w in 0..5 {
            tw.insert(w * 100, &DataInput::U64(w), 1);
        }

        // We should have exactly 3 closed windows (oldest evicted).
        assert!(
            tw.closed_count() <= 3,
            "closed_count {} should be <= max_windows 3",
            tw.closed_count()
        );
    }

    #[test]
    fn window_pool_recycles_on_eviction() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 2, config, 4);

        let initial_total = tw.pool_total_allocated();

        // Create enough windows to trigger eviction.
        for w in 0..6 {
            tw.insert(w * 100, &DataInput::U64(w), 1);
        }

        // Pool should have recycled sketches, so available > 0.
        assert!(
            tw.pool_available() > 0,
            "pool should have recycled sketches after eviction"
        );
        // Total allocated should not grow unboundedly.
        assert!(
            tw.pool_total_allocated() <= initial_total + 6,
            "pool should reuse sketches, not allocate indefinitely"
        );
    }

    // -- Merge correctness tests ---------------------------------------------

    #[test]
    fn query_all_matches_manual_merge() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 10, config.clone(), 4);

        let mut manual: FoldCMS = FoldCMS::new(
            config.rows,
            config.full_cols,
            config.fold_level,
            config.top_k,
        );

        let keys: Vec<DataInput> = (0..20u64).map(DataInput::U64).collect();
        for (i, key) in keys.iter().enumerate() {
            let time = (i as u64) * 30; // spread across windows
            tw.insert(time, key, 1);
            manual.insert(key, 1);
        }

        let merged = tw.query_all();
        for key in &keys {
            assert_eq!(
                merged.query(key),
                manual.query(key),
                "query_all mismatch for {key:?}"
            );
        }
    }

    #[test]
    fn query_recent_selects_subset() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 10, config, 4);

        // Window 0: key "old"
        tw.insert(0, &DataInput::Str("old"), 5);
        // Window 1: key "new"
        tw.insert(100, &DataInput::Str("new"), 10);
        // Window 2 (active): key "active"
        tw.insert(200, &DataInput::Str("active"), 7);

        // query_recent(1) should include 1 most recent closed + active.
        let recent = tw.query_recent(1);
        assert_eq!(recent.query(&DataInput::Str("new")), 10);
        assert_eq!(recent.query(&DataInput::Str("active")), 7);
        // "old" is in window 0 which is not in the recent 1.
        assert_eq!(recent.query(&DataInput::Str("old")), 0);
    }

    // -- FoldCMS hierarchical merge via tumbling windows ----------------------

    #[test]
    fn fold_cms_tumbling_hierarchical_merge() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 5000;
        let exponent = 1.1;
        let samples_per_window = 10_000;
        let num_windows = 8;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let mut truth = HashMap::<u64, i64>::new();
        let stream = sample_zipf_u64(
            domain,
            exponent,
            samples_per_window * num_windows,
            0xCAFE_BABE,
        );

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all_hierarchical();

        // Verify most estimates are within CMS error bound.
        let epsilon = std::f64::consts::E / full_cols as f64;
        let l1_norm: f64 = truth.values().map(|&c| c as f64).sum();
        let error_bound = epsilon * l1_norm;

        let mut within = 0usize;
        for (&key, &true_count) in &truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) < error_bound {
                within += 1;
            }
        }

        let pct = within as f64 / truth.len() as f64 * 100.0;
        assert!(
            pct > 90.0,
            "only {pct:.1}% within CMS error bound (expected > 90%)"
        );
    }

    // -- KLL quantile via tumbling windows ------------------------------------

    #[test]
    fn kll_tumbling_quantile_accuracy() {
        let config = KLLConfig { k: 200, m: 8 };
        let samples_per_window = 5000;
        let num_windows = 4;

        let mut tw: TumblingWindow<KLL> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let values = sample_uniform_f64(
            0.0,
            1_000_000.0,
            samples_per_window * num_windows,
            0xDEAD_BEEF,
        );

        for (i, &v) in values.iter().enumerate() {
            tw.insert(i as u64, &DataInput::F64(v), 1);
        }

        let merged = tw.query_all();
        let cdf = merged.cdf();

        let mut sorted = values.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());

        // Check median is roughly correct (within 2% rank tolerance).
        let est_median = cdf.query(0.5);
        let n = sorted.len();
        let lower_idx = ((0.48 * n as f64).ceil() as usize).min(n - 1);
        let upper_idx = ((0.52 * n as f64).ceil() as usize).min(n - 1);
        assert!(
            est_median >= sorted[lower_idx] && est_median <= sorted[upper_idx],
            "median estimate {est_median} outside [{}, {}]",
            sorted[lower_idx],
            sorted[upper_idx]
        );
    }

    // -- Flush test ----------------------------------------------------------

    #[test]
    fn flush_closes_active_window() {
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(100, 10, config, 4);

        tw.insert(10, &DataInput::Str("x"), 5);
        assert_eq!(tw.closed_count(), 0);

        tw.flush(50);
        assert_eq!(tw.closed_count(), 1);

        // Active should now be empty.
        assert_eq!(tw.active_sketch().query(&DataInput::Str("x")), 0);

        // But query_all should still find the data.
        let all = tw.query_all();
        assert_eq!(all.query(&DataInput::Str("x")), 5);
    }

    // -- FoldCS tumbling test ------------------------------------------------

    #[test]
    fn fold_cs_tumbling_basic() {
        let config = FoldCSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(100, 10, config, 4);

        tw.insert(0, &DataInput::Str("hello"), 5);
        tw.insert(100, &DataInput::Str("hello"), 3);
        tw.insert(200, &DataInput::Str("hello"), 2);

        let merged = tw.query_all();
        assert_eq!(merged.query(&DataInput::Str("hello")), 10);
    }

    #[test]
    fn fold_cs_tumbling_hierarchical_merge() {
        let config = FoldCSConfig {
            rows: 5,
            full_cols: 4096,
            fold_level: 2,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(100, 10, config, 6);

        for w in 0..4u64 {
            for i in (w * 10)..((w + 1) * 10) {
                tw.insert(w * 100 + i, &DataInput::U64(i), 1);
            }
        }

        let merged = tw.query_all_hierarchical();
        assert_eq!(merged.fold_level(), 0);

        // Count Sketch uses signed counters + median; allow small error.
        let mut errors = 0;
        for i in 0..40u64 {
            let est = merged.query(&DataInput::U64(i));
            if (est - 1).abs() > 1 {
                errors += 1;
            }
        }
        assert!(
            errors == 0,
            "{errors}/40 keys had error > 1 (expected 0 with wide sketch)"
        );
    }

    // -- Accuracy & correctness tests ----------------------------------------

    #[test]
    fn fold_cms_tumbling_accuracy_zipf() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.1;
        let total_samples = 500_000;
        let num_windows = 16;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xACC0_BAC1);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        // CMS error bound: epsilon = e / full_cols, bound = epsilon * L1
        let epsilon = std::f64::consts::E / full_cols as f64;
        let l1_norm: f64 = truth.values().map(|&c| c as f64).sum();
        let error_bound = epsilon * l1_norm;
        // delta = 1 / e^rows → expected fraction within bound = 1 - delta
        let delta = (-(rows as f64)).exp();
        let required_pct = (1.0 - delta) * 100.0;

        let mut within = 0usize;
        let mut total_abs_error = 0i64;
        let mut max_abs_error = 0i64;
        for (&key, &true_count) in &truth {
            let est = merged.query(&DataInput::U64(key));
            let err = (est - true_count).abs();
            total_abs_error += err;
            max_abs_error = max_abs_error.max(err);
            if (err as f64) <= error_bound {
                within += 1;
            }
        }

        let pct = within as f64 / truth.len() as f64 * 100.0;
        let mean_abs_error = total_abs_error as f64 / truth.len() as f64;
        eprintln!(
            "[fold_cms_tumbling_accuracy_zipf] mean_abs_error={mean_abs_error:.2}, \
             max_abs_error={max_abs_error}, pct_within_bound={pct:.1}% \
             (required>{required_pct:.1}%), error_bound={error_bound:.2}"
        );

        assert!(
            pct >= required_pct,
            "only {pct:.1}% within CMS error bound (expected >= {required_pct:.1}%)"
        );
    }

    #[test]
    fn fold_cms_hierarchical_vs_flat_merge() {
        let rows = 3;
        let full_cols = 4096;
        // fold_level = 3 so hierarchical merge with 8 windows (log2(8)=3 rounds)
        // reaches fold_level 0.
        let fold_level = 3;
        let top_k = 20;
        let domain = 5000;
        let exponent = 1.1;
        let total_samples = 100_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xF1A7_CAFE);

        // Build two identical tumbling window instances.
        let mut tumbling_flat: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config.clone(),
            num_windows + 2,
        );
        let mut tumbling_hier: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let mut truth = HashMap::<u64, i64>::new();
        for (i, &value) in stream.iter().enumerate() {
            let t = i as u64;
            let key = DataInput::U64(value);
            tumbling_flat.insert(t, &key, 1);
            tumbling_hier.insert(t, &key, 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged_flat = tumbling_flat.query_all();
        let merged_hier = tumbling_hier.query_all_hierarchical();

        // Hierarchical merge should reach fold_level 0.
        assert_eq!(
            merged_hier.fold_level(),
            0,
            "hierarchical merge should reach fold_level 0"
        );

        // Both should produce identical estimates for all keys.
        // Note: flat merge stays at the original fold_level, so we unfold it
        // for a fair comparison.
        let merged_flat_unfolded = merged_flat.unfold_full();

        for &key in truth.keys() {
            let est_flat = merged_flat_unfolded.query(&DataInput::U64(key));
            let est_hier = merged_hier.query(&DataInput::U64(key));
            assert_eq!(
                est_flat, est_hier,
                "flat vs hierarchical mismatch for key {key}: flat={est_flat}, hier={est_hier}"
            );
        }
    }

    #[test]
    fn fold_cs_tumbling_accuracy_zipf() {
        let rows = 5;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.1;
        let total_samples = 500_000;
        let num_windows = 16;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xC5_ACCA);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        // CS error bound: epsilon = sqrt(e / cols), bound = epsilon * L2
        let epsilon = (std::f64::consts::E / full_cols as f64).sqrt();
        let l2_norm: f64 = truth
            .values()
            .map(|&c| (c as f64) * (c as f64))
            .sum::<f64>()
            .sqrt();
        let error_bound = epsilon * l2_norm;
        let delta = (-(rows as f64)).exp();
        let required_pct = (1.0 - delta) * 100.0;

        let mut within = 0usize;
        let mut total_abs_error = 0i64;
        let mut max_abs_error = 0i64;
        for (&key, &true_count) in &truth {
            let est = merged.query(&DataInput::U64(key));
            let err = (est - true_count).abs();
            total_abs_error += err;
            max_abs_error = max_abs_error.max(err);
            if (err as f64) <= error_bound {
                within += 1;
            }
        }

        let pct = within as f64 / truth.len() as f64 * 100.0;
        let mean_abs_error = total_abs_error as f64 / truth.len() as f64;
        eprintln!(
            "[fold_cs_tumbling_accuracy_zipf] mean_abs_error={mean_abs_error:.2}, \
             max_abs_error={max_abs_error}, pct_within_bound={pct:.1}% \
             (required>{required_pct:.1}%), error_bound={error_bound:.2}"
        );

        assert!(
            pct >= required_pct,
            "only {pct:.1}% within CS error bound (expected >= {required_pct:.1}%)"
        );
    }

    #[test]
    fn kll_tumbling_multi_quantile_accuracy() {
        let config = KLLConfig { k: 200, m: 8 };
        let total_samples = 100_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let mut tw: TumblingWindow<KLL> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let values = sample_uniform_f64(0.0, 10_000_000.0, total_samples, 0x411_00171);

        for (i, &v) in values.iter().enumerate() {
            tw.insert(i as u64, &DataInput::F64(v), 1);
        }

        let merged = tw.query_all();
        let cdf = merged.cdf();

        let mut sorted = values.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let n = sorted.len();

        let quantiles = [0.10, 0.25, 0.50, 0.75, 0.90];
        let tolerance = 0.02;

        for &q in &quantiles {
            let est = cdf.query(q);
            let lo_idx = (((q - tolerance).max(0.0) * n as f64).ceil() as usize).min(n - 1);
            let hi_idx = (((q + tolerance).min(1.0) * n as f64).ceil() as usize).min(n - 1);
            assert!(
                est >= sorted[lo_idx] && est <= sorted[hi_idx],
                "quantile {q} estimate {est} outside [{}, {}] (rank tolerance {tolerance})",
                sorted[lo_idx],
                sorted[hi_idx]
            );
        }
    }

    #[test]
    fn kll_tumbling_distribution_shift() {
        let config = KLLConfig { k: 400, m: 8 };
        let samples_per_phase = 50_000;
        let windows_per_phase = 4;
        let samples_per_window = samples_per_phase / windows_per_phase;
        let num_windows = windows_per_phase * 2;

        let mut tw: TumblingWindow<KLL> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        // Phase 1: normal(100, 10)
        let phase1 = sample_normal_f64(100.0, 10.0, samples_per_phase, 0xFA_ACE1);
        // Phase 2: normal(500, 50)
        let phase2 = sample_normal_f64(500.0, 50.0, samples_per_phase, 0xFA_ACE2);

        for (i, &v) in phase1.iter().enumerate() {
            tw.insert(i as u64, &DataInput::F64(v), 1);
        }
        for (i, &v) in phase2.iter().enumerate() {
            let t = (samples_per_phase + i) as u64;
            tw.insert(t, &DataInput::F64(v), 1);
        }

        let merged = tw.query_all();
        let cdf = merged.cdf();

        // Check distributional shape rather than exact quantile bounds.
        // With equal halves from normal(100,10) and normal(500,50):
        // - p10 should be solidly in the first distribution (< 200)
        // - p50 should be between the two modes (50 .. 600)
        // - p90 should be solidly in the second distribution (> 350)
        let p10 = cdf.query(0.10);
        let p50 = cdf.query(0.50);
        let p90 = cdf.query(0.90);

        eprintln!("[kll_tumbling_distribution_shift] p10={p10:.1}, p50={p50:.1}, p90={p90:.1}");

        assert!(
            p10 < 200.0,
            "p10={p10:.1} should be in the first distribution (< 200)"
        );
        assert!(
            p50 > 50.0 && p50 < 600.0,
            "p50={p50:.1} should be between modes (50..600)"
        );
        assert!(
            p90 > 350.0,
            "p90={p90:.1} should be in the second distribution (> 350)"
        );

        // Verify ordering is monotonic.
        assert!(p10 < p50, "p10 ({p10:.1}) should be < p50 ({p50:.1})");
        assert!(p50 < p90, "p50 ({p50:.1}) should be < p90 ({p90:.1})");
    }

    #[test]
    fn tumbling_eviction_correctness() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 5000;
        let exponent = 1.1;
        let max_windows = 4;
        let total_windows = 8;
        let samples_per_window = 10_000;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            max_windows,
            config,
            max_windows + 2,
        );

        let stream = sample_zipf_u64(
            domain,
            exponent,
            samples_per_window * total_windows,
            0xE01C_0100,
        );

        // Track per-window truth to identify retained windows.
        let mut per_window_truth: Vec<HashMap<u64, i64>> = Vec::new();
        for w in 0..total_windows {
            let mut window_truth = HashMap::<u64, i64>::new();
            let start = w * samples_per_window;
            let end = start + samples_per_window;
            for (i, &value) in stream.iter().enumerate().take(end).skip(start) {
                // let value = stream[i];
                tw.insert(i as u64, &DataInput::U64(value), 1);
                *window_truth.entry(value).or_insert(0) += 1;
            }
            per_window_truth.push(window_truth);
        }

        // The last insert is at time (total_windows * samples_per_window - 1),
        // which falls in window (total_windows - 1). After all inserts:
        // - Windows 0..(total_windows-2) are closed.
        // - Window (total_windows-1) is active.
        // - With max_windows=4, only the 4 most recent closed windows are kept
        //   plus the active window.
        //
        // Retained: the most recent max_windows closed + active.
        // Closed windows are windows 0..6 (7 closed). Retain the last 4: 3,4,5,6.
        // Active window: 7.
        // So retained = windows 3,4,5,6,7.
        let retained_start = total_windows.saturating_sub(max_windows + 1);

        // Build ground truth for retained windows only.
        let mut retained_truth = HashMap::<u64, i64>::new();
        for w in per_window_truth
            .iter()
            .take(total_windows)
            .skip(retained_start)
        {
            for (&key, &count) in w {
                *retained_truth.entry(key).or_insert(0) += count;
            }
        }

        // Build ground truth for evicted windows only.
        let mut evicted_only = HashMap::<u64, i64>::new();
        for w in per_window_truth.iter().take(retained_start) {
            for (&key, &count) in w {
                *evicted_only.entry(key).or_insert(0) += count;
            }
        }

        let merged = tw.query_all();

        // CMS error bound for the retained data.
        let epsilon = std::f64::consts::E / full_cols as f64;
        let retained_l1: f64 = retained_truth.values().map(|&c| c as f64).sum();
        let error_bound = epsilon * retained_l1;

        // Retained keys: estimates should be close to retained truth.
        let mut within = 0usize;
        for (&key, &true_count) in &retained_truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) <= error_bound {
                within += 1;
            }
        }
        let pct = within as f64 / retained_truth.len() as f64 * 100.0;
        assert!(
            pct > 90.0,
            "only {pct:.1}% of retained keys within bound (expected > 90%)"
        );

        // Keys that appear ONLY in evicted windows should have small estimates.
        // CMS has inherent false positives (hash collisions), so we check that
        // evicted-only key estimates are within the CMS error bound rather than
        // demanding exact zero.
        for &key in evicted_only.keys() {
            if retained_truth.contains_key(&key) {
                continue; // key also appears in retained windows
            }
            let est = merged.query(&DataInput::U64(key));
            assert!(
                (est as f64) <= error_bound,
                "evicted-only key {key} estimate {est} exceeds error bound {error_bound:.2}"
            );
        }
    }

    #[test]
    fn tumbling_query_recent_accuracy() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 5000;
        let exponent = 1.1;
        let total_windows = 6;
        let recent_n = 3;
        let samples_per_window = 10_000;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            total_windows, // keep all closed
            config,
            total_windows + 2,
        );

        let stream = sample_zipf_u64(
            domain,
            exponent,
            samples_per_window * total_windows,
            0xBEC3_0A00,
        );

        let mut per_window_truth: Vec<HashMap<u64, i64>> = Vec::new();
        for w in 0..total_windows {
            let mut window_truth = HashMap::<u64, i64>::new();
            let start = w * samples_per_window;
            let end = start + samples_per_window;
            for (i, &value) in stream.iter().enumerate().take(end).skip(start) {
                // let value = stream[i];
                tw.insert(i as u64, &DataInput::U64(value), 1);
                *window_truth.entry(value).or_insert(0) += 1;
            }
            per_window_truth.push(window_truth);
        }

        // query_recent(3) returns: 3 most recent closed + active.
        // After 6 windows of data: windows 0..4 are closed, window 5 is active.
        // recent(3) → closed[2,3,4] + active(5) = windows 2,3,4,5.
        let recent_start = total_windows - recent_n - 1;
        let mut recent_truth = HashMap::<u64, i64>::new();
        for w in per_window_truth
            .iter()
            .take(total_windows)
            .skip(recent_start)
        {
            for (&key, &count) in w {
                *recent_truth.entry(key).or_insert(0) += count;
            }
        }

        let merged = tw.query_recent(recent_n);

        let epsilon = std::f64::consts::E / full_cols as f64;
        let recent_l1: f64 = recent_truth.values().map(|&c| c as f64).sum();
        let error_bound = epsilon * recent_l1;

        let mut within = 0usize;
        for (&key, &true_count) in &recent_truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) <= error_bound {
                within += 1;
            }
        }
        let pct = within as f64 / recent_truth.len() as f64 * 100.0;
        assert!(
            pct > 90.0,
            "only {pct:.1}% of recent keys within bound (expected > 90%)"
        );

        // Keys only in excluded windows (0, 1) should have small estimates.
        // CMS has inherent false positives from hash collisions, so we check
        // estimates are within the error bound rather than demanding exact zero.
        let mut excluded_truth = HashMap::<u64, i64>::new();
        for w in per_window_truth.iter().take(recent_start) {
            for (&key, &count) in w {
                *excluded_truth.entry(key).or_insert(0) += count;
            }
        }
        for &key in excluded_truth.keys() {
            if recent_truth.contains_key(&key) {
                continue;
            }
            let est = merged.query(&DataInput::U64(key));
            assert!(
                (est as f64) <= error_bound,
                "excluded key {key} estimate {est} exceeds error bound {error_bound:.2}"
            );
        }
    }

    #[test]
    fn fold_cms_tumbling_heap_correctness() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.3; // heavier skew → clearer heavy hitters
        let total_samples = 200_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xBEAF_C0DE);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        // Ground truth top-k sorted by frequency (descending).
        let mut truth_sorted: Vec<(u64, i64)> = truth.into_iter().collect();
        truth_sorted.sort_by_key(|b| std::cmp::Reverse(b.1));
        let true_top_k: Vec<u64> = truth_sorted.iter().take(top_k).map(|&(k, _)| k).collect();

        // Heap entries from merged sketch.
        let heap_entries = merged.heap().heap();
        assert!(
            !heap_entries.is_empty(),
            "heap should not be empty after merging {num_windows} windows"
        );

        // Every key in the true top-k should appear in the heap.
        let mut found_in_heap = 0usize;
        for &true_key in &true_top_k {
            let in_heap = heap_entries
                .iter()
                .any(|item| item.key == crate::HeapItem::U64(true_key));
            if in_heap {
                found_in_heap += 1;
            }
        }

        // With Zipf(1.3) and 200k samples, the top-k should be well-separated.
        // Require at least 80% of the true top-k to be present in the heap.
        let recall_pct = found_in_heap as f64 / top_k as f64 * 100.0;
        eprintln!(
            "[fold_cms_tumbling_heap_correctness] heap_size={}, \
             true_top_k_recall={found_in_heap}/{top_k} ({recall_pct:.0}%)",
            heap_entries.len()
        );
        assert!(
            recall_pct >= 80.0,
            "only {recall_pct:.0}% of true top-{top_k} found in heap (expected >= 80%)"
        );
    }

    // -- Gap 1: FoldCS query_recent accuracy ---------------------------------

    #[test]
    fn fold_cs_tumbling_query_recent_accuracy() {
        let rows = 5;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 5000;
        let exponent = 1.1;
        let total_windows = 6;
        let recent_n = 3;
        let samples_per_window = 10_000;

        let config = FoldCSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(
            samples_per_window as u64,
            total_windows,
            config,
            total_windows + 2,
        );

        let stream = sample_zipf_u64(
            domain,
            exponent,
            samples_per_window * total_windows,
            0xC5_0A01,
        );

        let mut per_window_truth: Vec<HashMap<u64, i64>> = Vec::new();
        for w in 0..total_windows {
            let mut window_truth = HashMap::<u64, i64>::new();
            let start = w * samples_per_window;
            let end = start + samples_per_window;
            for (i, &value) in stream.iter().enumerate().take(end).skip(start) {
                // let value = stream[i];
                tw.insert(i as u64, &DataInput::U64(value), 1);
                *window_truth.entry(value).or_insert(0) += 1;
            }
            per_window_truth.push(window_truth);
        }

        // query_recent(3) → 3 most recent closed + active.
        // After 6 windows: windows 0..4 closed, window 5 active.
        // recent(3) → closed[2,3,4] + active(5) = windows 2,3,4,5.
        let recent_start = total_windows - recent_n - 1;
        let mut recent_truth = HashMap::<u64, i64>::new();
        for w in per_window_truth
            .iter()
            .take(total_windows)
            .skip(recent_start)
        {
            for (&key, &count) in w {
                *recent_truth.entry(key).or_insert(0) += count;
            }
        }

        let merged = tw.query_recent(recent_n);

        // CS error bound: epsilon = sqrt(e / cols), bound = epsilon * L2
        let epsilon = (std::f64::consts::E / full_cols as f64).sqrt();
        let l2_norm: f64 = recent_truth
            .values()
            .map(|&c| (c as f64) * (c as f64))
            .sum::<f64>()
            .sqrt();
        let error_bound = epsilon * l2_norm;

        let mut within = 0usize;
        for (&key, &true_count) in &recent_truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) <= error_bound {
                within += 1;
            }
        }
        let pct = within as f64 / recent_truth.len() as f64 * 100.0;
        eprintln!(
            "[fold_cs_tumbling_query_recent_accuracy] pct_within_bound={pct:.1}%, \
             error_bound={error_bound:.2}"
        );
        assert!(
            pct > 90.0,
            "only {pct:.1}% of recent keys within CS bound (expected > 90%)"
        );

        // Keys only in excluded windows should have small estimates.
        let mut excluded_truth = HashMap::<u64, i64>::new();
        for w in per_window_truth.iter().take(recent_start) {
            for (&key, &count) in w {
                *excluded_truth.entry(key).or_insert(0) += count;
            }
        }
        for &key in excluded_truth.keys() {
            if recent_truth.contains_key(&key) {
                continue;
            }
            let est = merged.query(&DataInput::U64(key));
            assert!(
                (est.abs() as f64) <= error_bound,
                "excluded key {key} estimate {est} exceeds error bound {error_bound:.2}"
            );
        }
    }

    // -- Gap 2: KLL query_recent accuracy ------------------------------------

    #[test]
    fn kll_tumbling_query_recent_accuracy() {
        let config = KLLConfig { k: 200, m: 8 };
        let total_samples = 100_000;
        let num_windows = 8;
        let recent_n = 3;
        let samples_per_window = total_samples / num_windows;

        let mut tw: TumblingWindow<KLL> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let values = sample_uniform_f64(0.0, 10_000_000.0, total_samples, 0xA11_0072);

        let mut per_window: Vec<Vec<f64>> = Vec::new();
        for w in 0..num_windows {
            let start = w * samples_per_window;
            let end = start + samples_per_window;
            let window_values: Vec<f64> = values[start..end].to_vec();
            for (j, &v) in window_values.iter().enumerate() {
                tw.insert((start + j) as u64, &DataInput::F64(v), 1);
            }
            per_window.push(window_values);
        }

        // query_recent(3) → 3 most recent closed + active.
        // After 8 windows: windows 0..6 closed, window 7 active.
        // recent(3) → closed[4,5,6] + active(7) = windows 4,5,6,7.
        let recent_start = num_windows - recent_n - 1;
        let mut recent_values: Vec<f64> = Vec::new();
        for w in per_window.iter().take(num_windows).skip(recent_start) {
            recent_values.extend_from_slice(w);
        }
        recent_values.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let n = recent_values.len();

        let merged = tw.query_recent(recent_n);
        let cdf = merged.cdf();

        let quantiles = [0.10, 0.25, 0.50, 0.75, 0.90];
        let tolerance = 0.03;

        for &q in &quantiles {
            let est = cdf.query(q);
            let lo_idx = (((q - tolerance).max(0.0) * n as f64).ceil() as usize).min(n - 1);
            let hi_idx = (((q + tolerance).min(1.0) * n as f64).ceil() as usize).min(n - 1);
            assert!(
                est >= recent_values[lo_idx] && est <= recent_values[hi_idx],
                "quantile {q} estimate {est} outside [{}, {}] (rank tolerance {tolerance})",
                recent_values[lo_idx],
                recent_values[hi_idx]
            );
        }
    }

    // -- Gap 3: FoldCS heap correctness --------------------------------------

    #[test]
    fn fold_cs_tumbling_heap_correctness() {
        let rows = 5;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.3;
        let total_samples = 200_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xC5_4EA9);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        let mut truth_sorted: Vec<(u64, i64)> = truth.into_iter().collect();
        truth_sorted.sort_by_key(|b| std::cmp::Reverse(b.1));
        let true_top_k: Vec<u64> = truth_sorted.iter().take(top_k).map(|&(k, _)| k).collect();

        let heap_entries = merged.heap().heap();
        assert!(
            !heap_entries.is_empty(),
            "heap should not be empty after merging {num_windows} windows"
        );

        let mut found_in_heap = 0usize;
        for &true_key in &true_top_k {
            let in_heap = heap_entries
                .iter()
                .any(|item| item.key == crate::HeapItem::U64(true_key));
            if in_heap {
                found_in_heap += 1;
            }
        }

        let recall_pct = found_in_heap as f64 / top_k as f64 * 100.0;
        eprintln!(
            "[fold_cs_tumbling_heap_correctness] heap_size={}, \
             true_top_k_recall={found_in_heap}/{top_k} ({recall_pct:.0}%)",
            heap_entries.len()
        );
        assert!(
            recall_pct >= 80.0,
            "only {recall_pct:.0}% of true top-{top_k} found in heap (expected >= 80%)"
        );
    }

    // -- Gap 4: Tumbling vs monolithic degradation ---------------------------

    #[test]
    fn fold_cms_tumbling_vs_monolithic() {
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.1;
        let total_samples = 200_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config.clone(),
            num_windows + 2,
        );
        let mut mono: FoldCMS = FoldCMS::new(rows, full_cols, fold_level, top_k);

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xDE_AD01);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            let key = DataInput::U64(value);
            tw.insert(i as u64, &key, 1);
            mono.insert(&key, 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        let mut tumbling_total_err = 0i64;
        let mut mono_total_err = 0i64;
        for (&key, &true_count) in &truth {
            let sk = DataInput::U64(key);
            tumbling_total_err += (merged.query(&sk) - true_count).abs();
            mono_total_err += (mono.query(&sk) - true_count).abs();
        }

        let tumbling_mae = tumbling_total_err as f64 / truth.len() as f64;
        let mono_mae = mono_total_err as f64 / truth.len() as f64;
        eprintln!(
            "[fold_cms_tumbling_vs_monolithic] tumbling_mae={tumbling_mae:.2}, \
             mono_mae={mono_mae:.2}, ratio={:.2}",
            tumbling_mae / mono_mae.max(1.0)
        );
        assert!(
            tumbling_mae <= mono_mae * 1.5,
            "tumbling MAE ({tumbling_mae:.2}) > 1.5x monolithic ({mono_mae:.2})"
        );
    }

    #[test]
    fn fold_cs_tumbling_vs_monolithic() {
        let rows = 5;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let domain = 10_000;
        let exponent = 1.1;
        let total_samples = 200_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let config = FoldCSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config.clone(),
            num_windows + 2,
        );
        let mut mono: FoldCS = FoldCS::new(rows, full_cols, fold_level, top_k);

        let stream = sample_zipf_u64(domain, exponent, total_samples, 0xDE_AD02);
        let mut truth = HashMap::<u64, i64>::new();

        for (i, &value) in stream.iter().enumerate() {
            let key = DataInput::U64(value);
            tw.insert(i as u64, &key, 1);
            mono.insert(&key, 1);
            *truth.entry(value).or_insert(0) += 1;
        }

        let merged = tw.query_all();

        let mut tumbling_total_err = 0i64;
        let mut mono_total_err = 0i64;
        for (&key, &true_count) in &truth {
            let sk = DataInput::U64(key);
            tumbling_total_err += (merged.query(&sk) - true_count).abs();
            mono_total_err += (mono.query(&sk) - true_count).abs();
        }

        let tumbling_mae = tumbling_total_err as f64 / truth.len() as f64;
        let mono_mae = mono_total_err as f64 / truth.len() as f64;
        eprintln!(
            "[fold_cs_tumbling_vs_monolithic] tumbling_mae={tumbling_mae:.2}, \
             mono_mae={mono_mae:.2}, ratio={:.2}",
            tumbling_mae / mono_mae.max(1.0)
        );
        assert!(
            tumbling_mae <= mono_mae * 1.5,
            "tumbling MAE ({tumbling_mae:.2}) > 1.5x monolithic ({mono_mae:.2})"
        );
    }

    #[test]
    fn kll_tumbling_vs_monolithic() {
        let config = KLLConfig { k: 200, m: 8 };
        let total_samples = 100_000;
        let num_windows = 8;
        let samples_per_window = total_samples / num_windows;

        let mut tw: TumblingWindow<KLL> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config.clone(),
            num_windows + 2,
        );
        let mut mono = KLL::init(config.k, config.m);

        let values = sample_uniform_f64(0.0, 10_000_000.0, total_samples, 0xDE_AD03);

        for (i, &v) in values.iter().enumerate() {
            tw.insert(i as u64, &DataInput::F64(v), 1);
            mono.update_data_input(&DataInput::F64(v)).unwrap();
        }

        let merged = tw.query_all();
        let tw_cdf = merged.cdf();
        let mono_cdf = mono.cdf();

        let mut sorted = values.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let n = sorted.len();

        let quantiles = [0.10, 0.25, 0.50, 0.75, 0.90];
        let mut tw_max_rank_err = 0.0f64;
        let mut mono_max_rank_err = 0.0f64;

        for &q in &quantiles {
            let tw_est = tw_cdf.query(q);
            let mono_est = mono_cdf.query(q);

            // Compute rank error: how far off is the rank of the estimated value?
            let tw_rank = sorted.partition_point(|&x| x <= tw_est) as f64 / n as f64;
            let mono_rank = sorted.partition_point(|&x| x <= mono_est) as f64 / n as f64;

            tw_max_rank_err = tw_max_rank_err.max((tw_rank - q).abs());
            mono_max_rank_err = mono_max_rank_err.max((mono_rank - q).abs());
        }

        eprintln!(
            "[kll_tumbling_vs_monolithic] tw_max_rank_err={tw_max_rank_err:.4}, \
             mono_max_rank_err={mono_max_rank_err:.4}"
        );
        assert!(
            tw_max_rank_err <= mono_max_rank_err + 0.02,
            "tumbling rank error ({tw_max_rank_err:.4}) > monolithic ({mono_max_rank_err:.4}) + 0.02"
        );
    }

    // -- Gap 5: Edge cases ---------------------------------------------------

    #[test]
    fn tumbling_single_window_accuracy() {
        // All data fits in one window (no window closes).
        let total_samples = 50_000;

        // --- FoldCMS subsection ---
        {
            let config = FoldCMSConfig {
                rows: 3,
                full_cols: 4096,
                fold_level: 4,
                top_k: 20,
            };
            let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
                total_samples as u64 + 1, // window_size > total_samples → never closes
                10,
                config,
                4,
            );

            let stream = sample_zipf_u64(5000, 1.1, total_samples, 0x51_0001);
            let mut truth = HashMap::<u64, i64>::new();
            for (i, &value) in stream.iter().enumerate() {
                tw.insert(i as u64, &DataInput::U64(value), 1);
                *truth.entry(value).or_insert(0) += 1;
            }

            assert_eq!(tw.closed_count(), 0, "no windows should have closed");

            let merged = tw.query_all();
            let epsilon = std::f64::consts::E / 4096.0;
            let l1: f64 = truth.values().map(|&c| c as f64).sum();
            let bound = epsilon * l1;

            let mut within = 0usize;
            for (&key, &true_count) in &truth {
                let est = merged.query(&DataInput::U64(key));
                if ((est - true_count).abs() as f64) <= bound {
                    within += 1;
                }
            }
            let pct = within as f64 / truth.len() as f64 * 100.0;
            assert!(
                pct > 90.0,
                "FoldCMS single-window: only {pct:.1}% within bound"
            );
        }

        // --- FoldCS subsection ---
        {
            let config = FoldCSConfig {
                rows: 5,
                full_cols: 4096,
                fold_level: 4,
                top_k: 20,
            };
            let mut tw: TumblingWindow<FoldCS> =
                TumblingWindow::new(total_samples as u64 + 1, 10, config, 4);

            let stream = sample_zipf_u64(5000, 1.1, total_samples, 0x51_0002);
            let mut truth = HashMap::<u64, i64>::new();
            for (i, &value) in stream.iter().enumerate() {
                tw.insert(i as u64, &DataInput::U64(value), 1);
                *truth.entry(value).or_insert(0) += 1;
            }

            assert_eq!(tw.closed_count(), 0, "no windows should have closed");

            let merged = tw.query_all();
            let epsilon = (std::f64::consts::E / 4096.0f64).sqrt();
            let l2: f64 = truth
                .values()
                .map(|&c| (c as f64) * (c as f64))
                .sum::<f64>()
                .sqrt();
            let bound = epsilon * l2;

            let mut within = 0usize;
            for (&key, &true_count) in &truth {
                let est = merged.query(&DataInput::U64(key));
                if ((est - true_count).abs() as f64) <= bound {
                    within += 1;
                }
            }
            let pct = within as f64 / truth.len() as f64 * 100.0;
            assert!(
                pct > 90.0,
                "FoldCS single-window: only {pct:.1}% within bound"
            );
        }

        // --- KLL subsection ---
        {
            let config = KLLConfig { k: 200, m: 8 };
            let mut tw: TumblingWindow<KLL> =
                TumblingWindow::new(total_samples as u64 + 1, 10, config, 4);

            let values = sample_uniform_f64(0.0, 1_000_000.0, total_samples, 0x51_0003);
            for (i, &v) in values.iter().enumerate() {
                tw.insert(i as u64, &DataInput::F64(v), 1);
            }

            assert_eq!(tw.closed_count(), 0, "no windows should have closed");

            let merged = tw.query_all();
            let cdf = merged.cdf();

            let mut sorted = values.clone();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            let n = sorted.len();

            for &q in &[0.25, 0.50, 0.75] {
                let est = cdf.query(q);
                let lo = (((q - 0.02).max(0.0) * n as f64).ceil() as usize).min(n - 1);
                let hi = (((q + 0.02).min(1.0) * n as f64).ceil() as usize).min(n - 1);
                assert!(
                    est >= sorted[lo] && est <= sorted[hi],
                    "KLL single-window: quantile {q} est {est} outside [{}, {}]",
                    sorted[lo],
                    sorted[hi]
                );
            }
        }
    }

    #[test]
    fn tumbling_very_small_windows() {
        let window_size = 10u64;
        let total_samples = 5000;
        let max_windows = 50;

        // FoldCMS with tiny windows — many rotations.
        let config = FoldCMSConfig {
            rows: 3,
            full_cols: 1024,
            fold_level: 3,
            top_k: 10,
        };
        let mut tw: TumblingWindow<FoldCMS> =
            TumblingWindow::new(window_size, max_windows, config, max_windows + 2);

        let stream = sample_zipf_u64(500, 1.2, total_samples, 0x77_1100);

        for (i, &value) in stream.iter().enumerate() {
            tw.insert(i as u64, &DataInput::U64(value), 1);
        }

        // With 5000 samples and window_size=10, there are 500 windows total.
        // max_windows=50, so only the last ~50 closed + active are retained.
        // Just verify the system didn't crash and produces reasonable estimates.
        let merged = tw.query_all();

        // Build truth for what the tumbling window actually retains.
        // The retained windows cover the most recent portion of the stream.
        let total_windows_created = total_samples / window_size as usize;
        let retained_start_window = total_windows_created.saturating_sub(max_windows);
        let retained_start_sample = retained_start_window * window_size as usize;

        let mut retained_truth = HashMap::<u64, i64>::new();
        for &k in stream
            .iter()
            .take(total_samples)
            .skip(retained_start_sample)
        {
            *retained_truth.entry(k).or_insert(0) += 1;
        }

        let epsilon = std::f64::consts::E / 1024.0;
        let l1: f64 = retained_truth.values().map(|&c| c as f64).sum();
        let bound = epsilon * l1;

        let mut within = 0usize;
        for (&key, &true_count) in &retained_truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) <= bound {
                within += 1;
            }
        }
        let pct = within as f64 / retained_truth.len() as f64 * 100.0;
        eprintln!(
            "[tumbling_very_small_windows] retained_windows={max_windows}, \
             pct_within_bound={pct:.1}%, bound={bound:.2}"
        );
        assert!(
            pct > 85.0,
            "only {pct:.1}% within CMS bound with tiny windows (expected > 85%)"
        );
    }

    #[test]
    fn tumbling_skewed_load() {
        // 5 windows where window 2 gets 90% of data.
        let rows = 3;
        let full_cols = 4096;
        let fold_level = 4;
        let top_k = 20;
        let num_windows = 5;
        let light_samples = 1_000;
        let heavy_samples = 36_000; // window 2 gets ~90% of 40k total
        let samples_per_window = 10_000; // large enough that light samples fit in one window

        let config = FoldCMSConfig {
            rows,
            full_cols,
            fold_level,
            top_k,
        };
        let mut tw: TumblingWindow<FoldCMS> = TumblingWindow::new(
            samples_per_window as u64,
            num_windows,
            config,
            num_windows + 2,
        );

        let domain = 5000;
        let exponent = 1.1;
        let mut truth = HashMap::<u64, i64>::new();
        let mut time = 0u64;

        for w in 0..num_windows {
            let n_samples = if w == 2 { heavy_samples } else { light_samples };
            let stream = sample_zipf_u64(domain, exponent, n_samples, 0xBE_EF00 + w as u64);
            for &value in &stream {
                tw.insert(time, &DataInput::U64(value), 1);
                *truth.entry(value).or_insert(0) += 1;
                time += 1;
            }
            // Advance time to next window boundary.
            let next_boundary =
                ((time / samples_per_window as u64) + 1) * samples_per_window as u64;
            time = next_boundary;
        }

        let merged = tw.query_all();

        let epsilon = std::f64::consts::E / full_cols as f64;
        let l1: f64 = truth.values().map(|&c| c as f64).sum();
        let bound = epsilon * l1;

        let mut within = 0usize;
        for (&key, &true_count) in &truth {
            let est = merged.query(&DataInput::U64(key));
            if ((est - true_count).abs() as f64) <= bound {
                within += 1;
            }
        }
        let pct = within as f64 / truth.len() as f64 * 100.0;
        eprintln!("[tumbling_skewed_load] pct_within_bound={pct:.1}%, bound={bound:.2}");
        assert!(
            pct > 90.0,
            "only {pct:.1}% within CMS bound with skewed load (expected > 90%)"
        );
    }
}