armdb 0.15.0

sharded bitcask key-value storage optimized for NVMe
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
//! The manifest: the only source of truth about what a segmented collection
//! consists of.

use std::path::Path;

use super::FormatFault;
use super::fs::SegFs;
use super::sidecar::OrderKind;
use crate::entry::SEQUENCE_MASK;
use crate::error::{DbError, DbResult};

pub(crate) const MANIFEST_NAME: &str = "MANIFEST";
pub(crate) const MANIFEST_TMP: &str = "MANIFEST.tmp";
pub(crate) const MANIFEST_MAGIC: [u8; 4] = *b"ASM1";
pub(crate) const MANIFEST_FORMAT_VERSION: u16 = 1;

const FIXED_LEN: usize = 72;
const GEN_RECORD_LEN: usize = 48;
const SEG_RECORD_LEN: usize = 120;
const CRC_LEN: usize = 4;

/// Most generations a manifest may list: the active one plus the seal queue.
pub(crate) const MAX_GENERATIONS: usize = 1024;
/// Most sealed segments a manifest may list. Each is a separate lookup
/// step, so a collection far past this is unusable long before the limit.
pub(crate) const MAX_SEGMENTS: usize = 65_536;
/// Largest manifest this build writes or reads. v1 records have fixed sizes
/// (a local segment carries no location payload), so the counts bound it.
pub(crate) const MAX_MANIFEST_LEN: u64 =
    (FIXED_LEN + MAX_GENERATIONS * GEN_RECORD_LEN + MAX_SEGMENTS * SEG_RECORD_LEN + CRC_LEN) as u64;

const LOCATION_LOCAL: u8 = 0;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum GenState {
    Active = 1,
    Frozen = 2,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct GenRecord {
    pub gen_id: u64,
    pub state: GenState,
    /// Shard count the generation's engine was created with. An existing
    /// generation is always opened with this, never with the current config.
    pub shard_count: u8,
    pub opened_at_ms: u64,
    /// `0` while the generation is active.
    pub frozen_at_ms: u64,
    pub min_gsn: u64,
    /// `0` while the generation is active.
    pub max_gsn: u64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum SegState {
    Sealed = 1,
    // 2 = Cold and 3 = Remote are reserved.
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Location {
    Local,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SegRecord {
    pub segment_id: u64,
    pub version: u32,
    pub state: SegState,
    pub order: OrderKind,
    pub format_version: u16,
    pub min_gsn: u64,
    pub max_gsn: u64,
    pub entries: u64,
    pub tombstones: u64,
    pub opened_at_ms: u64,
    pub frozen_at_ms: u64,
    pub sealed_at_ms: u64,
    pub sdat_len: u64,
    /// xxh3-64 of the whole file.
    pub sdat_checksum: u64,
    pub sidx_len: u64,
    /// xxh3-64 of the whole file.
    pub sidx_checksum: u64,
    pub typ_hash: u64,
    pub value_version: u16,
    pub location: Location,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Manifest {
    pub manifest_version: u64,
    pub key_len: u16,
    pub order: OrderKind,
    pub seed: u64,
    pub created_at_ms: u64,
    pub next_segment_id: u64,
    pub next_gen_id: u64,
    /// Greatest GSN ever frozen, sealed or dropped.
    pub gsn_floor: u64,
    /// Oldest first. At most one is active, and it is the last.
    pub generations: Vec<GenRecord>,
    /// Oldest first.
    pub segments: Vec<SegRecord>,
}

fn broken(what: &'static str) -> DbError {
    DbError::Internal(what)
}

impl Manifest {
    pub(crate) fn new(key_len: u16, seed: u64, created_at_ms: u64) -> Self {
        Self {
            manifest_version: 1,
            key_len,
            order: OrderKind::ByHash,
            seed,
            created_at_ms,
            next_segment_id: 1,
            next_gen_id: 1,
            gsn_floor: 0,
            generations: Vec::new(),
            segments: Vec::new(),
        }
    }

    pub(crate) fn active(&self) -> Option<&GenRecord> {
        self.generations
            .last()
            .filter(|g| g.state == GenState::Active)
    }

    pub(crate) fn oldest_frozen(&self) -> Option<&GenRecord> {
        self.generations
            .first()
            .filter(|g| g.state == GenState::Frozen)
    }

    pub(crate) fn frozen_count(&self) -> usize {
        self.generations
            .iter()
            .filter(|g| g.state == GenState::Frozen)
            .count()
    }

    /// Newest time any layer records: a freeze time, or an open time
    /// (including the active generation's). `0` when there is no layer.
    fn newest_layer_time_ms(&self) -> u64 {
        let from_generations = self
            .generations
            .iter()
            .map(|g| g.opened_at_ms.max(g.frozen_at_ms))
            .max();
        let from_segments = self
            .segments
            .iter()
            .map(|s| s.opened_at_ms.max(s.frozen_at_ms))
            .max();
        from_generations.max(from_segments).unwrap_or(0)
    }

    /// Invariant I7: a layer is never frozen earlier than the layer before
    /// it, nor earlier than it was opened, whatever the wall clock says.
    pub(crate) fn monotone_time(&self, now_ms: u64) -> u64 {
        now_ms.max(self.newest_layer_time_ms())
    }

    /// Everything that must hold for a manifest to describe a collection.
    pub(crate) fn check(&self) -> Result<(), String> {
        if self.key_len == 0 {
            return Err("key length is zero".into());
        }
        if self.manifest_version == 0 || self.next_segment_id == 0 || self.next_gen_id == 0 {
            return Err("manifest version or next id is zero".into());
        }
        if self.generations.len() > MAX_GENERATIONS {
            return Err(format!(
                "too many generations: {} > {MAX_GENERATIONS}",
                self.generations.len()
            ));
        }
        if self.segments.len() > MAX_SEGMENTS {
            return Err(format!(
                "too many segments: {} > {MAX_SEGMENTS}",
                self.segments.len()
            ));
        }

        // A GSN is a 60-bit sequence; anything above it would wrap the next
        // GSN handed out after the floor.
        let mut gsns = std::iter::once(self.gsn_floor)
            .chain(self.generations.iter().flat_map(|g| [g.min_gsn, g.max_gsn]))
            .chain(self.segments.iter().flat_map(|s| [s.min_gsn, s.max_gsn]));
        if let Some(gsn) = gsns.find(|gsn| *gsn > SEQUENCE_MASK) {
            return Err(format!("GSN {gsn:#x} is outside the sequence range"));
        }

        let mut previous_id = 0u64;
        for s in &self.segments {
            if s.version != 1 || s.format_version != 1 {
                return Err("segment version is unsupported".into());
            }
            if s.order != self.order {
                return Err("segment order differs from manifest order".into());
            }
            if s.entries == 0 {
                return Err(format!("segment {:#x} has no entries", s.segment_id));
            }
            if s.tombstones > s.entries {
                return Err("segment tombstones exceed entries".into());
            }
            if s.opened_at_ms > s.frozen_at_ms {
                return Err(format!(
                    "segment {:#x} was frozen at {} before it was opened at {}",
                    s.segment_id, s.frozen_at_ms, s.opened_at_ms
                ));
            }
            if s.frozen_at_ms > s.sealed_at_ms {
                return Err(format!(
                    "segment {:#x} was sealed at {} before it was frozen at {}",
                    s.segment_id, s.sealed_at_ms, s.frozen_at_ms
                ));
            }
            if s.segment_id <= previous_id {
                return Err(format!(
                    "segment ids are not increasing at {:#x}",
                    s.segment_id
                ));
            }
            previous_id = s.segment_id;
        }
        if previous_id >= self.next_segment_id {
            return Err(format!(
                "segment {previous_id:#x} is not below next_segment_id {:#x}",
                self.next_segment_id
            ));
        }

        let mut previous_id = 0u64;
        for (i, g) in self.generations.iter().enumerate() {
            if g.gen_id <= previous_id {
                return Err(format!(
                    "generation ids are not increasing at {:#x}",
                    g.gen_id
                ));
            }
            previous_id = g.gen_id;
            if g.shard_count == 0 {
                return Err(format!("generation {:#x} has no shards", g.gen_id));
            }
            let last = i + 1 == self.generations.len();
            if g.state == GenState::Active && !last {
                return Err(format!(
                    "generation {:#x} is active but is not the newest; only one active generation is allowed",
                    g.gen_id
                ));
            }
            if g.state == GenState::Active && (g.frozen_at_ms != 0 || g.max_gsn != 0) {
                return Err("active generation has frozen fields".into());
            }
            if g.state == GenState::Frozen && g.opened_at_ms > g.frozen_at_ms {
                return Err(format!(
                    "generation {:#x} was frozen at {} before it was opened at {}",
                    g.gen_id, g.frozen_at_ms, g.opened_at_ms
                ));
            }
        }
        if previous_id >= self.next_gen_id {
            return Err(format!(
                "generation {previous_id:#x} is not below next_gen_id {:#x}",
                self.next_gen_id
            ));
        }

        // I1 and I7 over the whole chronology: segments, then generations.
        let mut previous_max_gsn = 0u64;
        let mut previous_frozen_at = 0u64;
        let sealed = self
            .segments
            .iter()
            .map(|s| (s.min_gsn, Some(s.max_gsn), Some(s.frozen_at_ms)));
        let generations = self.generations.iter().map(|g| match g.state {
            GenState::Frozen => (g.min_gsn, Some(g.max_gsn), Some(g.frozen_at_ms)),
            GenState::Active => (g.min_gsn, None, None),
        });
        for (min_gsn, max_gsn, frozen_at) in sealed.chain(generations) {
            if min_gsn <= previous_max_gsn {
                return Err(format!(
                    "GSN ranges overlap: a layer starts at {min_gsn}, the one before ends at {previous_max_gsn}"
                ));
            }
            if let Some(max) = max_gsn {
                if max < min_gsn {
                    return Err(format!("GSN range {min_gsn}..={max} is reversed"));
                }
                if max > self.gsn_floor {
                    return Err(format!(
                        "gsn_floor {} is below a frozen GSN {max}",
                        self.gsn_floor
                    ));
                }
                previous_max_gsn = max;
            }
            if let Some(at) = frozen_at {
                if at < previous_frozen_at {
                    return Err(format!(
                        "layer freeze time {at} goes back before {previous_frozen_at}"
                    ));
                }
                previous_frozen_at = at;
            }
        }
        if let Some(active) = self.active()
            && active.min_gsn <= self.gsn_floor
        {
            return Err("active generation is below gsn_floor".into());
        }
        Ok(())
    }

    fn next(&self) -> DbResult<Self> {
        let mut m = self.clone();
        m.manifest_version = m
            .manifest_version
            .checked_add(1)
            .ok_or_else(|| broken("manifest version exhausted"))?;
        Ok(m)
    }

    fn checked(self) -> DbResult<Self> {
        match self.check() {
            Ok(()) => Ok(self),
            Err(reason) => {
                tracing::error!(reason, "manifest mutation broke an invariant");
                Err(broken("manifest mutation broke an invariant"))
            }
        }
    }

    /// Invariant I4: the id is burned by publishing this manifest before
    /// anything is written under it.
    pub(crate) fn reserve_gen_id(&self) -> DbResult<(Self, u64)> {
        if self.check().is_err() {
            return Err(broken("cannot reserve from an invalid manifest"));
        }
        let mut m = self.next()?;
        let id = m.next_gen_id;
        m.next_gen_id = id
            .checked_add(1)
            .ok_or_else(|| broken("generation ids exhausted"))?;
        Ok((m.checked()?, id))
    }

    pub(crate) fn reserve_segment_id(&self) -> DbResult<(Self, u64)> {
        if self.check().is_err() {
            return Err(broken("cannot reserve from an invalid manifest"));
        }
        let mut m = self.next()?;
        let id = m.next_segment_id;
        m.next_segment_id = id
            .checked_add(1)
            .ok_or_else(|| broken("segment ids exhausted"))?;
        Ok((m.checked()?, id))
    }

    /// Add an active generation where there is none: at initial creation.
    pub(crate) fn with_active(&self, new: GenRecord) -> DbResult<Self> {
        if self.active().is_some() || new.state != GenState::Active {
            return Err(broken(
                "with_active needs a manifest without an active generation",
            ));
        }
        let mut m = self.next()?;
        m.generations.push(new);
        m.checked()
    }

    /// The active generation becomes frozen and `new` becomes active.
    pub(crate) fn with_freeze(
        &self,
        frozen_at_ms: u64,
        max_gsn: u64,
        new: GenRecord,
    ) -> DbResult<Self> {
        if self.active().is_none() || new.state != GenState::Active {
            return Err(broken("with_freeze needs an active generation"));
        }
        let mut m = self.next()?;
        let old = m.generations.last_mut().expect("checked above");
        old.state = GenState::Frozen;
        old.frozen_at_ms = frozen_at_ms;
        old.max_gsn = max_gsn;
        m.gsn_floor = m.gsn_floor.max(max_gsn);
        m.generations.push(new);
        m.checked()
    }

    /// Invariant I6: only the oldest frozen generation leaves. `segment` is
    /// `None` when the generation left nothing worth a segment.
    pub(crate) fn with_sealed(&self, gen_id: u64, segment: Option<SegRecord>) -> DbResult<Self> {
        self.sealed(gen_id, segment, false)
    }

    /// Retire the oldest frozen generation when it holds no entry at all.
    /// A freeze does not flush, so a crash can leave a frozen generation
    /// empty; unlike a seal that skipped tombstones, an empty generation
    /// masks nothing, whatever segments exist below it.
    pub(crate) fn with_empty_sealed(&self, gen_id: u64) -> DbResult<Self> {
        self.sealed(gen_id, None, true)
    }

    fn sealed(
        &self,
        gen_id: u64,
        segment: Option<SegRecord>,
        generation_empty: bool,
    ) -> DbResult<Self> {
        let Some(oldest) = self.oldest_frozen() else {
            return Err(broken("with_sealed needs a frozen generation"));
        };
        if oldest.gen_id != gen_id {
            return Err(broken("only the oldest frozen generation may be sealed"));
        }
        if let Some(s) = &segment {
            if s.min_gsn < oldest.min_gsn || s.max_gsn > oldest.max_gsn {
                return Err(broken("sealed segment GSN range leaves generation bounds"));
            }
            if (s.opened_at_ms, s.frozen_at_ms) != (oldest.opened_at_ms, oldest.frozen_at_ms) {
                return Err(broken("sealed segment times differ from generation"));
            }
        } else if !generation_empty && !self.segments.is_empty() {
            return Err(broken("empty seal could expose values in older segments"));
        }
        let max_gsn = oldest.max_gsn;
        let mut m = self.next()?;
        m.generations.remove(0);
        m.gsn_floor = m.gsn_floor.max(max_gsn);
        if let Some(segment) = segment {
            m.segments.push(segment);
        }
        m.checked()
    }

    /// Invariant I5: retention takes the oldest layer. By I6 that is always a
    /// segment while any segment exists.
    pub(crate) fn without_oldest_segment(&self) -> DbResult<Self> {
        if self.segments.is_empty() {
            return Err(broken("there is no segment to drop"));
        }
        let mut m = self.next()?;
        m.segments.remove(0);
        m.checked()
    }
}

fn u16_at(b: &[u8], at: usize) -> u16 {
    u16::from_le_bytes(b[at..at + 2].try_into().expect("2 bytes"))
}

fn u32_at(b: &[u8], at: usize) -> u32 {
    u32::from_le_bytes(b[at..at + 4].try_into().expect("4 bytes"))
}

fn u64_at(b: &[u8], at: usize) -> u64 {
    u64::from_le_bytes(b[at..at + 8].try_into().expect("8 bytes"))
}

impl Manifest {
    pub(crate) fn encode(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(
            FIXED_LEN
                + self.generations.len() * GEN_RECORD_LEN
                + self.segments.len() * SEG_RECORD_LEN
                + CRC_LEN,
        );
        out.extend_from_slice(&MANIFEST_MAGIC);
        out.extend_from_slice(&MANIFEST_FORMAT_VERSION.to_le_bytes());
        out.extend_from_slice(&[0u8; 2]);
        out.extend_from_slice(&self.manifest_version.to_le_bytes());
        out.extend_from_slice(&self.key_len.to_le_bytes());
        out.push(self.order as u8);
        out.extend_from_slice(&[0u8; 5]);
        out.extend_from_slice(&self.seed.to_le_bytes());
        out.extend_from_slice(&self.created_at_ms.to_le_bytes());
        out.extend_from_slice(&self.next_segment_id.to_le_bytes());
        out.extend_from_slice(&self.next_gen_id.to_le_bytes());
        out.extend_from_slice(&self.gsn_floor.to_le_bytes());
        out.extend_from_slice(&(self.generations.len() as u32).to_le_bytes());
        out.extend_from_slice(&(self.segments.len() as u32).to_le_bytes());
        debug_assert_eq!(out.len(), FIXED_LEN);

        for g in &self.generations {
            out.extend_from_slice(&g.gen_id.to_le_bytes());
            out.push(g.state as u8);
            out.push(g.shard_count);
            out.extend_from_slice(&[0u8; 6]);
            out.extend_from_slice(&g.opened_at_ms.to_le_bytes());
            out.extend_from_slice(&g.frozen_at_ms.to_le_bytes());
            out.extend_from_slice(&g.min_gsn.to_le_bytes());
            out.extend_from_slice(&g.max_gsn.to_le_bytes());
        }

        for s in &self.segments {
            out.extend_from_slice(&s.segment_id.to_le_bytes());
            out.extend_from_slice(&s.version.to_le_bytes());
            out.push(s.state as u8);
            out.push(s.order as u8);
            out.extend_from_slice(&s.format_version.to_le_bytes());
            for v in [
                s.min_gsn,
                s.max_gsn,
                s.entries,
                s.tombstones,
                s.opened_at_ms,
                s.frozen_at_ms,
                s.sealed_at_ms,
                s.sdat_len,
                s.sdat_checksum,
                s.sidx_len,
                s.sidx_checksum,
                s.typ_hash,
            ] {
                out.extend_from_slice(&v.to_le_bytes());
            }
            out.extend_from_slice(&s.value_version.to_le_bytes());
            match s.location {
                Location::Local => {
                    out.push(LOCATION_LOCAL);
                    out.push(0);
                    out.extend_from_slice(&0u32.to_le_bytes());
                }
            }
        }

        let crc = crc32fast::hash(&out);
        out.extend_from_slice(&crc.to_le_bytes());
        out
    }

    /// Decode and validate a manifest.
    ///
    /// The CRC is checked **before** the format version, deliberately: a
    /// version read from unverified bytes could turn plain corruption into a
    /// misleading "unsupported format" refusal. The price is that the magic,
    /// the `format_version` field at offset 4 and the CRC trailer (the last
    /// four bytes, over everything before them) are frozen across all
    /// manifest format versions. A future format may change anything else,
    /// but must keep those three, or a build that predates it will report
    /// its manifests as `Corrupt` instead of `Unsupported`.
    pub(crate) fn decode(bytes: &[u8]) -> Result<Self, FormatFault> {
        if bytes.len() < FIXED_LEN + CRC_LEN {
            return Err(FormatFault::corrupt("manifest is truncated"));
        }
        if bytes[0..4] != MANIFEST_MAGIC {
            return Err(FormatFault::corrupt("bad manifest magic"));
        }
        let body = &bytes[..bytes.len() - CRC_LEN];
        let stored = u32_at(bytes, bytes.len() - CRC_LEN);
        let computed = crc32fast::hash(body);
        if stored != computed {
            return Err(FormatFault::corrupt(format!(
                "manifest CRC mismatch: stored {stored:#x}, computed {computed:#x}"
            )));
        }
        let version = u16_at(body, 4);
        if version != MANIFEST_FORMAT_VERSION {
            return Err(FormatFault::unsupported(format!(
                "manifest format version {version}"
            )));
        }
        if body[6..8]
            .iter()
            .chain(body[19..24].iter())
            .any(|b| *b != 0)
        {
            return Err(FormatFault::unsupported("manifest reserved bytes are set"));
        }
        let order = OrderKind::from_byte(body[18])
            .ok_or_else(|| FormatFault::unsupported(format!("entry order {}", body[18])))?;
        let generation_count = u32_at(body, 64) as usize;
        let segment_count = u32_at(body, 68) as usize;

        let mut at = FIXED_LEN;
        let need = |at: usize, len: usize| {
            if at + len > body.len() {
                Err(FormatFault::corrupt("manifest record runs past the end"))
            } else {
                Ok(())
            }
        };

        let mut generations = Vec::with_capacity(generation_count.min(1024));
        for _ in 0..generation_count {
            need(at, GEN_RECORD_LEN)?;
            let r = &body[at..at + GEN_RECORD_LEN];
            if r[10..16].iter().any(|b| *b != 0) {
                return Err(FormatFault::unsupported(
                    "generation reserved bytes are set",
                ));
            }
            let state = match r[8] {
                1 => GenState::Active,
                2 => GenState::Frozen,
                other => {
                    return Err(FormatFault::unsupported(format!(
                        "generation state {other}"
                    )));
                }
            };
            generations.push(GenRecord {
                gen_id: u64_at(r, 0),
                state,
                shard_count: r[9],
                opened_at_ms: u64_at(r, 16),
                frozen_at_ms: u64_at(r, 24),
                min_gsn: u64_at(r, 32),
                max_gsn: u64_at(r, 40),
            });
            at += GEN_RECORD_LEN;
        }

        let mut segments = Vec::with_capacity(segment_count.min(1024));
        for _ in 0..segment_count {
            need(at, SEG_RECORD_LEN)?;
            let r = &body[at..at + SEG_RECORD_LEN];
            if r[115] != 0 {
                return Err(FormatFault::unsupported("segment reserved byte is set"));
            }
            let state = match r[12] {
                1 => SegState::Sealed,
                other => {
                    return Err(FormatFault::unsupported(format!("segment state {other}")));
                }
            };
            let segment_order = OrderKind::from_byte(r[13])
                .ok_or_else(|| FormatFault::unsupported(format!("entry order {}", r[13])))?;
            if segment_order != order {
                return Err(FormatFault::corrupt(
                    "segment order differs from manifest order",
                ));
            }
            if u32_at(r, 8) != 1 {
                return Err(FormatFault::unsupported(format!(
                    "segment version {}",
                    u32_at(r, 8)
                )));
            }
            if u16_at(r, 14) != 1 {
                return Err(FormatFault::unsupported(format!(
                    "segment format version {}",
                    u16_at(r, 14)
                )));
            }
            let location_kind = r[114];
            let location_len = u32_at(r, 116) as usize;
            if location_kind != LOCATION_LOCAL {
                return Err(FormatFault::unsupported(format!(
                    "segment location kind {location_kind}"
                )));
            }
            if location_len != 0 {
                return Err(FormatFault::corrupt(
                    "a local segment has a location payload",
                ));
            }
            segments.push(SegRecord {
                segment_id: u64_at(r, 0),
                version: u32_at(r, 8),
                state,
                order,
                format_version: u16_at(r, 14),
                min_gsn: u64_at(r, 16),
                max_gsn: u64_at(r, 24),
                entries: u64_at(r, 32),
                tombstones: u64_at(r, 40),
                opened_at_ms: u64_at(r, 48),
                frozen_at_ms: u64_at(r, 56),
                sealed_at_ms: u64_at(r, 64),
                sdat_len: u64_at(r, 72),
                sdat_checksum: u64_at(r, 80),
                sidx_len: u64_at(r, 88),
                sidx_checksum: u64_at(r, 96),
                typ_hash: u64_at(r, 104),
                value_version: u16_at(r, 112),
                location: Location::Local,
            });
            at += SEG_RECORD_LEN + location_len;
        }
        if at != body.len() {
            return Err(FormatFault::corrupt(format!(
                "manifest has {} bytes after its last record",
                body.len() - at
            )));
        }

        let manifest = Self {
            manifest_version: u64_at(body, 8),
            key_len: u16_at(body, 16),
            order,
            seed: u64_at(body, 24),
            created_at_ms: u64_at(body, 32),
            next_segment_id: u64_at(body, 40),
            next_gen_id: u64_at(body, 48),
            gsn_floor: u64_at(body, 56),
            generations,
            segments,
        };
        manifest.check().map_err(FormatFault::Corrupt)?;
        Ok(manifest)
    }
}

/// How a publication can fail. The two cases require different recovery.
#[derive(Debug)]
pub(crate) enum PublishError {
    /// The manifest was not renamed into place.
    NotPublished(DbError),
    /// The rename succeeded, but its durability is unknown.
    Indeterminate(DbError),
}

impl PublishError {
    pub(crate) fn into_inner(self) -> DbError {
        match self {
            Self::NotPublished(error) | Self::Indeterminate(error) => error,
        }
    }
}

/// Stage and durably publish a manifest in the required filesystem order.
///
/// A manifest that fails [`Manifest::check`] is refused before any file
/// operation: `load` would reject it, so publishing it would make the
/// collection unopenable.
pub(crate) fn publish(fs: &dyn SegFs, dir: &Path, manifest: &Manifest) -> Result<(), PublishError> {
    if let Err(reason) = manifest.check() {
        tracing::error!(reason, path = %dir.display(), "refusing to publish an invalid manifest");
        return Err(PublishError::NotPublished(broken(
            "refusing to publish a manifest that breaks an invariant",
        )));
    }
    let tmp = dir.join(MANIFEST_TMP);
    let dst = dir.join(MANIFEST_NAME);
    let bytes = manifest.encode();

    let staged = (|| -> std::io::Result<()> {
        let mut file = fs.create(&tmp)?;
        fs.write_all(&mut file, &tmp, &bytes)?;
        fs.sync_file(&file, &tmp)?;
        drop(file);
        // A failed rename is treated as not performed on the supported
        // local filesystem.
        super::failpoint!(MANIFEST_TMP_WRITTEN);
        fs.rename(&tmp, &dst)
    })();
    if let Err(error) = staged {
        if let Err(cleanup) = fs.remove_file(&tmp) {
            tracing::warn!(error = %cleanup, path = %tmp.display(), "could not remove the temporary manifest");
        }
        return Err(PublishError::NotPublished(error.into()));
    }

    super::failpoint!(MANIFEST_RENAMED);
    fs.sync_dir(dir)
        .map_err(|error| PublishError::Indeterminate(error.into()))
}

/// Load the published manifest, ignoring any leftover staging file.
///
/// A file longer than [`MAX_MANIFEST_LEN`] is corrupt and is refused from its
/// length, without reading it into memory.
pub(crate) fn load(dir: &Path) -> DbResult<Option<Manifest>> {
    use std::io::Read;

    let path = dir.join(MANIFEST_NAME);
    let file = match std::fs::File::open(&path) {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(error) => return Err(error.into()),
    };
    let too_large = |len: u64| DbError::ManifestCorrupt {
        path: path.clone(),
        reason: format!("manifest is {len} bytes, larger than the {MAX_MANIFEST_LEN}-byte maximum"),
    };
    let len = file.metadata()?.len();
    if len > MAX_MANIFEST_LEN {
        return Err(too_large(len));
    }
    // The length can change between the check and the read: never take more
    // than one byte past the bound.
    let mut bytes = Vec::with_capacity(len as usize);
    file.take(MAX_MANIFEST_LEN + 1).read_to_end(&mut bytes)?;
    if bytes.len() as u64 > MAX_MANIFEST_LEN {
        return Err(too_large(bytes.len() as u64));
    }
    match Manifest::decode(&bytes) {
        Ok(manifest) => Ok(Some(manifest)),
        Err(FormatFault::Unsupported(reason)) => Err(DbError::FormatMismatch(format!(
            "{}: {reason}",
            path.display()
        ))),
        Err(FormatFault::Corrupt(reason)) => Err(DbError::ManifestCorrupt { path, reason }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::DbError;
    use crate::seg::fs::{FsOp, FsOpKind, TraceFs};

    fn first() -> Manifest {
        Manifest::new(32, 7, 1)
    }

    fn second() -> Manifest {
        first().reserve_gen_id().unwrap().0
    }

    #[test]
    fn publication_follows_the_durable_order() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        publish(&*fs, dir.path(), &first()).unwrap();

        let tmp = dir.path().join(MANIFEST_TMP);
        let dst = dir.path().join(MANIFEST_NAME);
        assert_eq!(
            fs.ops(),
            [
                FsOp::Create(tmp.clone()),
                FsOp::WriteAll(tmp.clone()),
                FsOp::SyncFile(tmp.clone()),
                FsOp::Rename(tmp, dst),
                FsOp::SyncDir(dir.path().to_path_buf()),
            ]
        );
        assert_eq!(load(dir.path()).unwrap(), Some(first()));
        assert!(!dir.path().join(MANIFEST_TMP).exists());
    }

    #[test]
    fn an_invalid_manifest_is_never_published() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();

        let mut bad = sample();
        bad.key_len = 0;
        let mut floor_below_a_layer = sample();
        floor_below_a_layer.gsn_floor = 250;
        for manifest in [Manifest::new(0, 7, 1), bad, floor_below_a_layer] {
            assert!(manifest.check().is_err());
            let err = publish(&*fs, dir.path(), &manifest).unwrap_err();
            assert!(
                matches!(err, PublishError::NotPublished(DbError::Internal(_))),
                "{err:?}"
            );
            assert!(fs.ops().is_empty(), "no file operation: {:?}", fs.ops());
            assert!(!dir.path().join(MANIFEST_NAME).exists());
            assert!(!dir.path().join(MANIFEST_TMP).exists());
        }
    }

    #[test]
    fn a_failure_before_the_rename_publishes_nothing() {
        for kind in [FsOpKind::Create, FsOpKind::SyncFile, FsOpKind::Rename] {
            let dir = tempfile::tempdir().unwrap();
            let fs = TraceFs::new();
            publish(&*fs, dir.path(), &first()).unwrap();

            fs.fail_on(kind, "MANIFEST", 0);
            let err = publish(&*fs, dir.path(), &second()).unwrap_err();
            assert!(
                matches!(err, PublishError::NotPublished(_)),
                "{kind:?}: {err:?}"
            );
            assert_eq!(
                load(dir.path()).unwrap(),
                Some(first()),
                "{kind:?}: the previous manifest must stay in force"
            );
            assert!(
                !dir.path().join(MANIFEST_TMP).exists(),
                "{kind:?}: the temporary file must be removed"
            );
            publish(&*fs, dir.path(), &second()).unwrap();
            assert_eq!(load(dir.path()).unwrap(), Some(second()));
        }
    }

    #[test]
    fn a_write_failure_preserves_the_published_manifest_and_allows_retry() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        publish(&*fs, dir.path(), &first()).unwrap();

        fs.fail_on(FsOpKind::WriteAll, MANIFEST_TMP, 0);
        let err = publish(&*fs, dir.path(), &second()).unwrap_err();
        assert!(matches!(err, PublishError::NotPublished(_)), "{err:?}");
        assert_eq!(load(dir.path()).unwrap(), Some(first()));
        assert!(!dir.path().join(MANIFEST_TMP).exists());

        publish(&*fs, dir.path(), &second()).unwrap();
        assert_eq!(load(dir.path()).unwrap(), Some(second()));
    }

    #[test]
    fn a_failed_directory_fsync_is_indeterminate() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        publish(&*fs, dir.path(), &first()).unwrap();

        fs.fail_on(FsOpKind::SyncDir, "", 0);
        let err = publish(&*fs, dir.path(), &second()).unwrap_err();
        assert!(matches!(err, PublishError::Indeterminate(_)), "{err:?}");
        assert_eq!(load(dir.path()).unwrap(), Some(second()));
    }

    #[test]
    fn loading_distinguishes_absent_corrupt_and_unsupported() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(load(dir.path()).unwrap(), None);

        let path = dir.path().join(MANIFEST_NAME);
        std::fs::write(&path, vec![b'x'; FIXED_LEN + CRC_LEN]).unwrap();
        match load(dir.path()).unwrap_err() {
            DbError::ManifestCorrupt { path: p, reason } => {
                assert_eq!(p, path);
                assert!(reason.contains("magic"), "{reason}");
            }
            other => panic!("{other:?}"),
        }

        let mut newer = first().encode();
        newer[4] = 2;
        let at = newer.len() - 4;
        let crc = crc32fast::hash(&newer[..at]);
        newer[at..].copy_from_slice(&crc.to_le_bytes());
        std::fs::write(&path, newer).unwrap();
        assert!(matches!(
            load(dir.path()).unwrap_err(),
            DbError::FormatMismatch(m) if m.contains("version")
        ));
    }

    #[test]
    fn a_leftover_temporary_file_does_not_affect_loading() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        publish(&*fs, dir.path(), &first()).unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"torn").unwrap();
        assert_eq!(load(dir.path()).unwrap(), Some(first()));
    }

    fn seg(id: u64, min_gsn: u64, max_gsn: u64, frozen_at_ms: u64) -> SegRecord {
        SegRecord {
            segment_id: id,
            version: 1,
            state: SegState::Sealed,
            order: OrderKind::ByHash,
            format_version: 1,
            min_gsn,
            max_gsn,
            entries: max_gsn - min_gsn + 1,
            tombstones: 0,
            opened_at_ms: frozen_at_ms - 10,
            frozen_at_ms,
            sealed_at_ms: frozen_at_ms + 5,
            sdat_len: 4096,
            sdat_checksum: 0xaaaa,
            sidx_len: 512,
            sidx_checksum: 0xbbbb,
            typ_hash: 0xcccc,
            value_version: 3,
            location: Location::Local,
        }
    }

    fn frozen(id: u64, min_gsn: u64, max_gsn: u64, frozen_at_ms: u64) -> GenRecord {
        GenRecord {
            gen_id: id,
            state: GenState::Frozen,
            shard_count: 4,
            opened_at_ms: frozen_at_ms - 10,
            frozen_at_ms,
            min_gsn,
            max_gsn,
        }
    }

    fn active(id: u64, min_gsn: u64, opened_at_ms: u64) -> GenRecord {
        GenRecord {
            gen_id: id,
            state: GenState::Active,
            shard_count: 8,
            opened_at_ms,
            frozen_at_ms: 0,
            min_gsn,
            max_gsn: 0,
        }
    }

    /// Two segments, one frozen generation, one active generation.
    fn sample() -> Manifest {
        Manifest {
            manifest_version: 9,
            key_len: 32,
            order: OrderKind::ByHash,
            seed: 0x1234,
            created_at_ms: 50,
            next_segment_id: 3,
            next_gen_id: 5,
            gsn_floor: 300,
            generations: vec![frozen(3, 201, 300, 3_000), active(4, 301, 3_000)],
            segments: vec![seg(1, 1, 100, 1_000), seg(2, 101, 200, 2_000)],
        }
    }

    fn reseal(bytes: &mut [u8]) {
        let at = bytes.len() - 4;
        let crc = crc32fast::hash(&bytes[..at]);
        bytes[at..].copy_from_slice(&crc.to_le_bytes());
    }

    fn decode_edited(edit: impl FnOnce(&mut Vec<u8>)) -> Result<Manifest, FormatFault> {
        let mut bytes = sample().encode();
        edit(&mut bytes);
        reseal(&mut bytes);
        Manifest::decode(&bytes)
    }

    const GEN0: usize = 72;
    const SEG0: usize = 72 + 2 * 48;

    #[test]
    fn manifest_orders_must_agree() {
        let mut m = sample();
        m.order = OrderKind::ByKey;
        for s in &mut m.segments {
            s.order = OrderKind::ByKey;
        }
        assert_eq!(Manifest::decode(&m.encode()).unwrap(), m);
        for offset in [18, SEG0 + 13] {
            assert!(matches!(
                decode_edited(|b| b[offset] = 1),
                Err(FormatFault::Corrupt(_))
            ));
        }
    }

    #[test]
    fn a_manifest_round_trips() {
        let m = sample();
        m.check().unwrap();
        assert_eq!(Manifest::decode(&m.encode()).unwrap(), m);

        let empty = Manifest::new(32, 7, 1);
        empty.check().unwrap();
        assert_eq!(Manifest::decode(&empty.encode()).unwrap(), empty);
        assert_eq!(empty.manifest_version, 1);
        assert_eq!(empty.next_gen_id, 1);
        assert_eq!(empty.next_segment_id, 1);
    }

    #[test]
    fn the_fixed_part_has_the_documented_layout() {
        let bytes = sample().encode();
        assert_eq!(&bytes[0..4], b"ASM1");
        assert_eq!(u16::from_le_bytes([bytes[4], bytes[5]]), 1);
        assert_eq!(u64::from_le_bytes(bytes[8..16].try_into().unwrap()), 9);
        assert_eq!(u16::from_le_bytes([bytes[16], bytes[17]]), 32);
        assert_eq!(bytes[18], 0);
        assert_eq!(
            u64::from_le_bytes(bytes[24..32].try_into().unwrap()),
            0x1234
        );
        assert_eq!(u64::from_le_bytes(bytes[40..48].try_into().unwrap()), 3);
        assert_eq!(u64::from_le_bytes(bytes[48..56].try_into().unwrap()), 5);
        assert_eq!(u64::from_le_bytes(bytes[56..64].try_into().unwrap()), 300);
        assert_eq!(u32::from_le_bytes(bytes[64..68].try_into().unwrap()), 2);
        assert_eq!(u32::from_le_bytes(bytes[68..72].try_into().unwrap()), 2);
        assert_eq!(bytes.len(), 72 + 2 * 48 + 2 * 120 + 4);
        assert_eq!(
            u64::from_le_bytes(bytes[GEN0..GEN0 + 8].try_into().unwrap()),
            3
        );
        assert_eq!(bytes[GEN0 + 8], 2, "frozen");
        assert_eq!(bytes[GEN0 + 9], 4, "shard count");
        assert_eq!(
            u64::from_le_bytes(bytes[SEG0..SEG0 + 8].try_into().unwrap()),
            1
        );
    }

    #[test]
    fn damage_is_detected() {
        let good = sample().encode();

        let mut magic = good.clone();
        magic[0] = b'Z';
        assert!(matches!(
            Manifest::decode(&magic),
            Err(FormatFault::Corrupt(m)) if m.contains("magic")
        ));

        let mut flipped = good.clone();
        flipped[30] ^= 1;
        assert!(matches!(
            Manifest::decode(&flipped),
            Err(FormatFault::Corrupt(m)) if m.contains("CRC")
        ));

        for cut in [0, 3, 71, good.len() - 1] {
            assert!(
                matches!(Manifest::decode(&good[..cut]), Err(FormatFault::Corrupt(_))),
                "cut at {cut}"
            );
        }
    }

    #[test]
    fn what_this_build_cannot_read_is_refused() {
        assert!(matches!(
            decode_edited(|b| b[4] = 2),
            Err(FormatFault::Unsupported(m)) if m.contains("version")
        ));
        assert!(matches!(
            decode_edited(|b| b[18] = 7),
            Err(FormatFault::Unsupported(m)) if m.contains("order")
        ));
        assert!(matches!(
            decode_edited(|b| b[GEN0 + 8] = 9),
            Err(FormatFault::Unsupported(m)) if m.contains("generation state")
        ));
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 12] = 2),
            Err(FormatFault::Unsupported(m)) if m.contains("segment state")
        ));
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 114] = 1),
            Err(FormatFault::Unsupported(m)) if m.contains("location")
        ));
    }

    #[test]
    fn a_manifest_that_breaks_an_invariant_is_corrupt() {
        // Two active generations.
        assert!(matches!(
            decode_edited(|b| b[GEN0 + 8] = 1),
            Err(FormatFault::Corrupt(m)) if m.contains("active")
        ));
        // A generation with no shards.
        assert!(matches!(
            decode_edited(|b| b[GEN0 + 9] = 0),
            Err(FormatFault::Corrupt(m)) if m.contains("shard")
        ));
        // I1: the second segment's GSN range reaches into the first.
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 120 + 16..SEG0 + 120 + 24]
                .copy_from_slice(&100u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("GSN")
        ));
        // I7: the second segment was frozen before the first. It was opened
        // before its freeze, so only the chronology rule can reject it.
        assert!(matches!(
            decode_edited(|b| {
                b[SEG0 + 120 + 48..SEG0 + 120 + 56].copy_from_slice(&989u64.to_le_bytes());
                b[SEG0 + 120 + 56..SEG0 + 120 + 64].copy_from_slice(&999u64.to_le_bytes());
            }),
            Err(FormatFault::Corrupt(m)) if m.contains("goes back")
        ));
        // I4: an id at or above the high-water mark.
        assert!(matches!(
            decode_edited(|b| b[40..48].copy_from_slice(&2u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("next_segment_id")
        ));
        assert!(matches!(
            decode_edited(|b| b[48..56].copy_from_slice(&4u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("next_gen_id")
        ));
        // The floor below a sealed GSN.
        assert!(matches!(
            decode_edited(|b| b[56..64].copy_from_slice(&250u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("gsn_floor")
        ));
        // Segment ids out of order.
        assert!(matches!(
            decode_edited(|b| b[SEG0..SEG0 + 8].copy_from_slice(&2u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("segment ids")
        ));
        // A zero-length key.
        assert!(matches!(
            decode_edited(|b| b[16..18].copy_from_slice(&0u16.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("key")
        ));
    }

    #[test]
    fn ids_are_reserved_without_changing_the_composition() {
        let m = sample();
        let (next, gen_id) = m.reserve_gen_id().unwrap();
        assert_eq!(gen_id, 5);
        assert_eq!(next.next_gen_id, 6);
        assert_eq!(next.manifest_version, 10);
        assert_eq!(next.generations, m.generations);
        next.check().unwrap();

        let (next, segment_id) = m.reserve_segment_id().unwrap();
        assert_eq!(segment_id, 3);
        assert_eq!(next.next_segment_id, 4);
        assert_eq!(next.segments, m.segments);
        next.check().unwrap();
    }

    #[test]
    fn the_first_generation_is_added_to_an_empty_manifest() {
        let (m, gen_id) = Manifest::new(32, 7, 1).reserve_gen_id().unwrap();
        let m = m.with_active(active(gen_id, 1, 100)).unwrap();
        assert_eq!(m.active().unwrap().gen_id, 1);
        assert_eq!(m.manifest_version, 3);
        m.check().unwrap();

        // A second active generation is refused.
        let (m2, id2) = m.reserve_gen_id().unwrap();
        assert!(m2.with_active(active(id2, 1, 100)).is_err());
    }

    #[test]
    fn a_freeze_turns_the_active_generation_frozen() {
        let (m, gen_id) = sample().reserve_gen_id().unwrap();
        let m = m
            .with_freeze(4_000, 400, active(gen_id, 401, 4_000))
            .unwrap();
        m.check().unwrap();
        assert_eq!(m.frozen_count(), 2);
        assert_eq!(m.oldest_frozen().unwrap().gen_id, 3);
        let was_active = &m.generations[1];
        assert_eq!(was_active.gen_id, 4);
        assert_eq!(was_active.state, GenState::Frozen);
        assert_eq!(was_active.max_gsn, 400);
        assert_eq!(was_active.frozen_at_ms, 4_000);
        assert_eq!(m.active().unwrap().gen_id, 5);
        assert_eq!(m.gsn_floor, 400);
    }

    #[test]
    fn a_freeze_needs_an_active_generation() {
        let (m, gen_id) = Manifest::new(32, 7, 1).reserve_gen_id().unwrap();
        assert!(m.with_freeze(10, 5, active(gen_id, 6, 10)).is_err());
    }

    #[test]
    fn sealing_replaces_the_oldest_frozen_generation_with_a_segment() {
        let (m, segment_id) = sample().reserve_segment_id().unwrap();
        let m = m
            .with_sealed(3, Some(seg(segment_id, 201, 300, 3_000)))
            .unwrap();
        m.check().unwrap();
        assert_eq!(m.frozen_count(), 0);
        assert_eq!(m.segments.len(), 3);
        assert_eq!(m.segments[2].segment_id, 3);
        assert_eq!(m.active().unwrap().gen_id, 4);
    }

    #[test]
    fn sealing_a_generation_that_left_nothing_adds_no_segment() {
        let mut source = sample();
        source.segments.clear();
        let m = source.with_sealed(3, None).unwrap();
        m.check().unwrap();
        assert_eq!(m.frozen_count(), 0);
        assert!(m.segments.is_empty());
        assert_eq!(m.gsn_floor, 300);
    }

    #[test]
    fn only_the_oldest_frozen_generation_may_be_sealed() {
        let (m, gen_id) = sample().reserve_gen_id().unwrap();
        let m = m
            .with_freeze(4_000, 400, active(gen_id, 401, 4_000))
            .unwrap();
        // Generation 4 is frozen, but generation 3 is older.
        assert!(m.with_sealed(4, None).is_err());
        assert!(m.with_sealed(3, None).is_err());
        // The active generation cannot be sealed at all.
        assert!(sample().with_sealed(4, None).is_err());
    }

    #[test]
    fn retention_drops_the_oldest_segment() {
        let m = sample().without_oldest_segment().unwrap();
        m.check().unwrap();
        assert_eq!(m.segments.len(), 1);
        assert_eq!(m.segments[0].segment_id, 2);
        assert_eq!(m.gsn_floor, 300, "the floor never goes down");
        assert!(Manifest::new(32, 7, 1).without_oldest_segment().is_err());
    }

    #[test]
    fn layer_times_never_go_back() {
        let m = sample();
        assert_eq!(m.monotone_time(10_000), 10_000);
        // The clock went back behind the newest frozen layer.
        assert_eq!(m.monotone_time(2_500), 3_000);
        assert_eq!(Manifest::new(32, 7, 1).monotone_time(5), 5);
    }

    #[test]
    fn layer_times_never_go_back_behind_the_active_generation() {
        // Only an active generation, opened at 10_000; the clock then went
        // back to 5_000. Freezing it at 5_000 would record a layer frozen
        // before it was opened.
        let (m, gen_id) = Manifest::new(32, 7, 1).reserve_gen_id().unwrap();
        let m = m.with_active(active(gen_id, 1, 10_000)).unwrap();
        assert_eq!(m.monotone_time(5_000), 10_000);

        let at = m.monotone_time(5_000);
        let (m, next_id) = m.reserve_gen_id().unwrap();
        let m = m.with_freeze(at, 10, active(next_id, 11, at)).unwrap();
        assert!(m.generations[0].opened_at_ms <= m.generations[0].frozen_at_ms);

        // An active generation opened after the newest frozen layer.
        let mut m = sample();
        m.generations[1].opened_at_ms = 3_500;
        m.check().unwrap();
        assert_eq!(m.monotone_time(3_200), 3_500);
    }

    #[test]
    fn a_layer_is_never_frozen_before_it_was_opened() {
        let mut m = sample();
        m.generations[0].opened_at_ms = 3_001;
        assert!(m.check().unwrap_err().contains("opened"));

        let mut m = sample();
        m.segments[1].opened_at_ms = 2_001;
        assert!(m.check().unwrap_err().contains("opened"));

        let mut m = sample();
        m.segments[1].sealed_at_ms = m.segments[1].frozen_at_ms - 1;
        assert!(m.check().unwrap_err().contains("sealed at"));

        // A freeze that would do it is refused by the mutator.
        let (m, gen_id) = sample().reserve_gen_id().unwrap();
        let mut m = m;
        m.generations[1].opened_at_ms = 5_000;
        assert!(
            m.with_freeze(4_000, 400, active(gen_id, 401, 5_000))
                .is_err()
        );
    }

    #[test]
    fn a_gsn_above_the_sequence_range_is_refused() {
        let top = SEQUENCE_MASK;
        let over = SEQUENCE_MASK + 1;

        // The largest representable GSN is accepted everywhere.
        let mut m = sample();
        m.generations[1] = active(4, top, 3_000);
        m.gsn_floor = 300;
        m.check().unwrap();
        let mut m = sample();
        m.gsn_floor = top;
        m.generations[1] = frozen(4, top, top, 3_000);
        m.check().unwrap();

        type Edit = (&'static str, fn(&mut Manifest, u64));
        let edits: [Edit; 6] = [
            ("gsn_floor", |m, v| m.gsn_floor = v),
            ("generation min_gsn", |m, v| m.generations[1].min_gsn = v),
            ("generation max_gsn", |m, v| {
                m.gsn_floor = v;
                m.generations[0].max_gsn = v;
            }),
            ("segment min_gsn", |m, v| {
                m.segments[1].min_gsn = v;
                m.segments[1].max_gsn = v;
            }),
            ("segment max_gsn", |m, v| {
                m.segments[1].max_gsn = v;
                m.segments[1].entries = 1;
            }),
            ("frozen generation min_gsn", |m, v| {
                m.generations[0].min_gsn = v;
            }),
        ];
        for (what, edit) in edits {
            let mut m = sample();
            edit(&mut m, over);
            let reason = m.check().unwrap_err();
            assert!(reason.contains("sequence range"), "{what}: {reason}");
        }
    }

    #[test]
    fn a_segment_without_entries_is_refused() {
        let mut m = sample();
        m.segments[0].entries = 0;
        assert!(m.check().unwrap_err().contains("no entries"));
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 32..SEG0 + 40].copy_from_slice(&0u64.to_le_bytes())),
            Err(FormatFault::Corrupt(m)) if m.contains("no entries")
        ));
    }

    #[test]
    fn an_oversized_manifest_is_corrupt_without_being_read() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(MANIFEST_NAME);
        // A sparse file: the refusal must come from its length alone.
        let file = std::fs::File::create(&path).unwrap();
        file.set_len(MAX_MANIFEST_LEN + 1).unwrap();
        drop(file);
        match load(dir.path()).unwrap_err() {
            DbError::ManifestCorrupt { path: p, reason } => {
                assert_eq!(p, path);
                assert!(reason.contains("larger"), "{reason}");
            }
            other => panic!("{other:?}"),
        }
    }

    /// A manifest with `segments` one-entry segments followed by
    /// `generations` frozen generations, all valid.
    fn filled(segments: usize, generations: usize) -> Manifest {
        let mut m = Manifest::new(32, 7, 1);
        m.next_segment_id = segments as u64 + 1;
        m.next_gen_id = generations as u64 + 1;
        let mut gsn = 0;
        for id in 1..=segments as u64 {
            gsn += 1;
            m.segments.push(seg(id, gsn, gsn, 1_000));
        }
        for id in 1..=generations as u64 {
            gsn += 1;
            m.generations.push(frozen(id, gsn, gsn, 1_000));
        }
        m.gsn_floor = gsn;
        m
    }

    #[test]
    fn the_size_bound_admits_the_largest_valid_manifest() {
        let largest = filled(MAX_SEGMENTS, MAX_GENERATIONS);
        largest.check().unwrap();
        assert_eq!(largest.encode().len() as u64, MAX_MANIFEST_LEN);

        let reason = filled(MAX_SEGMENTS + 1, 0).check().unwrap_err();
        assert!(reason.contains("too many segments"), "{reason}");
        let reason = filled(0, MAX_GENERATIONS + 1).check().unwrap_err();
        assert!(reason.contains("too many generations"), "{reason}");
    }

    #[test]
    fn reserved_bytes_and_mixed_orders_are_refused() {
        for offset in [6, 19, GEN0 + 10, SEG0 + 115] {
            assert!(
                matches!(
                    decode_edited(|b| b[offset] = 1),
                    Err(FormatFault::Unsupported(_))
                ),
                "reserved byte {offset}"
            );
        }
        for offset in [18, SEG0 + 13] {
            assert!(
                matches!(
                    decode_edited(|b| b[offset] = 1),
                    Err(FormatFault::Corrupt(_))
                ),
                "mixed order at {offset}"
            );
        }
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 116] = 1),
            Err(FormatFault::Corrupt(_))
        ));
    }

    #[test]
    fn segment_metadata_must_match_this_manifest() {
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 8] = 2),
            Err(FormatFault::Unsupported(_))
        ));
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 14] = 2),
            Err(FormatFault::Unsupported(_))
        ));
        assert!(matches!(
            decode_edited(|b| b[SEG0 + 40..SEG0 + 48].copy_from_slice(&999u64.to_le_bytes())),
            Err(FormatFault::Corrupt(_))
        ));
    }

    #[test]
    fn sealing_cannot_substitute_an_unrelated_gsn_range() {
        let (m, id) = sample().reserve_segment_id().unwrap();
        assert!(m.with_sealed(3, Some(seg(id, 200, 299, 3_000))).is_err());
        assert!(m.with_sealed(3, Some(seg(id, 201, 301, 3_000))).is_err());
    }

    /// GSN gaps around the frozen generation: segments end at 200, the
    /// generation spans 250..=300, and the floor is 350 below an active
    /// generation at 351. A segment that leaves the generation's bounds
    /// into a gap still yields a manifest `check()` accepts, so only the
    /// explicit bounds check in `with_sealed` can refuse it.
    fn gapped() -> (Manifest, u64) {
        let mut m = sample();
        m.generations = vec![frozen(3, 250, 300, 3_000), active(4, 351, 3_000)];
        m.gsn_floor = 350;
        m.check().unwrap();
        m.reserve_segment_id().unwrap()
    }

    #[test]
    fn sealing_is_bounded_by_the_generation_not_only_by_its_neighbours() {
        let sealing_error = |m: &Manifest, segment: SegRecord| {
            let err = m.with_sealed(3, Some(segment.clone())).unwrap_err();
            // The same composition assembled by hand is valid, so nothing
            // but the bounds check could have refused it.
            let mut by_hand = m.clone();
            by_hand.generations.remove(0);
            by_hand.segments.push(segment);
            by_hand.check().unwrap();
            err
        };
        let (m, id) = gapped();
        for (min_gsn, max_gsn) in [(220, 300), (250, 320)] {
            let err = sealing_error(&m, seg(id, min_gsn, max_gsn, 3_000));
            assert!(
                matches!(err, DbError::Internal(msg) if msg.contains("generation bounds")),
                "{min_gsn}..={max_gsn}: {err:?}"
            );
        }
        m.with_sealed(3, Some(seg(id, 250, 300, 3_000))).unwrap();
    }

    #[test]
    fn sealing_keeps_the_generation_high_water_mark_when_keys_collapse() {
        let (m, id) = sample().reserve_segment_id().unwrap();
        let sealed = m.with_sealed(3, Some(seg(id, 220, 280, 3_000))).unwrap();
        assert_eq!(sealed.segments[2].min_gsn, 220);
        assert_eq!(sealed.segments[2].max_gsn, 280);
        assert_eq!(sealed.gsn_floor, 300);
        sealed.check().unwrap();
    }

    #[test]
    fn sealing_preserves_generation_open_and_freeze_times() {
        let (m, id) = sample().reserve_segment_id().unwrap();
        let mut segment = seg(id, 201, 300, 3_000);
        segment.opened_at_ms += 1;
        assert!(m.with_sealed(3, Some(segment.clone())).is_err());
        segment.opened_at_ms -= 1;
        segment.frozen_at_ms += 1;
        assert!(m.with_sealed(3, Some(segment)).is_err());
    }

    #[test]
    fn empty_seal_cannot_expose_an_older_segments_values() {
        assert!(sample().with_sealed(3, None).is_err());
    }

    #[test]
    fn an_empty_generation_leaves_without_a_segment_above_older_ones() {
        let m = sample().with_empty_sealed(3).unwrap();
        m.check().unwrap();
        assert_eq!(m.frozen_count(), 0);
        assert_eq!(m.segments.len(), 2);
        assert_eq!(m.gsn_floor, 300);
        // Still only the oldest frozen generation.
        assert!(sample().with_empty_sealed(4).is_err());
    }

    #[test]
    fn exhausted_version_and_id_counters_return_errors() {
        fn exhausted(result: DbResult<impl std::fmt::Debug>, what: &str) {
            match result {
                Err(DbError::Internal(msg)) => assert_eq!(msg, what),
                other => panic!("expected {what:?}, got {other:?}"),
            }
        }
        const VERSION: &str = "manifest version exhausted";

        // Every id below is reserved before the version runs out, so each
        // mutation is valid except for the version counter.
        let (m, gen_id) = sample().reserve_gen_id().unwrap();
        let (mut m, segment_id) = m.reserve_segment_id().unwrap();
        let freeze = active(gen_id, 401, 4_000);
        let sealed = seg(segment_id, 201, 300, 3_000);
        m.with_freeze(4_000, 400, freeze).unwrap();
        m.with_sealed(3, Some(sealed.clone())).unwrap();
        m.without_oldest_segment().unwrap();

        m.manifest_version = u64::MAX;
        m.check().unwrap();
        exhausted(m.reserve_gen_id(), VERSION);
        exhausted(m.reserve_segment_id(), VERSION);
        exhausted(m.with_freeze(4_000, 400, freeze), VERSION);
        exhausted(m.with_sealed(3, Some(sealed)), VERSION);
        exhausted(m.without_oldest_segment(), VERSION);

        let (mut empty, gen_id) = Manifest::new(32, 7, 1).reserve_gen_id().unwrap();
        empty.with_active(active(gen_id, 1, 100)).unwrap();
        empty.manifest_version = u64::MAX;
        exhausted(empty.with_active(active(gen_id, 1, 100)), VERSION);

        let mut m = sample();
        m.next_gen_id = u64::MAX;
        m.check().unwrap();
        exhausted(m.reserve_gen_id(), "generation ids exhausted");
        let mut m = sample();
        m.next_segment_id = u64::MAX;
        m.check().unwrap();
        exhausted(m.reserve_segment_id(), "segment ids exhausted");
    }

    #[test]
    fn in_memory_manifest_obeys_the_same_v1_constraints() {
        let mut m = sample();
        m.order = OrderKind::ByKey;
        assert!(m.check().is_err());
        let mut m = sample();
        m.segments[0].version = 2;
        assert!(m.check().is_err());
        let mut m = sample();
        m.generations[1].frozen_at_ms = 1;
        assert!(m.check().is_err());
        let mut m = sample();
        m.generations[1].min_gsn = 300;
        assert!(m.check().is_err());
    }
}