radixdb-storage 1.1.0

Storage contracts and physical persistence engine for RadixDB
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
use std::mem::size_of;
use std::ops::Range;

use radixdb_catalog::{CatalogDataType, ObjectId};
use radixdb_core::{DataType, Value};

use super::super::{
    ArtifactId, ArtifactKind, ArtifactRef, ArtifactSource, CatalogGeneration, DatabaseGeneration,
    DatabaseId, FormatError, FormatResult, SegmentId, SegmentKind, MAX_ARTIFACT_FILE_BYTES,
};
use super::bloom::{decode_bloom_payload, DataBloom};
use super::column::{decode_column_payload, decode_typed_column_payload, DecodedColumn};
use super::column_model::DataColumn;
use super::model::{
    collect_column_block_map, invalid, limit, validate_block_lengths, validate_kind_layout,
    DataArtifactHeader, DataArtifactInput, DataArtifactLayout, DataBlockKind, DataBlockRef,
    DataLayout, DataPhysicalCodec, DataRowGroup, DataSectionKind, DataSectionRef,
    DATA_BLOCK_REF_BYTES, DATA_FOOTER_BYTES, DATA_HEADER_BYTES, DATA_SECTION_COUNT,
    DATA_SECTION_REF_BYTES, MAX_BLOCKS_PER_DATA_ARTIFACT, MAX_DATA_DIRECTORY_BYTES,
    MAX_STATISTICS_VALUES_BYTES,
};
use super::row_ids::decode_row_id_payload;
use super::source::{DataOpenLimits, DataOpenMetrics, OpenedDataArtifact};
use super::statistics::{decode_statistics, STATISTICS_ENTRY_BYTES};

const MAGIC: [u8; 8] = *b"RDX6DAT\0";
pub(crate) const FOOTER_MAGIC: [u8; 8] = *b"RDX6END\0";
const FORMAT_MAJOR: u16 = 6;
const FORMAT_MINOR: u16 = 0;
pub(crate) const SECTION_DIRECTORY_OFFSET: usize = DATA_HEADER_BYTES;
pub(crate) const SECTION_DIRECTORY_BYTES: usize = DATA_SECTION_COUNT * DATA_SECTION_REF_BYTES;
pub(crate) const BODY_START: usize = SECTION_DIRECTORY_OFFSET + SECTION_DIRECTORY_BYTES;

const COLUMN_ENTRY_BYTES: u64 = 64;
const ROW_GROUP_ENTRY_BYTES: u64 = 48;

pub fn encode_data_artifact(input: &DataArtifactInput) -> FormatResult<(Vec<u8>, ArtifactRef)> {
    let mut output = vec![0_u8; BODY_START];
    let mut ranges: [Range<usize>; DATA_SECTION_COUNT] = std::array::from_fn(|_| 0..0);
    let column_directory = encode_columns(input.columns());
    let row_group_directory = encode_row_groups(input.row_groups());

    ranges[0] = append_section(&mut output, &column_directory)?;
    ranges[1] = append_section(&mut output, &row_group_directory)?;
    let block_directory_bytes = input
        .blocks()
        .len()
        .checked_mul(DATA_BLOCK_REF_BYTES)
        .ok_or_else(|| invalid("block directory length overflows"))?;
    ranges[2] = append_section_placeholder(&mut output, block_directory_bytes)?;
    ranges[3] = append_section(&mut output, input.statistics_directory())?;

    for (index, block) in input.blocks().iter().enumerate() {
        align_output(&mut output);
        let offset = output.len();
        output.extend_from_slice(block.stored_bytes());
        let directory_offset = ranges[2].start + index * DATA_BLOCK_REF_BYTES;
        let entry = &mut output[directory_offset..directory_offset + DATA_BLOCK_REF_BYTES];
        let stored_crc32 = radixdb_core::crc32_ieee(block.stored_bytes());
        let block_ref = DataBlockRef::new(
            block.kind(),
            block.codec(),
            block.column_ordinal(),
            block.row_group_ordinal(),
            block.layout(),
            offset as u64,
            block.stored_bytes().len() as u64,
            block.logical_length(),
            block.item_count(),
            stored_crc32,
        )?;
        encode_block_ref(entry, &block_ref);
    }
    // Variable-size statistic values intentionally follow the row-group
    // payloads.  The four fixed-size directories therefore form a prefix that
    // a streaming writer can reserve before it consumes the source rows;
    // blocks can then be written once, directly to their final offsets.
    ranges[4] = append_section(&mut output, input.statistics_values())?;

    let body_length = output
        .len()
        .checked_add(DATA_FOOTER_BYTES)
        .ok_or_else(|| invalid("file length overflows"))?;
    if body_length as u64 > MAX_ARTIFACT_FILE_BYTES {
        return Err(limit(
            "file bytes",
            body_length as u64,
            MAX_ARTIFACT_FILE_BYTES,
        ));
    }

    encode_header(
        &mut output[..DATA_HEADER_BYTES],
        input.header(),
        body_length,
    )?;
    let counts = [
        u64::from(input.header().column_count()),
        u64::from(input.header().row_group_count()),
        input.blocks().len() as u64,
        input.statistics().len() as u64,
        input.statistics_values().len() as u64,
    ];
    for (index, kind) in DataSectionKind::ALL.into_iter().enumerate() {
        let stored_crc32 = radixdb_core::crc32_ieee(&output[ranges[index].clone()]);
        let entry_offset = SECTION_DIRECTORY_OFFSET + index * DATA_SECTION_REF_BYTES;
        let entry = &mut output[entry_offset..entry_offset + DATA_SECTION_REF_BYTES];
        encode_section_ref(entry, kind, &ranges[index], counts[index], stored_crc32)?;
    }

    let header_crc = radixdb_core::crc32_ieee(&output[..248]);
    put_u32(&mut output, 248, header_crc);
    let body_sha = radixdb_core::sha256_digest(&output);
    output.extend_from_slice(&FOOTER_MAGIC);
    output.extend_from_slice(&(body_length as u64).to_le_bytes());
    output.extend_from_slice(&body_sha);

    let reference = ArtifactRef::new(
        input.header().artifact_id(),
        ArtifactKind::Data,
        input.header().creation_generation(),
        body_length as u64,
        body_sha,
    )?;
    Ok((output, reference))
}

pub fn decode_data_artifact_layout(
    bytes: &[u8],
    expected: ArtifactRef,
) -> FormatResult<DataArtifactLayout> {
    validate_file_shell(bytes, expected)?;
    let header = decode_header(bytes, bytes.len() as u64)?;
    if header.artifact_id() != expected.id() {
        return Err(invalid("artifact ID differs from manifest reference"));
    }
    if header.creation_generation() != expected.creation_generation() {
        return Err(invalid(
            "creation generation differs from manifest reference",
        ));
    }

    let footer_start = bytes.len() - DATA_FOOTER_BYTES;
    let mut sections =
        [DataSectionRef::new(DataSectionKind::ColumnDirectory, 0, 0, 0, 0); DATA_SECTION_COUNT];
    let mut directory_bytes = SECTION_DIRECTORY_BYTES as u64;

    for (index, expected_kind) in DataSectionKind::ALL.into_iter().enumerate() {
        let entry_offset = SECTION_DIRECTORY_OFFSET + index * DATA_SECTION_REF_BYTES;
        let entry = &bytes[entry_offset..entry_offset + DATA_SECTION_REF_BYTES];
        let section = decode_section_ref(entry, expected_kind)?;
        validate_section_count(&header, section)?;
        if expected_kind != DataSectionKind::StatisticsValues {
            directory_bytes = directory_bytes
                .checked_add(section.stored_length())
                .ok_or_else(|| invalid("directory byte count overflows"))?;
        }
        let section_bytes = section_slice(bytes, section)?;
        if radixdb_core::crc32_ieee(section_bytes) != section.stored_crc32() {
            return Err(FormatError::DataArtifactChecksumMismatch { scope: "section" });
        }
        sections[index] = section;
    }
    if directory_bytes > MAX_DATA_DIRECTORY_BYTES {
        return Err(limit(
            "directory bytes",
            directory_bytes,
            MAX_DATA_DIRECTORY_BYTES,
        ));
    }

    let section_bytes: [&[u8]; DATA_SECTION_COUNT] = std::array::from_fn(|index| {
        section_slice(bytes, sections[index]).expect("validated section range")
    });
    let columns = decode_columns(section_bytes[0], sections[0], sections[3].item_count())?;
    let row_groups = decode_row_groups(section_bytes[1], &header, sections[1])?;
    let blocks = decode_blocks(section_bytes[2], &header, sections[2])?;
    validate_group_block_map(&columns, &row_groups, &blocks)?;
    validate_column_block_map(&columns, &row_groups, &blocks)?;
    let statistics = decode_statistics(
        section_bytes[3],
        section_bytes[4],
        usize::try_from(sections[3].item_count())
            .map_err(|_| invalid("statistics count does not fit this platform"))?,
        &columns,
        &row_groups,
        &blocks,
    )?;
    let cursor = validate_slice_topology(bytes, &sections, &blocks, footer_start)?;
    if cursor != footer_start {
        return Err(invalid("artifact has bytes outside declared ranges"));
    }

    Ok(DataArtifactLayout::new(
        expected, header, sections, columns, row_groups, statistics, blocks,
    ))
}

pub fn open_data_artifact_metadata(
    source: &(impl ArtifactSource + ?Sized),
    expected: ArtifactRef,
) -> FormatResult<OpenedDataArtifact> {
    open_data_artifact_metadata_with_limits(source, expected, DataOpenLimits::default())
}

pub fn open_data_artifact_metadata_with_limits(
    source: &(impl ArtifactSource + ?Sized),
    expected: ArtifactRef,
    limits: DataOpenLimits,
) -> FormatResult<OpenedDataArtifact> {
    let file_length = source.byte_length()?;
    validate_source_length(file_length, expected)?;
    let footer_start = file_length - DATA_FOOTER_BYTES as u64;
    let mut metrics = DataOpenMetrics::default();
    let mut prefix = [0_u8; BODY_START];
    read_source(source, 0, &mut prefix, &mut metrics)?;
    let mut footer = [0_u8; DATA_FOOTER_BYTES];
    read_source(source, footer_start, &mut footer, &mut metrics)?;
    validate_source_footer(&footer, file_length, expected)?;

    let header = decode_header(&prefix, file_length)?;
    validate_expected_header(header, expected)?;
    let sections = decode_source_sections(&prefix, &header, footer_start)?;
    metrics.account_allocation(metadata_allocation_bound(&sections)?, limits)?;

    let mut section_bytes: [Vec<u8>; DATA_SECTION_COUNT] = std::array::from_fn(|_| Vec::new());
    for (index, section) in sections.iter().copied().enumerate() {
        if section.stored_length() == 0 {
            continue;
        }
        let length = usize::try_from(section.stored_length())
            .map_err(|_| invalid("section length does not fit this platform"))?;
        let mut bytes = vec![0_u8; length];
        read_source(source, section.offset(), &mut bytes, &mut metrics)?;
        if radixdb_core::crc32_ieee(&bytes) != section.stored_crc32() {
            return Err(FormatError::DataArtifactChecksumMismatch { scope: "section" });
        }
        section_bytes[index] = bytes;
    }

    let columns = decode_columns(&section_bytes[0], sections[0], sections[3].item_count())?;
    let row_groups = decode_row_groups(&section_bytes[1], &header, sections[1])?;
    let blocks = decode_blocks(&section_bytes[2], &header, sections[2])?;
    validate_group_block_map(&columns, &row_groups, &blocks)?;
    validate_column_block_map(&columns, &row_groups, &blocks)?;
    let statistics = decode_statistics(
        &section_bytes[3],
        &section_bytes[4],
        usize::try_from(sections[3].item_count())
            .map_err(|_| invalid("statistics count does not fit this platform"))?,
        &columns,
        &row_groups,
        &blocks,
    )?;
    let cursor = validate_source_topology(&sections, &blocks, footer_start)?;
    if cursor != footer_start {
        return Err(invalid("artifact has bytes outside declared ranges"));
    }

    Ok(OpenedDataArtifact::new(
        DataArtifactLayout::new(
            expected, header, sections, columns, row_groups, statistics, blocks,
        ),
        metrics,
    ))
}

pub fn read_data_block<'a>(
    bytes: &'a [u8],
    layout: &DataArtifactLayout,
    block_index: usize,
) -> FormatResult<&'a [u8]> {
    if bytes.len() as u64 != layout.reference().byte_length() {
        return Err(invalid(
            "block source length differs from artifact identity",
        ));
    }
    let block = layout
        .blocks()
        .get(block_index)
        .ok_or_else(|| invalid("block index is out of range"))?;
    let start = usize::try_from(block.offset())
        .map_err(|_| invalid("block offset does not fit this platform"))?;
    let length = usize::try_from(block.stored_length())
        .map_err(|_| invalid("block length does not fit this platform"))?;
    let end = start
        .checked_add(length)
        .ok_or_else(|| invalid("block range overflows"))?;
    let stored = bytes
        .get(start..end)
        .ok_or_else(|| invalid("block range is outside source bytes"))?;
    if radixdb_core::crc32_ieee(stored) != block.stored_crc32() {
        return Err(FormatError::DataArtifactChecksumMismatch { scope: "block" });
    }
    Ok(stored)
}

pub fn read_data_block_from_source(
    source: &(impl ArtifactSource + ?Sized),
    layout: &DataArtifactLayout,
    block_index: usize,
) -> FormatResult<Vec<u8>> {
    if source.byte_length()? != layout.reference().byte_length() {
        return Err(invalid(
            "block source length differs from artifact identity",
        ));
    }
    let block = layout
        .blocks()
        .get(block_index)
        .ok_or_else(|| invalid("block index is out of range"))?;
    let length = usize::try_from(block.stored_length())
        .map_err(|_| invalid("block length does not fit this platform"))?;
    let mut stored = vec![0_u8; length];
    source.read_exact_at(block.offset(), &mut stored)?;
    if radixdb_core::crc32_ieee(&stored) != block.stored_crc32() {
        return Err(FormatError::DataArtifactChecksumMismatch { scope: "block" });
    }
    Ok(stored)
}

pub fn read_data_row_ids(
    bytes: &[u8],
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
) -> FormatResult<Vec<u64>> {
    let group = layout
        .row_groups()
        .get(row_group_ordinal as usize)
        .copied()
        .filter(|group| group.group_ordinal() == row_group_ordinal)
        .ok_or_else(|| invalid("row-group ordinal is out of range"))?;
    let start = group.first_block_index() as usize;
    let end = start
        .checked_add(group.block_count() as usize)
        .ok_or_else(|| invalid("row-group block range overflows"))?;
    let group_blocks = layout
        .blocks()
        .get(start..end)
        .ok_or_else(|| invalid("row-group block range is outside directory"))?;
    let (block_index, block) = group_blocks
        .iter()
        .enumerate()
        .find(|(_, block)| block.kind() == DataBlockKind::RowIds)
        .map(|(index, block)| (start + index, block))
        .ok_or_else(|| invalid("row group has no row-ID block"))?;
    let stored = read_data_block(bytes, layout, block_index)?;
    decode_row_id_payload(stored, block, group)
}

pub fn read_data_column(
    bytes: &[u8],
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
    column_ordinal: u32,
) -> FormatResult<Vec<Value>> {
    let group = layout
        .row_groups()
        .get(row_group_ordinal as usize)
        .copied()
        .filter(|group| group.group_ordinal() == row_group_ordinal)
        .ok_or_else(|| invalid("row-group ordinal is out of range"))?;
    let column = layout
        .columns()
        .get(column_ordinal as usize)
        .copied()
        .filter(|column| column.ordinal() == column_ordinal)
        .ok_or_else(|| invalid("column ordinal is out of range"))?;
    let start = group.first_block_index() as usize;
    let end = start
        .checked_add(group.block_count() as usize)
        .ok_or_else(|| invalid("row-group block range overflows"))?;
    let group_blocks = layout
        .blocks()
        .get(start..end)
        .ok_or_else(|| invalid("row-group block range is outside directory"))?;
    let (block_index, block) = group_blocks
        .iter()
        .enumerate()
        .find(|(_, block)| {
            block.kind() == DataBlockKind::Column && block.column_ordinal() == column_ordinal
        })
        .map(|(index, block)| (start + index, block))
        .ok_or_else(|| invalid("row group has no block for column"))?;
    let stored = read_data_block(bytes, layout, block_index)?;
    decode_column_payload(stored, block, group, column)
}

pub fn read_data_bloom(
    bytes: &[u8],
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
    column_ordinal: u32,
) -> FormatResult<Option<DataBloom>> {
    layout
        .row_groups()
        .get(row_group_ordinal as usize)
        .filter(|group| group.group_ordinal() == row_group_ordinal)
        .ok_or_else(|| invalid("row-group ordinal is out of range"))?;
    let column = layout
        .columns()
        .get(column_ordinal as usize)
        .copied()
        .filter(|column| column.ordinal() == column_ordinal)
        .ok_or_else(|| invalid("column ordinal is out of range"))?;
    let statistics = layout.statistics().iter().find(|statistics| {
        statistics.row_group_ordinal() == row_group_ordinal
            && statistics.column_ordinal() == column_ordinal
    });
    let Some(block_index) = statistics.and_then(|statistics| statistics.bloom_block_index()) else {
        return Ok(None);
    };
    let block = layout
        .blocks()
        .get(block_index as usize)
        .ok_or_else(|| invalid("bloom block index is out of range"))?;
    let stored = read_data_block(bytes, layout, block_index as usize)?;
    decode_bloom_payload(stored, block, column).map(Some)
}

pub fn read_data_row_ids_from_source(
    source: &(impl ArtifactSource + ?Sized),
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
) -> FormatResult<Vec<u64>> {
    let group = find_group(layout, row_group_ordinal)?;
    let (block_index, block) = find_group_block(layout, group, DataBlockKind::RowIds, u32::MAX)?;
    let stored = read_data_block_from_source(source, layout, block_index)?;
    decode_row_id_payload(&stored, block, *group)
}

pub fn read_data_column_from_source(
    source: &(impl ArtifactSource + ?Sized),
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
    column_ordinal: u32,
) -> FormatResult<Vec<Value>> {
    let group = find_group(layout, row_group_ordinal)?;
    let column = find_column(layout, column_ordinal)?;
    let (block_index, block) =
        find_group_block(layout, group, DataBlockKind::Column, column_ordinal)?;
    let stored = read_data_block_from_source(source, layout, block_index)?;
    decode_column_payload(&stored, block, *group, *column)
}

pub(crate) fn read_data_typed_column_from_source(
    source: &(impl ArtifactSource + ?Sized),
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
    column_ordinal: u32,
) -> FormatResult<DecodedColumn> {
    let group = find_group(layout, row_group_ordinal)?;
    let column = find_column(layout, column_ordinal)?;
    let (block_index, block) =
        find_group_block(layout, group, DataBlockKind::Column, column_ordinal)?;
    let stored = read_data_block_from_source(source, layout, block_index)?;
    decode_typed_column_payload(&stored, block, *group, *column)
}

pub fn read_data_bloom_from_source(
    source: &(impl ArtifactSource + ?Sized),
    layout: &DataArtifactLayout,
    row_group_ordinal: u32,
    column_ordinal: u32,
) -> FormatResult<Option<DataBloom>> {
    find_group(layout, row_group_ordinal)?;
    let column = find_column(layout, column_ordinal)?;
    let statistics = layout.statistics().iter().find(|statistics| {
        statistics.row_group_ordinal() == row_group_ordinal
            && statistics.column_ordinal() == column_ordinal
    });
    let Some(block_index) = statistics.and_then(|statistics| statistics.bloom_block_index()) else {
        return Ok(None);
    };
    let block = layout
        .blocks()
        .get(block_index as usize)
        .ok_or_else(|| invalid("bloom block index is out of range"))?;
    let stored = read_data_block_from_source(source, layout, block_index as usize)?;
    decode_bloom_payload(&stored, block, *column).map(Some)
}

pub(crate) fn encode_header(
    output: &mut [u8],
    header: DataArtifactHeader,
    file_length: usize,
) -> FormatResult<()> {
    output[..8].copy_from_slice(&MAGIC);
    put_u16(output, 8, FORMAT_MAJOR);
    put_u16(output, 10, FORMAT_MINOR);
    put_u32(output, 12, DATA_HEADER_BYTES as u32);
    put_u64(output, 16, file_length as u64);
    output[24..40].copy_from_slice(header.artifact_id().as_bytes());
    output[40..56].copy_from_slice(header.database_id().as_bytes());
    output[56..72].copy_from_slice(header.table_id().as_bytes());
    output[72..88].copy_from_slice(header.segment_id().as_bytes());
    put_u64(output, 88, header.creation_generation().get());
    put_u64(output, 96, header.catalog_generation().get());
    put_u64(output, 104, header.min_transaction_id());
    put_u64(output, 112, header.max_transaction_id());
    put_u64(output, 120, header.row_count());
    put_u32(output, 128, header.column_count());
    put_u32(output, 132, header.row_group_count());
    put_u32(output, 136, DATA_SECTION_COUNT as u32);
    put_u32(
        output,
        140,
        u32::from(header.segment_kind() == SegmentKind::Tombstones),
    );
    put_u64(output, 144, SECTION_DIRECTORY_OFFSET as u64);
    put_u64(output, 152, SECTION_DIRECTORY_BYTES as u64);
    put_u64(output, 160, header.created_unix_ns());
    Ok(())
}

fn decode_header(bytes: &[u8], file_length: u64) -> FormatResult<DataArtifactHeader> {
    if bytes[..8] != MAGIC {
        return Err(invalid("magic mismatch"));
    }
    let major = read_u16(bytes, 8);
    let minor = read_u16(bytes, 10);
    if (major, minor) != (FORMAT_MAJOR, FORMAT_MINOR) {
        return Err(FormatError::UnsupportedFormatVersion {
            owner: "data artifact",
            major,
            minor,
        });
    }
    if read_u32(bytes, 12) != DATA_HEADER_BYTES as u32 {
        return Err(invalid("header length is not 256"));
    }
    if read_u64(bytes, 16) != file_length {
        return Err(invalid("header file length mismatch"));
    }
    if read_u32(bytes, 136) != DATA_SECTION_COUNT as u32 {
        return Err(invalid("section count is not five"));
    }
    let flags = read_u32(bytes, 140);
    if flags & !1 != 0 {
        return Err(invalid("unknown header flags"));
    }
    if read_u64(bytes, 144) != SECTION_DIRECTORY_OFFSET as u64
        || read_u64(bytes, 152) != SECTION_DIRECTORY_BYTES as u64
    {
        return Err(invalid("section directory is not canonical"));
    }
    require_zero(bytes, 168..248, "reserved header bytes are non-zero")?;
    require_zero(bytes, 252..256, "reserved header trailer is non-zero")?;
    if read_u32(bytes, 248) != radixdb_core::crc32_ieee(&bytes[..248]) {
        return Err(FormatError::DataArtifactChecksumMismatch { scope: "header" });
    }
    DataArtifactHeader::new(
        ArtifactId::from_bytes(read_array(bytes, 24))?,
        DatabaseId::from_bytes(read_array(bytes, 40))?,
        ObjectId::from_user_bytes(read_array(bytes, 56))
            .map_err(|_| invalid("table ID is not a user catalog identity"))?,
        SegmentId::from_bytes(read_array(bytes, 72))?,
        DatabaseGeneration::new(read_u64(bytes, 88))?,
        CatalogGeneration::new(read_u64(bytes, 96))?,
        read_u64(bytes, 104),
        read_u64(bytes, 112),
        read_u64(bytes, 120),
        read_u32(bytes, 128),
        read_u32(bytes, 132),
        if flags == 1 {
            SegmentKind::Tombstones
        } else {
            SegmentKind::Rows
        },
        read_u64(bytes, 160),
    )
}

fn validate_file_shell(bytes: &[u8], expected: ArtifactRef) -> FormatResult<()> {
    if expected.kind() != ArtifactKind::Data {
        return Err(invalid("expected reference is not a data artifact"));
    }
    if bytes.len() < BODY_START + DATA_FOOTER_BYTES {
        return Err(invalid("file is shorter than fixed metadata shell"));
    }
    if bytes.len() as u64 > MAX_ARTIFACT_FILE_BYTES {
        return Err(limit(
            "file bytes",
            bytes.len() as u64,
            MAX_ARTIFACT_FILE_BYTES,
        ));
    }
    if bytes.len() as u64 != expected.byte_length() {
        return Err(invalid("file length differs from manifest reference"));
    }
    let footer = bytes.len() - DATA_FOOTER_BYTES;
    if bytes[footer..footer + 8] != FOOTER_MAGIC {
        return Err(invalid("footer magic mismatch"));
    }
    if read_u64(bytes, footer + 8) != bytes.len() as u64 {
        return Err(invalid("footer file length mismatch"));
    }
    if bytes[footer + 16..] != *expected.body_sha256() {
        return Err(FormatError::DataArtifactChecksumMismatch {
            scope: "footer identity",
        });
    }
    Ok(())
}

fn validate_source_length(file_length: u64, expected: ArtifactRef) -> FormatResult<()> {
    if expected.kind() != ArtifactKind::Data {
        return Err(invalid("expected reference is not a data artifact"));
    }
    let minimum_length = (BODY_START + DATA_FOOTER_BYTES) as u64;
    if file_length < minimum_length {
        return Err(invalid("file is shorter than fixed metadata shell"));
    }
    if file_length > MAX_ARTIFACT_FILE_BYTES {
        return Err(limit("file bytes", file_length, MAX_ARTIFACT_FILE_BYTES));
    }
    if file_length != expected.byte_length() {
        return Err(invalid("file length differs from manifest reference"));
    }
    Ok(())
}

fn read_source(
    source: &(impl ArtifactSource + ?Sized),
    offset: u64,
    destination: &mut [u8],
    metrics: &mut DataOpenMetrics,
) -> FormatResult<()> {
    if destination.is_empty() {
        return Ok(());
    }
    source.read_exact_at(offset, destination)?;
    metrics.record_read(destination.len() as u64)
}

fn validate_source_footer(
    footer: &[u8; DATA_FOOTER_BYTES],
    file_length: u64,
    expected: ArtifactRef,
) -> FormatResult<()> {
    if footer[..8] != FOOTER_MAGIC {
        return Err(invalid("footer magic mismatch"));
    }
    if read_u64(footer, 8) != file_length {
        return Err(invalid("footer file length mismatch"));
    }
    if footer[16..] != *expected.body_sha256() {
        return Err(FormatError::DataArtifactChecksumMismatch {
            scope: "footer identity",
        });
    }
    Ok(())
}

fn validate_expected_header(header: DataArtifactHeader, expected: ArtifactRef) -> FormatResult<()> {
    if header.artifact_id() != expected.id() {
        return Err(invalid("artifact ID differs from manifest reference"));
    }
    if header.creation_generation() != expected.creation_generation() {
        return Err(invalid(
            "creation generation differs from manifest reference",
        ));
    }
    Ok(())
}

fn decode_source_sections(
    prefix: &[u8; BODY_START],
    header: &DataArtifactHeader,
    footer_start: u64,
) -> FormatResult<[DataSectionRef; DATA_SECTION_COUNT]> {
    let mut sections =
        [DataSectionRef::new(DataSectionKind::ColumnDirectory, 0, 0, 0, 0); DATA_SECTION_COUNT];
    let mut directory_bytes = SECTION_DIRECTORY_BYTES as u64;

    for (index, expected_kind) in DataSectionKind::ALL.into_iter().enumerate() {
        let entry_offset = SECTION_DIRECTORY_OFFSET + index * DATA_SECTION_REF_BYTES;
        let entry = &prefix[entry_offset..entry_offset + DATA_SECTION_REF_BYTES];
        let section = decode_section_ref(entry, expected_kind)?;
        validate_section_count(header, section)?;
        if expected_kind != DataSectionKind::StatisticsValues {
            directory_bytes = directory_bytes
                .checked_add(section.stored_length())
                .ok_or_else(|| invalid("directory byte count overflows"))?;
        }
        validate_source_bounds(
            footer_start,
            section.offset(),
            section.stored_length(),
            "section range",
        )?;
        sections[index] = section;
    }
    if directory_bytes > MAX_DATA_DIRECTORY_BYTES {
        return Err(limit(
            "directory bytes",
            directory_bytes,
            MAX_DATA_DIRECTORY_BYTES,
        ));
    }
    Ok(sections)
}

fn validate_slice_topology(
    bytes: &[u8],
    sections: &[DataSectionRef; DATA_SECTION_COUNT],
    blocks: &[DataBlockRef],
    footer_start: usize,
) -> FormatResult<usize> {
    let mut cursor = BODY_START;
    for section in &sections[..4] {
        validate_canonical_range(
            bytes,
            &mut cursor,
            footer_start,
            section.offset(),
            section.stored_length(),
            "directory section range",
        )?;
    }
    for block in blocks {
        validate_canonical_range(
            bytes,
            &mut cursor,
            footer_start,
            block.offset(),
            block.stored_length(),
            "block range",
        )?;
    }
    let statistics_values = sections[4];
    validate_canonical_range(
        bytes,
        &mut cursor,
        footer_start,
        statistics_values.offset(),
        statistics_values.stored_length(),
        "statistics value section range",
    )?;
    Ok(cursor)
}

fn validate_source_topology(
    sections: &[DataSectionRef; DATA_SECTION_COUNT],
    blocks: &[DataBlockRef],
    footer_start: u64,
) -> FormatResult<u64> {
    let mut cursor = BODY_START as u64;
    for section in &sections[..4] {
        validate_source_range(
            &mut cursor,
            footer_start,
            section.offset(),
            section.stored_length(),
            "directory section range",
        )?;
    }
    for block in blocks {
        validate_source_range(
            &mut cursor,
            footer_start,
            block.offset(),
            block.stored_length(),
            "block range",
        )?;
    }
    let statistics_values = sections[4];
    validate_source_range(
        &mut cursor,
        footer_start,
        statistics_values.offset(),
        statistics_values.stored_length(),
        "statistics value section range",
    )?;
    Ok(cursor)
}

fn validate_source_bounds(
    footer_start: u64,
    offset: u64,
    length: u64,
    detail: &'static str,
) -> FormatResult<()> {
    if length == 0 {
        return if offset == 0 {
            Ok(())
        } else {
            Err(invalid("empty range has non-zero offset"))
        };
    }
    let end = offset.checked_add(length).ok_or_else(|| invalid(detail))?;
    if offset < BODY_START as u64 || !offset.is_multiple_of(8) || end > footer_start {
        return Err(invalid(detail));
    }
    Ok(())
}

fn metadata_allocation_bound(sections: &[DataSectionRef; DATA_SECTION_COUNT]) -> FormatResult<u64> {
    let columns = sections[0]
        .item_count()
        .checked_mul(size_of::<DataColumn>() as u64)
        .ok_or_else(|| invalid("column allocation accounting overflows"))?;
    let row_groups = sections[1]
        .item_count()
        .checked_mul(size_of::<DataRowGroup>() as u64)
        .ok_or_else(|| invalid("row-group allocation accounting overflows"))?;
    let blocks = sections[2]
        .item_count()
        .checked_mul(size_of::<DataBlockRef>() as u64)
        .ok_or_else(|| invalid("block allocation accounting overflows"))?;
    let statistics = sections[3]
        .item_count()
        .checked_mul(size_of::<super::statistics::DataStatistics>() as u64)
        .ok_or_else(|| invalid("statistics allocation accounting overflows"))?;

    let mut total = 0_u64;
    for section in sections {
        total = total
            .checked_add(section.stored_length())
            .ok_or_else(|| invalid("metadata section allocation accounting overflows"))?;
    }
    for decoded in [columns, row_groups, blocks, statistics] {
        total = total
            .checked_add(decoded)
            .ok_or_else(|| invalid("decoded metadata allocation accounting overflows"))?;
    }

    // Decoded min/max values may own copies of the statistics value bytes.
    // Account the complete section again instead of depending on Value's
    // current heap representation. Vec<bool> bloom ownership bookkeeping is
    // conservatively charged at one byte per block.
    total = total
        .checked_add(sections[4].stored_length())
        .and_then(|value| value.checked_add(sections[2].item_count()))
        .ok_or_else(|| invalid("variable metadata allocation accounting overflows"))?;
    Ok(total)
}

fn validate_source_range(
    cursor: &mut u64,
    footer_start: u64,
    offset: u64,
    length: u64,
    detail: &'static str,
) -> FormatResult<()> {
    if length == 0 {
        if offset != 0 {
            return Err(invalid("empty range has non-zero offset"));
        }
        return Ok(());
    }
    let aligned = cursor
        .checked_add(7)
        .map(|value| value & !7)
        .ok_or_else(|| invalid("range alignment overflows"))?;
    let end = offset.checked_add(length).ok_or_else(|| invalid(detail))?;
    if offset != aligned || offset < BODY_START as u64 || end > footer_start {
        return Err(invalid(detail));
    }
    *cursor = end;
    Ok(())
}

fn find_group(layout: &DataArtifactLayout, row_group_ordinal: u32) -> FormatResult<&DataRowGroup> {
    layout
        .row_groups()
        .get(row_group_ordinal as usize)
        .filter(|group| group.group_ordinal() == row_group_ordinal)
        .ok_or_else(|| invalid("row-group ordinal is out of range"))
}

fn find_column(layout: &DataArtifactLayout, column_ordinal: u32) -> FormatResult<&DataColumn> {
    layout
        .columns()
        .get(column_ordinal as usize)
        .filter(|column| column.ordinal() == column_ordinal)
        .ok_or_else(|| invalid("column ordinal is out of range"))
}

fn find_group_block<'a>(
    layout: &'a DataArtifactLayout,
    group: &DataRowGroup,
    kind: DataBlockKind,
    column_ordinal: u32,
) -> FormatResult<(usize, &'a DataBlockRef)> {
    let start = group.first_block_index() as usize;
    let end = start
        .checked_add(group.block_count() as usize)
        .ok_or_else(|| invalid("row-group block range overflows"))?;
    let group_blocks = layout
        .blocks()
        .get(start..end)
        .ok_or_else(|| invalid("row-group block range is outside directory"))?;
    group_blocks
        .iter()
        .enumerate()
        .find(|(_, block)| {
            block.kind() == kind
                && (kind == DataBlockKind::RowIds || block.column_ordinal() == column_ordinal)
        })
        .map(|(index, block)| (start + index, block))
        .ok_or_else(|| invalid("row group has no requested block"))
}

fn section_slice(bytes: &[u8], section: DataSectionRef) -> FormatResult<&[u8]> {
    if section.stored_length() == 0 {
        return Ok(&[]);
    }
    let start = usize::try_from(section.offset())
        .map_err(|_| invalid("section offset does not fit this platform"))?;
    let length = usize::try_from(section.stored_length())
        .map_err(|_| invalid("section length does not fit this platform"))?;
    let end = start
        .checked_add(length)
        .ok_or_else(|| invalid("section range overflows"))?;
    bytes
        .get(start..end)
        .ok_or_else(|| invalid("section range is outside artifact"))
}

pub(crate) fn encode_section_ref(
    entry: &mut [u8],
    kind: DataSectionKind,
    range: &Range<usize>,
    item_count: u64,
    stored_crc32: u32,
) -> FormatResult<()> {
    put_u16(entry, 0, kind.tag());
    put_u16(entry, 2, 1);
    if range.is_empty() {
        if item_count != 0 {
            return Err(invalid("empty section has non-zero item count"));
        }
        return Ok(());
    }
    put_u64(entry, 8, range.start as u64);
    put_u64(entry, 16, range.len() as u64);
    put_u64(entry, 24, range.len() as u64);
    put_u64(entry, 32, item_count);
    put_u32(entry, 40, stored_crc32);
    Ok(())
}

fn decode_section_ref(
    entry: &[u8],
    expected_kind: DataSectionKind,
) -> FormatResult<DataSectionRef> {
    if read_u16(entry, 0) != expected_kind.tag() {
        return Err(invalid("section kind/order mismatch"));
    }
    if read_u16(entry, 2) != 1 {
        return Err(invalid("unsupported section version"));
    }
    if read_u32(entry, 4) != 0 {
        return Err(invalid("unknown section flags"));
    }
    require_zero(entry, 44..48, "section reserved bytes are non-zero")?;
    let offset = read_u64(entry, 8);
    let stored_length = read_u64(entry, 16);
    let logical_length = read_u64(entry, 24);
    let item_count = read_u64(entry, 32);
    let stored_crc32 = read_u32(entry, 40);
    if stored_length == 0 {
        if offset != 0 || logical_length != 0 || item_count != 0 || stored_crc32 != 0 {
            return Err(invalid("empty section reference is not canonical"));
        }
    } else if logical_length != stored_length {
        return Err(invalid("metadata section is unexpectedly compressed"));
    }
    Ok(DataSectionRef::new(
        expected_kind,
        offset,
        stored_length,
        item_count,
        stored_crc32,
    ))
}

fn validate_section_count(
    header: &DataArtifactHeader,
    section: DataSectionRef,
) -> FormatResult<()> {
    let (expected_count, width) = match section.kind() {
        DataSectionKind::ColumnDirectory => (u64::from(header.column_count()), COLUMN_ENTRY_BYTES),
        DataSectionKind::RowGroupDirectory => {
            (u64::from(header.row_group_count()), ROW_GROUP_ENTRY_BYTES)
        }
        DataSectionKind::BlockDirectory => {
            if section.item_count() > MAX_BLOCKS_PER_DATA_ARTIFACT {
                return Err(limit(
                    "block count",
                    section.item_count(),
                    MAX_BLOCKS_PER_DATA_ARTIFACT,
                ));
            }
            (section.item_count(), DATA_BLOCK_REF_BYTES as u64)
        }
        DataSectionKind::StatisticsDirectory => {
            let maximum = u64::from(header.column_count())
                .checked_mul(u64::from(header.row_group_count()))
                .ok_or_else(|| invalid("statistics count multiplication overflows"))?;
            if section.item_count() > maximum {
                return Err(limit(
                    "statistics entry count",
                    section.item_count(),
                    maximum,
                ));
            }
            (section.item_count(), STATISTICS_ENTRY_BYTES as u64)
        }
        DataSectionKind::StatisticsValues => {
            if section.stored_length() > MAX_STATISTICS_VALUES_BYTES {
                return Err(limit(
                    "statistics values bytes",
                    section.stored_length(),
                    MAX_STATISTICS_VALUES_BYTES,
                ));
            }
            if section.item_count() != section.stored_length() {
                return Err(invalid(
                    "statistics values item count is not its byte length",
                ));
            }
            return Ok(());
        }
    };
    if section.item_count() != expected_count {
        return Err(invalid("section item count differs from header"));
    }
    let expected_length = expected_count
        .checked_mul(width)
        .ok_or_else(|| invalid("section length multiplication overflows"))?;
    if section.stored_length() != expected_length {
        return Err(invalid("section length differs from fixed entry width"));
    }
    Ok(())
}

fn decode_block_ref(entry: &[u8]) -> FormatResult<DataBlockRef> {
    let flags = read_u32(entry, 12);
    if flags & !0xff != 0 {
        return Err(invalid("unknown block flags"));
    }
    require_zero(entry, 52..64, "block reserved bytes are non-zero")?;
    DataBlockRef::new(
        DataBlockKind::from_tag(read_u16(entry, 0))?,
        DataPhysicalCodec::from_tag(read_u16(entry, 2))?,
        read_u32(entry, 4),
        read_u32(entry, 8),
        DataLayout::from_tag(flags as u8)?,
        read_u64(entry, 16),
        read_u64(entry, 24),
        read_u64(entry, 32),
        read_u64(entry, 40),
        read_u32(entry, 48),
    )
}

fn validate_block_against_header(
    header: &DataArtifactHeader,
    block: &DataBlockRef,
) -> FormatResult<()> {
    validate_kind_layout(block.kind(), block.layout(), block.column_ordinal())?;
    validate_block_lengths(block.codec(), block.stored_length(), block.logical_length())?;
    if block.row_group_ordinal() >= header.row_group_count() {
        return Err(invalid("block row-group ordinal is out of range"));
    }
    if block.kind() != DataBlockKind::RowIds && block.column_ordinal() >= header.column_count() {
        return Err(invalid("block column ordinal is out of range"));
    }
    Ok(())
}

pub(crate) fn encode_columns(columns: &[DataColumn]) -> Vec<u8> {
    let mut output = vec![0_u8; columns.len() * COLUMN_ENTRY_BYTES as usize];
    for (index, column) in columns.iter().copied().enumerate() {
        let offset = index * COLUMN_ENTRY_BYTES as usize;
        let entry = &mut output[offset..offset + COLUMN_ENTRY_BYTES as usize];
        entry[..16].copy_from_slice(column.column_id().as_bytes());
        put_u32(entry, 16, column.ordinal());
        put_u16(entry, 20, column.data_type().descriptor_marker());
        put_u16(entry, 22, column.data_type().descriptor_version());
        put_u32(entry, 24, u32::from(column.nullable()));
        put_u32(entry, 28, column.data_type().parameter_1());
        put_u32(entry, 32, column.data_type().parameter_2());
        put_u32(entry, 36, column.first_block_index());
        put_u32(entry, 40, column.block_count());
        put_u32(entry, 44, column.statistics_entry_index());
        entry[48..64].copy_from_slice(&column.data_type().collation_id());
    }
    output
}

fn decode_columns(
    bytes: &[u8],
    section: DataSectionRef,
    statistics_count: u64,
) -> FormatResult<Vec<DataColumn>> {
    let count = usize::try_from(section.item_count())
        .map_err(|_| invalid("column count does not fit this platform"))?;
    let mut columns = Vec::with_capacity(count);
    let mut column_ids = Vec::with_capacity(count);
    for index in 0..count {
        let offset = index * COLUMN_ENTRY_BYTES as usize;
        let entry = &bytes[offset..offset + COLUMN_ENTRY_BYTES as usize];
        let column_id = ObjectId::from_user_bytes(read_array(entry, 0))
            .map_err(|_| invalid("column ID is not a user catalog identity"))?;
        column_ids.push(column_id);
        let ordinal = read_u32(entry, 16);
        if ordinal != index as u32 {
            return Err(invalid("column ordinal is not contiguous"));
        }
        let logical_type_marker = read_u16(entry, 20);
        let flags = read_u32(entry, 24);
        if flags & !1 != 0 {
            return Err(invalid("unknown column flags"));
        }
        let data_type = if logical_type_marker == 0xffff {
            if read_u16(entry, 22) != 2 || read_u32(entry, 32) != 0 {
                return Err(invalid("external column type descriptor is invalid"));
            }
            let type_object_id = ObjectId::from_user_bytes(read_array(entry, 48))
                .map_err(|_| invalid("external type ID is not a user catalog identity"))?;
            CatalogDataType::external(type_object_id, read_u32(entry, 28))
                .map_err(|_| invalid("external column type descriptor is invalid"))?
        } else {
            let logical_type_tag = u8::try_from(logical_type_marker)
                .map_err(|_| invalid("column logical type tag exceeds u8"))?;
            let logical_type = DataType::from_u8(logical_type_tag)
                .ok_or_else(|| invalid("column logical type tag is unknown"))?;
            CatalogDataType::from_fields(
                logical_type,
                read_u16(entry, 22),
                0,
                read_u32(entry, 28),
                read_u32(entry, 32),
                read_array(entry, 48),
            )
            .map_err(|_| invalid("column type descriptor is invalid"))?
        };
        let statistics_entry_index = read_u32(entry, 44);
        if statistics_entry_index != u32::MAX
            && u64::from(statistics_entry_index) >= statistics_count
        {
            return Err(invalid("column statistics index is out of range"));
        }
        columns.push(DataColumn::new(
            column_id,
            ordinal,
            data_type,
            flags == 1,
            read_u32(entry, 36),
            read_u32(entry, 40),
            statistics_entry_index,
        ));
    }
    column_ids.sort_unstable();
    if column_ids.windows(2).any(|pair| pair[0] == pair[1]) {
        return Err(invalid("column IDs are not unique"));
    }
    Ok(columns)
}

pub(crate) fn encode_row_groups(groups: &[DataRowGroup]) -> Vec<u8> {
    let mut output = vec![0_u8; groups.len() * ROW_GROUP_ENTRY_BYTES as usize];
    for (index, group) in groups.iter().copied().enumerate() {
        let offset = index * ROW_GROUP_ENTRY_BYTES as usize;
        let entry = &mut output[offset..offset + ROW_GROUP_ENTRY_BYTES as usize];
        put_u32(entry, 0, group.group_ordinal());
        put_u32(entry, 4, group.row_count());
        put_u64(entry, 8, group.first_row_ordinal());
        put_u64(entry, 16, group.min_row_id());
        put_u64(entry, 24, group.max_row_id());
        put_u32(entry, 32, group.first_block_index());
        put_u32(entry, 36, group.block_count());
    }
    output
}

fn decode_row_groups(
    bytes: &[u8],
    header: &DataArtifactHeader,
    section: DataSectionRef,
) -> FormatResult<Vec<DataRowGroup>> {
    let count = usize::try_from(section.item_count())
        .map_err(|_| invalid("row-group count does not fit this platform"))?;
    let mut groups = Vec::with_capacity(count);
    let mut expected_first_row = 0_u64;
    for index in 0..count {
        let offset = index * ROW_GROUP_ENTRY_BYTES as usize;
        let entry = &bytes[offset..offset + ROW_GROUP_ENTRY_BYTES as usize];
        if read_u32(entry, 40) != 0 || read_u32(entry, 44) != 0 {
            return Err(invalid("row-group flags/reserved bytes are non-zero"));
        }
        let group = DataRowGroup::new(
            read_u32(entry, 0),
            read_u32(entry, 4),
            read_u64(entry, 8),
            read_u64(entry, 16),
            read_u64(entry, 24),
            read_u32(entry, 32),
            read_u32(entry, 36),
        )?;
        if group.group_ordinal() != index as u32 {
            return Err(invalid("row-group ordinal is not contiguous"));
        }
        if group.first_row_ordinal() != expected_first_row {
            return Err(invalid("row-group row ordinals are not contiguous"));
        }
        expected_first_row = expected_first_row
            .checked_add(u64::from(group.row_count()))
            .ok_or_else(|| invalid("row-group row count sum overflows"))?;
        groups.push(group);
    }
    if expected_first_row != header.row_count() {
        return Err(invalid("row-group counts do not sum to header row count"));
    }
    Ok(groups)
}

pub(crate) fn encode_block_ref(entry: &mut [u8], block: &DataBlockRef) {
    debug_assert_eq!(entry.len(), DATA_BLOCK_REF_BYTES);
    put_u16(entry, 0, block.kind().tag());
    put_u16(entry, 2, block.codec().tag());
    put_u32(entry, 4, block.column_ordinal());
    put_u32(entry, 8, block.row_group_ordinal());
    put_u32(entry, 12, u32::from(block.layout().tag()));
    put_u64(entry, 16, block.offset());
    put_u64(entry, 24, block.stored_length());
    put_u64(entry, 32, block.logical_length());
    put_u64(entry, 40, block.item_count());
    put_u32(entry, 48, block.stored_crc32());
}

fn decode_blocks(
    bytes: &[u8],
    header: &DataArtifactHeader,
    section: DataSectionRef,
) -> FormatResult<Vec<DataBlockRef>> {
    let count = usize::try_from(section.item_count())
        .map_err(|_| invalid("block count does not fit this platform"))?;
    let mut blocks = Vec::with_capacity(count);
    let mut previous_key = None;
    for index in 0..count {
        let offset = index * DATA_BLOCK_REF_BYTES;
        let block = decode_block_ref(&bytes[offset..offset + DATA_BLOCK_REF_BYTES])?;
        validate_block_against_header(header, &block)?;
        let key = (
            block.row_group_ordinal(),
            block.kind().tag(),
            block.column_ordinal(),
        );
        if previous_key.is_some_and(|previous| previous >= key) {
            return Err(invalid("block directory order is not canonical"));
        }
        previous_key = Some(key);
        blocks.push(block);
    }
    Ok(blocks)
}

fn validate_group_block_map(
    columns: &[DataColumn],
    groups: &[DataRowGroup],
    blocks: &[DataBlockRef],
) -> FormatResult<()> {
    let mut expected_first_block = 0_usize;
    for group in groups {
        if group.first_block_index() as usize != expected_first_block {
            return Err(invalid("row-group block ranges are not contiguous"));
        }
        let end = expected_first_block
            .checked_add(group.block_count() as usize)
            .ok_or_else(|| invalid("row-group block range overflows"))?;
        let group_blocks = blocks
            .get(expected_first_block..end)
            .ok_or_else(|| invalid("row-group block range is outside directory"))?;
        if group_blocks
            .iter()
            .any(|block| block.row_group_ordinal() != group.group_ordinal())
        {
            return Err(invalid("row-group block range owns another group"));
        }
        let mut row_id_blocks = group_blocks
            .iter()
            .filter(|block| block.kind() == DataBlockKind::RowIds);
        let row_ids = row_id_blocks
            .next()
            .ok_or_else(|| invalid("row group has no row-ID block"))?;
        if row_id_blocks.next().is_some() {
            return Err(invalid("row group has multiple row-ID blocks"));
        }
        if row_ids.item_count() != u64::from(group.row_count()) {
            return Err(invalid("row-ID block count differs from row group"));
        }
        let mut seen_columns = vec![false; columns.len()];
        for block in group_blocks
            .iter()
            .filter(|block| block.kind() == DataBlockKind::Column)
        {
            if block.item_count() != u64::from(group.row_count()) {
                return Err(invalid("column block count differs from row group"));
            }
            let ordinal = block.column_ordinal() as usize;
            let seen = seen_columns
                .get_mut(ordinal)
                .ok_or_else(|| invalid("column block ordinal is out of range"))?;
            if *seen {
                return Err(invalid("row group has multiple blocks for one column"));
            }
            *seen = true;
        }
        if seen_columns.iter().any(|seen| !seen) {
            return Err(invalid("row group does not have one block per column"));
        }
        expected_first_block = end;
    }
    if expected_first_block != blocks.len() {
        return Err(invalid("block directory has unowned entries"));
    }
    Ok(())
}

fn validate_column_block_map(
    columns: &[DataColumn],
    groups: &[DataRowGroup],
    blocks: &[DataBlockRef],
) -> FormatResult<()> {
    let (first_block_indexes, block_counts) = collect_column_block_map(blocks, columns.len())?;
    for column in columns {
        let ordinal = column.ordinal() as usize;
        if first_block_indexes[ordinal] != column.first_block_index() {
            return Err(invalid("column first block index is not canonical"));
        }
        let block_count = block_counts[ordinal];
        if block_count != column.block_count() || block_count as usize != groups.len() {
            return Err(invalid("column block count differs from row-group count"));
        }
    }
    Ok(())
}

fn append_section(output: &mut Vec<u8>, bytes: &[u8]) -> FormatResult<Range<usize>> {
    if bytes.is_empty() {
        return Ok(0..0);
    }
    align_output(output);
    let start = output.len();
    output.extend_from_slice(bytes);
    Ok(start..output.len())
}

fn append_section_placeholder(
    output: &mut Vec<u8>,
    byte_length: usize,
) -> FormatResult<Range<usize>> {
    if byte_length == 0 {
        return Ok(0..0);
    }
    align_output(output);
    let start = output.len();
    let end = start
        .checked_add(byte_length)
        .ok_or_else(|| invalid("section allocation length overflows"))?;
    output.resize(end, 0);
    Ok(start..end)
}

fn align_output(output: &mut Vec<u8>) {
    let padding = (8 - output.len() % 8) % 8;
    output.resize(output.len() + padding, 0);
}

fn validate_canonical_range(
    bytes: &[u8],
    cursor: &mut usize,
    footer_start: usize,
    offset: u64,
    length: u64,
    detail: &'static str,
) -> FormatResult<Range<usize>> {
    if length == 0 {
        if offset != 0 {
            return Err(invalid("empty range has non-zero offset"));
        }
        return Ok(0..0);
    }
    let aligned = cursor
        .checked_add(7)
        .map(|value| value & !7)
        .ok_or_else(|| invalid("range alignment overflows"))?;
    if bytes[*cursor..aligned].iter().any(|byte| *byte != 0) {
        return Err(invalid("alignment padding is non-zero"));
    }
    let start = usize::try_from(offset).map_err(|_| invalid(detail))?;
    let length = usize::try_from(length).map_err(|_| invalid(detail))?;
    let end = start.checked_add(length).ok_or_else(|| invalid(detail))?;
    if start != aligned || start < BODY_START || end > footer_start {
        return Err(invalid(detail));
    }
    *cursor = end;
    Ok(start..end)
}

fn require_zero(bytes: &[u8], range: Range<usize>, detail: &'static str) -> FormatResult<()> {
    if bytes[range].iter().any(|byte| *byte != 0) {
        return Err(invalid(detail));
    }
    Ok(())
}

fn read_array<const N: usize>(bytes: &[u8], offset: usize) -> [u8; N] {
    bytes[offset..offset + N]
        .try_into()
        .expect("fixed data-artifact range was validated")
}

fn read_u16(bytes: &[u8], offset: usize) -> u16 {
    u16::from_le_bytes(read_array(bytes, offset))
}

fn read_u32(bytes: &[u8], offset: usize) -> u32 {
    u32::from_le_bytes(read_array(bytes, offset))
}

fn read_u64(bytes: &[u8], offset: usize) -> u64 {
    u64::from_le_bytes(read_array(bytes, offset))
}

fn put_u16(bytes: &mut [u8], offset: usize, value: u16) {
    bytes[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
}

fn put_u32(bytes: &mut [u8], offset: usize, value: u32) {
    bytes[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}

fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}