cjc-data 0.1.9

Tidyverse-inspired data manipulation: DataFrame, filter, group_by, join
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
//! Adaptive selection representations for TidyView.
//!
//! A `TidyView` describes a subset of rows from a base `DataFrame`. Until v2,
//! the subset was stored as a single `BitMask` regardless of density. The
//! adaptive engine picks one of five deterministic representations based on
//! result density, so that sparse predicates do not pay the cost of a full
//! bitscan and dense predicates retain the existing fast O(nrows/64) path.
//!
//! # Modes
//!
//! - `Empty` — no rows selected (zero allocation)
//! - `All` — every row selected (zero allocation; nrows stored)
//! - `SelectionVector` — ascending `Vec<u32>` of selected row indices (sparse)
//! - `VerbatimMask` — backing `BitMask` for the dense path (≥30% density)
//! - `Hybrid` — chunked, locally-classified per [`HYBRID_CHUNK_SIZE`]-row block.
//!   Active for mid-density results when `nrows >= 2 * HYBRID_CHUNK_SIZE`.
//!
//! # Determinism
//!
//! - Iteration order is **always ascending row index** for every arm.
//! - Density classification uses pure integer arithmetic; thresholds are
//!   bit-stable across platforms.
//! - `intersect`/`union` produce a single deterministic arm choice for any
//!   pair of inputs.

use crate::BitMask;

// ── Constants ────────────────────────────────────────────────────────────────

/// Sparse threshold: count strictly less than `nrows / SPARSE_DIVISOR` is sparse.
const SPARSE_DIVISOR: usize = 1024;

/// Dense threshold: count strictly greater than `nrows * DENSE_NUM / DENSE_DEN`
/// is dense. 3/10 = 30%.
const DENSE_NUM: usize = 3;
const DENSE_DEN: usize = 10;

/// Hybrid chunk size in rows. 4096 rows = 64 u64 words per dense chunk = 512 B.
pub const HYBRID_CHUNK_SIZE: usize = 4096;

/// Words-per-chunk for the Dense variant. `HYBRID_CHUNK_SIZE / 64`.
const HYBRID_WORDS_PER_CHUNK: usize = HYBRID_CHUNK_SIZE / 64;

/// Per-chunk sparse threshold: a chunk with < `HYBRID_CHUNK_SIZE / 32` set bits
/// uses `HybridChunk::Sparse`. 128 hits at 4096-row chunk size.
const HYBRID_CHUNK_SPARSE_THRESHOLD: usize = HYBRID_CHUNK_SIZE / 32;

// ── HybridChunk ──────────────────────────────────────────────────────────────

/// A per-chunk selection state. Each chunk represents `HYBRID_CHUNK_SIZE` rows
/// (the final chunk may be partial — see `HybridChunk::partial_size`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HybridChunk {
    /// 0 hits in this chunk.
    Empty,
    /// All `chunk_len` rows selected (where `chunk_len` is the partial-aware
    /// row count for this chunk).
    All,
    /// Sparse: chunk-local row indices in ascending order, range `[0, chunk_len)`.
    Sparse(Vec<u16>),
    /// Dense: word-packed bitmap, length `HYBRID_WORDS_PER_CHUNK`. Tail bits
    /// past `chunk_len` are zero.
    Dense(Box<[u64]>),
}

impl HybridChunk {
    /// Count of selected rows in this chunk.
    pub fn count(&self, chunk_len: usize) -> usize {
        match self {
            HybridChunk::Empty => 0,
            HybridChunk::All => chunk_len,
            HybridChunk::Sparse(rows) => rows.len(),
            HybridChunk::Dense(words) => {
                words.iter().map(|w| w.count_ones() as usize).sum()
            }
        }
    }

    /// True if chunk-local row `off` (in `[0, chunk_len)`) is selected.
    pub fn contains_local(&self, off: usize, chunk_len: usize) -> bool {
        if off >= chunk_len {
            return false;
        }
        match self {
            HybridChunk::Empty => false,
            HybridChunk::All => true,
            HybridChunk::Sparse(rows) => rows.binary_search(&(off as u16)).is_ok(),
            HybridChunk::Dense(words) => {
                let wi = off / 64;
                let bi = off % 64;
                (words[wi] >> bi) & 1 == 1
            }
        }
    }
}

// ── AdaptiveSelection ────────────────────────────────────────────────────────

/// A row-selection representation chosen adaptively by density.
///
/// All variants carry `nrows` (the size of the underlying DataFrame) so that
/// `count`/`contains`/iteration are answerable without consulting the base.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdaptiveSelection {
    /// No rows selected. `nrows` is the underlying frame size.
    Empty { nrows: usize },
    /// Every row selected.
    All { nrows: usize },
    /// Sparse: ascending u32 row indices.
    SelectionVector { rows: Vec<u32>, nrows: usize },
    /// Dense: backing BitMask.
    VerbatimMask { mask: BitMask },
    /// Mid-density chunked representation. `chunks.len() == ceil(nrows / HYBRID_CHUNK_SIZE)`.
    Hybrid { nrows: usize, chunks: Vec<HybridChunk> },
}

impl AdaptiveSelection {
    // ── Constructors ─────────────────────────────────────────────────────

    /// All rows selected.
    pub fn all(nrows: usize) -> Self {
        AdaptiveSelection::All { nrows }
    }

    /// No rows selected.
    pub fn empty(nrows: usize) -> Self {
        AdaptiveSelection::Empty { nrows }
    }

    /// Wrap a `BitMask` directly (force the dense arm). Used by call sites
    /// that already produced a mask through the existing pipeline and do
    /// not want a re-classification.
    pub fn from_bitmask(mask: BitMask) -> Self {
        let nrows = mask.nrows();
        let count = mask.count_ones();
        if count == 0 {
            AdaptiveSelection::Empty { nrows }
        } else if count == nrows {
            AdaptiveSelection::All { nrows }
        } else {
            AdaptiveSelection::VerbatimMask { mask }
        }
    }

    /// Construct from raw predicate-result words (LSB-first within each u64).
    ///
    /// This is the canonical entry point from `try_eval_predicate_columnar`
    /// and the row-wise filter fallback. The classifier:
    ///
    /// 1. Counts set bits across `words`.
    /// 2. Picks `Empty`/`All`/`SelectionVector`/`VerbatimMask` per density.
    /// 3. Mid-band selections become `Hybrid` when `nrows >= 2 * HYBRID_CHUNK_SIZE`.
    ///
    /// The caller is responsible for masking off tail bits past `nrows` before
    /// invoking — `BitMask::all_true` / `BitMask::from_bools` and the
    /// columnar predicate path already do this.
    pub fn from_predicate_result(words: Vec<u64>, nrows: usize) -> Self {
        let count: usize = words.iter().map(|w| w.count_ones() as usize).sum();
        Self::classify(words, nrows, count)
    }

    /// Test-only and conversion helper — same as `from_predicate_result` but
    /// caller already knows the count.
    pub fn from_words_with_count(words: Vec<u64>, nrows: usize, count: usize) -> Self {
        Self::classify(words, nrows, count)
    }

    fn classify(words: Vec<u64>, nrows: usize, count: usize) -> Self {
        if count == 0 {
            return AdaptiveSelection::Empty { nrows };
        }
        if count == nrows {
            return AdaptiveSelection::All { nrows };
        }
        if Self::is_sparse(count, nrows) {
            let rows = words_to_indices(&words);
            return AdaptiveSelection::SelectionVector { rows, nrows };
        }
        let mask = bitmask_from_words(words, nrows);
        if Self::is_dense(count, nrows) {
            AdaptiveSelection::VerbatimMask { mask }
        } else if Self::should_hybrid(nrows) {
            // Mid-band: chunk it. Cheap one-pass classifier per chunk.
            let chunks = chunks_from_mask(&mask);
            AdaptiveSelection::Hybrid { nrows, chunks }
        } else {
            // Mid-band but the frame is too small to benefit from chunking.
            AdaptiveSelection::VerbatimMask { mask }
        }
    }

    /// `count < nrows / 1024`. Saturates safely for nrows < 1024 (then no
    /// non-empty selection is sparse, which is correct: a hand-typed
    /// 5-element df with 1 hit should not allocate a `Vec<u32>`).
    #[inline]
    fn is_sparse(count: usize, nrows: usize) -> bool {
        count < nrows / SPARSE_DIVISOR
    }

    /// `count > nrows * 3/10`. Uses 128-bit intermediate to avoid overflow on
    /// extreme nrows.
    #[inline]
    fn is_dense(count: usize, nrows: usize) -> bool {
        let lhs = (count as u128) * (DENSE_DEN as u128);
        let rhs = (nrows as u128) * (DENSE_NUM as u128);
        lhs > rhs
    }

    /// Frames smaller than 2 chunks gain nothing from chunking — keep them
    /// on `VerbatimMask`.
    #[inline]
    fn should_hybrid(nrows: usize) -> bool {
        nrows >= 2 * HYBRID_CHUNK_SIZE
    }

    // ── SelectionRepr surface ────────────────────────────────────────────

    /// Total number of rows in the underlying DataFrame.
    pub fn nrows(&self) -> usize {
        match self {
            AdaptiveSelection::Empty { nrows } => *nrows,
            AdaptiveSelection::All { nrows } => *nrows,
            AdaptiveSelection::SelectionVector { nrows, .. } => *nrows,
            AdaptiveSelection::VerbatimMask { mask } => mask.nrows(),
            AdaptiveSelection::Hybrid { nrows, .. } => *nrows,
        }
    }

    /// Number of rows actually selected.
    pub fn count(&self) -> usize {
        match self {
            AdaptiveSelection::Empty { .. } => 0,
            AdaptiveSelection::All { nrows } => *nrows,
            AdaptiveSelection::SelectionVector { rows, .. } => rows.len(),
            AdaptiveSelection::VerbatimMask { mask } => mask.count_ones(),
            AdaptiveSelection::Hybrid { nrows, chunks } => {
                let mut total = 0;
                for (i, c) in chunks.iter().enumerate() {
                    total += c.count(chunk_len_for(i, *nrows));
                }
                total
            }
        }
    }

    /// True if `row` is in the selection. Out-of-range rows return `false`.
    pub fn contains(&self, row: usize) -> bool {
        match self {
            AdaptiveSelection::Empty { .. } => false,
            AdaptiveSelection::All { nrows } => row < *nrows,
            AdaptiveSelection::SelectionVector { rows, nrows } => {
                if row >= *nrows {
                    return false;
                }
                let target = row as u32;
                rows.binary_search(&target).is_ok()
            }
            AdaptiveSelection::VerbatimMask { mask } => {
                if row >= mask.nrows() {
                    return false;
                }
                mask.get(row)
            }
            AdaptiveSelection::Hybrid { nrows, chunks } => {
                if row >= *nrows {
                    return false;
                }
                let ci = row / HYBRID_CHUNK_SIZE;
                let off = row % HYBRID_CHUNK_SIZE;
                chunks[ci].contains_local(off, chunk_len_for(ci, *nrows))
            }
        }
    }

    /// Iterate selected rows in ascending order.
    pub fn iter_indices(&self) -> SelectionIndices<'_> {
        match self {
            AdaptiveSelection::Empty { .. } => SelectionIndices::Empty,
            AdaptiveSelection::All { nrows } => SelectionIndices::Range(0..*nrows),
            AdaptiveSelection::SelectionVector { rows, .. } => SelectionIndices::Vec(rows.iter()),
            AdaptiveSelection::VerbatimMask { mask } => SelectionIndices::Mask {
                mask,
                next: 0,
                nrows: mask.nrows(),
            },
            AdaptiveSelection::Hybrid { nrows, chunks } => SelectionIndices::Hybrid {
                chunks,
                nrows: *nrows,
                ci: 0,
                inner: HybridInner::Start,
            },
        }
    }

    /// Materialize the selection as a `BitMask`. Always allocates `O(nrows/64)`.
    pub fn materialize_mask(&self) -> BitMask {
        match self {
            AdaptiveSelection::Empty { nrows } => BitMask::all_false(*nrows),
            AdaptiveSelection::All { nrows } => BitMask::all_true(*nrows),
            AdaptiveSelection::SelectionVector { rows, nrows } => {
                let mut bools = vec![false; *nrows];
                for &r in rows {
                    bools[r as usize] = true;
                }
                BitMask::from_bools(&bools)
            }
            AdaptiveSelection::VerbatimMask { mask } => mask.clone(),
            AdaptiveSelection::Hybrid { nrows, chunks } => {
                let mut bools = vec![false; *nrows];
                for (ci, chunk) in chunks.iter().enumerate() {
                    let base = ci * HYBRID_CHUNK_SIZE;
                    let chunk_len = chunk_len_for(ci, *nrows);
                    match chunk {
                        HybridChunk::Empty => {}
                        HybridChunk::All => {
                            for off in 0..chunk_len {
                                bools[base + off] = true;
                            }
                        }
                        HybridChunk::Sparse(rows) => {
                            for &r in rows {
                                bools[base + r as usize] = true;
                            }
                        }
                        HybridChunk::Dense(words) => {
                            for off in 0..chunk_len {
                                let wi = off / 64;
                                let bi = off % 64;
                                if (words[wi] >> bi) & 1 == 1 {
                                    bools[base + off] = true;
                                }
                            }
                        }
                    }
                }
                BitMask::from_bools(&bools)
            }
        }
    }

    /// Materialize the selection as an ascending `Vec<u32>` of row indices.
    pub fn materialize_indices(&self) -> Vec<u32> {
        match self {
            AdaptiveSelection::Empty { .. } => Vec::new(),
            AdaptiveSelection::All { nrows } => (0..*nrows as u32).collect(),
            AdaptiveSelection::SelectionVector { rows, .. } => rows.clone(),
            AdaptiveSelection::VerbatimMask { mask } => {
                mask.iter_set().map(|i| i as u32).collect()
            }
            AdaptiveSelection::Hybrid { nrows, chunks } => {
                let mut out = Vec::with_capacity(self.count());
                for (ci, chunk) in chunks.iter().enumerate() {
                    let base = (ci * HYBRID_CHUNK_SIZE) as u32;
                    let chunk_len = chunk_len_for(ci, *nrows);
                    match chunk {
                        HybridChunk::Empty => {}
                        HybridChunk::All => {
                            for off in 0..chunk_len as u32 {
                                out.push(base + off);
                            }
                        }
                        HybridChunk::Sparse(rows) => {
                            for &r in rows {
                                out.push(base + r as u32);
                            }
                        }
                        HybridChunk::Dense(words) => {
                            for (wi, &w) in words.iter().enumerate() {
                                let mut bits = w;
                                while bits != 0 {
                                    let tz = bits.trailing_zeros() as usize;
                                    let off = wi * 64 + tz;
                                    if off < chunk_len {
                                        out.push(base + off as u32);
                                    }
                                    bits &= bits - 1;
                                }
                            }
                        }
                    }
                }
                out
            }
        }
    }

    /// Intersection (AND). Output mode is re-classified by density.
    ///
    /// Panics if `nrows` differ — programming error (different base frames).
    pub fn intersect(&self, other: &AdaptiveSelection) -> AdaptiveSelection {
        assert_eq!(
            self.nrows(),
            other.nrows(),
            "AdaptiveSelection::intersect: nrows mismatch ({} vs {})",
            self.nrows(),
            other.nrows()
        );
        // Identity / annihilator fast paths
        match (self, other) {
            (AdaptiveSelection::Empty { nrows }, _) | (_, AdaptiveSelection::Empty { nrows }) => {
                return AdaptiveSelection::Empty { nrows: *nrows };
            }
            (AdaptiveSelection::All { .. }, _) => return other.clone(),
            (_, AdaptiveSelection::All { .. }) => return self.clone(),
            _ => {}
        }
        // Sparse ∩ Sparse: merge-walk in O(|A|+|B|), no bitmap allocation.
        if let (
            AdaptiveSelection::SelectionVector { rows: a, nrows },
            AdaptiveSelection::SelectionVector { rows: b, .. },
        ) = (self, other)
        {
            let merged = sorted_merge_intersect(a, b);
            return Self::classify_sparse(merged, *nrows);
        }
        // Sparse ∩ VerbatimMask: filter the sparse vector by mask test.
        if let (
            AdaptiveSelection::SelectionVector { rows, nrows },
            AdaptiveSelection::VerbatimMask { mask },
        )
        | (
            AdaptiveSelection::VerbatimMask { mask },
            AdaptiveSelection::SelectionVector { rows, nrows },
        ) = (self, other)
        {
            let filtered: Vec<u32> =
                rows.iter().copied().filter(|&r| mask.get(r as usize)).collect();
            return Self::classify_sparse(filtered, *nrows);
        }
        // ── v3 Phase 3: Hybrid streaming fast paths ──────────────────────
        // Hybrid ∩ Hybrid: per-chunk dispatch over the 16-way shape table.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks: ac },
            AdaptiveSelection::Hybrid { chunks: bc, .. },
        ) = (self, other)
        {
            let mut out = Vec::with_capacity(ac.len());
            for ci in 0..ac.len() {
                let chunk_len = chunk_len_for(ci, *nrows);
                out.push(intersect_chunks(&ac[ci], &bc[ci], chunk_len));
            }
            return Self::simplify_hybrid(*nrows, out);
        }
        // Hybrid ∩ SelectionVector: walk the sparse vector once, dispatch
        // each row to its chunk via row >> 12. Output stays sparse.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks },
            AdaptiveSelection::SelectionVector { rows, .. },
        )
        | (
            AdaptiveSelection::SelectionVector { rows, .. },
            AdaptiveSelection::Hybrid { nrows, chunks },
        ) = (self, other)
        {
            let mut filtered: Vec<u32> = Vec::with_capacity(rows.len());
            for &r in rows {
                let row = r as usize;
                let ci = row / HYBRID_CHUNK_SIZE;
                let off = row % HYBRID_CHUNK_SIZE;
                let chunk_len = chunk_len_for(ci, *nrows);
                if chunks[ci].contains_local(off, chunk_len) {
                    filtered.push(r);
                }
            }
            return Self::classify_sparse(filtered, *nrows);
        }
        // Hybrid ∩ VerbatimMask: per-chunk word-AND against the matching
        // 64-word slice of the verbatim mask. Output stays Hybrid.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks },
            AdaptiveSelection::VerbatimMask { mask },
        )
        | (
            AdaptiveSelection::VerbatimMask { mask },
            AdaptiveSelection::Hybrid { nrows, chunks },
        ) = (self, other)
        {
            let words = mask.words_slice();
            let mut out_chunks = Vec::with_capacity(chunks.len());
            for ci in 0..chunks.len() {
                let chunk_len = chunk_len_for(ci, *nrows);
                let w_start = ci * HYBRID_WORDS_PER_CHUNK;
                let w_end = (w_start + HYBRID_WORDS_PER_CHUNK).min(words.len());
                let mask_chunk = &words[w_start..w_end];
                out_chunks.push(intersect_chunk_with_words(
                    &chunks[ci],
                    mask_chunk,
                    chunk_len,
                ));
            }
            return Self::simplify_hybrid(*nrows, out_chunks);
        }
        // General path: materialize both as words, AND, reclassify.
        let lhs = self.materialize_mask();
        let rhs = other.materialize_mask();
        let words: Vec<u64> = lhs
            .words_slice()
            .iter()
            .zip(rhs.words_slice().iter())
            .map(|(a, b)| a & b)
            .collect();
        AdaptiveSelection::from_predicate_result(words, lhs.nrows())
    }

    /// Union (OR). Output mode re-classified by density.
    pub fn union(&self, other: &AdaptiveSelection) -> AdaptiveSelection {
        assert_eq!(
            self.nrows(),
            other.nrows(),
            "AdaptiveSelection::union: nrows mismatch ({} vs {})",
            self.nrows(),
            other.nrows()
        );
        match (self, other) {
            (AdaptiveSelection::All { nrows }, _) | (_, AdaptiveSelection::All { nrows }) => {
                return AdaptiveSelection::All { nrows: *nrows };
            }
            (AdaptiveSelection::Empty { .. }, _) => return other.clone(),
            (_, AdaptiveSelection::Empty { .. }) => return self.clone(),
            _ => {}
        }
        // Sparse ∪ Sparse: merge-walk, no bitmap allocation.
        if let (
            AdaptiveSelection::SelectionVector { rows: a, nrows },
            AdaptiveSelection::SelectionVector { rows: b, .. },
        ) = (self, other)
        {
            let merged = sorted_merge_union(a, b);
            // Re-classify: union may push us out of the sparse band.
            if merged.len() >= *nrows / SPARSE_DIVISOR {
                // No longer sparse — fall through to bitmap path below.
            } else {
                return Self::classify_sparse(merged, *nrows);
            }
        }
        // ── v3 Phase 3: Hybrid streaming fast paths ──────────────────────
        // Hybrid ∪ Hybrid: per-chunk dispatch.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks: ac },
            AdaptiveSelection::Hybrid { chunks: bc, .. },
        ) = (self, other)
        {
            let mut out = Vec::with_capacity(ac.len());
            for ci in 0..ac.len() {
                let chunk_len = chunk_len_for(ci, *nrows);
                out.push(union_chunks(&ac[ci], &bc[ci], chunk_len));
            }
            return Self::simplify_hybrid(*nrows, out);
        }
        // Hybrid ∪ SelectionVector: scatter the sparse rows into the
        // matching chunks. Output stays Hybrid.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks },
            AdaptiveSelection::SelectionVector { rows, .. },
        )
        | (
            AdaptiveSelection::SelectionVector { rows, .. },
            AdaptiveSelection::Hybrid { nrows, chunks },
        ) = (self, other)
        {
            let mut out_chunks: Vec<HybridChunk> = chunks.clone();
            // Bucket sparse rows by chunk index, then union each bucket.
            // Single linear pass: ascending input, ascending bucket order.
            let mut i = 0usize;
            while i < rows.len() {
                let first_row = rows[i] as usize;
                let ci = first_row / HYBRID_CHUNK_SIZE;
                let chunk_base = ci * HYBRID_CHUNK_SIZE;
                let chunk_end = chunk_base + HYBRID_CHUNK_SIZE;
                let mut bucket: Vec<u16> = Vec::new();
                while i < rows.len() && (rows[i] as usize) < chunk_end {
                    bucket.push((rows[i] as usize - chunk_base) as u16);
                    i += 1;
                }
                let chunk_len = chunk_len_for(ci, *nrows);
                let bucket_chunk = if bucket.len() == chunk_len {
                    HybridChunk::All
                } else {
                    HybridChunk::Sparse(bucket)
                };
                out_chunks[ci] = union_chunks(&out_chunks[ci], &bucket_chunk, chunk_len);
            }
            return Self::simplify_hybrid(*nrows, out_chunks);
        }
        // Hybrid ∪ VerbatimMask: per-chunk word-OR against the matching
        // 64-word slice. Output stays Hybrid.
        if let (
            AdaptiveSelection::Hybrid { nrows, chunks },
            AdaptiveSelection::VerbatimMask { mask },
        )
        | (
            AdaptiveSelection::VerbatimMask { mask },
            AdaptiveSelection::Hybrid { nrows, chunks },
        ) = (self, other)
        {
            let words = mask.words_slice();
            let mut out_chunks = Vec::with_capacity(chunks.len());
            for ci in 0..chunks.len() {
                let chunk_len = chunk_len_for(ci, *nrows);
                let w_start = ci * HYBRID_WORDS_PER_CHUNK;
                let w_end = (w_start + HYBRID_WORDS_PER_CHUNK).min(words.len());
                let mask_chunk = &words[w_start..w_end];
                out_chunks.push(union_chunk_with_words(
                    &chunks[ci],
                    mask_chunk,
                    chunk_len,
                ));
            }
            return Self::simplify_hybrid(*nrows, out_chunks);
        }
        let lhs = self.materialize_mask();
        let rhs = other.materialize_mask();
        let words: Vec<u64> = lhs
            .words_slice()
            .iter()
            .zip(rhs.words_slice().iter())
            .map(|(a, b)| a | b)
            .collect();
        AdaptiveSelection::from_predicate_result(words, lhs.nrows())
    }

    /// Stable identifier of the chosen mode. Useful for debug, tests, and
    /// the planned `explain_selection_mode` user-facing call.
    pub fn explain_selection_mode(&self) -> &'static str {
        match self {
            AdaptiveSelection::Empty { .. } => "Empty",
            AdaptiveSelection::All { .. } => "All",
            AdaptiveSelection::SelectionVector { .. } => "SelectionVector",
            AdaptiveSelection::VerbatimMask { .. } => "VerbatimMask",
            AdaptiveSelection::Hybrid { .. } => "Hybrid",
        }
    }

    // ── Internal helpers ─────────────────────────────────────────────────

    /// Build a `SelectionVector`/`Empty`/`All` from an already-sorted-ascending
    /// `Vec<u32>`. Used by sparse-fast-path set ops.
    fn classify_sparse(rows: Vec<u32>, nrows: usize) -> Self {
        if rows.is_empty() {
            AdaptiveSelection::Empty { nrows }
        } else if rows.len() == nrows {
            AdaptiveSelection::All { nrows }
        } else {
            AdaptiveSelection::SelectionVector { rows, nrows }
        }
    }

    /// Collapse a chunked Hybrid result into `Empty`/`All` if every chunk
    /// agrees; otherwise keep the chunked layout. Phase 3 deliberately does
    /// not re-globalize mid-density Hybrids — preserving chunks is the point.
    fn simplify_hybrid(nrows: usize, chunks: Vec<HybridChunk>) -> AdaptiveSelection {
        let mut total = 0usize;
        for (i, c) in chunks.iter().enumerate() {
            total += c.count(chunk_len_for(i, nrows));
        }
        if total == 0 {
            return AdaptiveSelection::Empty { nrows };
        }
        if total == nrows {
            return AdaptiveSelection::All { nrows };
        }
        AdaptiveSelection::Hybrid { nrows, chunks }
    }
}

// ── Iterator ─────────────────────────────────────────────────────────────────

/// An ascending iterator over selected row indices. One variant per
/// `AdaptiveSelection` arm so the hot path stays monomorphic and inlines.
pub enum SelectionIndices<'a> {
    Empty,
    Range(std::ops::Range<usize>),
    Vec(std::slice::Iter<'a, u32>),
    Mask {
        mask: &'a BitMask,
        next: usize,
        nrows: usize,
    },
    Hybrid {
        chunks: &'a [HybridChunk],
        nrows: usize,
        /// Current chunk index.
        ci: usize,
        inner: HybridInner<'a>,
    },
}

/// Per-chunk iteration state.
pub enum HybridInner<'a> {
    /// About to advance to the next chunk.
    Start,
    /// Iterating an `All` chunk: emit `[next, end)` plus chunk base.
    AllRange { base: u32, next: u32, end: u32 },
    /// Iterating a sparse chunk's index list.
    Sparse {
        base: u32,
        iter: std::slice::Iter<'a, u16>,
    },
    /// Iterating a dense chunk's word vector.
    Dense {
        base: u32,
        words: &'a [u64],
        wi: usize,
        bits: u64,
        chunk_len: usize,
    },
}

impl<'a> Iterator for SelectionIndices<'a> {
    type Item = usize;
    fn next(&mut self) -> Option<usize> {
        match self {
            SelectionIndices::Empty => None,
            SelectionIndices::Range(r) => r.next(),
            SelectionIndices::Vec(it) => it.next().map(|&v| v as usize),
            SelectionIndices::Mask { mask, next, nrows } => {
                while *next < *nrows {
                    let i = *next;
                    *next += 1;
                    if mask.get(i) {
                        return Some(i);
                    }
                }
                None
            }
            SelectionIndices::Hybrid {
                chunks,
                nrows,
                ci,
                inner,
            } => loop {
                // Try to drain the current chunk's inner iterator first.
                match inner {
                    HybridInner::Start => {
                        // Fall through to chunk advance.
                    }
                    HybridInner::AllRange { base, next, end } => {
                        if *next < *end {
                            let v = *next;
                            *next += 1;
                            return Some((*base + v) as usize);
                        }
                        // exhausted; fall through
                    }
                    HybridInner::Sparse { base, iter } => {
                        if let Some(&off) = iter.next() {
                            return Some((*base + off as u32) as usize);
                        }
                        // exhausted; fall through
                    }
                    HybridInner::Dense {
                        base,
                        words,
                        wi,
                        bits,
                        chunk_len,
                    } => {
                        loop {
                            if *bits != 0 {
                                let tz = bits.trailing_zeros() as usize;
                                let off = *wi * 64 + tz;
                                *bits &= *bits - 1;
                                if off < *chunk_len {
                                    return Some((*base + off as u32) as usize);
                                }
                                continue;
                            }
                            *wi += 1;
                            if *wi >= words.len() {
                                break; // exhausted current chunk
                            }
                            *bits = words[*wi];
                        }
                    }
                }
                // Advance to next chunk
                if *ci >= chunks.len() {
                    return None;
                }
                let chunk = &chunks[*ci];
                let chunk_idx = *ci;
                *ci += 1;
                let chunk_len = chunk_len_for(chunk_idx, *nrows);
                let base = (chunk_idx * HYBRID_CHUNK_SIZE) as u32;
                *inner = match chunk {
                    HybridChunk::Empty => HybridInner::Start,
                    HybridChunk::All => HybridInner::AllRange {
                        base,
                        next: 0,
                        end: chunk_len as u32,
                    },
                    HybridChunk::Sparse(rows) => HybridInner::Sparse {
                        base,
                        iter: rows.iter(),
                    },
                    HybridChunk::Dense(words) => HybridInner::Dense {
                        base,
                        words: &words[..],
                        wi: 0,
                        bits: words[0],
                        chunk_len,
                    },
                };
            },
        }
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Convert raw u64 words into an ascending `Vec<u32>` of set-bit indices.
///
/// Uses `trailing_zeros` to skip zero runs — O(count), not O(nrows).
fn words_to_indices(words: &[u64]) -> Vec<u32> {
    let mut out = Vec::with_capacity(64);
    for (wi, &w) in words.iter().enumerate() {
        let mut bits = w;
        while bits != 0 {
            let tz = bits.trailing_zeros() as usize;
            let row = wi * 64 + tz;
            out.push(row as u32);
            // Clear the lowest set bit
            bits &= bits - 1;
        }
    }
    out
}

/// Build a `BitMask` from raw words (used after AND/OR ops). Tail bits past
/// `nrows` are masked off to preserve the BitMask invariant.
fn bitmask_from_words(mut words: Vec<u64>, nrows: usize) -> BitMask {
    let nwords = (nrows + 63) / 64;
    if words.len() < nwords {
        words.resize(nwords, 0);
    } else if words.len() > nwords {
        words.truncate(nwords);
    }
    if nwords > 0 && nrows % 64 != 0 {
        let tail = nrows % 64;
        words[nwords - 1] &= (1u64 << tail) - 1;
    }
    BitMask::from_words_for_test(words, nrows)
}

/// Row count for chunk `ci` given a total `nrows`. The final chunk may be
/// partial.
#[inline]
fn chunk_len_for(ci: usize, nrows: usize) -> usize {
    let base = ci * HYBRID_CHUNK_SIZE;
    let remaining = nrows.saturating_sub(base);
    remaining.min(HYBRID_CHUNK_SIZE)
}

/// Slice the words of a fully-materialized BitMask into per-chunk
/// `HybridChunk`s, classifying each chunk by local density.
fn chunks_from_mask(mask: &BitMask) -> Vec<HybridChunk> {
    let nrows = mask.nrows();
    let total_words = mask.words_slice().len();
    let nchunks = (nrows + HYBRID_CHUNK_SIZE - 1) / HYBRID_CHUNK_SIZE;
    let mut chunks = Vec::with_capacity(nchunks);
    let words = mask.words_slice();
    for ci in 0..nchunks {
        let chunk_len = chunk_len_for(ci, nrows);
        let w_start = ci * HYBRID_WORDS_PER_CHUNK;
        let w_end = (w_start + HYBRID_WORDS_PER_CHUNK).min(total_words);
        let chunk_words = &words[w_start..w_end];
        let count: usize = chunk_words.iter().map(|w| w.count_ones() as usize).sum();
        let chunk = if count == 0 {
            HybridChunk::Empty
        } else if count == chunk_len {
            HybridChunk::All
        } else if count < HYBRID_CHUNK_SPARSE_THRESHOLD {
            // Sparse chunk: pull u16 offsets directly from the words.
            let mut offs: Vec<u16> = Vec::with_capacity(count);
            for (i, &w) in chunk_words.iter().enumerate() {
                let mut bits = w;
                while bits != 0 {
                    let tz = bits.trailing_zeros() as usize;
                    let off = i * 64 + tz;
                    if off < chunk_len {
                        offs.push(off as u16);
                    }
                    bits &= bits - 1;
                }
            }
            HybridChunk::Sparse(offs)
        } else {
            // Dense chunk: copy the (up to) HYBRID_WORDS_PER_CHUNK words.
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for (i, &w) in chunk_words.iter().enumerate() {
                buf[i] = w;
            }
            HybridChunk::Dense(buf.into_boxed_slice())
        };
        chunks.push(chunk);
    }
    chunks
}

// ── v3 Phase 3: per-chunk set-op helpers ─────────────────────────────────────

/// Per-chunk classifier: take an ascending `Vec<u16>` of chunk-local offsets
/// and a `chunk_len`, decide between `Empty`/`All`/`Sparse`/`Dense`. Used by
/// outputs of sparse-shaped per-chunk operations.
fn classify_sparse_chunk(offs: Vec<u16>, chunk_len: usize) -> HybridChunk {
    if offs.is_empty() {
        HybridChunk::Empty
    } else if offs.len() == chunk_len {
        HybridChunk::All
    } else {
        // Per-Phase-3 invariant: sparse output of sparse-shape input keeps
        // the sparse arm regardless of size — overflow into Dense is the
        // caller's responsibility (they classify via `classify_dense_chunk`).
        HybridChunk::Sparse(offs)
    }
}

/// Per-chunk classifier: take a populated word buffer and a `chunk_len`,
/// pick the most compact arm by local count. Used by outputs of word-shaped
/// per-chunk operations.
fn classify_dense_chunk(buf: Vec<u64>, chunk_len: usize) -> HybridChunk {
    let count: usize = buf.iter().map(|w| w.count_ones() as usize).sum();
    if count == 0 {
        HybridChunk::Empty
    } else if count == chunk_len {
        HybridChunk::All
    } else if count < HYBRID_CHUNK_SPARSE_THRESHOLD {
        // Demote to Sparse: extract chunk-local offsets ascending.
        let mut offs = Vec::with_capacity(count);
        for (i, &w) in buf.iter().enumerate() {
            let mut bits = w;
            while bits != 0 {
                let tz = bits.trailing_zeros() as usize;
                let off = i * 64 + tz;
                if off < chunk_len {
                    offs.push(off as u16);
                }
                bits &= bits - 1;
            }
        }
        HybridChunk::Sparse(offs)
    } else {
        HybridChunk::Dense(buf.into_boxed_slice())
    }
}

/// Merge-walk intersection of two sorted ascending `&[u16]` slices.
fn merge_intersect_u16(a: &[u16], b: &[u16]) -> Vec<u16> {
    let mut out = Vec::with_capacity(a.len().min(b.len()));
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => i += 1,
            std::cmp::Ordering::Greater => j += 1,
            std::cmp::Ordering::Equal => {
                out.push(a[i]);
                i += 1;
                j += 1;
            }
        }
    }
    out
}

/// Merge-walk union of two sorted ascending `&[u16]` slices.
fn merge_union_u16(a: &[u16], b: &[u16]) -> Vec<u16> {
    let mut out = Vec::with_capacity(a.len() + b.len());
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => {
                out.push(a[i]);
                i += 1;
            }
            std::cmp::Ordering::Greater => {
                out.push(b[j]);
                j += 1;
            }
            std::cmp::Ordering::Equal => {
                out.push(a[i]);
                i += 1;
                j += 1;
            }
        }
    }
    out.extend_from_slice(&a[i..]);
    out.extend_from_slice(&b[j..]);
    out
}

/// 16-way per-chunk intersection. The 5 effective shapes after annihilator
/// folding: Empty/_, _/Empty, All/X, X/All, Sparse∩Sparse (merge-walk),
/// Sparse∩Dense (filter-walk), Dense∩Dense (word-AND).
fn intersect_chunks(a: &HybridChunk, b: &HybridChunk, chunk_len: usize) -> HybridChunk {
    use HybridChunk::*;
    match (a, b) {
        (Empty, _) | (_, Empty) => Empty,
        (All, x) | (x, All) => x.clone(),
        (Sparse(ax), Sparse(bx)) => {
            let merged = merge_intersect_u16(ax, bx);
            classify_sparse_chunk(merged, chunk_len)
        }
        (Sparse(offs), Dense(words)) | (Dense(words), Sparse(offs)) => {
            let mut out: Vec<u16> = Vec::with_capacity(offs.len());
            for &off in offs {
                let off_u = off as usize;
                let wi = off_u / 64;
                let bi = off_u % 64;
                if (words[wi] >> bi) & 1 == 1 {
                    out.push(off);
                }
            }
            classify_sparse_chunk(out, chunk_len)
        }
        (Dense(aw), Dense(bw)) => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for i in 0..HYBRID_WORDS_PER_CHUNK {
                buf[i] = aw[i] & bw[i];
            }
            classify_dense_chunk(buf, chunk_len)
        }
    }
}

/// 16-way per-chunk union.
fn union_chunks(a: &HybridChunk, b: &HybridChunk, chunk_len: usize) -> HybridChunk {
    use HybridChunk::*;
    match (a, b) {
        (All, _) | (_, All) => All,
        (Empty, x) | (x, Empty) => x.clone(),
        (Sparse(ax), Sparse(bx)) => {
            let merged = merge_union_u16(ax, bx);
            // May overflow the sparse threshold → promote to Dense.
            if merged.len() == chunk_len {
                All
            } else if merged.len() < HYBRID_CHUNK_SPARSE_THRESHOLD {
                if merged.is_empty() {
                    Empty
                } else {
                    Sparse(merged)
                }
            } else {
                let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
                for &off in &merged {
                    let off = off as usize;
                    buf[off / 64] |= 1u64 << (off % 64);
                }
                classify_dense_chunk(buf, chunk_len)
            }
        }
        (Sparse(offs), Dense(words)) | (Dense(words), Sparse(offs)) => {
            let mut buf: Vec<u64> = words.iter().copied().collect();
            for &off in offs {
                let off = off as usize;
                buf[off / 64] |= 1u64 << (off % 64);
            }
            classify_dense_chunk(buf, chunk_len)
        }
        (Dense(aw), Dense(bw)) => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for i in 0..HYBRID_WORDS_PER_CHUNK {
                buf[i] = aw[i] | bw[i];
            }
            classify_dense_chunk(buf, chunk_len)
        }
    }
}

/// Hybrid chunk × VerbatimMask 64-word slice → Hybrid chunk (intersection).
/// `mask_words` may be shorter than `HYBRID_WORDS_PER_CHUNK` for the final
/// (partial) chunk.
fn intersect_chunk_with_words(
    chunk: &HybridChunk,
    mask_words: &[u64],
    chunk_len: usize,
) -> HybridChunk {
    use HybridChunk::*;
    match chunk {
        Empty => Empty,
        All => {
            // Result = whatever bits are set in mask_words (pre-zeroed past
            // chunk_len by BitMask invariant).
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for (i, &w) in mask_words.iter().enumerate() {
                buf[i] = w;
            }
            classify_dense_chunk(buf, chunk_len)
        }
        Sparse(offs) => {
            let mut out: Vec<u16> = Vec::with_capacity(offs.len());
            for &off in offs {
                let off_u = off as usize;
                let wi = off_u / 64;
                if wi < mask_words.len() {
                    let bi = off_u % 64;
                    if (mask_words[wi] >> bi) & 1 == 1 {
                        out.push(off);
                    }
                }
            }
            classify_sparse_chunk(out, chunk_len)
        }
        Dense(words) => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for i in 0..HYBRID_WORDS_PER_CHUNK {
                let mw = if i < mask_words.len() { mask_words[i] } else { 0 };
                buf[i] = words[i] & mw;
            }
            classify_dense_chunk(buf, chunk_len)
        }
    }
}

/// Hybrid chunk × VerbatimMask 64-word slice → Hybrid chunk (union).
fn union_chunk_with_words(
    chunk: &HybridChunk,
    mask_words: &[u64],
    chunk_len: usize,
) -> HybridChunk {
    use HybridChunk::*;
    match chunk {
        Empty => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for (i, &w) in mask_words.iter().enumerate() {
                buf[i] = w;
            }
            classify_dense_chunk(buf, chunk_len)
        }
        All => All,
        Sparse(offs) => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for (i, &w) in mask_words.iter().enumerate() {
                buf[i] = w;
            }
            for &off in offs {
                let off = off as usize;
                buf[off / 64] |= 1u64 << (off % 64);
            }
            classify_dense_chunk(buf, chunk_len)
        }
        Dense(words) => {
            let mut buf = vec![0u64; HYBRID_WORDS_PER_CHUNK];
            for i in 0..HYBRID_WORDS_PER_CHUNK {
                let mw = if i < mask_words.len() { mask_words[i] } else { 0 };
                buf[i] = words[i] | mw;
            }
            classify_dense_chunk(buf, chunk_len)
        }
    }
}

/// Merge-walk intersection of two sorted ascending `Vec<u32>` slices.
fn sorted_merge_intersect(a: &[u32], b: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(a.len().min(b.len()));
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => i += 1,
            std::cmp::Ordering::Greater => j += 1,
            std::cmp::Ordering::Equal => {
                out.push(a[i]);
                i += 1;
                j += 1;
            }
        }
    }
    out
}

/// Merge-walk union of two sorted ascending `Vec<u32>` slices.
fn sorted_merge_union(a: &[u32], b: &[u32]) -> Vec<u32> {
    let mut out = Vec::with_capacity(a.len() + b.len());
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        match a[i].cmp(&b[j]) {
            std::cmp::Ordering::Less => {
                out.push(a[i]);
                i += 1;
            }
            std::cmp::Ordering::Greater => {
                out.push(b[j]);
                j += 1;
            }
            std::cmp::Ordering::Equal => {
                out.push(a[i]);
                i += 1;
                j += 1;
            }
        }
    }
    out.extend_from_slice(&a[i..]);
    out.extend_from_slice(&b[j..]);
    out
}

// ── Unit tests ───────────────────────────────────────────────────────────────

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

    fn mk_bools(n: usize, set: &[usize]) -> Vec<bool> {
        let mut v = vec![false; n];
        for &i in set {
            v[i] = true;
        }
        v
    }

    fn classify_from_bools(bools: &[bool]) -> AdaptiveSelection {
        let mask = BitMask::from_bools(bools);
        let words: Vec<u64> = mask.words_slice().to_vec();
        AdaptiveSelection::from_predicate_result(words, bools.len())
    }

    // ── Constructors / classifier ────────────────────────────────────

    #[test]
    fn empty_when_no_bits_set() {
        let s = classify_from_bools(&mk_bools(100, &[]));
        assert_eq!(s.explain_selection_mode(), "Empty");
        assert_eq!(s.count(), 0);
        assert_eq!(s.nrows(), 100);
    }

    #[test]
    fn all_when_every_bit_set() {
        let s = classify_from_bools(&vec![true; 100]);
        assert_eq!(s.explain_selection_mode(), "All");
        assert_eq!(s.count(), 100);
        assert_eq!(s.nrows(), 100);
    }

    #[test]
    fn sparse_picks_selection_vector() {
        // 100_000 rows, 50 hits → 50 < 100_000/1024 (~97) → sparse
        let mut hits = vec![];
        for i in (0..100_000).step_by(2_000) {
            hits.push(i);
        }
        assert_eq!(hits.len(), 50);
        let s = classify_from_bools(&mk_bools(100_000, &hits));
        assert_eq!(s.explain_selection_mode(), "SelectionVector");
        assert_eq!(s.count(), 50);
    }

    #[test]
    fn dense_picks_verbatim_mask() {
        // 1000 rows, every other → 50% → dense
        let hits: Vec<usize> = (0..1000).step_by(2).collect();
        let s = classify_from_bools(&mk_bools(1000, &hits));
        assert_eq!(s.explain_selection_mode(), "VerbatimMask");
        assert_eq!(s.count(), 500);
    }

    #[test]
    fn mid_band_small_frame_stays_verbatim() {
        // 1000 rows < 2 * HYBRID_CHUNK_SIZE → small frame, mid-band → VerbatimMask.
        let hits: Vec<usize> = (0..1000).step_by(5).collect();
        assert_eq!(hits.len(), 200);
        let s = classify_from_bools(&mk_bools(1000, &hits));
        assert_eq!(s.explain_selection_mode(), "VerbatimMask");
        assert_eq!(s.count(), 200);
    }

    #[test]
    fn mid_band_large_frame_picks_hybrid() {
        // 100_000 rows, 5_000 hits = 5%. Above sparse threshold (97), below
        // dense threshold (30%). nrows >= 2 * 4096 → Hybrid.
        let hits: Vec<usize> = (0..100_000).step_by(20).collect();
        assert_eq!(hits.len(), 5_000);
        let s = classify_from_bools(&mk_bools(100_000, &hits));
        assert_eq!(s.explain_selection_mode(), "Hybrid");
        assert_eq!(s.count(), 5_000);
    }

    // ── SelectionRepr surface ────────────────────────────────────────

    #[test]
    fn count_and_contains_agree_for_sparse() {
        let hits = vec![3usize, 17, 99, 5_000];
        let s = classify_from_bools(&mk_bools(100_000, &hits));
        assert_eq!(s.explain_selection_mode(), "SelectionVector");
        for h in &hits {
            assert!(s.contains(*h), "expected contains({})", h);
        }
        assert!(!s.contains(0));
        assert!(!s.contains(100_001)); // out of range
    }

    #[test]
    fn iter_indices_ascending_for_every_arm() {
        let hybrid_hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let cases: Vec<(usize, Vec<usize>, &'static str)> = vec![
            (10, vec![], "Empty"),
            (10, (0..10).collect(), "All"),
            (100_000, vec![3, 17, 99, 5_000], "SelectionVector"),
            (1000, (0..1000).step_by(2).collect(), "VerbatimMask"),
            (100_000, hybrid_hits, "Hybrid"),
        ];
        for (nrows, hits, expected_mode) in cases {
            let s = classify_from_bools(&mk_bools(nrows, &hits));
            assert_eq!(s.explain_selection_mode(), expected_mode);
            let collected: Vec<usize> = s.iter_indices().collect();
            assert_eq!(collected, hits, "{expected_mode} iter mismatch");
            // Strictly ascending invariant
            for w in collected.windows(2) {
                assert!(w[0] < w[1]);
            }
        }
    }

    #[test]
    fn materialize_round_trip_agrees_for_every_arm() {
        let hits = vec![1usize, 5, 10, 64, 65, 200];
        let nrows = 256;
        let s = classify_from_bools(&mk_bools(nrows, &hits));
        let mask = s.materialize_mask();
        let idx = s.materialize_indices();
        assert_eq!(mask.count_ones(), hits.len());
        assert_eq!(idx.len(), hits.len());
        for h in &hits {
            assert!(mask.get(*h));
            assert!(idx.binary_search(&(*h as u32)).is_ok());
        }
    }

    // ── Set ops ──────────────────────────────────────────────────────

    #[test]
    fn intersect_identity_with_all() {
        let s = classify_from_bools(&mk_bools(1000, &[1, 2, 3]));
        let all = AdaptiveSelection::all(1000);
        let r = s.intersect(&all);
        assert_eq!(r.count(), 3);
        assert!(r.contains(1) && r.contains(2) && r.contains(3));
    }

    #[test]
    fn intersect_with_empty_is_empty() {
        let s = classify_from_bools(&mk_bools(1000, &[1, 2, 3]));
        let empty = AdaptiveSelection::empty(1000);
        let r = s.intersect(&empty);
        assert_eq!(r.explain_selection_mode(), "Empty");
        assert_eq!(r.count(), 0);
    }

    #[test]
    fn union_with_all_is_all() {
        let s = classify_from_bools(&mk_bools(1000, &[1, 2, 3]));
        let all = AdaptiveSelection::all(1000);
        let r = s.union(&all);
        assert_eq!(r.explain_selection_mode(), "All");
        assert_eq!(r.count(), 1000);
    }

    #[test]
    fn intersect_mode_mixing_sparse_and_dense_gives_sparse_or_empty() {
        // sparse: a few hits in a 100k-row frame
        let sparse = classify_from_bools(&mk_bools(100_000, &[3, 17, 99, 5_000]));
        // dense: every other row in the same frame
        let dense_hits: Vec<usize> = (0..100_000).step_by(2).collect();
        let dense = classify_from_bools(&mk_bools(100_000, &dense_hits));
        // 50% over 100k → mid band → Hybrid (large frame).
        assert_eq!(dense.explain_selection_mode(), "VerbatimMask"); // 50% > 30% → dense
        assert_eq!(sparse.explain_selection_mode(), "SelectionVector");

        let r = sparse.intersect(&dense);
        // 3, 17, 99 are odd → don't survive even-only filter; 5_000 is even.
        assert_eq!(r.count(), 1);
        assert!(r.contains(5_000));
    }

    #[test]
    fn intersect_is_commutative_and_associative_for_three_inputs() {
        let a = classify_from_bools(&mk_bools(256, &[1, 5, 7, 99]));
        let b = classify_from_bools(&mk_bools(256, &[5, 99, 100, 200]));
        let c = classify_from_bools(&mk_bools(256, &[5, 50, 99, 250]));

        let ab_c = a.intersect(&b).intersect(&c);
        let bc_a = b.intersect(&c).intersect(&a);
        let ba_c = b.intersect(&a).intersect(&c);

        assert_eq!(ab_c.materialize_indices(), bc_a.materialize_indices());
        assert_eq!(ab_c.materialize_indices(), ba_c.materialize_indices());
    }

    // ── Density classifier edges ─────────────────────────────────────

    #[test]
    fn small_nrows_never_classifies_as_sparse() {
        // nrows=10, 1 hit. nrows/1024 = 0, count=1, 1 < 0 is false → not sparse.
        let s = classify_from_bools(&mk_bools(10, &[3]));
        assert_ne!(s.explain_selection_mode(), "SelectionVector");
    }

    #[test]
    fn dense_threshold_is_exclusive_30_percent() {
        // 1000 rows, exactly 300 hits (= 30%). 300*10 = 3000, 1000*3 = 3000,
        // strict > fails → mid band, not dense. Small frame → VerbatimMask.
        let hits: Vec<usize> = (0..300).collect();
        let s = classify_from_bools(&mk_bools(1000, &hits));
        assert_eq!(s.explain_selection_mode(), "VerbatimMask");
    }

    #[test]
    fn sparse_iter_uses_word_skipping() {
        // 1M rows, 5 hits scattered far apart. iter must succeed quickly and
        // return exactly the hits.
        let hits = vec![100_usize, 50_000, 200_000, 500_000, 999_000];
        let s = classify_from_bools(&mk_bools(1_000_000, &hits));
        assert_eq!(s.explain_selection_mode(), "SelectionVector");
        let collected: Vec<usize> = s.iter_indices().collect();
        assert_eq!(collected, hits);
    }

    // ── Hybrid arm coverage ──────────────────────────────────────────

    #[test]
    fn hybrid_iter_matches_bitmask_iter_under_bimodal_density() {
        // Bimodal: first half empty, second half mostly-set
        let mut hits: Vec<usize> = Vec::new();
        for i in 50_000..100_000 {
            if i % 2 == 0 {
                hits.push(i);
            }
        }
        let bools = mk_bools(100_000, &hits);
        let s = classify_from_bools(&bools);
        // 25k hits / 100k = 25% mid band → Hybrid.
        assert_eq!(s.explain_selection_mode(), "Hybrid");
        let collected: Vec<usize> = s.iter_indices().collect();
        assert_eq!(collected, hits);
        assert_eq!(s.count(), hits.len());
    }

    #[test]
    fn hybrid_contains_matches_bitmask() {
        let hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let s = classify_from_bools(&mk_bools(100_000, &hits));
        assert_eq!(s.explain_selection_mode(), "Hybrid");
        for h in &hits {
            assert!(s.contains(*h));
        }
        assert!(!s.contains(99_999));
        assert!(!s.contains(100_001));
    }

    #[test]
    fn hybrid_materialize_round_trip() {
        let hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let s = classify_from_bools(&mk_bools(100_000, &hits));
        assert_eq!(s.explain_selection_mode(), "Hybrid");
        let bm = s.materialize_mask();
        assert_eq!(bm.count_ones(), hits.len());
        let idx = s.materialize_indices();
        assert_eq!(idx.len(), hits.len());
        for h in &hits {
            assert!(bm.get(*h));
            assert!(idx.binary_search(&(*h as u32)).is_ok());
        }
    }

    #[test]
    fn hybrid_chunks_pick_local_modes() {
        // 8 chunks × 4096 rows = 32_768 rows. Layout chosen so global density
        // lands in the mid band (~16%) so the classifier picks Hybrid:
        //   Chunk 0: All           (4096 hits)
        //   Chunks 1, 4, 5, 6, 7:  Empty (0 hits)
        //   Chunk 2: Sparse        (5 hits)
        //   Chunk 3: Dense         (1024 hits, 25% of chunk — past per-chunk sparse threshold)
        let nrows = 8 * HYBRID_CHUNK_SIZE;
        let mut hits = Vec::new();
        for i in 0..HYBRID_CHUNK_SIZE {
            hits.push(i);
        }
        for k in 0..5 {
            hits.push(2 * HYBRID_CHUNK_SIZE + k * 100);
        }
        for off in (0..HYBRID_CHUNK_SIZE).step_by(4) {
            hits.push(3 * HYBRID_CHUNK_SIZE + off);
        }
        let s = classify_from_bools(&mk_bools(nrows, &hits));
        assert_eq!(s.explain_selection_mode(), "Hybrid");
        if let AdaptiveSelection::Hybrid { chunks, .. } = &s {
            assert_eq!(chunks.len(), 8);
            assert!(matches!(chunks[0], HybridChunk::All));
            assert!(matches!(chunks[1], HybridChunk::Empty));
            assert!(matches!(chunks[2], HybridChunk::Sparse(_)));
            assert!(matches!(chunks[3], HybridChunk::Dense(_)));
            assert!(matches!(chunks[7], HybridChunk::Empty));
        } else {
            panic!("expected Hybrid");
        }
    }

    // ── Merge-walk fast paths ────────────────────────────────────────

    #[test]
    fn sparse_intersect_sparse_uses_merge_walk() {
        let a = classify_from_bools(&mk_bools(100_000, &[1, 5, 17, 99, 5_000, 50_000]));
        let b = classify_from_bools(&mk_bools(100_000, &[5, 17, 200, 5_000, 99_000]));
        assert_eq!(a.explain_selection_mode(), "SelectionVector");
        assert_eq!(b.explain_selection_mode(), "SelectionVector");
        let r = a.intersect(&b);
        // {5, 17, 5000} survive
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, vec![5usize, 17, 5_000]);
    }

    #[test]
    fn sparse_union_sparse_uses_merge_walk() {
        let a = classify_from_bools(&mk_bools(100_000, &[1, 5, 17]));
        let b = classify_from_bools(&mk_bools(100_000, &[5, 99, 200]));
        let r = a.union(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, vec![1usize, 5, 17, 99, 200]);
    }

    #[test]
    fn intersect_cardinality_identity_holds_across_modes() {
        // |A| + |B| = |A ∪ B| + |A ∩ B|
        let a = classify_from_bools(&mk_bools(100_000, &[1, 5, 17, 99, 5_000, 50_000]));
        let b = classify_from_bools(&mk_bools(100_000, &[5, 17, 200, 5_000, 99_000]));
        let inter = a.intersect(&b);
        let union = a.union(&b);
        assert_eq!(a.count() + b.count(), inter.count() + union.count());
    }

    #[test]
    fn merge_walk_intersect_helper_is_correct() {
        let a = vec![1u32, 3, 5, 7, 9];
        let b = vec![2u32, 3, 5, 6, 9, 11];
        let out = sorted_merge_intersect(&a, &b);
        assert_eq!(out, vec![3, 5, 9]);
    }

    #[test]
    fn merge_walk_union_helper_is_correct() {
        let a = vec![1u32, 3, 5];
        let b = vec![2u32, 3, 7];
        let out = sorted_merge_union(&a, &b);
        assert_eq!(out, vec![1, 2, 3, 5, 7]);
    }

    // ── v3 Phase 3: Hybrid streaming set-op fast paths ───────────────

    /// Build a Hybrid selection from explicit hits, asserting Hybrid arm.
    fn hybrid_from_hits(nrows: usize, hits: &[usize]) -> AdaptiveSelection {
        let s = classify_from_bools(&mk_bools(nrows, hits));
        assert_eq!(
            s.explain_selection_mode(),
            "Hybrid",
            "expected Hybrid for {nrows} rows × {} hits",
            hits.len()
        );
        s
    }

    /// Brute-force oracle: materialize both sides and AND/OR via BitMask.
    fn oracle_intersect(a: &AdaptiveSelection, b: &AdaptiveSelection) -> Vec<usize> {
        let am = a.materialize_mask();
        let bm = b.materialize_mask();
        let n = am.nrows();
        let mut out = Vec::new();
        for i in 0..n {
            if am.get(i) && bm.get(i) {
                out.push(i);
            }
        }
        out
    }
    fn oracle_union(a: &AdaptiveSelection, b: &AdaptiveSelection) -> Vec<usize> {
        let am = a.materialize_mask();
        let bm = b.materialize_mask();
        let n = am.nrows();
        let mut out = Vec::new();
        for i in 0..n {
            if am.get(i) || bm.get(i) {
                out.push(i);
            }
        }
        out
    }

    #[test]
    fn phase3_hybrid_intersect_hybrid_matches_oracle() {
        // Two mid-band selections over a 100k-row frame at different phases.
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect(); // 5%
        let b_hits: Vec<usize> = (0..100_000).step_by(15).collect(); // ~6.67%
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = hybrid_from_hits(100_000, &b_hits);
        let r = a.intersect(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_intersect(&a, &b));
    }

    #[test]
    fn phase3_hybrid_union_hybrid_matches_oracle() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let b_hits: Vec<usize> = (0..100_000).step_by(15).collect();
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = hybrid_from_hits(100_000, &b_hits);
        let r = a.union(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_union(&a, &b));
    }

    #[test]
    fn phase3_hybrid_intersect_sparse_matches_oracle() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect(); // Hybrid (5%)
        let b_hits: Vec<usize> = vec![100, 5_000, 50_020, 99_980]; // SelectionVector
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = classify_from_bools(&mk_bools(100_000, &b_hits));
        assert_eq!(b.explain_selection_mode(), "SelectionVector");
        let r = a.intersect(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_intersect(&a, &b));
        // Symmetric
        let r2 = b.intersect(&a);
        let collected2: Vec<usize> = r2.iter_indices().collect();
        assert_eq!(collected2, oracle_intersect(&a, &b));
    }

    #[test]
    fn phase3_hybrid_union_sparse_matches_oracle() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let b_hits: Vec<usize> = vec![1, 50, 100, 5_000, 50_020, 99_999];
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = classify_from_bools(&mk_bools(100_000, &b_hits));
        assert_eq!(b.explain_selection_mode(), "SelectionVector");
        let r = a.union(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_union(&a, &b));
    }

    #[test]
    fn phase3_hybrid_intersect_verbatim_matches_oracle() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect(); // Hybrid
        let b_hits: Vec<usize> = (0..100_000).step_by(2).collect(); // 50% → VerbatimMask
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = classify_from_bools(&mk_bools(100_000, &b_hits));
        assert_eq!(b.explain_selection_mode(), "VerbatimMask");
        let r = a.intersect(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_intersect(&a, &b));
        // Symmetric
        let r2 = b.intersect(&a);
        assert_eq!(
            r2.iter_indices().collect::<Vec<usize>>(),
            oracle_intersect(&a, &b)
        );
    }

    #[test]
    fn phase3_hybrid_union_verbatim_matches_oracle() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let b_hits: Vec<usize> = (0..100_000).step_by(2).collect();
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = classify_from_bools(&mk_bools(100_000, &b_hits));
        let r = a.union(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_union(&a, &b));
    }

    #[test]
    fn phase3_hybrid_chain_intersect_three_way() {
        let a_hits: Vec<usize> = (0..100_000).step_by(20).collect();
        let b_hits: Vec<usize> = (0..100_000).step_by(15).collect();
        let c_hits: Vec<usize> = (0..100_000).step_by(12).collect();
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = hybrid_from_hits(100_000, &b_hits);
        let c = hybrid_from_hits(100_000, &c_hits);
        let abc = a.intersect(&b).intersect(&c);
        let cba = c.intersect(&b).intersect(&a);
        assert_eq!(abc.materialize_indices(), cba.materialize_indices());
        // Compare against scalar oracle.
        let am = a.materialize_mask();
        let bm = b.materialize_mask();
        let cm = c.materialize_mask();
        let oracle: Vec<usize> = (0..100_000)
            .filter(|&i| am.get(i) && bm.get(i) && cm.get(i))
            .collect();
        assert_eq!(abc.iter_indices().collect::<Vec<usize>>(), oracle);
    }

    #[test]
    fn phase3_per_chunk_intersect_sparse_sparse_uses_merge_walk() {
        // Two Hybrids whose corresponding chunks are both Sparse — verifies
        // the merge-walk path actually fires and produces correct sparse output.
        // Stride 200 over 100k = 500 hits; per-chunk count ≈ 4096/200 ≈ 20 (well
        // below 128 sparse threshold), so chunks are Sparse-shaped.
        let a_hits: Vec<usize> = (0..100_000).step_by(200).collect();
        let b_hits: Vec<usize> = (100..100_000).step_by(200).collect();
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = hybrid_from_hits(100_000, &b_hits);
        // Disjoint hits → intersection is empty.
        let r = a.intersect(&b);
        assert_eq!(r.count(), 0);
        assert_eq!(r.explain_selection_mode(), "Empty");
    }

    #[test]
    fn phase3_per_chunk_union_sparse_sparse_promotes_to_dense_when_large() {
        // Force per-chunk overflow past sparse threshold (128 hits/chunk):
        // stride 30 across 100k = ~3333 hits, per-chunk ≈ 4096/30 ≈ 136 → just
        // above sparse threshold per-chunk. Union with itself stays sparse-shaped
        // via merge-walk, but cross-streamed unions can promote.
        let a_hits: Vec<usize> = (0..100_000).step_by(30).collect();
        let b_hits: Vec<usize> = (15..100_000).step_by(30).collect();
        let a_count = a_hits.len();
        let b_count = b_hits.len();
        let a = hybrid_from_hits(100_000, &a_hits);
        let b = hybrid_from_hits(100_000, &b_hits);
        let r = a.union(&b);
        // Disjoint hits → union count = a_count + b_count.
        assert_eq!(r.count(), a_count + b_count);
        // Confirm content matches oracle.
        assert_eq!(
            r.iter_indices().collect::<Vec<usize>>(),
            oracle_union(&a, &b)
        );
    }

    #[test]
    fn phase3_simplify_hybrid_collapses_to_all_when_full() {
        // a + b cover every row → simplify_hybrid must collapse to All.
        let a_hits: Vec<usize> = (0..100_000).filter(|i| i % 2 == 0).collect();
        let b_hits: Vec<usize> = (0..100_000).filter(|i| i % 2 == 1).collect();
        // Each is 50% over 100k → VerbatimMask, not Hybrid. Build Hybrid by
        // forcing mid-band: take 6/10 of rows in each side so mid-band fires.
        let a_hits: Vec<usize> = (0..100_000).filter(|i| i % 5 != 0).collect(); // 80% — dense
        let b_hits: Vec<usize> = (0..100_000).step_by(5).collect(); // 20%
        let _ = (a_hits, b_hits); // unused — see next assertion-style test.
        // Instead: assert simplify_hybrid directly on a fully-set chunked arg.
        let nrows = 8 * HYBRID_CHUNK_SIZE;
        let chunks = vec![HybridChunk::All; 8];
        let s = AdaptiveSelection::simplify_hybrid(nrows, chunks);
        assert_eq!(s.explain_selection_mode(), "All");
        assert_eq!(s.count(), nrows);
    }

    #[test]
    fn phase3_simplify_hybrid_collapses_to_empty_when_drained() {
        let nrows = 8 * HYBRID_CHUNK_SIZE;
        let chunks = vec![HybridChunk::Empty; 8];
        let s = AdaptiveSelection::simplify_hybrid(nrows, chunks);
        assert_eq!(s.explain_selection_mode(), "Empty");
        assert_eq!(s.count(), 0);
    }

    #[test]
    fn phase3_per_chunk_helpers_handle_partial_final_chunk() {
        // 9000 rows = 2 full chunks + 1 partial (808 rows). Mid-band density.
        let nrows = 2 * HYBRID_CHUNK_SIZE + 808;
        let a_hits: Vec<usize> = (0..nrows).step_by(20).collect();
        let b_hits: Vec<usize> = (0..nrows).step_by(15).collect();
        let a = hybrid_from_hits(nrows, &a_hits);
        let b = hybrid_from_hits(nrows, &b_hits);
        let r = a.intersect(&b);
        let collected: Vec<usize> = r.iter_indices().collect();
        assert_eq!(collected, oracle_intersect(&a, &b));
        // No row should leak past nrows.
        for &row in &collected {
            assert!(row < nrows, "row {row} out of bounds");
        }
    }

    #[test]
    fn phase3_intersect_chunks_helper_dense_and_sparse() {
        // Direct unit test on intersect_chunks: Sparse vs Dense, pinning that
        // we get a sparse result with correct offsets.
        let chunk_len = HYBRID_CHUNK_SIZE;
        let sparse = HybridChunk::Sparse(vec![0u16, 5, 17, 100, 4000]);
        // Dense bitmap with bit 5, 17, 4000 set.
        let mut dense_words = vec![0u64; HYBRID_WORDS_PER_CHUNK];
        for off in [5usize, 17, 4000] {
            dense_words[off / 64] |= 1u64 << (off % 64);
        }
        let dense = HybridChunk::Dense(dense_words.into_boxed_slice());
        let r = intersect_chunks(&sparse, &dense, chunk_len);
        match r {
            HybridChunk::Sparse(offs) => assert_eq!(offs, vec![5, 17, 4000]),
            other => panic!("expected Sparse, got {other:?}"),
        }
    }

    #[test]
    fn phase3_union_chunks_helper_demotes_to_sparse_when_small() {
        // Sparse ∪ Sparse below threshold stays Sparse.
        let chunk_len = HYBRID_CHUNK_SIZE;
        let a = HybridChunk::Sparse(vec![1u16, 2, 3]);
        let b = HybridChunk::Sparse(vec![4u16, 5, 6]);
        let r = union_chunks(&a, &b, chunk_len);
        match r {
            HybridChunk::Sparse(offs) => assert_eq!(offs, vec![1, 2, 3, 4, 5, 6]),
            other => panic!("expected Sparse, got {other:?}"),
        }
    }

    #[test]
    fn phase3_union_chunks_helper_promotes_to_dense_above_threshold() {
        // Build two disjoint sparse chunks each with 70 hits (140 union >
        // 128 threshold) → output must be Dense.
        let chunk_len = HYBRID_CHUNK_SIZE;
        let a_offs: Vec<u16> = (0..70).map(|i| i * 2).collect();
        let b_offs: Vec<u16> = (0..70).map(|i| i * 2 + 1).collect();
        let a = HybridChunk::Sparse(a_offs);
        let b = HybridChunk::Sparse(b_offs);
        let r = union_chunks(&a, &b, chunk_len);
        match r {
            HybridChunk::Dense(words) => {
                let count: usize = words.iter().map(|w| w.count_ones() as usize).sum();
                assert_eq!(count, 140);
            }
            other => panic!("expected Dense (overflow), got {other:?}"),
        }
    }
}