hawdb-storage 0.13.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Node group artifact: id-ordered rows stored column-wise (§3.1, §3.5.2).
//!
//! File layout:
//!
//! ```text
//! SKNCOLG01 | id chunk | column chunks ... | directory
//!           | u64 directory length | u32 crc32c(directory) | SKNCOLG01
//! ```
//!
//! The directory is a fixed-layout offset table in the FlatBuffers style:
//! scalars at fixed offsets, the column-entry array addressed by an
//! (offset, stride, count) triple, and per-entry zone maps as fixed-size
//! records — a reader opens the checksummed footer and addresses any chunk
//! directly without materializing a parsed object graph. Columns are keyed
//! by interned `PropertyId` (§3.5.3(c)); key strings never appear in the
//! artifact.

use super::deletion::DeletionVector;
use super::encoding::{
    bits_for, decode_byte_chunk, decode_chunk, encode_byte_chunk, encode_chunk_auto, pack_values,
    unpack_values, ChunkEncoding, Cursor,
};
use super::zone::{ChunkZoneMap, ZONE_MAP_RECORD_BYTES};
#[cfg(test)]
use super::DeletionVectorBinding;
use super::{corrupt, unsupported, ColumnGroupError, COLUMN_GROUP_MAGIC};
use crate::cache::ManifestGeneration;
use crate::durability::durable_replace_file;
use crate::file_io::{self as fs, File};
use crate::io::read_exact_at;
use crate::scan::RangeBound;
use hawdb_core::{PropertyId, Value};
use hawdb_integrity::crc32c;
use std::io::Write;
use std::path::Path;

/// Default fixed row capacity of one node group (§2: node group).
pub const DEFAULT_GROUP_ROW_CAPACITY: u32 = 65_536;
/// Encoding id of the delta-encoded, bit-packed id column.
pub const ID_CHUNK_ENCODING: u8 = 8;

const DIRECTORY_VERSION: u32 = 1;
const DIRECTORY_HEADER_BYTES: usize = 88;
const COLUMN_ENTRY_STRIDE: usize = 32 + ZONE_MAP_RECORD_BYTES;
const FOOTER_BYTES: usize = 8 + 4 + COLUMN_GROUP_MAGIC.len();
const HEADER_BYTES: u64 = COLUMN_GROUP_MAGIC.len() as u64;
const MAX_GROUP_DIRECTORY_BYTES: u64 = 16 * 1024 * 1024;

/// Configuration of the group writer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ColumnGroupConfig {
    /// Maximum rows in one group.
    pub row_capacity: u32,
    /// Whether chunk bodies may be zstd-compressed.
    pub compress: bool,
}

impl Default for ColumnGroupConfig {
    fn default() -> Self {
        Self {
            row_capacity: DEFAULT_GROUP_ROW_CAPACITY,
            compress: true,
        }
    }
}

/// Extent and integrity facts of the id column chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IdChunkDescriptor {
    pub offset: u64,
    pub length: u64,
    pub crc32c: u32,
}

/// Directory entry of one column chunk, addressable independently of its
/// siblings (§3.1.2).
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnChunkDescriptor {
    pub property_id: PropertyId,
    pub encoding: ChunkEncoding,
    pub compressed: bool,
    pub offset: u64,
    pub length: u64,
    pub crc32c: u32,
    pub zone_map: ChunkZoneMap,
}

/// The decoded group directory: every fact needed to plan and execute reads
/// without touching chunk bytes (§3.5.3(b)).
#[derive(Debug, Clone, PartialEq)]
pub struct ColumnGroupDirectory {
    pub group_id: u64,
    pub generation: ManifestGeneration,
    pub row_capacity: u32,
    pub row_count: u32,
    pub min_id: u64,
    pub max_id: u64,
    pub id_chunk: IdChunkDescriptor,
    /// Sorted by ascending property id.
    pub columns: Vec<ColumnChunkDescriptor>,
}

impl ColumnGroupDirectory {
    /// The directory entry for a property, if the group stores it.
    pub fn column(&self, property_id: PropertyId) -> Option<&ColumnChunkDescriptor> {
        self.columns
            .binary_search_by_key(&property_id.0, |column| column.property_id.0)
            .ok()
            .map(|index| &self.columns[index])
    }

    fn encode(&self) -> Result<Vec<u8>, ColumnGroupError> {
        let mut bytes =
            Vec::with_capacity(DIRECTORY_HEADER_BYTES + self.columns.len() * COLUMN_ENTRY_STRIDE);
        bytes.extend(DIRECTORY_VERSION.to_le_bytes());
        bytes.extend(self.row_capacity.to_le_bytes());
        bytes.extend(self.group_id.to_le_bytes());
        bytes.extend(self.generation.0.to_le_bytes());
        bytes.extend(self.row_count.to_le_bytes());
        let column_count = u32::try_from(self.columns.len())
            .map_err(|_| unsupported("group column count exceeds u32".to_string()))?;
        bytes.extend(column_count.to_le_bytes());
        bytes.extend(self.min_id.to_le_bytes());
        bytes.extend(self.max_id.to_le_bytes());
        bytes.extend(self.id_chunk.offset.to_le_bytes());
        bytes.extend(self.id_chunk.length.to_le_bytes());
        bytes.extend(self.id_chunk.crc32c.to_le_bytes());
        bytes.push(ID_CHUNK_ENCODING);
        bytes.push(0);
        bytes.extend(0u16.to_le_bytes());
        bytes.extend((DIRECTORY_HEADER_BYTES as u64).to_le_bytes());
        bytes.extend((COLUMN_ENTRY_STRIDE as u32).to_le_bytes());
        bytes.extend(0u32.to_le_bytes());
        debug_assert_eq!(bytes.len(), DIRECTORY_HEADER_BYTES);
        for column in &self.columns {
            bytes.extend(column.property_id.0.to_le_bytes());
            bytes.push(column.encoding.id());
            bytes.push(u8::from(column.compressed));
            bytes.extend(0u16.to_le_bytes());
            bytes.extend(column.offset.to_le_bytes());
            bytes.extend(column.length.to_le_bytes());
            bytes.extend(column.crc32c.to_le_bytes());
            bytes.extend(0u32.to_le_bytes());
            bytes.extend(column.zone_map.encode()?);
        }
        Ok(bytes)
    }

    fn decode(bytes: &[u8], data_end: u64) -> Result<Self, ColumnGroupError> {
        let mut cursor = Cursor::new(bytes);
        let version = cursor.read_u32("group directory version")?;
        if version != DIRECTORY_VERSION {
            return Err(corrupt(format!(
                "unsupported group directory version {version}"
            )));
        }
        let row_capacity = cursor.read_u32("group row capacity")?;
        let group_id = cursor.read_u64("group id")?;
        let generation = ManifestGeneration(cursor.read_u64("group generation")?);
        let row_count = cursor.read_u32("group row count")?;
        let column_count = cursor.read_u32("group column count")?;
        let min_id = cursor.read_u64("group min record id")?;
        let max_id = cursor.read_u64("group max record id")?;
        if row_capacity == 0 || row_count > row_capacity {
            return Err(corrupt(format!(
                "group row count {row_count} exceeds its capacity {row_capacity}"
            )));
        }
        if row_count > 0 && min_id > max_id {
            return Err(corrupt("group record id bounds are inverted".to_string()));
        }
        let id_chunk = IdChunkDescriptor {
            offset: cursor.read_u64("id chunk offset")?,
            length: cursor.read_u64("id chunk length")?,
            crc32c: cursor.read_u32("id chunk checksum")?,
        };
        validate_extent(id_chunk.offset, id_chunk.length, data_end, "id chunk")?;
        let id_encoding = cursor.read_u8("id chunk encoding")?;
        if id_encoding != ID_CHUNK_ENCODING {
            return Err(corrupt(format!("unknown id chunk encoding {id_encoding}")));
        }
        let id_flags = cursor.read_u8("id chunk flags")?;
        if id_flags != 0 {
            return Err(corrupt("id chunk flags are invalid".to_string()));
        }
        cursor.read_bytes(2, "id chunk reserved bytes")?;
        let entries_offset = cursor.read_u64("column entry array offset")?;
        let entry_stride = cursor.read_u32("column entry stride")?;
        cursor.read_bytes(4, "directory reserved bytes")?;
        if entries_offset != DIRECTORY_HEADER_BYTES as u64
            || entry_stride != COLUMN_ENTRY_STRIDE as u32
        {
            return Err(corrupt(
                "group directory column array layout is invalid".to_string(),
            ));
        }
        let expected_len = DIRECTORY_HEADER_BYTES
            .checked_add(
                (column_count as usize)
                    .checked_mul(COLUMN_ENTRY_STRIDE)
                    .ok_or_else(|| corrupt("group column count overflows".to_string()))?,
            )
            .ok_or_else(|| corrupt("group column count overflows".to_string()))?;
        if bytes.len() != expected_len {
            return Err(corrupt(format!(
                "group directory holds {} bytes but {column_count} columns need {expected_len}",
                bytes.len()
            )));
        }
        let mut columns = Vec::with_capacity(column_count as usize);
        let mut previous_property: Option<u32> = None;
        for _ in 0..column_count {
            let property_id = cursor.read_u32("column property id")?;
            if previous_property.is_some_and(|previous| previous >= property_id) {
                return Err(corrupt(
                    "group directory columns are not sorted by property id".to_string(),
                ));
            }
            previous_property = Some(property_id);
            let encoding = ChunkEncoding::from_id(cursor.read_u8("column encoding id")?)?;
            let flags = cursor.read_u8("column flags")?;
            if flags > 1 {
                return Err(corrupt(format!("column flags {flags} are invalid")));
            }
            cursor.read_bytes(2, "column reserved bytes")?;
            let offset = cursor.read_u64("column chunk offset")?;
            let length = cursor.read_u64("column chunk length")?;
            let checksum = cursor.read_u32("column chunk checksum")?;
            cursor.read_bytes(4, "column reserved bytes")?;
            validate_extent(offset, length, data_end, "column chunk")?;
            let zone_map = ChunkZoneMap::decode(&mut cursor)?;
            if zone_map.row_count() != u64::from(row_count) {
                return Err(corrupt(format!(
                    "column zone map covers {} rows in a {row_count} row group",
                    zone_map.row_count()
                )));
            }
            columns.push(ColumnChunkDescriptor {
                property_id: PropertyId(property_id),
                encoding,
                compressed: flags == 1,
                offset,
                length,
                crc32c: checksum,
                zone_map,
            });
        }
        cursor.expect_exhausted("group directory")?;
        Ok(Self {
            group_id,
            generation,
            row_capacity,
            row_count,
            min_id,
            max_id,
            id_chunk,
            columns,
        })
    }
}

fn validate_extent(
    offset: u64,
    length: u64,
    data_end: u64,
    what: &str,
) -> Result<(), ColumnGroupError> {
    let end = offset
        .checked_add(length)
        .ok_or_else(|| corrupt(format!("{what} extent overflows")))?;
    if offset < HEADER_BYTES || end > data_end {
        return Err(corrupt(format!(
            "{what} extent [{offset}, {end}) is outside the data region \
             [{HEADER_BYTES}, {data_end})"
        )));
    }
    Ok(())
}

// --- id column codec --------------------------------------------------------

fn encode_ids(ids: &[u64]) -> Vec<u8> {
    let mut bytes = Vec::new();
    bytes.extend((ids.len() as u32).to_le_bytes());
    let Some(first) = ids.first() else {
        return bytes;
    };
    let deltas = ids
        .windows(2)
        .map(|window| window[1] - window[0])
        .collect::<Vec<_>>();
    let width = bits_for(deltas.iter().copied().max().unwrap_or(0));
    bytes.extend(first.to_le_bytes());
    bytes.push(width);
    bytes.extend(pack_values(&deltas, width));
    bytes
}

fn decode_ids(bytes: &[u8], expected_rows: u32) -> Result<Vec<u64>, ColumnGroupError> {
    let mut cursor = Cursor::new(bytes);
    let count = cursor.read_u32("id chunk row count")?;
    if count != expected_rows {
        return Err(corrupt(format!(
            "id chunk holds {count} rows but the directory declares {expected_rows}"
        )));
    }
    if count == 0 {
        cursor.expect_exhausted("id chunk")?;
        return Ok(Vec::new());
    }
    let first = cursor.read_u64("first record id")?;
    let width = cursor.read_u8("id delta width")?;
    let deltas = unpack_values(&mut cursor, width, count as usize - 1, "id deltas")?;
    let mut ids = Vec::with_capacity(count as usize);
    ids.push(first);
    let mut current = first;
    for delta in deltas {
        if delta == 0 {
            return Err(corrupt(
                "record ids are not strictly increasing".to_string(),
            ));
        }
        current = current
            .checked_add(delta)
            .ok_or_else(|| corrupt("record id delta overflows the u64 id space".to_string()))?;
        ids.push(current);
    }
    cursor.expect_exhausted("id chunk")?;
    Ok(ids)
}

// --- writer -----------------------------------------------------------------

/// Writes node groups with the temp-file, fsync, rename publish protocol.
#[derive(Debug, Clone, Copy, Default)]
pub struct ColumnGroupWriter {
    config: ColumnGroupConfig,
}

impl ColumnGroupWriter {
    pub fn new(config: ColumnGroupConfig) -> Self {
        Self { config }
    }

    /// Writes one group: `ids` are the strictly increasing record ids and
    /// each column supplies one `Value` per row (`Value::Null` = absent).
    pub fn write(
        &self,
        path: &Path,
        group_id: u64,
        generation: ManifestGeneration,
        ids: &[u64],
        columns: &[(PropertyId, Vec<Value>)],
    ) -> Result<ColumnGroupDirectory, ColumnGroupError> {
        self.write_with_byte_columns(path, group_id, generation, ids, columns, &[])
    }

    /// Writes one group carrying both `Value` columns and byte-table blob
    /// columns (`None` = absent). Blob columns share the directory, footer,
    /// and validity machinery; their zone maps record only presence counts
    /// and the nested-content marker, so no value predicate ever opens them.
    pub fn write_with_byte_columns(
        &self,
        path: &Path,
        group_id: u64,
        generation: ManifestGeneration,
        ids: &[u64],
        columns: &[(PropertyId, Vec<Value>)],
        byte_columns: &[(PropertyId, Vec<Option<Vec<u8>>>)],
    ) -> Result<ColumnGroupDirectory, ColumnGroupError> {
        self.validate(ids, columns, byte_columns)?;
        let tmp_path = path.with_extension("hawdb.tmp");
        let result = self.write_inner(&tmp_path, group_id, generation, ids, columns, byte_columns);
        let directory = match result {
            Ok(directory) => directory,
            Err(error) => {
                let _ = fs::remove_file(&tmp_path);
                return Err(error);
            }
        };
        durable_replace_file(&tmp_path, path)?;
        Ok(directory)
    }

    fn validate(
        &self,
        ids: &[u64],
        columns: &[(PropertyId, Vec<Value>)],
        byte_columns: &[(PropertyId, Vec<Option<Vec<u8>>>)],
    ) -> Result<(), ColumnGroupError> {
        if ids.len() > self.config.row_capacity as usize {
            return Err(unsupported(format!(
                "group holds {} rows, exceeding its {} row capacity",
                ids.len(),
                self.config.row_capacity
            )));
        }
        if ids.windows(2).any(|window| window[0] >= window[1]) {
            return Err(unsupported(
                "group record ids must be strictly increasing".to_string(),
            ));
        }
        let mut seen = std::collections::BTreeSet::new();
        let lengths = columns
            .iter()
            .map(|(property_id, values)| (*property_id, values.len()))
            .chain(
                byte_columns
                    .iter()
                    .map(|(property_id, rows)| (*property_id, rows.len())),
            );
        for (property_id, length) in lengths {
            if !seen.insert(property_id.0) {
                return Err(unsupported(format!(
                    "group declares property {} twice",
                    property_id.0
                )));
            }
            if length != ids.len() {
                return Err(unsupported(format!(
                    "column {} holds {} values for {} rows",
                    property_id.0,
                    length,
                    ids.len()
                )));
            }
        }
        Ok(())
    }

    fn write_inner(
        &self,
        path: &Path,
        group_id: u64,
        generation: ManifestGeneration,
        ids: &[u64],
        columns: &[(PropertyId, Vec<Value>)],
        byte_columns: &[(PropertyId, Vec<Option<Vec<u8>>>)],
    ) -> Result<ColumnGroupDirectory, ColumnGroupError> {
        enum ColumnPayload<'a> {
            Values(&'a Vec<Value>),
            Bytes(&'a Vec<Option<Vec<u8>>>),
        }

        let mut file = File::create(path)?;
        let mut offset = 0u64;
        file.write_all(COLUMN_GROUP_MAGIC)?;
        offset += HEADER_BYTES;

        let id_bytes = encode_ids(ids);
        let id_chunk = IdChunkDescriptor {
            offset,
            length: id_bytes.len() as u64,
            crc32c: crc32c(&id_bytes).get(),
        };
        file.write_all(&id_bytes)?;
        offset += id_bytes.len() as u64;

        let mut sorted = columns
            .iter()
            .map(|(property_id, values)| (*property_id, ColumnPayload::Values(values)))
            .chain(
                byte_columns
                    .iter()
                    .map(|(property_id, rows)| (*property_id, ColumnPayload::Bytes(rows))),
            )
            .collect::<Vec<_>>();
        sorted.sort_by_key(|(property_id, _)| property_id.0);
        let mut descriptors = Vec::with_capacity(sorted.len());
        for (property_id, payload) in sorted {
            let (chunk, zone_map) = match payload {
                ColumnPayload::Values(values) => (
                    encode_chunk_auto(values, self.config.compress)?,
                    ChunkZoneMap::build(values),
                ),
                ColumnPayload::Bytes(rows) => {
                    // Presence-only zone map: blobs are opaque, so their
                    // statistics carry the nested-content marker and no
                    // scalar bounds, keeping pruning trivially sound.
                    let presence = rows
                        .iter()
                        .map(|row| match row {
                            Some(_) => Value::List(Vec::new()),
                            None => Value::Null,
                        })
                        .collect::<Vec<_>>();
                    (
                        encode_byte_chunk(rows, self.config.compress)?,
                        ChunkZoneMap::build(&presence),
                    )
                }
            };
            let descriptor = ColumnChunkDescriptor {
                property_id,
                encoding: chunk.encoding,
                compressed: chunk.compressed,
                offset,
                length: chunk.bytes.len() as u64,
                crc32c: crc32c(&chunk.bytes).get(),
                zone_map,
            };
            file.write_all(&chunk.bytes)?;
            offset += chunk.bytes.len() as u64;
            descriptors.push(descriptor);
        }

        let directory = ColumnGroupDirectory {
            group_id,
            generation,
            row_capacity: self.config.row_capacity,
            row_count: ids.len() as u32,
            min_id: ids.first().copied().unwrap_or(0),
            max_id: ids.last().copied().unwrap_or(0),
            id_chunk,
            columns: descriptors,
        };
        let directory_bytes = directory.encode()?;
        if directory_bytes.len() as u64 > MAX_GROUP_DIRECTORY_BYTES {
            return Err(unsupported(format!(
                "group directory holds {} bytes, exceeding {MAX_GROUP_DIRECTORY_BYTES}",
                directory_bytes.len()
            )));
        }
        file.write_all(&directory_bytes)?;
        file.write_all(&(directory_bytes.len() as u64).to_le_bytes())?;
        file.write_all(&crc32c(&directory_bytes).get().to_le_bytes())?;
        file.write_all(COLUMN_GROUP_MAGIC)?;
        file.sync_all()?;
        Ok(directory)
    }
}

// --- streaming single-row writer --------------------------------------------

/// A blob streamed into a byte-table chunk without materializing its bytes
/// in memory: the source declares its exact encoded length, then writes
/// itself through an incremental-CRC sink.
pub trait StreamedBlob {
    /// Exact byte length `write_blob` will produce.
    fn blob_len(&self) -> u64;
    fn write_blob(&self, out: &mut dyn Write) -> std::io::Result<()>;
}

impl StreamedBlob for &[u8] {
    fn blob_len(&self) -> u64 {
        self.len() as u64
    }

    fn write_blob(&self, out: &mut dyn Write) -> std::io::Result<()> {
        out.write_all(self)
    }
}

/// File sink that tracks the running offset and a per-chunk incremental
/// CRC32C, so streamed chunk bodies never coexist with a buffered copy.
struct StreamingChunkSink<'a> {
    file: &'a mut File,
    offset: u64,
    hasher: hawdb_integrity::Crc32cHasher,
}

impl<'a> StreamingChunkSink<'a> {
    fn new(file: &'a mut File, offset: u64) -> Self {
        Self {
            file,
            offset,
            hasher: hawdb_integrity::Crc32cHasher::new(),
        }
    }

    fn begin_chunk(&mut self) {
        self.hasher = hawdb_integrity::Crc32cHasher::new();
    }

    fn chunk_crc32c(&self) -> u32 {
        // `Crc32cHasher` accumulates with crc32c_append from zero, which is
        // exactly what the whole-buffer `crc32c` the readers verify against
        // computes.
        self.hasher.finish_u32()
    }
}

impl Write for StreamingChunkSink<'_> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.file.write_all(bytes)?;
        self.hasher.update(bytes);
        self.offset += bytes.len() as u64;
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.file.flush()
    }
}

/// Shared chunk-body prelude for one present row: `row_count = 1`,
/// `value_count = 1`, validity bit set.
const SINGLE_ROW_PRELUDE: [u8; 9] = [1, 0, 0, 0, 1, 0, 0, 0, 0x01];

impl ColumnGroupWriter {
    /// Streams one single-row group to disk. Value columns hold the row's
    /// non-null scalar cells (strings stream their borrowed bytes; nested
    /// values belong in blob columns); blob columns stream through
    /// [`StreamedBlob`]. Every chunk body flows through an incremental-CRC
    /// sink, so the transient memory is O(io block), never O(value) — the
    /// convergence path for rows larger than any buffering budget.
    pub fn write_single_row_streaming(
        &self,
        path: &Path,
        group_id: u64,
        generation: ManifestGeneration,
        id: u64,
        value_columns: &[(PropertyId, &Value)],
        byte_columns: &[(PropertyId, &dyn StreamedBlob)],
    ) -> Result<ColumnGroupDirectory, ColumnGroupError> {
        let mut seen = std::collections::BTreeSet::new();
        for property_id in value_columns
            .iter()
            .map(|(property_id, _)| *property_id)
            .chain(byte_columns.iter().map(|(property_id, _)| *property_id))
        {
            if !seen.insert(property_id.0) {
                return Err(unsupported(format!(
                    "group declares property {} twice",
                    property_id.0
                )));
            }
        }
        for (property_id, value) in value_columns {
            if matches!(value, Value::Null | Value::List(_) | Value::Map(_)) {
                return Err(unsupported(format!(
                    "streamed single-row value column {} must hold a scalar",
                    property_id.0
                )));
            }
        }
        let tmp_path = path.with_extension("hawdb.tmp");
        let result = self.write_single_row_inner(
            &tmp_path,
            group_id,
            generation,
            id,
            value_columns,
            byte_columns,
        );
        let directory = match result {
            Ok(directory) => directory,
            Err(error) => {
                let _ = fs::remove_file(&tmp_path);
                return Err(error);
            }
        };
        durable_replace_file(&tmp_path, path)?;
        Ok(directory)
    }

    fn write_single_row_inner(
        &self,
        path: &Path,
        group_id: u64,
        generation: ManifestGeneration,
        id: u64,
        value_columns: &[(PropertyId, &Value)],
        byte_columns: &[(PropertyId, &dyn StreamedBlob)],
    ) -> Result<ColumnGroupDirectory, ColumnGroupError> {
        enum StreamedColumn<'a> {
            Value(&'a Value),
            Blob(&'a dyn StreamedBlob),
        }

        let mut file = File::create(path)?;
        file.write_all(COLUMN_GROUP_MAGIC)?;
        let mut offset = HEADER_BYTES;

        let id_bytes = encode_ids(&[id]);
        let id_chunk = IdChunkDescriptor {
            offset,
            length: id_bytes.len() as u64,
            crc32c: crc32c(&id_bytes).get(),
        };
        file.write_all(&id_bytes)?;
        offset += id_bytes.len() as u64;

        let mut sorted = value_columns
            .iter()
            .map(|(property_id, value)| (*property_id, StreamedColumn::Value(value)))
            .chain(
                byte_columns
                    .iter()
                    .map(|(property_id, blob)| (*property_id, StreamedColumn::Blob(*blob))),
            )
            .collect::<Vec<_>>();
        sorted.sort_by_key(|(property_id, _)| property_id.0);

        let mut descriptors = Vec::with_capacity(sorted.len());
        let mut sink = StreamingChunkSink::new(&mut file, offset);
        for (property_id, column) in sorted {
            let chunk_offset = sink.offset;
            sink.begin_chunk();
            let (encoding, zone_map) = match column {
                StreamedColumn::Value(value) => {
                    let encoding = match value {
                        Value::Int(_) => ChunkEncoding::PlainInt,
                        Value::Float(_) => ChunkEncoding::PlainFloat,
                        Value::Bool(_) => ChunkEncoding::BoolBitmap,
                        Value::String(_) => ChunkEncoding::StringTable,
                        Value::Binary(_) => ChunkEncoding::ByteTable,
                        Value::Uuid(_) | Value::Vector(_) => {
                            return Err(unsupported(
                                "streaming single-row column groups do not support UUID or vector values"
                                    .to_string(),
                            ));
                        }
                        Value::Null | Value::List(_) | Value::Map(_) => {
                            unreachable!("validated scalar cells")
                        }
                    };
                    sink.write_all(&SINGLE_ROW_PRELUDE)?;
                    match value {
                        Value::Int(value) => sink.write_all(&value.to_le_bytes())?,
                        Value::Float(value) => sink.write_all(&value.to_bits().to_le_bytes())?,
                        Value::Bool(value) => sink.write_all(&[u8::from(*value)])?,
                        Value::String(value) => {
                            let length = u32::try_from(value.len()).map_err(|_| {
                                unsupported("string table chunk exceeds u32 bytes".to_string())
                            })?;
                            sink.write_all(&0u32.to_le_bytes())?;
                            sink.write_all(&length.to_le_bytes())?;
                            // The borrowed string bytes stream straight to
                            // the file: no value-sized buffer exists.
                            sink.write_all(value.as_bytes())?;
                        }
                        Value::Binary(value) => {
                            let length = u32::try_from(value.len()).map_err(|_| {
                                unsupported("byte table chunk exceeds u32 bytes".to_string())
                            })?;
                            sink.write_all(&0u32.to_le_bytes())?;
                            sink.write_all(&length.to_le_bytes())?;
                            sink.write_all(value)?;
                        }
                        Value::Uuid(_) | Value::Vector(_) => {
                            unreachable!("unsupported values were rejected above")
                        }
                        Value::Null | Value::List(_) | Value::Map(_) => {
                            unreachable!("validated scalar cells")
                        }
                    }
                    (encoding, ChunkZoneMap::build(std::slice::from_ref(value)))
                }
                StreamedColumn::Blob(blob) => {
                    let length = u32::try_from(blob.blob_len()).map_err(|_| {
                        unsupported("byte table chunk exceeds u32 bytes".to_string())
                    })?;
                    sink.write_all(&SINGLE_ROW_PRELUDE)?;
                    sink.write_all(&0u32.to_le_bytes())?;
                    sink.write_all(&length.to_le_bytes())?;
                    let before = sink.offset;
                    blob.write_blob(&mut sink)?;
                    if sink.offset - before != u64::from(length) {
                        return Err(unsupported(format!(
                            "streamed blob for column {} wrote {} bytes but declared {length}",
                            property_id.0,
                            sink.offset - before
                        )));
                    }
                    // Presence-only zone map, exactly like buffered byte
                    // columns: opaque content, no scalar bounds.
                    (
                        ChunkEncoding::ByteTable,
                        ChunkZoneMap::build(&[Value::List(Vec::new())]),
                    )
                }
            };
            descriptors.push(ColumnChunkDescriptor {
                property_id,
                encoding,
                compressed: false,
                offset: chunk_offset,
                length: sink.offset - chunk_offset,
                crc32c: sink.chunk_crc32c(),
                zone_map,
            });
        }
        let data_end = sink.offset;

        let directory = ColumnGroupDirectory {
            group_id,
            generation,
            row_capacity: self.config.row_capacity,
            row_count: 1,
            min_id: id,
            max_id: id,
            id_chunk,
            columns: descriptors,
        };
        let directory_bytes = directory.encode()?;
        if directory_bytes.len() as u64 > MAX_GROUP_DIRECTORY_BYTES {
            return Err(unsupported(format!(
                "group directory holds {} bytes, exceeding {MAX_GROUP_DIRECTORY_BYTES}",
                directory_bytes.len()
            )));
        }
        let _ = data_end;
        file.write_all(&directory_bytes)?;
        file.write_all(&(directory_bytes.len() as u64).to_le_bytes())?;
        file.write_all(&crc32c(&directory_bytes).get().to_le_bytes())?;
        file.write_all(COLUMN_GROUP_MAGIC)?;
        file.sync_all()?;
        Ok(directory)
    }
}

// --- scan surface -----------------------------------------------------------

/// A single-column predicate over a node group, keyed by `PropertyId`.
///
/// Value-match semantics (the contract the pruning soundness obligation is
/// stated against; null values never match any predicate):
///
/// - `Equals`: the stored value equals the predicate value under the
///   `Value` total order (so types must match; float comparison is
///   `total_cmp`, hence `NaN == NaN` and `-0.0 != 0.0`).
/// - `Range` with an `Int` or finite `Float` bound: matches `Int`/`Float`
///   values by numeric comparison.
/// - `Range` with a `String` bound that parses as RFC 3339: matches only
///   string values that also parse, compared as epoch milliseconds
///   (mirrors `SegmentPruner::range_disjoint_datetime`).
/// - `Range` with any other `String` bound: matches string values by byte
///   order.
/// - `Range` with a `Bool` bound: matches bool values (`false < true`).
/// - `Range` with a null, non-finite, or nested bound never prunes.
#[derive(Debug, Clone, PartialEq)]
pub enum ColumnPredicate {
    Equals {
        property_id: PropertyId,
        value: Value,
    },
    Range {
        property_id: PropertyId,
        lower: Option<RangeBound>,
        upper: Option<RangeBound>,
    },
}

impl ColumnPredicate {
    pub fn property_id(&self) -> PropertyId {
        match self {
            Self::Equals { property_id, .. } | Self::Range { property_id, .. } => *property_id,
        }
    }
}

/// Why a group or chunk was skipped without reading chunk bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnGroupPruneReason {
    /// The group holds no rows.
    EmptyGroup,
    /// The group stores no chunk for the predicate's property.
    PropertyAbsent,
    /// The chunk stores only nulls, which no predicate matches.
    AllNull,
    /// The chunk's zone map proves no stored value can qualify.
    ZoneMapExcluded,
}

/// Directory-only pruning verdict for one predicate (§3.2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColumnGroupPruneDecision {
    /// No row of the whole group can match.
    SkipGroup(ColumnGroupPruneReason),
    /// The predicate's chunk cannot contain a qualifying row; the scan may
    /// skip decoding it while still opening sibling chunks.
    SkipChunk(ColumnGroupPruneReason),
    /// The chunk may contain qualifying rows and must be read.
    Open,
}

impl ColumnGroupPruneDecision {
    pub fn should_open(&self) -> bool {
        matches!(self, Self::Open)
    }
}

// --- byte source ------------------------------------------------------------

/// Byte-range access to a group artifact. The indirection exists so tests
/// can observe exactly which extents a read touches (§3.2.3).
pub trait ColumnGroupByteSource {
    fn byte_len(&self) -> Result<u64, ColumnGroupError>;
    fn read_at(&self, offset: u64, length: u64) -> Result<Vec<u8>, ColumnGroupError>;
}

/// File-backed byte source using positioned reads.
#[derive(Debug)]
pub struct FileByteSource {
    file: File,
}

impl FileByteSource {
    pub fn open(path: &Path) -> Result<Self, ColumnGroupError> {
        Ok(Self {
            file: File::open(path)?,
        })
    }
}

impl ColumnGroupByteSource for FileByteSource {
    fn byte_len(&self) -> Result<u64, ColumnGroupError> {
        Ok(self.file.metadata()?.len())
    }

    fn read_at(&self, offset: u64, length: u64) -> Result<Vec<u8>, ColumnGroupError> {
        let length = usize::try_from(length)
            .map_err(|_| corrupt(format!("read of {length} bytes is not addressable")))?;
        let mut buffer = vec![0u8; length];
        read_exact_at(&self.file, &mut buffer, offset)?;
        Ok(buffer)
    }
}

// --- reader -----------------------------------------------------------------

/// Opens a group by validating the checksummed footer, then serves chunk
/// reads that touch only the requested extents.
#[derive(Debug)]
pub struct ColumnGroupReader<S: ColumnGroupByteSource> {
    source: S,
    directory: ColumnGroupDirectory,
}

impl ColumnGroupReader<FileByteSource> {
    pub fn open_path(path: &Path) -> Result<Self, ColumnGroupError> {
        Self::open(FileByteSource::open(path)?)
    }
}

impl<S: ColumnGroupByteSource> ColumnGroupReader<S> {
    pub fn open(source: S) -> Result<Self, ColumnGroupError> {
        let len = source.byte_len()?;
        let minimum = HEADER_BYTES + FOOTER_BYTES as u64;
        if len < minimum {
            return Err(corrupt(format!(
                "group artifact holds {len} bytes, below the {minimum} byte minimum"
            )));
        }
        let header = source.read_at(0, HEADER_BYTES)?;
        if header != COLUMN_GROUP_MAGIC {
            return Err(corrupt(
                "group artifact header magic is invalid".to_string(),
            ));
        }
        let footer = source.read_at(len - FOOTER_BYTES as u64, FOOTER_BYTES as u64)?;
        if &footer[12..] != COLUMN_GROUP_MAGIC {
            return Err(corrupt(
                "group artifact footer magic is invalid".to_string(),
            ));
        }
        let directory_len = u64::from_le_bytes(footer[..8].try_into().expect("8B"));
        if directory_len > MAX_GROUP_DIRECTORY_BYTES {
            return Err(corrupt(format!(
                "group directory length {directory_len} exceeds {MAX_GROUP_DIRECTORY_BYTES}"
            )));
        }
        let stored_crc = u32::from_le_bytes(footer[8..12].try_into().expect("4B"));
        let directory_end = len - FOOTER_BYTES as u64;
        let directory_start = directory_end
            .checked_sub(directory_len)
            .filter(|start| *start >= HEADER_BYTES)
            .ok_or_else(|| {
                corrupt(format!(
                    "group directory length {directory_len} exceeds the artifact"
                ))
            })?;
        let directory_bytes = source.read_at(directory_start, directory_len)?;
        if crc32c(&directory_bytes).get() != stored_crc {
            return Err(corrupt(
                "group directory checksum does not match its contents".to_string(),
            ));
        }
        let directory = ColumnGroupDirectory::decode(&directory_bytes, directory_start)?;
        Ok(Self { source, directory })
    }

    pub fn directory(&self) -> &ColumnGroupDirectory {
        &self.directory
    }

    pub fn row_count(&self) -> u32 {
        self.directory.row_count
    }

    /// Decodes the id column.
    pub fn read_ids(&self) -> Result<Vec<u64>, ColumnGroupError> {
        let chunk = self.directory.id_chunk;
        let bytes = self.source.read_at(chunk.offset, chunk.length)?;
        if crc32c(&bytes).get() != chunk.crc32c {
            return Err(corrupt(
                "id chunk checksum does not match its contents".to_string(),
            ));
        }
        decode_ids(&bytes, self.directory.row_count)
    }

    fn read_column_chunk(
        &self,
        column: &ColumnChunkDescriptor,
    ) -> Result<Vec<Value>, ColumnGroupError> {
        let bytes = self.source.read_at(column.offset, column.length)?;
        if crc32c(&bytes).get() != column.crc32c {
            return Err(corrupt(format!(
                "column chunk {} checksum does not match its contents",
                column.property_id.0
            )));
        }
        let values = decode_chunk(&bytes, column.encoding, column.compressed)?;
        if values.len() != self.directory.row_count as usize {
            return Err(corrupt(format!(
                "column chunk {} decodes {} rows in a {} row group",
                column.property_id.0,
                values.len(),
                self.directory.row_count
            )));
        }
        Ok(values)
    }

    /// Decodes one column, honoring the validity bitmap: the result holds
    /// one `Value` per selected row, `Value::Null` at null positions. With
    /// `selection`, only those row indices are returned, in order.
    pub fn read_column(
        &self,
        property_id: PropertyId,
        selection: Option<&[u32]>,
    ) -> Result<Vec<Value>, ColumnGroupError> {
        let column = self
            .directory
            .column(property_id)
            .ok_or(ColumnGroupError::PropertyMissing(property_id))?;
        let values = self.read_column_chunk(column)?;
        let Some(selection) = selection else {
            return Ok(values);
        };
        selection
            .iter()
            .map(|row| {
                usize::try_from(*row)
                    .ok()
                    .filter(|row| *row < values.len())
                    .map(|row| values[row].clone())
                    .ok_or(ColumnGroupError::RowOutOfRange {
                        row_index: *row,
                        row_count: self.directory.row_count,
                    })
            })
            .collect()
    }

    /// Decodes one byte-table blob column: one optional blob per row,
    /// `None` at null positions. Only columns written as byte columns
    /// decode this way; a `Value` column is rejected rather than
    /// reinterpreted.
    pub fn read_byte_column(
        &self,
        property_id: PropertyId,
    ) -> Result<Vec<Option<Vec<u8>>>, ColumnGroupError> {
        let column = self
            .directory
            .column(property_id)
            .ok_or(ColumnGroupError::PropertyMissing(property_id))?;
        if column.encoding != ChunkEncoding::ByteTable {
            return Err(unsupported(format!(
                "column {} is not a byte-table column",
                property_id.0
            )));
        }
        let bytes = self.source.read_at(column.offset, column.length)?;
        if crc32c(&bytes).get() != column.crc32c {
            return Err(corrupt(format!(
                "column chunk {} checksum does not match its contents",
                column.property_id.0
            )));
        }
        let rows = decode_byte_chunk(&bytes, column.compressed)?;
        if rows.len() != self.directory.row_count as usize {
            return Err(corrupt(format!(
                "column chunk {} decodes {} rows in a {} row group",
                column.property_id.0,
                rows.len(),
                self.directory.row_count
            )));
        }
        Ok(rows)
    }

    /// Directory-only pruning: decides from zone maps and null counts
    /// whether the predicate's chunk (or the whole group) can be skipped,
    /// without reading any chunk bytes. Sound by the mirror of the
    /// `HawDBPropertyIndexPruning` obligation: a skipped chunk never
    /// contains a qualifying row.
    pub fn prune(&self, predicate: &ColumnPredicate) -> ColumnGroupPruneDecision {
        if self.directory.row_count == 0 {
            return ColumnGroupPruneDecision::SkipGroup(ColumnGroupPruneReason::EmptyGroup);
        }
        let Some(column) = self.directory.column(predicate.property_id()) else {
            // No chunk for the property means no row of the group stores
            // it, so a match-requiring predicate rules out the group.
            return ColumnGroupPruneDecision::SkipGroup(ColumnGroupPruneReason::PropertyAbsent);
        };
        if column.zone_map.value_count() == 0 {
            return ColumnGroupPruneDecision::SkipChunk(ColumnGroupPruneReason::AllNull);
        }
        let may_match = match predicate {
            ColumnPredicate::Equals { value, .. } => column.zone_map.may_match_equals(value),
            ColumnPredicate::Range { lower, upper, .. } => column
                .zone_map
                .may_match_range(lower.as_ref(), upper.as_ref()),
        };
        if may_match {
            ColumnGroupPruneDecision::Open
        } else {
            ColumnGroupPruneDecision::SkipChunk(ColumnGroupPruneReason::ZoneMapExcluded)
        }
    }

    /// The rows of this group still visible under a deletion vector,
    /// ascending. The vector must be bound to this group's physical
    /// generation (§3.5.3(d)); a vector published after the pinned
    /// snapshot is also rejected. Older cumulative vectors may be reused by
    /// newer manifests when no additional deletes were published.
    pub fn visible_rows<'a>(
        &self,
        deletion_vector: &'a DeletionVector,
        snapshot_generation: ManifestGeneration,
    ) -> Result<impl Iterator<Item = u32> + 'a, ColumnGroupError> {
        if deletion_vector.group_id() != self.directory.group_id
            || deletion_vector.group_generation() != self.directory.generation
        {
            return Err(ColumnGroupError::DeletionVectorGroupMismatch {
                expected_group: self.directory.group_id,
                actual_group: deletion_vector.group_id(),
                expected_group_generation: self.directory.generation.0,
                actual_group_generation: deletion_vector.group_generation().0,
            });
        }
        if deletion_vector.publication_generation().0 > snapshot_generation.0 {
            return Err(ColumnGroupError::DeletionVectorFromFuture {
                snapshot_generation: snapshot_generation.0,
                publication_generation: deletion_vector.publication_generation().0,
            });
        }
        if deletion_vector.row_count() != self.directory.row_count {
            return Err(corrupt(format!(
                "deletion vector covers {} rows of a {} row group",
                deletion_vector.row_count(),
                self.directory.row_count
            )));
        }
        Ok(deletion_vector.visible_rows())
    }

    /// Point read: reconstructs the requested properties of one row,
    /// touching only the chunks of requested columns (§3.2.3). A property
    /// the group does not store reads as `Value::Null`.
    pub fn read_row(
        &self,
        row_index: u32,
        properties: &[PropertyId],
    ) -> Result<Vec<Value>, ColumnGroupError> {
        if row_index >= self.directory.row_count {
            return Err(ColumnGroupError::RowOutOfRange {
                row_index,
                row_count: self.directory.row_count,
            });
        }
        properties
            .iter()
            .map(|property_id| match self.directory.column(*property_id) {
                Some(column) => {
                    let mut values = self.read_column_chunk(column)?;
                    Ok(std::mem::replace(
                        &mut values[row_index as usize],
                        Value::Null,
                    ))
                }
                None => Ok(Value::Null),
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scan::DateTimeMinMax;
    use std::path::PathBuf;

    fn unique_path(name: &str) -> PathBuf {
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("hawdb-column-group-{name}-{nonce}.hawdb"))
    }

    fn sample_columns(rows: usize) -> Vec<(PropertyId, Vec<Value>)> {
        vec![
            (
                PropertyId(3),
                (0..rows)
                    .map(|row| {
                        if row % 5 == 0 {
                            Value::Null
                        } else {
                            Value::Int(row as i64 * 7 - 100)
                        }
                    })
                    .collect(),
            ),
            (
                PropertyId(1),
                (0..rows)
                    .map(|row| Value::String(format!("name-{}", row % 17)))
                    .collect(),
            ),
            (
                PropertyId(9),
                (0..rows).map(|row| Value::Bool(row % 3 == 0)).collect(),
            ),
        ]
    }

    #[test]
    fn group_round_trips_ids_and_columns() {
        let path = unique_path("round_trip");
        let ids = (0..500u64).map(|index| index * 3 + 11).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        let written = ColumnGroupWriter::default()
            .write(&path, 42, ManifestGeneration(7), &ids, &columns)
            .unwrap();
        assert_eq!(written.min_id, 11);
        assert_eq!(written.max_id, 11 + 499 * 3);
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert_eq!(reader.directory(), &written);
        assert_eq!(reader.read_ids().unwrap(), ids);
        // The directory lists columns sorted by property id.
        assert_eq!(
            reader
                .directory()
                .columns
                .iter()
                .map(|column| column.property_id.0)
                .collect::<Vec<_>>(),
            vec![1, 3, 9]
        );
        for (property_id, values) in &columns {
            assert_eq!(
                reader.read_column(*property_id, None).unwrap(),
                *values,
                "property {}",
                property_id.0
            );
        }
        assert!(matches!(
            reader.read_column(PropertyId(999), None),
            Err(ColumnGroupError::PropertyMissing(PropertyId(999)))
        ));
        // No temp file remains after publish.
        assert!(!path.with_extension("hawdb.tmp").exists());
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn empty_group_round_trips() {
        let path = unique_path("empty");
        let written = ColumnGroupWriter::default()
            .write(&path, 1, ManifestGeneration(1), &[], &[])
            .unwrap();
        assert_eq!(written.row_count, 0);
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert_eq!(reader.read_ids().unwrap(), Vec::<u64>::new());
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn byte_columns_ride_the_group_beside_value_columns() {
        let path = unique_path("byte_columns");
        let ids = (0..300u64).map(|index| index * 2 + 1).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        let blobs = (0..ids.len())
            .map(|row| match row % 3 {
                0 => None,
                1 => Some(vec![row as u8, 0, 255, 7]),
                _ => Some(Vec::new()),
            })
            .collect::<Vec<_>>();
        let written = ColumnGroupWriter::default()
            .write_with_byte_columns(
                &path,
                11,
                ManifestGeneration(2),
                &ids,
                &columns,
                &[(PropertyId(0), blobs.clone())],
            )
            .unwrap();
        // Byte columns sort into the shared directory by property id.
        assert_eq!(
            written
                .columns
                .iter()
                .map(|column| column.property_id.0)
                .collect::<Vec<_>>(),
            vec![0, 1, 3, 9]
        );
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert_eq!(reader.read_byte_column(PropertyId(0)).unwrap(), blobs);
        for (property_id, values) in &columns {
            assert_eq!(reader.read_column(*property_id, None).unwrap(), *values);
        }
        // Binary values use the shared Value read path, while typed byte reads
        // remain unavailable for non-binary columns.
        assert_eq!(
            reader.read_column(PropertyId(0), None).unwrap(),
            blobs
                .iter()
                .map(|value| value
                    .as_ref()
                    .map_or(Value::Null, |bytes| Value::Binary(bytes.clone())))
                .collect::<Vec<_>>()
        );
        assert!(matches!(
            reader.read_byte_column(PropertyId(1)),
            Err(ColumnGroupError::Unsupported(_))
        ));
        assert!(matches!(
            reader.read_byte_column(PropertyId(404)),
            Err(ColumnGroupError::PropertyMissing(PropertyId(404)))
        ));
        // A duplicate property across the two column sets is rejected.
        assert!(matches!(
            ColumnGroupWriter::default().write_with_byte_columns(
                &path,
                12,
                ManifestGeneration(2),
                &[1],
                &[(PropertyId(0), vec![Value::Int(1)])],
                &[(PropertyId(0), vec![None])],
            ),
            Err(ColumnGroupError::Unsupported(_))
        ));
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn id_column_survives_sparse_ids_at_the_u64_boundary() {
        let path = unique_path("id_boundary");
        let ids = vec![
            3,
            u64::MAX / 2,
            u64::MAX - 65_536,
            u64::MAX - 2,
            u64::MAX - 1,
            u64::MAX,
        ];
        let columns = vec![(
            PropertyId(0),
            ids.iter().map(|id| Value::Int(*id as i64)).collect(),
        )];
        ColumnGroupWriter::default()
            .write(&path, 2, ManifestGeneration(1), &ids, &columns)
            .unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert_eq!(reader.read_ids().unwrap(), ids);
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn writer_rejects_invalid_input() {
        let path = unique_path("invalid_input");
        let writer = ColumnGroupWriter::default();
        // Unsorted ids.
        assert!(matches!(
            writer.write(&path, 1, ManifestGeneration(1), &[5, 5], &[]),
            Err(ColumnGroupError::Unsupported(_))
        ));
        // Column length mismatch.
        assert!(matches!(
            writer.write(
                &path,
                1,
                ManifestGeneration(1),
                &[1, 2],
                &[(PropertyId(0), vec![Value::Int(1)])]
            ),
            Err(ColumnGroupError::Unsupported(_))
        ));
        // Duplicate property.
        assert!(matches!(
            writer.write(
                &path,
                1,
                ManifestGeneration(1),
                &[1],
                &[
                    (PropertyId(0), vec![Value::Int(1)]),
                    (PropertyId(0), vec![Value::Int(2)])
                ]
            ),
            Err(ColumnGroupError::Unsupported(_))
        ));
        // Capacity overflow.
        let small = ColumnGroupWriter::new(ColumnGroupConfig {
            row_capacity: 2,
            compress: false,
        });
        assert!(matches!(
            small.write(&path, 1, ManifestGeneration(1), &[1, 2, 3], &[]),
            Err(ColumnGroupError::Unsupported(_))
        ));
        assert!(!path.exists());
    }

    #[test]
    fn truncated_artifacts_are_corrupt() {
        let path = unique_path("truncated");
        let ids = (0..64u64).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 3, ManifestGeneration(2), &ids, &columns)
            .unwrap();
        let bytes = fs::read(&path).unwrap();
        for cut in [0, 5, 12, bytes.len() / 2, bytes.len() - 1] {
            fs::write(&path, &bytes[..cut]).unwrap();
            assert!(
                matches!(
                    ColumnGroupReader::open_path(&path),
                    Err(ColumnGroupError::Corrupt(_))
                ),
                "cut at {cut}"
            );
        }
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn directory_and_chunk_corruption_is_detected() {
        let path = unique_path("bitflip");
        let ids = (0..128u64).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 4, ManifestGeneration(3), &ids, &columns)
            .unwrap();
        let bytes = fs::read(&path).unwrap();
        let footer_start = bytes.len() - FOOTER_BYTES;
        let directory_len =
            u64::from_le_bytes(bytes[footer_start..footer_start + 8].try_into().unwrap()) as usize;
        let directory_start = footer_start - directory_len;
        // Flip one byte inside the directory: the footer CRC catches it.
        let mut tampered = bytes.clone();
        tampered[directory_start + 20] ^= 0x01;
        fs::write(&path, &tampered).unwrap();
        assert!(matches!(
            ColumnGroupReader::open_path(&path),
            Err(ColumnGroupError::Corrupt(_))
        ));
        // Flip one byte inside a chunk body: the open path succeeds (chunks
        // are not read) and the per-chunk CRC catches it on first read.
        let mut tampered = bytes.clone();
        tampered[HEADER_BYTES as usize + 2] ^= 0x40;
        fs::write(&path, &tampered).unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert!(matches!(
            reader.read_ids(),
            Err(ColumnGroupError::Corrupt(_))
        ));
        let first_column = reader.directory().columns[0].clone();
        let mut tampered = bytes.clone();
        tampered[first_column.offset as usize] ^= 0x80;
        fs::write(&path, &tampered).unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert!(matches!(
            reader.read_column(first_column.property_id, None),
            Err(ColumnGroupError::Corrupt(_))
        ));
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn out_of_range_chunk_extents_are_corrupt() {
        let path = unique_path("extent");
        let ids = (0..32u64).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 5, ManifestGeneration(4), &ids, &columns)
            .unwrap();
        let bytes = fs::read(&path).unwrap();
        let footer_start = bytes.len() - FOOTER_BYTES;
        let directory_len =
            u64::from_le_bytes(bytes[footer_start..footer_start + 8].try_into().unwrap()) as usize;
        let directory_start = footer_start - directory_len;
        // Point the first column entry's offset past the data region and
        // recompute the directory CRC so only the extent check can object.
        let mut tampered = bytes.clone();
        let entry_offset = directory_start + DIRECTORY_HEADER_BYTES + 8;
        tampered[entry_offset..entry_offset + 8]
            .copy_from_slice(&(bytes.len() as u64).to_le_bytes());
        let new_crc = crc32c(&tampered[directory_start..footer_start]).get();
        tampered[footer_start + 8..footer_start + 12].copy_from_slice(&new_crc.to_le_bytes());
        fs::write(&path, &tampered).unwrap();
        let error = ColumnGroupReader::open_path(&path).unwrap_err();
        assert!(matches!(error, ColumnGroupError::Corrupt(_)));
        assert!(error.to_string().contains("extent"));
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn pruning_distinguishes_group_and_chunk_skips() {
        let path = unique_path("prune");
        let ids = (0..50u64).collect::<Vec<_>>();
        let columns = vec![
            (
                PropertyId(1),
                (0..50).map(|row| Value::Int(row * 10)).collect::<Vec<_>>(),
            ),
            (PropertyId(2), vec![Value::Null; 50]),
        ];
        ColumnGroupWriter::default()
            .write(&path, 8, ManifestGeneration(1), &ids, &columns)
            .unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        assert_eq!(
            reader.prune(&ColumnPredicate::Equals {
                property_id: PropertyId(99),
                value: Value::Int(1),
            }),
            ColumnGroupPruneDecision::SkipGroup(ColumnGroupPruneReason::PropertyAbsent)
        );
        assert_eq!(
            reader.prune(&ColumnPredicate::Equals {
                property_id: PropertyId(2),
                value: Value::Int(1),
            }),
            ColumnGroupPruneDecision::SkipChunk(ColumnGroupPruneReason::AllNull)
        );
        assert_eq!(
            reader.prune(&ColumnPredicate::Equals {
                property_id: PropertyId(1),
                value: Value::Int(-5),
            }),
            ColumnGroupPruneDecision::SkipChunk(ColumnGroupPruneReason::ZoneMapExcluded)
        );
        assert_eq!(
            reader.prune(&ColumnPredicate::Equals {
                property_id: PropertyId(1),
                value: Value::Int(90),
            }),
            ColumnGroupPruneDecision::Open
        );
        assert_eq!(
            reader.prune(&ColumnPredicate::Range {
                property_id: PropertyId(1),
                lower: Some(RangeBound::exclusive(Value::Int(490))),
                upper: None,
            }),
            ColumnGroupPruneDecision::SkipChunk(ColumnGroupPruneReason::ZoneMapExcluded)
        );
        assert!(reader
            .prune(&ColumnPredicate::Range {
                property_id: PropertyId(1),
                lower: Some(RangeBound::inclusive(Value::Int(490))),
                upper: None,
            })
            .should_open());
        fs::remove_file(&path).unwrap();
        // An empty group is skipped outright.
        let empty = unique_path("prune_empty");
        ColumnGroupWriter::default()
            .write(&empty, 9, ManifestGeneration(1), &[], &[])
            .unwrap();
        let reader = ColumnGroupReader::open_path(&empty).unwrap();
        assert_eq!(
            reader.prune(&ColumnPredicate::Equals {
                property_id: PropertyId(1),
                value: Value::Int(1),
            }),
            ColumnGroupPruneDecision::SkipGroup(ColumnGroupPruneReason::EmptyGroup)
        );
        fs::remove_file(empty).unwrap();
    }

    // Deterministic xorshift64* generator: no external rand dependency.
    struct XorShift(u64);

    impl XorShift {
        fn next(&mut self) -> u64 {
            let mut state = self.0;
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            self.0 = state;
            state.wrapping_mul(0x2545_f491_4f6c_dd1d)
        }

        fn below(&mut self, bound: u64) -> u64 {
            self.next() % bound
        }
    }

    fn random_value(rng: &mut XorShift, style: u64) -> Value {
        if rng.below(5) == 0 {
            return Value::Null;
        }
        match style {
            0 => Value::Int(rng.below(200) as i64 - 100),
            1 => Value::Int(i64::MAX - rng.below(64) as i64),
            2 => Value::Float(rng.below(400) as f64 / 4.0 - 50.0),
            3 => match rng.below(12) {
                0 => Value::Float(f64::INFINITY),
                1 => Value::Float(f64::NAN),
                _ => Value::Float(rng.below(100) as f64),
            },
            4 => {
                let length = rng.below(30) as usize;
                let letter = b'a' + rng.below(6) as u8;
                Value::String(String::from_utf8(vec![letter; length.max(1)]).unwrap())
            }
            5 => Value::String(format!(
                "2024-{:02}-{:02}T{:02}:00:00Z",
                rng.below(12) + 1,
                rng.below(28) + 1,
                rng.below(24)
            )),
            6 => Value::Bool(rng.below(2) == 1),
            _ => {
                let style = rng.below(7);
                random_value(rng, style)
            }
        }
    }

    /// Reference row matcher for the semantics documented on
    /// `ColumnPredicate`. Null values match nothing.
    fn value_matches(value: &Value, predicate: &ColumnPredicate) -> bool {
        if matches!(value, Value::Null) {
            return false;
        }
        match predicate {
            ColumnPredicate::Equals {
                value: expected, ..
            } => value == expected,
            ColumnPredicate::Range { lower, upper, .. } => {
                lower
                    .as_ref()
                    .is_none_or(|bound| bound_matches(value, bound, true))
                    && upper
                        .as_ref()
                        .is_none_or(|bound| bound_matches(value, bound, false))
            }
        }
    }

    fn bound_matches(value: &Value, bound: &RangeBound, is_lower: bool) -> bool {
        use std::cmp::Ordering;
        let ordering = match (&bound.value, value) {
            (Value::Int(bound), Value::Int(value)) => Some(value.cmp(bound)),
            (Value::Int(bound), Value::Float(value)) => {
                cmp_i64_f64(*bound, *value).map(Ordering::reverse)
            }
            (Value::Float(bound), Value::Int(value)) if bound.is_finite() => {
                cmp_i64_f64(*value, *bound)
            }
            (Value::Float(bound), Value::Float(value)) if bound.is_finite() => {
                value.partial_cmp(bound)
            }
            (Value::String(bound), Value::String(value)) => {
                match DateTimeMinMax::parse_rfc3339(bound) {
                    Some(bound_millis) => DateTimeMinMax::parse_rfc3339(value)
                        .map(|value_millis| value_millis.cmp(&bound_millis)),
                    None => Some(value.as_str().cmp(bound.as_str())),
                }
            }
            (Value::Bool(bound), Value::Bool(value)) => Some(value.cmp(bound)),
            _ => None,
        };
        let Some(ordering) = ordering else {
            return false;
        };
        match (is_lower, bound.inclusive) {
            (true, true) => ordering.is_ge(),
            (true, false) => ordering.is_gt(),
            (false, true) => ordering.is_le(),
            (false, false) => ordering.is_lt(),
        }
    }

    /// Exact comparison of an i64 against a finite f64.
    fn cmp_i64_f64(int: i64, float: f64) -> Option<std::cmp::Ordering> {
        use std::cmp::Ordering;
        if float.is_nan() {
            return None;
        }
        if float >= 9_223_372_036_854_775_808.0 {
            return Some(Ordering::Less);
        }
        if float < -9_223_372_036_854_775_808.0 {
            return Some(Ordering::Greater);
        }
        let floor = float.floor();
        let floor_int = floor as i128;
        Some(match i128::from(int).cmp(&floor_int) {
            Ordering::Less => Ordering::Less,
            Ordering::Greater => Ordering::Greater,
            Ordering::Equal if float == floor => Ordering::Equal,
            Ordering::Equal => Ordering::Less,
        })
    }

    fn random_predicate(rng: &mut XorShift, property_ids: &[PropertyId]) -> ColumnPredicate {
        let property_id = if rng.below(10) == 0 {
            PropertyId(4096)
        } else {
            property_ids[rng.below(property_ids.len() as u64) as usize]
        };
        let style = rng.below(8);
        if rng.below(2) == 0 {
            ColumnPredicate::Equals {
                property_id,
                value: random_value(rng, style),
            }
        } else {
            let bound = |rng: &mut XorShift, style| {
                let value = random_value(rng, style);
                if rng.below(2) == 0 {
                    RangeBound::inclusive(value)
                } else {
                    RangeBound::exclusive(value)
                }
            };
            let lower = (rng.below(4) != 0).then(|| bound(rng, style));
            let upper = (rng.below(4) != 0).then(|| bound(rng, style));
            ColumnPredicate::Range {
                property_id,
                lower,
                upper,
            }
        }
    }

    #[test]
    fn zone_map_pruning_never_skips_a_qualifying_row() {
        let mut rng = XorShift(0x5ee5_c01d_beef_cafe);
        let path = unique_path("prune_soundness");
        let property_ids = [PropertyId(0), PropertyId(1), PropertyId(2)];
        for round in 0..80 {
            let row_count = rng.below(100) as usize + 1;
            let ids = {
                let mut current = rng.below(1000);
                (0..row_count)
                    .map(|_| {
                        current += rng.below(9) + 1;
                        current
                    })
                    .collect::<Vec<_>>()
            };
            let columns = property_ids
                .iter()
                .map(|property_id| {
                    let style = rng.below(8);
                    (
                        *property_id,
                        (0..row_count)
                            .map(|_| random_value(&mut rng, style))
                            .collect::<Vec<_>>(),
                    )
                })
                .collect::<Vec<_>>();
            ColumnGroupWriter::default()
                .write(&path, round, ManifestGeneration(round), &ids, &columns)
                .unwrap();
            let reader = ColumnGroupReader::open_path(&path).unwrap();
            for _ in 0..6 {
                let predicate = random_predicate(&mut rng, &property_ids);
                if reader.prune(&predicate).should_open() {
                    continue;
                }
                // A pruned chunk must not contain a qualifying row.
                let column = columns
                    .iter()
                    .find(|(property_id, _)| *property_id == predicate.property_id());
                if let Some((property_id, values)) = column {
                    for (row, value) in values.iter().enumerate() {
                        assert!(
                            !value_matches(value, &predicate),
                            "round {round}: pruned chunk of property {} hides matching \
                             row {row} ({value:?}) from {predicate:?}",
                            property_id.0
                        );
                    }
                }
            }
        }
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn deletion_vectors_bind_to_group_and_generation() {
        let path = unique_path("dv_binding");
        let ids = (0..40u64).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 7, ManifestGeneration(9), &ids, &columns)
            .unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        let mut vector = DeletionVector::new(
            DeletionVectorBinding::new(7, ManifestGeneration(9), ManifestGeneration(10), 40)
                .unwrap(),
        );
        vector.mark_deleted(0).unwrap();
        vector.mark_deleted(39).unwrap();
        let visible = reader
            .visible_rows(&vector, ManifestGeneration(10))
            .unwrap()
            .collect::<Vec<_>>();
        assert_eq!(visible.len(), 38);
        assert_eq!(visible.first(), Some(&1));
        assert_eq!(visible.last(), Some(&38));
        // Wrong physical group generation.
        let stale = DeletionVector::new(
            DeletionVectorBinding::new(7, ManifestGeneration(8), ManifestGeneration(10), 40)
                .unwrap(),
        );
        assert!(matches!(
            reader
                .visible_rows(&stale, ManifestGeneration(10))
                .map(|_| ()),
            Err(ColumnGroupError::DeletionVectorGroupMismatch { .. })
        ));
        // Wrong group.
        let foreign = DeletionVector::new(
            DeletionVectorBinding::new(6, ManifestGeneration(9), ManifestGeneration(10), 40)
                .unwrap(),
        );
        assert!(matches!(
            reader
                .visible_rows(&foreign, ManifestGeneration(10))
                .map(|_| ()),
            Err(ColumnGroupError::DeletionVectorGroupMismatch { .. })
        ));
        // A reader pinned before the vector's publication cannot see future
        // deletes, even though it addresses the same immutable group.
        assert!(matches!(
            reader
                .visible_rows(&vector, ManifestGeneration(9))
                .map(|_| ()),
            Err(ColumnGroupError::DeletionVectorFromFuture { .. })
        ));
        // Wrong row count.
        let short = DeletionVector::new(
            DeletionVectorBinding::new(7, ManifestGeneration(9), ManifestGeneration(10), 39)
                .unwrap(),
        );
        assert!(matches!(
            reader
                .visible_rows(&short, ManifestGeneration(10))
                .map(|_| ()),
            Err(ColumnGroupError::Corrupt(_))
        ));
        fs::remove_file(path).unwrap();
    }

    #[test]
    fn point_reads_reconstruct_rows_and_selections_project() {
        let path = unique_path("point_read");
        let ids = (0..200u64).map(|index| index * 2).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 6, ManifestGeneration(5), &ids, &columns)
            .unwrap();
        let reader = ColumnGroupReader::open_path(&path).unwrap();
        let row = reader
            .read_row(10, &[PropertyId(3), PropertyId(1), PropertyId(777)])
            .unwrap();
        assert_eq!(row[0], Value::Null); // row 10 % 5 == 0 -> null
        assert_eq!(row[1], Value::String("name-10".to_string()));
        assert_eq!(row[2], Value::Null); // property absent from the group
        let row = reader.read_row(11, &[PropertyId(3)]).unwrap();
        assert_eq!(row[0], Value::Int(11 * 7 - 100));
        assert!(matches!(
            reader.read_row(200, &[PropertyId(3)]),
            Err(ColumnGroupError::RowOutOfRange { .. })
        ));
        let selected = reader
            .read_column(PropertyId(1), Some(&[199, 0, 17]))
            .unwrap();
        assert_eq!(
            selected,
            vec![
                Value::String(format!("name-{}", 199 % 17)),
                Value::String("name-0".to_string()),
                Value::String("name-0".to_string()),
            ]
        );
        assert!(matches!(
            reader.read_column(PropertyId(1), Some(&[200])),
            Err(ColumnGroupError::RowOutOfRange { .. })
        ));
        fs::remove_file(path).unwrap();
    }

    /// Byte source that records every range it serves.
    struct CountingSource {
        inner: FileByteSource,
        reads: std::rc::Rc<std::cell::RefCell<Vec<(u64, u64)>>>,
    }

    impl ColumnGroupByteSource for CountingSource {
        fn byte_len(&self) -> Result<u64, ColumnGroupError> {
            self.inner.byte_len()
        }

        fn read_at(&self, offset: u64, length: u64) -> Result<Vec<u8>, ColumnGroupError> {
            self.reads.borrow_mut().push((offset, length));
            self.inner.read_at(offset, length)
        }
    }

    #[test]
    fn point_reads_touch_only_requested_chunk_extents() {
        let path = unique_path("counting");
        let ids = (0..300u64).collect::<Vec<_>>();
        let columns = sample_columns(ids.len());
        ColumnGroupWriter::default()
            .write(&path, 10, ManifestGeneration(6), &ids, &columns)
            .unwrap();
        let reads = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        let source = CountingSource {
            inner: FileByteSource::open(&path).unwrap(),
            reads: std::rc::Rc::clone(&reads),
        };
        let reader = ColumnGroupReader::open(source).unwrap();
        let requested_extent = {
            let column = reader.directory().column(PropertyId(3)).unwrap();
            (column.offset, column.length)
        };
        let sibling_extents = reader
            .directory()
            .columns
            .iter()
            .filter(|column| column.property_id != PropertyId(3))
            .map(|column| (column.offset, column.length))
            .chain(std::iter::once((
                reader.directory().id_chunk.offset,
                reader.directory().id_chunk.length,
            )))
            .collect::<Vec<_>>();
        reads.borrow_mut().clear();
        let row = reader.read_row(7, &[PropertyId(3)]).unwrap();
        assert_eq!(row, vec![Value::Int(7 * 7 - 100)]);
        let logged = reads.borrow().clone();
        assert!(!logged.is_empty());
        for (offset, length) in &logged {
            assert_eq!(
                (*offset, *length),
                requested_extent,
                "point read touched bytes outside the requested chunk"
            );
            for (sibling_offset, sibling_length) in &sibling_extents {
                let disjoint = offset + length <= *sibling_offset
                    || sibling_offset + sibling_length <= *offset;
                assert!(disjoint, "point read overlapped an unrequested chunk");
            }
        }
        // A selective column read is equally surgical.
        reads.borrow_mut().clear();
        reader.read_column(PropertyId(3), Some(&[1, 2])).unwrap();
        assert!(reads
            .borrow()
            .iter()
            .all(|extent| *extent == requested_extent));
        fs::remove_file(path).unwrap();
    }
}