armdb 0.15.1

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
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
//! The segmented collection over raw value bytes.

use std::collections::HashSet;
use std::fs::File;
use std::hash::{BuildHasher, Hash, Hasher};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

use super::cache::SegBlockCache;
use super::config::SegConfig;
use super::fs::{SegFs, real};
use super::generation::{CollectionFence, GEN_DIR, GenLookup, GenProbe, Generation, gen_dir_name};
use super::hash::key_hash;
use super::manifest::{
    self, GenRecord, GenState, MANIFEST_NAME, MANIFEST_TMP, Manifest, PublishError,
};
use super::seal::{SEG_DIR, sdat_name, sidx_name};
use super::segment::{Lookup, Segment};
use super::sidecar::OrderKind;
use crate::error::{DbError, DbResult};
use crate::key::Key;
use crate::meta::{Backend, DbMeta, META_VERSION};
use crate::sync::{self, Condvar, Mutex, RwLock};

const ROOT_META: &str = "db.meta";
const ROOT_META_TMP: &str = "db.meta.tmp";
const SEGMENT_LOAD_THREADS: usize = 8;

/// Wall clock in epoch milliseconds. A seam, so that tests can move time.
pub(crate) type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;

pub(crate) fn wall_clock() -> Clock {
    Arc::new(|| {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0)
    })
}

/// What the collection is, as far as the byte level needs to know.
#[derive(Debug, Clone, Copy)]
pub struct SegMeta {
    /// Collection name used in diagnostics.
    pub name: &'static str,
    /// Recorded in every segment sealed by this build.
    pub typ_hash: u64,
    /// Recorded in every segment sealed by this build.
    pub value_version: u16,
}

pub(crate) struct OpenOptions {
    pub fs: Arc<dyn SegFs>,
    pub clock: Clock,
    /// Start the `SealWorker` thread. Tests that drive the steps themselves
    /// turn it off.
    pub worker: bool,
}

impl OpenOptions {
    pub(crate) fn production() -> Self {
        Self {
            fs: real(),
            clock: wall_clock(),
            worker: true,
        }
    }
}

/// The composition a reader works on. Replaced as a whole; never mutated.
pub(crate) struct View<K: Key + Hash + Eq + Send + Sync> {
    pub active: Arc<Generation<K>>,
    /// Newest first.
    pub frozen: Vec<Arc<Generation<K>>>,
    /// Newest first.
    pub sealed: Vec<Arc<Segment>>,
}

/// What the worker last did. Guarded by `SegCore::seal`.
#[derive(Debug, Clone, Default)]
pub(crate) struct SealState {
    /// Generation being sealed right now.
    pub in_flight: Option<u64>,
    pub last_error: Option<String>,
    pub retry_at_ms: Option<u64>,
    pub last_sealed_at_ms: Option<u64>,
    /// Failed attempts since the open. A waiter compares two readings to
    /// learn that an attempt failed while it waited.
    pub failures: u64,
}

/// Metadata state shared by every wrapper in a collection.
pub(crate) struct SegShared {
    pub(crate) io: super::page_index::MetaIo,
    pub(crate) slots: super::skeleton::BuildSlots,
    pub(crate) foreground_builds: AtomicU64,
    pub(crate) build_failures: AtomicU64,
    #[cfg(test)]
    pub(crate) built: Mutex<Vec<u64>>,
}
impl SegShared {
    pub(crate) fn new() -> Self {
        Self {
            io: super::page_index::MetaIo::new(),
            slots: super::skeleton::BuildSlots::new(2),
            foreground_builds: AtomicU64::new(0),
            build_failures: AtomicU64::new(0),
            #[cfg(test)]
            built: Mutex::new(Vec::new()),
        }
    }
}

pub(crate) struct SegCore<K: Key + Hash + Eq + Send + Sync> {
    pub(crate) meta: SegMeta,
    pub(crate) dir: PathBuf,
    pub(crate) gen_root: PathBuf,
    pub(crate) seg_root: PathBuf,
    pub(crate) config: SegConfig,
    pub(crate) order: OrderKind,
    pub(crate) prefix_filters: Vec<usize>,
    pub(crate) fs: Arc<dyn SegFs>,
    pub(crate) clock: Clock,
    pub(crate) seed: u64,
    view: RwLock<Arc<View<K>>>,
    /// The manifest mutex. Every change of composition happens under it.
    pub(crate) manifest: Mutex<Manifest>,
    pub(crate) cache: SegBlockCache,
    pub(crate) shared: Arc<SegShared>,
    pub(crate) collection_fence: Arc<CollectionFence>,
    pub(crate) shut_down: AtomicBool,
    pub(crate) seal: Mutex<SealState>,
    /// Serializes complete seal attempts, including their output cleanup.
    pub(crate) seal_attempt: Mutex<()>,
    /// Notified whenever a seal attempt ends.
    pub(crate) seal_cv: Condvar,
    /// Shared with the worker thread, which must not keep the collection
    /// alive while it sleeps.
    pub(crate) signal: Arc<WorkerSignal>,
    pub(crate) worker: Mutex<Option<std::thread::JoinHandle<()>>>,
    /// When maintenance last ran, by the collection's clock. `0` is never.
    pub(crate) last_tick_ms: AtomicU64,
    _lease: File,
}

#[derive(Default)]
struct WorkerFlags {
    wake: bool,
    stop: bool,
}

/// How the collection talks to its worker thread.
pub(crate) struct WorkerSignal {
    flags: Mutex<WorkerFlags>,
    cv: Condvar,
}

impl WorkerSignal {
    fn new() -> Self {
        Self {
            flags: Mutex::new(WorkerFlags::default()),
            cv: Condvar::new(),
        }
    }

    /// Make the worker run now instead of at its next tick.
    pub(crate) fn wake(&self) {
        sync::lock(&self.flags).wake = true;
        self.cv.notify_all();
    }

    pub(crate) fn stop(&self) {
        sync::lock(&self.flags).stop = true;
        self.cv.notify_all();
    }

    /// Sleep for at most `pause`, less when woken. Returns `true` when the
    /// worker must stop.
    pub(crate) fn wait(&self, pause: std::time::Duration) -> bool {
        let mut flags = sync::lock(&self.flags);
        if !flags.stop && !flags.wake && !pause.is_zero() {
            flags = sync::cv_wait_timeout(&self.cv, &self.flags, flags, pause);
        }
        flags.wake = false;
        flags.stop
    }
}

fn random_seed() -> u64 {
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    hasher.write_u128(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0),
    );
    hasher.finish()
}

fn holds_anything(dir: &Path) -> DbResult<bool> {
    match std::fs::read_dir(dir) {
        Ok(mut entries) => Ok(entries.next().is_some()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(e) => Err(e.into()),
    }
}

/// Prefix filters must end inside a key and, for typed keys, on a field boundary.
pub(crate) fn validate_prefix_filters<K: Key>(lengths: &[usize]) -> DbResult<()> {
    let mut seen = HashSet::new();
    for &length in lengths {
        if length == 0 || length >= size_of::<K>() || !seen.insert(length) {
            return Err(DbError::Config(
                "prefix filter lengths must be distinct interior key positions",
            ));
        }
        if let armour_core::KeyScheme::Typed(parts) = K::KEY_SCHEME {
            let mut end = 0;
            if !parts.iter().any(|part| {
                end += part.byte_len();
                end == length
            }) {
                return Err(DbError::Config(
                    "a typed prefix filter must end on a field boundary",
                ));
            }
        }
    }
    Ok(())
}

/// The root's `db.meta`, when there is one, must name this backend.
fn check_root_meta(dir: &Path, required: bool) -> DbResult<()> {
    let path = dir.join(ROOT_META);
    let bytes = match std::fs::read(&path) {
        Ok(bytes) => bytes,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return if required {
                Err(DbError::FormatMismatch(format!(
                    "{}: db.meta is missing",
                    dir.display()
                )))
            } else {
                Ok(())
            };
        }
        Err(e) => return Err(e.into()),
    };
    let meta = DbMeta::decode(&bytes)?;
    if meta.backend != Backend::Segmented {
        return Err(DbError::FormatMismatch(format!(
            "{}: db.meta names backend {:?}, not a segmented collection",
            dir.display(),
            meta.backend
        )));
    }
    Ok(())
}

/// Initial creation, step 1: the root's contents, durable.
pub(crate) fn create_layout(fs: &dyn SegFs, dir: &Path) -> DbResult<()> {
    fs.create_dir_all(dir)?;
    fs.create_dir_all(&dir.join(GEN_DIR))?;
    fs.create_dir_all(&dir.join(SEG_DIR))?;

    let meta = DbMeta {
        version: META_VERSION,
        backend: Backend::Segmented,
        shard_count: 0,
        shard_prefix_bits: 0,
        flags: 0,
    };
    let tmp = dir.join(ROOT_META_TMP);
    let mut file = fs.create(&tmp)?;
    file.write_all(&meta.encode())?;
    fs.sync_file(&file, &tmp)?;
    drop(file);
    fs.rename(&tmp, &dir.join(ROOT_META))?;
    fs.sync_dir(dir)?;
    super::failpoint!(LAYOUT_CREATED);
    Ok(())
}

/// Open step 4. Runs only after every referenced object was validated.
fn remove_garbage(
    fs: &dyn SegFs,
    dir: &Path,
    gen_root: &Path,
    seg_root: &Path,
    manifest: &Manifest,
) -> DbResult<()> {
    fs.remove_file(&dir.join(MANIFEST_TMP))?;
    fs.remove_file(&dir.join(ROOT_META_TMP))?;

    let generations: HashSet<String> = manifest
        .generations
        .iter()
        .map(|g| gen_dir_name(g.gen_id))
        .collect();
    let mut removed = 0usize;
    if gen_root.is_dir() {
        for entry in std::fs::read_dir(gen_root)? {
            let entry = entry?;
            if generations.contains(entry.file_name().to_string_lossy().as_ref()) {
                continue;
            }
            let path = entry.path();
            tracing::info!(path = %path.display(), "removing a generation the manifest does not mention");
            if path.is_dir() {
                fs.remove_dir_all(&path)?;
            } else {
                fs.remove_file(&path)?;
            }
            removed += 1;
        }
        fs.sync_dir(gen_root)?;
    }

    let segments: HashSet<String> = manifest
        .segments
        .iter()
        .flat_map(|s| {
            [
                sdat_name(s.segment_id, s.version),
                sidx_name(s.segment_id, s.version),
            ]
        })
        .collect();
    if seg_root.is_dir() {
        for entry in std::fs::read_dir(seg_root)? {
            let entry = entry?;
            if segments.contains(entry.file_name().to_string_lossy().as_ref()) {
                continue;
            }
            let path = entry.path();
            tracing::info!(path = %path.display(), "removing a segment file the manifest does not mention");
            if path.is_dir() {
                fs.remove_dir_all(&path)?;
            } else {
                fs.remove_file(&path)?;
            }
            removed += 1;
        }
        fs.sync_dir(seg_root)?;
    }
    if removed > 0 {
        metrics::counter!("armdb.seg.garbage_removed").increment(removed as u64);
    }
    Ok(())
}

fn join_preparations<T>(
    handles: Vec<std::thread::ScopedJoinHandle<'_, DbResult<T>>>,
) -> DbResult<Vec<T>> {
    // Join every handle before returning an ordinary error: an unjoined panic
    // would otherwise unwind thread::scope instead of becoming RecoveryPanic.
    let results = handles
        .into_iter()
        .map(|h| h.join().unwrap_or(Err(DbError::RecoveryPanic)))
        .collect::<Vec<_>>();
    results.into_iter().collect()
}

/// Validate handles first, assign newest-first residency, then load metadata.
fn load_segments(
    fs: &Arc<dyn SegFs>,
    seg_root: &Path,
    manifest: &Manifest,
    shared: &Arc<SegShared>,
    budget: Option<u64>,
) -> DbResult<Vec<Arc<Segment>>> {
    let mut records: Vec<_> = manifest.segments.iter().collect();
    records.sort_by_key(|rec| std::cmp::Reverse((rec.frozen_at_ms, rec.segment_id)));
    let mut loaded = Vec::with_capacity(records.len());
    let mut remaining = budget;
    let mut prefix_closed = false;
    for batch in records.chunks(SEGMENT_LOAD_THREADS) {
        let checked = std::thread::scope(|scope| {
            let handles: Vec<_> = batch
                .iter()
                .map(|rec| {
                    scope.spawn(move || {
                        Segment::check_files(seg_root, rec, manifest.key_len, manifest.seed, shared)
                    })
                })
                .collect();
            join_preparations(handles)
        })?;
        // Consume this batch before preparing another. Each constructor uses
        // its checked inodes; only completed wrappers survive across batches.
        let inputs: Vec<_> = batch
            .iter()
            .zip(checked)
            .map(|(rec, checked)| {
                let hot = if prefix_closed {
                    false
                } else if let Some(left) = remaining {
                    if let Some(next) = left.checked_sub(checked.cost) {
                        remaining = Some(next);
                        true
                    } else {
                        prefix_closed = true;
                        false
                    }
                } else {
                    true
                };
                (rec, checked, hot)
            })
            .collect();
        let results = std::thread::scope(|scope| {
            let handles: Vec<_> = inputs
                .into_iter()
                .map(|(rec, checked, hot)| {
                    let fs = fs.clone();
                    scope.spawn(move || {
                        if hot {
                            Segment::open_hot_checked(fs, seg_root, rec, shared, checked)
                        } else {
                            Segment::open_cold(fs, seg_root, rec, shared, checked)
                        }
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|h| h.join().unwrap_or(Err(DbError::RecoveryPanic)))
                .collect::<Vec<_>>()
        });
        for result in results {
            loaded.push(Arc::new(result?));
        }
    }
    Ok(loaded)
}
impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    /// Recover without starting maintenance; managed open replays first.
    pub(crate) fn open_deferred(
        dir: &Path,
        meta: SegMeta,
        config: SegConfig,
        mut options: OpenOptions,
    ) -> DbResult<Arc<Self>> {
        options.worker = false;
        Self::open(dir, meta, config, options)
    }

    /// Start the existing idempotent worker after managed replay completes.
    pub(crate) fn start_background(self: &Arc<Self>) -> DbResult<()> {
        self.start_worker()
    }

    pub(crate) fn open(
        dir: &Path,
        meta: SegMeta,
        config: SegConfig,
        options: OpenOptions,
    ) -> DbResult<Arc<Self>> {
        Self::open_mode(dir, meta, config, options, OrderKind::ByHash, &[])
    }

    /// Open a byte-ordered collection, validating prefix declarations before filesystem mutations.
    #[allow(dead_code)] // Consumed by the tree facade in Task 6.
    pub(crate) fn open_tree(
        dir: &Path,
        meta: SegMeta,
        prefix_filters: &'static [usize],
        config: SegConfig,
        options: OpenOptions,
    ) -> DbResult<Arc<Self>> {
        Self::open_mode(dir, meta, config, options, OrderKind::ByKey, prefix_filters)
    }

    /// Recover a tree before managed replay starts maintenance.
    #[allow(dead_code)] // Consumed by managed tree open in Task 7.
    pub(crate) fn open_tree_deferred(
        dir: &Path,
        meta: SegMeta,
        prefix_filters: &'static [usize],
        config: SegConfig,
        mut options: OpenOptions,
    ) -> DbResult<Arc<Self>> {
        options.worker = false;
        Self::open_tree(dir, meta, prefix_filters, config, options)
    }

    fn open_mode(
        dir: &Path,
        meta: SegMeta,
        config: SegConfig,
        options: OpenOptions,
        order: OrderKind,
        prefix_filters: &[usize],
    ) -> DbResult<Arc<Self>> {
        config.validate()?;
        validate_prefix_filters::<K>(prefix_filters)?;
        let key_len = u16::try_from(size_of::<K>())
            .ok()
            .filter(|&len| len > 0)
            .ok_or(DbError::Config(
                "a segmented key must be 1 to 65535 bytes long",
            ))?;
        let OpenOptions { fs, clock, worker } = options;
        let gen_root = dir.join(GEN_DIR);
        let seg_root = dir.join(SEG_DIR);

        fs.create_dir_all(dir)?;
        let lease = crate::lock::acquire(dir)?;

        // Steps 1 and 2.
        let mut manifest = match manifest::load(dir)? {
            Some(manifest) => {
                check_root_meta(dir, true)?;
                if manifest.order != order {
                    return Err(DbError::FormatMismatch(format!(
                        "{}: collection order {:?} differs from requested {:?}",
                        dir.display(),
                        manifest.order,
                        order
                    )));
                }
                manifest
            }
            None => {
                check_root_meta(dir, false)?;
                if holds_anything(&gen_root)? || holds_anything(&seg_root)? {
                    return Err(DbError::ManifestCorrupt {
                        path: dir.join(MANIFEST_NAME),
                        reason: "the manifest is missing while gen/ or seg/ holds data".into(),
                    });
                }
                create_layout(&*fs, dir)?;
                let mut manifest = Manifest::new(key_len, random_seed(), clock());
                manifest.order = order;
                manifest::publish(&*fs, dir, &manifest).map_err(PublishError::into_inner)?;
                super::failpoint!(FIRST_MANIFEST_PUBLISHED);
                manifest
            }
        };
        if manifest.key_len != key_len {
            return Err(DbError::FormatMismatch(format!(
                "{}: the collection has key length {}, the type has {key_len}",
                dir.display(),
                manifest.key_len
            )));
        }
        let seed = manifest.seed;
        let collection_fence = Arc::new(CollectionFence::new(meta.name));

        // Step 3: validate every referenced object, changing nothing.
        let shared = Arc::new(SegShared::new());
        let sealed = load_segments(
            &fs,
            &seg_root,
            &manifest,
            &shared,
            config.resident_metadata_bytes,
        )?;
        for rec in &manifest.generations {
            Generation::<K>::check_existing(&gen_root, rec)?;
        }

        // A visible MANIFEST is not necessarily a durable one: a crash
        // between its rename and the directory fsync, or a reopen after a
        // publication whose outcome was unknown, shows the newer manifest
        // while the disk may still hold the older one. Step 4 deletes what
        // only the older one names; after a power loss that older manifest
        // would come back naming a deleted object. Make the manifest we
        // read durable first, and fail the open if that is not possible.
        fs.sync_dir(dir)?;

        // Finish replay before garbage cleanup. Bitcask recovery itself may
        // repair journal tails or hints; its operational errors are resumable.
        let mut generations = Vec::with_capacity(manifest.generations.len());
        for rec in &manifest.generations {
            let mut generation =
                Generation::<K>::open_existing(fs.clone(), &gen_root, rec, &config, order)?;
            generation.bind_fence(collection_fence.clone());
            generations.push(Arc::new(generation));
        }

        remove_garbage(&*fs, dir, &gen_root, &seg_root, &manifest)?;

        // Step 7.
        let recovered = generations
            .iter()
            .map(|g| g.next_gsn() - 1)
            .max()
            .unwrap_or(0);
        let next_gsn = manifest
            .gsn_floor
            .max(recovered)
            .checked_add(1)
            .ok_or(DbError::Internal("segmented GSN exhausted"))?;

        // Step 8.
        let active = if manifest.active().is_some() {
            let active = generations
                .pop()
                .expect("the active generation is the newest");
            active.raise_gsn(next_gsn);
            active
        } else {
            let mut generation = Self::create_first_generation(
                &fs,
                dir,
                &gen_root,
                &config,
                &clock,
                &mut manifest,
                next_gsn,
            )?;
            generation.bind_fence(collection_fence.clone());
            Arc::new(generation)
        };
        generations.reverse();

        // Step 9.
        let core = Arc::new(Self {
            meta,
            dir: dir.to_path_buf(),
            gen_root,
            seg_root,
            cache: SegBlockCache::new(config.block_cache_bytes),
            shared,
            config,
            order,
            prefix_filters: prefix_filters.to_vec(),
            fs,
            clock,
            seed,
            view: RwLock::new(Arc::new(View {
                active,
                frozen: generations,
                sealed,
            })),
            manifest: Mutex::new(manifest),
            collection_fence,
            shut_down: AtomicBool::new(false),
            seal: Mutex::new(SealState::default()),
            seal_attempt: Mutex::new(()),
            seal_cv: Condvar::new(),
            signal: Arc::new(WorkerSignal::new()),
            worker: Mutex::new(None),
            last_tick_ms: AtomicU64::new(0),
            _lease: lease,
        });
        if worker {
            core.start_worker()?;
        }
        Ok(core)
    }

    /// Freeze steps 0, 1 and 3 with no generation to freeze: reserve an id,
    /// create the generation, name it in the manifest.
    fn create_first_generation(
        fs: &Arc<dyn SegFs>,
        dir: &Path,
        gen_root: &Path,
        config: &SegConfig,
        clock: &Clock,
        manifest: &mut Manifest,
        next_gsn: u64,
    ) -> DbResult<Generation<K>> {
        let (reserved, gen_id) = manifest.reserve_gen_id()?;
        manifest::publish(&**fs, dir, &reserved).map_err(PublishError::into_inner)?;
        *manifest = reserved;
        super::failpoint!(GENERATION_ID_RESERVED);

        let opened_at_ms = manifest.monotone_time(clock());
        let generation = Generation::create(
            fs.clone(),
            gen_root,
            gen_id,
            config,
            opened_at_ms,
            manifest.order,
        )?;
        generation.seed_gsn(next_gsn);
        super::failpoint!(GENERATION_CREATED);

        let named = manifest
            .with_active(GenRecord {
                gen_id,
                state: GenState::Active,
                shard_count: generation.shard_count() as u8,
                opened_at_ms,
                frozen_at_ms: 0,
                min_gsn: next_gsn,
                max_gsn: 0,
            })
            .inspect_err(|_| generation.doom())?;
        match manifest::publish(&**fs, dir, &named) {
            Ok(()) => *manifest = named,
            Err(PublishError::NotPublished(e)) => {
                generation.doom();
                return Err(e);
            }
            Err(PublishError::Indeterminate(e)) => {
                // The disk may already name the generation, so its directory
                // stays. The open fails; the next open makes whichever
                // manifest it finds durable, and its garbage pass removes the
                // directory only if that manifest does not name it.
                return Err(e);
            }
        }
        Ok(generation)
    }
}
impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    pub(crate) fn view(&self) -> Arc<View<K>> {
        sync::read(&self.view).clone()
    }

    /// Call with the manifest mutex held: the view changes only there.
    pub(crate) fn set_view(&self, view: View<K>) {
        *sync::write(&self.view) = Arc::new(view);
    }

    pub(crate) fn now_ms(&self) -> u64 {
        (self.clock)()
    }

    pub(crate) fn key_len(&self) -> u16 {
        size_of::<K>() as u16
    }

    /// Refuse writes and maintenance until the collection is reopened. The
    /// first reason is kept.
    pub(crate) fn fence(&self, reason: String) -> DbError {
        let mut fence = sync::lock(&self.collection_fence.reason);
        if fence.is_none() {
            tracing::error!(collection = self.meta.name, reason = %reason, "segmented collection fenced");
            metrics::gauge!("armdb.seg.fenced", "collection" => self.meta.name).set(1.0);
            *fence = Some(reason);
            self.collection_fence.fenced.store(true, Ordering::Release);
        }
        DbError::CollectionFenced {
            collection: self.meta.name,
            reason: fence.clone().expect("set above"),
        }
    }

    pub(crate) fn fence_reason(&self) -> Option<String> {
        sync::lock(&self.collection_fence.reason).clone()
    }

    pub(crate) fn check_writable(&self) -> DbResult<()> {
        self.collection_fence.check()
    }

    /// Publish `next` and make it the current manifest.
    ///
    /// A publication that did not happen leaves `current` as it was and
    /// returns the error. One whose outcome is unknown fences the collection.
    pub(crate) fn publish_next(&self, current: &mut Manifest, next: Manifest) -> DbResult<()> {
        match manifest::publish(&*self.fs, &self.dir, &next) {
            Ok(()) => {
                *current = next;
                Ok(())
            }
            Err(PublishError::NotPublished(e)) => Err(e),
            Err(PublishError::Indeterminate(e)) => Err(self.fence(format!(
                "the outcome of a manifest publication is unknown: {e}"
            ))),
        }
    }

    /// The newest version of `key`, walking the layers newest first and
    /// stopping at the first layer frozen before `since_ms`.
    pub(crate) fn get_pruned(&self, key: &K, since_ms: Option<u64>) -> DbResult<Option<Vec<u8>>> {
        let h = key_hash(key.as_bytes(), self.seed);
        let view = self.view();
        let too_old = |frozen_at_ms: u64| since_ms.is_some_and(|since| frozen_at_ms < since);

        match view.active.lookup(h, key)? {
            GenLookup::Live(value) => return Ok(Some(value)),
            GenLookup::Tombstone => return Ok(None),
            GenLookup::Absent => {}
        }
        for generation in &view.frozen {
            if too_old(generation.frozen_at_ms()) {
                return Ok(None);
            }
            match generation.lookup(h, key)? {
                GenLookup::Live(value) => return Ok(Some(value)),
                GenLookup::Tombstone => return Ok(None),
                GenLookup::Absent => {}
            }
        }
        for segment in &view.sealed {
            if too_old(segment.record().frozen_at_ms) {
                return Ok(None);
            }
            match segment.lookup(h, key.as_bytes(), &self.cache)? {
                Lookup::Live(value) => return Ok(Some(value)),
                Lookup::Tombstone => return Ok(None),
                Lookup::Absent => {}
            }
        }
        Ok(None)
    }

    pub(crate) fn get(&self, key: &K) -> DbResult<Option<Vec<u8>>> {
        self.get_pruned(key, None)
    }

    /// A point read that trusts the caller's claim: the key, if it exists,
    /// was last written at or after `written_since_ms`.
    ///
    /// When the claim holds the result equals [`get`](Self::get). When it
    /// does not, the result may be `None` for a key that exists. Entries
    /// carry no timestamp, so a version older than the hint is returned when
    /// its layer was frozen after it.
    pub(crate) fn get_hinted(&self, key: &K, written_since_ms: u64) -> DbResult<Option<Vec<u8>>> {
        self.get_pruned(key, Some(written_since_ms))
    }

    /// Whether the layers of `view` hold a live version of `key`.
    /// Generations answer from their index; only a segment reads a block.
    pub(crate) fn exists_in(
        &self,
        view: &View<K>,
        h: u64,
        key: &K,
        with_active: bool,
        since_ms: Option<u64>,
    ) -> DbResult<bool> {
        if with_active {
            match view.active.probe(h, key) {
                GenProbe::Live => return Ok(true),
                GenProbe::Tombstone => return Ok(false),
                GenProbe::Absent => {}
            }
        }
        for generation in &view.frozen {
            if since_ms.is_some_and(|since| generation.frozen_at_ms() < since) {
                return Ok(false);
            }
            match generation.probe(h, key) {
                GenProbe::Live => return Ok(true),
                GenProbe::Tombstone => return Ok(false),
                GenProbe::Absent => {}
            }
        }
        for segment in &view.sealed {
            if since_ms.is_some_and(|since| segment.record().frozen_at_ms < since) {
                return Ok(false);
            }
            match segment.lookup(h, key.as_bytes(), &self.cache)? {
                Lookup::Live(_) => return Ok(true),
                Lookup::Tombstone => return Ok(false),
                Lookup::Absent => {}
            }
        }
        Ok(false)
    }

    /// Resolve only the layers below the active generation, newest first.
    pub(crate) fn read_below(
        &self,
        view: &View<K>,
        h: u64,
        key: &K,
        since_ms: Option<u64>,
    ) -> DbResult<Option<Vec<u8>>> {
        for generation in &view.frozen {
            if since_ms.is_some_and(|since| generation.frozen_at_ms() < since) {
                return Ok(None);
            }
            match generation.lookup(h, key)? {
                GenLookup::Live(value) => return Ok(Some(value)),
                GenLookup::Tombstone => return Ok(None),
                GenLookup::Absent => {}
            }
        }
        for segment in &view.sealed {
            if since_ms.is_some_and(|since| segment.record().frozen_at_ms < since) {
                return Ok(None);
            }
            match segment.lookup(h, key.as_bytes(), &self.cache)? {
                Lookup::Live(value) => return Ok(Some(value)),
                Lookup::Tombstone => return Ok(None),
                Lookup::Absent => {}
            }
        }
        Ok(None)
    }

    pub(crate) fn contains_below(
        &self,
        view: &View<K>,
        h: u64,
        key: &K,
        since_ms: Option<u64>,
    ) -> DbResult<bool> {
        self.exists_in(view, h, key, false, since_ms)
    }

    pub(crate) fn contains(&self, key: &K) -> DbResult<bool> {
        let h = key_hash(key.as_bytes(), self.seed);
        self.exists_in(&self.view(), h, key, true, None)
    }

    /// Live entries of every layer. An upper bound on the visible keys: a
    /// shadowed or deleted version is counted while its layer lives.
    pub(crate) fn len(&self) -> usize {
        let view = self.view();
        let generations: u64 = std::iter::once(&view.active)
            .chain(view.frozen.iter())
            .map(|g| g.live())
            .sum();
        let segments: u64 = view
            .sealed
            .iter()
            .map(|s| s.record().entries - s.record().tombstones)
            .sum();
        (generations + segments) as usize
    }

    /// Physical entries of every layer: generation keys and segment entries,
    /// tombstones and shadowed versions included.
    pub(crate) fn physical_entries(&self) -> u64 {
        let view = self.view();
        let generations: u64 = std::iter::once(&view.active)
            .chain(view.frozen.iter())
            .map(|g| g.keys())
            .sum();
        let segments: u64 = view.sealed.iter().map(|s| s.record().entries).sum();
        generations + segments
    }
}

impl<K: Key + Hash + Eq + Send + Sync + 'static> SegCore<K> {
    /// Run `f` on every generation of the current view, frozen ones first.
    /// Every generation is attempted; the first error is returned.
    ///
    /// This covers every write that returned before the call: it is in a
    /// generation of the view, or its generation was sealed, and a segment
    /// is named only after its generation and its files were made durable.
    fn for_each_generation(
        &self,
        mut f: impl FnMut(&Generation<K>) -> DbResult<()>,
    ) -> DbResult<()> {
        let view = self.view();
        let mut first = None;
        for generation in view
            .frozen
            .iter()
            .rev()
            .chain(std::iter::once(&view.active))
        {
            if let Err(e) = f(generation)
                && first.is_none()
            {
                first = Some(e);
            }
        }
        first.map_or(Ok(()), Err)
    }

    /// Write buffers to the operating system, without an fsync.
    pub(crate) fn flush(&self) -> DbResult<()> {
        self.for_each_generation(|g| g.flush_buffers())
    }

    /// The strongest barrier: buffers and fsync of every generation.
    pub(crate) fn durable_flush(&self) -> DbResult<()> {
        self.for_each_generation(|g| g.durable_flush())
    }

    /// Shards of any generation that hold writes no barrier covers yet.
    pub(crate) fn dirty_shards(&self) -> usize {
        let view = self.view();
        view.frozen
            .iter()
            .chain(std::iter::once(&view.active))
            .map(|g| g.dirty_shards())
            .sum()
    }

    /// Stop the worker, then make every generation durable and write its
    /// hint files. A running seal is aborted; its generation stays frozen
    /// and is sealed after the next open.
    ///
    /// After this no freeze and no seal happens. A write is still taken
    /// while the active generation has room.
    pub(crate) fn clean_shutdown(&self) -> DbResult<()> {
        self.stop_worker();
        self.seal_cv.notify_all();
        self.for_each_generation(|g| {
            let hints = g.write_hints();
            let close = g.close();
            hints.and(close)
        })
    }
}

impl<K: Key + Hash + Eq + Send + Sync> Drop for SegCore<K> {
    fn drop(&mut self) {
        {
            let _manifest = sync::lock(&self.manifest);
            self.shut_down.store(true, Ordering::Release);
        }
        self.signal.stop();
        let handle = sync::lock(&self.worker).take();
        if let Some(handle) = handle
            && handle.thread().id() != std::thread::current().id()
        {
            let _ = handle.join();
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn preparation_joins_a_later_panic_after_an_ordinary_error() {
        let result = std::thread::scope(|scope| {
            let first = scope.spawn(|| Err::<(), _>(DbError::Internal("first error")));
            let later = scope.spawn(|| -> DbResult<()> { panic!("later preparation panic") });
            join_preparations(vec![first, later])
        });
        assert!(matches!(result, Err(DbError::Internal("first error"))));
        let result = std::thread::scope(|scope| {
            join_preparations(vec![
                scope.spawn(|| -> DbResult<()> { panic!("preparation panic") }),
            ])
        });
        assert!(matches!(result, Err(DbError::RecoveryPanic)));
    }

    use std::time::Duration;

    use super::*;
    use crate::error::DbError;
    use crate::seg::fs::{FsOpKind, TraceFs};
    use crate::seg::manifest::{MANIFEST_NAME, MANIFEST_TMP, load};
    use crate::seg::seal::{sdat_name, sidx_name};
    use crate::seg::testkit::{
        self, KEY_LEN, SEED, TestClock, build_collection, copy_collection, key_of, open_core,
        try_open_core,
    };

    #[test]
    fn batched_reopen_matches_newest_first_prefix_across_boundaries() {
        let dir = tempfile::tempdir().unwrap();
        let mut manifest = Manifest::new(KEY_LEN as u16, SEED, 0);
        for id in 1..=21 {
            let entries = testkit::entries(id * 20, 1);
            let mut rec =
                testkit::write_segment(super::super::fs::real(), dir.path(), id, &entries);
            rec.frozen_at_ms = id;
            manifest.segments.push(rec);
        }
        let shared = Arc::new(SegShared::new());
        let costs: Vec<_> = load_segments(
            &super::super::fs::real(),
            dir.path(),
            &manifest,
            &shared,
            None,
        )
        .unwrap()
        .iter()
        .map(|s| s.cost())
        .collect();
        for prefix in [0, 1, 7, 8, 9, 16, 17, 21] {
            let exact: u64 = costs[..prefix].iter().sum();
            let slack = costs.get(prefix).map_or(exact, |next| exact + next - 1);
            for budget in [exact, slack] {
                let loaded = load_segments(
                    &super::super::fs::real(),
                    dir.path(),
                    &manifest,
                    &shared,
                    Some(budget),
                )
                .unwrap();
                assert_eq!(loaded.iter().take_while(|s| s.is_hot()).count(), prefix);
                assert!(loaded.iter().skip(prefix).all(|s| !s.is_hot()));
                assert_eq!(loaded.iter().map(|s| s.cost()).collect::<Vec<_>>(), costs);
            }
        }
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn default_reopen_bounds_checked_descriptors() {
        const CHILD: &str = "ARMDB_TASK5_FD_CHILD";
        if std::env::var_os(CHILD).is_none() {
            let output = std::process::Command::new(std::env::current_exe().unwrap())
                .args([
                    "--exact",
                    "seg::core::tests::default_reopen_bounds_checked_descriptors",
                    "--nocapture",
                ])
                .env(CHILD, "1")
                .output()
                .unwrap();
            assert!(
                output.status.success(),
                "child: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            return;
        }
        let dir = tempfile::tempdir().unwrap();
        let mut manifest = Manifest::new(KEY_LEN as u16, SEED, 0);
        let entries = testkit::entries(3, 1);
        for id in 1..=180 {
            let mut rec =
                testkit::write_segment(super::super::fs::real(), dir.path(), id, &entries);
            rec.frozen_at_ms = id;
            manifest.segments.push(rec);
        }
        // Only this dedicated child changes its process resource limit.
        let limit = libc::rlimit {
            rlim_cur: 256,
            rlim_max: 256,
        };
        assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }, 0);
        let shared = Arc::new(SegShared::new());
        let loaded = load_segments(
            &super::super::fs::real(),
            dir.path(),
            &manifest,
            &shared,
            None,
        )
        .unwrap();
        assert_eq!(loaded.len(), 180);
        assert!(loaded.iter().all(|s| s.is_hot()));
        assert_eq!(loaded.first().unwrap().record().segment_id, 180);
        assert_eq!(loaded.last().unwrap().record().segment_id, 1);
    }

    #[test]
    fn deferred_open_starts_no_worker_until_requested() {
        let dir = tempfile::tempdir().unwrap();
        let meta = SegMeta {
            name: "deferred",
            typ_hash: 1,
            value_version: 1,
        };
        let core = SegCore::<testkit::TestKey>::open_deferred(
            dir.path(),
            meta,
            SegConfig::test(),
            OpenOptions::production(),
        )
        .unwrap();
        assert!(!core.worker_running());
        core.start_background().unwrap();
        assert!(core.worker_running());
        let worker_id = sync::lock(&core.worker).as_ref().unwrap().thread().id();
        core.start_background().unwrap();
        assert_eq!(
            sync::lock(&core.worker).as_ref().unwrap().thread().id(),
            worker_id,
            "repeated startup must retain the original worker handle"
        );
        core.stop_worker();
        assert!(!core.worker_running());
        drop(core);
        let core = SegCore::<testkit::TestKey>::open(
            dir.path(),
            meta,
            SegConfig::test(),
            OpenOptions::production(),
        )
        .unwrap();
        assert!(core.worker_running());
    }

    #[test]
    fn start_background_concurrently_retains_one_worker() {
        let dir = tempfile::tempdir().unwrap();
        let core = SegCore::<testkit::TestKey>::open_deferred(
            dir.path(),
            SegMeta {
                name: "concurrent-start",
                typ_hash: 1,
                value_version: 1,
            },
            SegConfig::test(),
            OpenOptions::production(),
        )
        .unwrap();
        let barrier = std::sync::Barrier::new(8);
        let ids = std::thread::scope(|scope| {
            let callers: Vec<_> = (0..8)
                .map(|_| {
                    scope.spawn(|| {
                        barrier.wait();
                        core.start_background().unwrap();
                        sync::lock(&core.worker).as_ref().unwrap().thread().id()
                    })
                })
                .collect();
            callers
                .into_iter()
                .map(|caller| caller.join().unwrap())
                .collect::<Vec<_>>()
        });
        let first = ids[0];
        let retained = sync::lock(&core.worker).as_ref().unwrap().thread().id();
        // Concurrent callers must all observe the one handle installed by startup.
        assert!(ids.iter().all(|id| *id == first));
        assert_eq!(retained, first);
        let barrier = std::sync::Barrier::new(8);
        std::thread::scope(|scope| {
            for _ in 0..8 {
                let barrier = &barrier;
                let core = &core;
                scope.spawn(move || {
                    barrier.wait();
                    core.start_background().unwrap();
                    assert_eq!(
                        sync::lock(&core.worker).as_ref().unwrap().thread().id(),
                        first
                    );
                });
            }
        });
        core.stop_worker();
        assert!(!core.worker_running());
    }

    #[test]
    fn hinted_lower_reads_skip_layers_frozen_before_the_hint() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(
            dir.path(),
            SegConfig {
                block_cache_bytes: 0,
                resident_metadata_bytes: Some(0),
                ..wide()
            },
        );
        let view = core.view();
        let key = key_of(50);
        let h = key_hash(&key, core.seed);
        let at = view
            .sealed
            .iter()
            .find(|s| matches!(s.lookup(h, &key, &core.cache).unwrap(), Lookup::Live(_)))
            .map(|s| s.record().frozen_at_ms)
            .unwrap();
        assert_eq!(
            core.read_below(&view, h, &key, None).unwrap(),
            Some(testkit::value_of(50))
        );
        assert_eq!(core.read_below(&view, h, &key, Some(at + 1)).unwrap(), None);
        assert!(!core.contains_below(&view, h, &key, Some(at + 1)).unwrap());
        assert!(core.contains_below(&view, h, &key, Some(at)).unwrap());
        let frozen_key = key_of(150);
        let fh = key_hash(&frozen_key, core.seed);
        let frozen_at = view.frozen[0].frozen_at_ms();
        assert!(
            core.read_below(&view, fh, &frozen_key, Some(frozen_at))
                .unwrap()
                .is_some()
        );
        assert_eq!(
            core.read_below(&view, fh, &frozen_key, Some(frozen_at + 1))
                .unwrap(),
            None
        );
        assert!(
            !core
                .contains_below(&view, fh, &frozen_key, Some(frozen_at + 1))
                .unwrap()
        );
        core.put(&key, b"active").unwrap();
        assert!(
            core.exists_in(&core.view(), h, &key, true, Some(u64::MAX))
                .unwrap()
        );
    }

    #[test]
    fn held_lower_reads_skip_active_and_obey_tombstones_and_errors() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(
            dir.path(),
            SegConfig {
                block_cache_bytes: 0,
                ..wide()
            },
        );
        let key = key_of(50);
        core.put(&key, b"newer").unwrap();
        let view = core.view();
        let held = view
            .active
            .lock_owned(&(0..view.active.shard_count()).collect::<Vec<_>>())
            .unwrap();
        let h = key_hash(&key, core.seed);
        assert_eq!(
            core.read_below(&view, h, &key, None).unwrap(),
            Some(testkit::value_of(50))
        );
        assert!(core.contains_below(&view, h, &key, None).unwrap());
        let deleted = key_of(105);
        let dh = key_hash(&deleted, core.seed);
        assert_eq!(core.read_below(&view, dh, &deleted, None).unwrap(), None);
        assert!(!core.contains_below(&view, dh, &deleted, None).unwrap());
        std::fs::OpenOptions::new()
            .write(true)
            .open(dir.path().join("seg").join(sdat_name(1, 1)))
            .unwrap()
            .set_len(64)
            .unwrap();
        assert!(core.read_below(&view, h, &key, None).is_err());
        assert!(core.contains_below(&view, h, &key, None).is_err());
        drop(held);
    }

    #[test]
    fn a_shutdown_hint_error_still_flushes_the_remaining_shards() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), wide());
        for i in 0..100 {
            core.put(&key_of(i), b"v").unwrap();
        }
        assert_eq!(core.dirty_shards(), 2);
        let shard = dir.path().join("gen/0000000000000001/shard_000");
        let journal = std::fs::read_dir(&shard)
            .unwrap()
            .map(|entry| entry.unwrap().path())
            .find(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "data")
            })
            .unwrap();
        let moved = journal.with_extension("moved");
        // The open descriptor can still flush, but hint generation cannot
        // reopen shard zero's journal and exits before reaching shard one.
        std::fs::rename(&journal, &moved).unwrap();
        let result = core.clean_shutdown();
        std::fs::rename(&moved, &journal).unwrap();
        assert!(
            matches!(result, Err(DbError::Io(ref error)) if error.kind() == std::io::ErrorKind::NotFound)
        );
        assert_eq!(
            core.dirty_shards(),
            0,
            "close must flush after a hint error"
        );
    }

    #[test]
    fn a_generation_barrier_attempts_all_generations_and_returns_the_first_error() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), wide());
        core.put(&key_of(0), b"first").unwrap();
        core.seal().unwrap();
        core.put(&key_of(1), b"second").unwrap();
        core.seal().unwrap();
        core.put(&key_of(2), b"active").unwrap();
        let mut attempted = Vec::new();
        let error = core
            .for_each_generation(|generation| {
                attempted.push(generation.id());
                Err(DbError::Client(if attempted.len() == 1 {
                    "first barrier error"
                } else {
                    "later barrier error"
                }))
            })
            .unwrap_err();
        assert_eq!(attempted, [1, 2, 3]);
        assert!(matches!(error, DbError::Client("first barrier error")));
    }

    fn wide() -> SegConfig {
        SegConfig {
            seal_max_keys: 1_000_000,
            max_frozen_generations: 8,
            ..SegConfig::test()
        }
    }

    #[test]
    fn a_barrier_covers_frozen_generations() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), wide());
        for i in 0..200 {
            core.put(&key_of(i), b"in the frozen generation").unwrap();
        }
        // The seal never runs: the worker is off.
        core.seal().unwrap();
        for i in 200..300 {
            core.put(&key_of(i), b"in the active generation").unwrap();
        }
        assert!(core.dirty_shards() > 0);
        assert!(
            core.view().frozen[0].dirty_shards() > 0,
            "the freeze did not flush"
        );

        core.durable_flush().unwrap();
        assert_eq!(core.dirty_shards(), 0);

        // What a crash right after the barrier leaves behind.
        let crashed = tempfile::tempdir().unwrap();
        copy_collection(dir.path(), crashed.path());
        let recovered = open_core(crashed.path(), wide());
        for i in 0..300 {
            assert!(recovered.get(&key_of(i)).unwrap().is_some(), "key {i}");
        }
        assert_eq!(recovered.view().frozen.len(), 1);
    }

    #[test]
    fn a_plain_flush_empties_the_buffers_of_every_generation() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), wide());
        for i in 0..50 {
            core.put(&key_of(i), b"v").unwrap();
        }
        core.seal().unwrap();
        for i in 50..100 {
            core.put(&key_of(i), b"v").unwrap();
        }
        core.flush().unwrap();

        let crashed = tempfile::tempdir().unwrap();
        copy_collection(dir.path(), crashed.path());
        let recovered = open_core(crashed.path(), wide());
        for i in 0..100 {
            assert!(recovered.get(&key_of(i)).unwrap().is_some(), "key {i}");
        }
    }

    #[test]
    fn a_clean_shutdown_leaves_every_generation_durable_and_hinted() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), wide());
        for i in 0..50 {
            core.put(&key_of(i), b"v").unwrap();
        }
        core.seal().unwrap();
        for i in 50..100 {
            core.put(&key_of(i), b"v").unwrap();
        }
        core.clean_shutdown().unwrap();
        assert_eq!(core.dirty_shards(), 0);

        for generation in ["gen/0000000000000001", "gen/0000000000000002"] {
            let hints = std::fs::read_dir(dir.path().join(generation).join("shard_000"))
                .unwrap()
                .filter(|e| {
                    e.as_ref()
                        .unwrap()
                        .path()
                        .extension()
                        .is_some_and(|x| x == "hint")
                })
                .count();
            assert!(hints > 0, "{generation} has no hint file");
        }
        // Idempotent.
        core.clean_shutdown().unwrap();
    }

    #[test]
    fn after_a_shutdown_nothing_is_frozen_or_sealed() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 5,
            max_frozen_generations: 4,
            seal_wait_timeout: Duration::from_secs(5),
            ..SegConfig::test()
        };
        let core = open_core(dir.path(), config);
        for i in 0..3 {
            core.put(&key_of(i), b"v").unwrap();
        }
        core.seal().unwrap();
        core.clean_shutdown().unwrap();

        // A write is still taken while the generation has room.
        core.put(&key_of(10), b"v").unwrap();
        core.put(&key_of(11), b"v").unwrap();
        for i in 12..15 {
            core.put(&key_of(i), b"v").unwrap();
        }
        assert!(core.view().active.is_full());

        let started = std::time::Instant::now();
        assert!(matches!(
            core.put(&key_of(99), b"v"),
            Err(DbError::SealBackpressure { .. })
        ));
        assert!(
            started.elapsed() < Duration::from_secs(1),
            "a shut-down collection does not wait for a seal that cannot come"
        );
        assert_eq!(core.view().frozen.len(), 1, "no freeze after the shutdown");

        // A seal asked for after the shutdown is aborted and leaves no file.
        assert!(core.seal_oldest().is_err());
        assert_eq!(
            std::fs::read_dir(dir.path().join("seg")).unwrap().count(),
            0
        );
        core.tick().unwrap();
        assert_eq!(core.view().frozen.len(), 1);
    }

    /// Layers, oldest first: a segment frozen at 1000 holding A; a segment
    /// frozen at 2000 holding B and a tombstone for A2; a frozen generation
    /// frozen at 3000 holding C and E; the active generation holding D.
    fn layered(dir: &Path, clock: &TestClock) -> Arc<SegCore<crate::seg::testkit::TestKey>> {
        let config = SegConfig {
            seal_max_keys: 1_000_000,
            max_frozen_generations: 8,
            ..SegConfig::test()
        };
        let core = try_open_core(dir, config, crate::seg::fs::real(), clock).unwrap();
        clock.set(1_000);
        core.put(&key_of(b'A' as u64), b"a").unwrap();
        core.put(&key_of(0xA2), b"a2").unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();

        clock.set(2_000);
        core.put(&key_of(b'B' as u64), b"b").unwrap();
        core.delete(&key_of(0xA2)).unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();

        clock.set(2_100);
        core.put(&key_of(b'E' as u64), b"e").unwrap();
        clock.set(3_000);
        core.put(&key_of(b'C' as u64), b"c").unwrap();
        core.seal().unwrap();

        clock.set(4_000);
        core.put(&key_of(b'D' as u64), b"d").unwrap();
        core
    }

    fn hinted(
        core: &SegCore<crate::seg::testkit::TestKey>,
        name: u8,
        since: u64,
    ) -> Option<Vec<u8>> {
        core.get_hinted(&key_of(name as u64), since).unwrap()
    }

    #[test]
    fn a_hint_prunes_layers_frozen_before_it() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = layered(dir.path(), &clock);

        for name in *b"ABCDE" {
            assert!(hinted(&core, name, 0).is_some(), "{}", name as char);
        }
        assert_eq!(hinted(&core, b'A', 1_000), Some(b"a".to_vec()));
        assert_eq!(
            hinted(&core, b'A', 1_001),
            None,
            "its layer froze before the hint"
        );
        assert_eq!(hinted(&core, b'B', 2_000), Some(b"b".to_vec()));
        assert_eq!(hinted(&core, b'B', 2_001), None);
        assert_eq!(hinted(&core, b'C', 3_000), Some(b"c".to_vec()));
        assert_eq!(hinted(&core, b'C', 3_001), None);
    }

    #[test]
    fn the_active_generation_is_always_consulted() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = layered(dir.path(), &clock);
        assert_eq!(hinted(&core, b'D', u64::MAX), Some(b"d".to_vec()));
        assert_eq!(hinted(&core, b'C', u64::MAX), None);
    }

    #[test]
    fn a_version_older_than_the_hint_is_returned_when_its_layer_is_newer() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = layered(dir.path(), &clock);
        // E was written at 2100, in a layer frozen at 3000.
        assert_eq!(hinted(&core, b'E', 2_500), Some(b"e".to_vec()));
    }

    #[test]
    fn a_newer_tombstone_is_never_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let core = layered(dir.path(), &clock);
        for since in [0, 1_000, 1_500, 2_000] {
            assert_eq!(
                core.get_hinted(&key_of(0xA2), since).unwrap(),
                None,
                "hint {since}"
            );
        }
        assert_eq!(core.get(&key_of(0xA2)).unwrap(), None);
    }

    #[test]
    fn a_clock_that_went_back_does_not_reorder_the_layers() {
        let dir = tempfile::tempdir().unwrap();
        let clock = TestClock::new(1);
        let config = SegConfig {
            seal_max_keys: 1_000_000,
            max_frozen_generations: 8,
            ..SegConfig::test()
        };
        let core = try_open_core(dir.path(), config, crate::seg::fs::real(), &clock).unwrap();
        clock.set(5_000);
        core.put(&key_of(1), b"old").unwrap();
        core.seal().unwrap();
        clock.set(100);
        core.delete(&key_of(1)).unwrap();
        core.seal().unwrap();

        let view = core.view();
        assert_eq!(view.frozen[0].frozen_at_ms(), 5_000, "clamped by I7");
        assert_eq!(view.frozen[1].frozen_at_ms(), 5_000);
        // Both layers pass the hint, newest first: the tombstone decides.
        assert_eq!(core.get_hinted(&key_of(1), 5_000).unwrap(), None);
    }

    fn config() -> SegConfig {
        SegConfig::test()
    }

    fn tree(dir: &Path) -> Vec<String> {
        fn walk(base: &Path, dir: &Path, out: &mut Vec<String>) {
            for entry in std::fs::read_dir(dir).unwrap() {
                let path = entry.unwrap().path();
                out.push(path.strip_prefix(base).unwrap().display().to_string());
                if path.is_dir() {
                    walk(base, &path, out);
                }
            }
        }
        let mut out = Vec::new();
        walk(dir, dir, &mut out);
        out.retain(|p| !p.ends_with("db.lock"));
        out.sort();
        out
    }

    #[test]
    fn a_new_collection_has_one_active_generation() {
        let dir = tempfile::tempdir().unwrap();
        let core = open_core(dir.path(), config());
        assert_eq!(core.len(), 0);
        assert_eq!(core.get(&key_of(1)).unwrap(), None);
        assert_eq!(core.key_len(), KEY_LEN as u16);

        let view = core.view();
        assert_eq!(view.active.id(), 1);
        assert!(view.frozen.is_empty() && view.sealed.is_empty());
        assert_eq!(view.active.next_gsn(), 1);

        let manifest = load(dir.path()).unwrap().unwrap();
        assert_eq!(manifest.generations.len(), 1);
        assert_eq!(manifest.next_gen_id, 2);
        assert_eq!(manifest.key_len, KEY_LEN as u16);
        assert_eq!(manifest.seed, core.seed);
        assert!(dir.path().join("db.meta").is_file());
        assert!(dir.path().join("gen/0000000000000001").is_dir());
        assert!(dir.path().join("seg").is_dir());
    }

    #[test]
    fn two_collections_get_different_seeds() {
        let a = tempfile::tempdir().unwrap();
        let b = tempfile::tempdir().unwrap();
        assert_ne!(
            open_core(a.path(), config()).seed,
            open_core(b.path(), config()).seed
        );
    }

    #[test]
    fn creation_publishes_a_manifest_before_the_first_generation_exists() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let _core = try_open_core(dir.path(), config(), fs.clone(), &TestClock::new(5)).unwrap();

        let first_manifest = fs.position(FsOpKind::Rename, MANIFEST_NAME).unwrap();
        let generation = fs.position(FsOpKind::SyncDir, "0000000000000001").unwrap();
        assert!(first_manifest < generation);
        // Reserve the id, then name the generation: three publications.
        let publications = fs
            .ops()
            .iter()
            .filter(|op| op.kind() == FsOpKind::Rename && op.target().ends_with(MANIFEST_NAME))
            .count();
        assert_eq!(publications, 3);
    }

    #[test]
    fn an_interrupted_creation_is_completed_by_the_next_open() {
        let dir = tempfile::tempdir().unwrap();
        create_layout(&*crate::seg::fs::real(), dir.path()).unwrap();
        let manifest = Manifest::new(KEY_LEN as u16, SEED, 1);
        manifest::publish(&*crate::seg::fs::real(), dir.path(), &manifest).unwrap();

        let core = open_core(dir.path(), config());
        assert_eq!(core.view().active.id(), 1);
        assert_eq!(core.seed, SEED);
    }

    #[test]
    fn an_unknown_naming_of_the_first_generation_keeps_its_directory() {
        // The publication that names the first generation renames MANIFEST
        // and then fails to sync the directory. The visible manifest names
        // the generation, so its directory must stay: the next open needs it.
        fn prepare(dir: &Path) {
            create_layout(&*crate::seg::fs::real(), dir).unwrap();
            let manifest = Manifest::new(KEY_LEN as u16, SEED, 1);
            manifest::publish(&*crate::seg::fs::real(), dir, &manifest).unwrap();
        }
        // A dry run finds that publication's directory sync: the last sync
        // of the collection directory during the open.
        let dry = tempfile::tempdir().unwrap();
        prepare(dry.path());
        let trace = TraceFs::new();
        drop(try_open_core(dry.path(), config(), trace.clone(), &TestClock::new(1)).unwrap());
        let syncs: Vec<_> = trace
            .ops()
            .into_iter()
            .filter(|op| op.kind() == FsOpKind::SyncDir)
            .collect();
        let naming = syncs
            .iter()
            .rposition(|op| op.target() == dry.path())
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        prepare(dir.path());
        let fs = TraceFs::new();
        fs.fail_on(FsOpKind::SyncDir, "", naming);
        assert!(try_open_core(dir.path(), config(), fs, &TestClock::new(1)).is_err());
        assert!(
            dir.path().join("gen/0000000000000001").is_dir(),
            "an Indeterminate publication must not doom the generation"
        );
        let visible = load(dir.path()).unwrap().unwrap();
        assert_eq!(visible.active().map(|g| g.gen_id), Some(1));

        let core = open_core(dir.path(), config());
        assert_eq!(core.view().active.id(), 1);
    }

    #[test]
    fn data_without_a_manifest_is_refused_and_left_alone() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("gen/0000000000000007/shard_000")).unwrap();
        let before = tree(dir.path());
        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(
            matches!(err, DbError::ManifestCorrupt { reason, .. } if reason.contains("missing"))
        );
        assert_eq!(tree(dir.path()), before);
    }

    #[test]
    fn a_directory_of_another_backend_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let meta = DbMeta {
            version: META_VERSION,
            backend: Backend::Bitcask,
            shard_count: 2,
            shard_prefix_bits: 0,
            flags: 0,
        };
        std::fs::write(dir.path().join("db.meta"), meta.encode()).unwrap();
        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(matches!(err, DbError::FormatMismatch(m) if m.contains("backend")));
    }

    #[test]
    fn another_key_length_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        drop(open_core(dir.path(), config()));
        let result: DbResult<Arc<SegCore<[u8; 16]>>> = SegCore::open(
            dir.path(),
            testkit::meta(),
            config(),
            OpenOptions {
                fs: crate::seg::fs::real(),
                clock: wall_clock(),
                worker: false,
            },
        );
        assert!(
            matches!(result.err().unwrap(), DbError::FormatMismatch(m) if m.contains("key length"))
        );
    }

    #[test]
    fn a_collection_cannot_be_opened_twice() {
        let dir = tempfile::tempdir().unwrap();
        let _first = open_core(dir.path(), config());
        let second = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        );
        assert!(matches!(second.err().unwrap(), DbError::Locked { .. }));
    }

    /// The value a read must return for key `i` of [`build_collection`].
    fn expected(i: u64) -> Option<Vec<u8>> {
        match i {
            200..210 => None,
            210..300 => Some(format!("active-{i}").into_bytes()),
            100..110 => None,
            110..200 => Some(format!("frozen-{i}").into_bytes()),
            // Only the segment holds these; every tenth is a tombstone there.
            0..100 if i % 10 == 9 => None,
            0..100 => Some(testkit::value_of(i)),
            _ => None,
        }
    }

    #[test]
    fn reads_take_the_newest_layer() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), config());

        let view = core.view();
        assert_eq!(view.active.id(), 2);
        assert_eq!(view.frozen.len(), 1);
        assert!(view.frozen[0].is_frozen());
        assert_eq!(view.sealed.len(), 1);

        for i in 0..320u64 {
            let key = key_of(i);
            assert_eq!(core.get(&key).unwrap(), expected(i), "key {i}");
            assert_eq!(
                core.contains(&key).unwrap(),
                expected(i).is_some(),
                "key {i}"
            );
        }
    }

    #[test]
    fn len_counts_live_entries_of_every_layer() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), config());
        // Segment: 200 entries, 20 tombstones. Frozen: 150, 10 deleted.
        // Active: 100, 10 deleted. Shadowed versions are counted.
        assert_eq!(core.len(), 180 + 140 + 90);
    }

    #[test]
    fn the_gsn_continues_above_everything_recovered() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), config());
        assert_eq!(core.view().active.next_gsn(), 451);
        assert_eq!(core.view().active.min_gsn(), 351);
    }

    #[test]
    fn the_floor_wins_over_a_journal_that_lost_its_tail() {
        let dir = tempfile::tempdir().unwrap();
        drop(open_core(dir.path(), config()));
        let mut manifest = load(dir.path()).unwrap().unwrap();
        manifest.gsn_floor = 500;
        manifest.generations[0].min_gsn = 501;
        manifest.manifest_version += 1;
        manifest::publish(&*crate::seg::fs::real(), dir.path(), &manifest).unwrap();

        let core = open_core(dir.path(), config());
        assert_eq!(core.view().active.next_gsn(), 501);
    }

    #[test]
    fn garbage_is_removed_by_a_successful_open() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff/shard_000")).unwrap();
        std::fs::write(dir.path().join("seg/00000000000000ee-0001.sdat"), b"stray").unwrap();
        std::fs::write(
            dir.path().join("seg/0000000000000002-0001.sdat.tmp"),
            b"torn",
        )
        .unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"torn").unwrap();

        let _core = open_core(dir.path(), config());
        assert!(!dir.path().join("gen/00000000000000ff").exists());
        assert!(!dir.path().join("seg/00000000000000ee-0001.sdat").exists());
        assert!(
            !dir.path()
                .join("seg/0000000000000002-0001.sdat.tmp")
                .exists()
        );
        assert!(!dir.path().join(MANIFEST_TMP).exists());
        // What the manifest mentions stays.
        assert!(dir.path().join("seg").join(sdat_name(1, 1)).exists());
        assert!(dir.path().join("seg").join(sidx_name(1, 1)).exists());
        assert!(dir.path().join("gen/0000000000000001").exists());
    }

    #[test]
    fn the_manifest_is_made_durable_before_garbage_is_removed() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        let fs = TraceFs::new();
        drop(try_open_core(dir.path(), config(), fs.clone(), &TestClock::new(1)).unwrap());

        let ops = fs.ops();
        let synced = ops
            .iter()
            .position(|op| op.kind() == FsOpKind::SyncDir && op.target() == dir.path())
            .expect("open syncs the collection directory");
        let first_removal = ops
            .iter()
            .position(|op| matches!(op.kind(), FsOpKind::RemoveFile | FsOpKind::RemoveDirAll))
            .expect("open removes garbage");
        assert!(synced < first_removal, "{ops:?}");
        assert!(!dir.path().join("gen/00000000000000ff").exists());
    }

    #[test]
    fn an_open_that_cannot_make_the_manifest_durable_removes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        let before = tree(dir.path());
        let fs = TraceFs::new();
        // Nothing syncs a directory earlier in the open of an existing
        // collection, so the first sync is the manifest's.
        fs.fail_on(FsOpKind::SyncDir, "", 0);
        assert!(try_open_core(dir.path(), config(), fs, &TestClock::new(1)).is_err());
        assert_eq!(tree(dir.path()), before);
    }

    #[test]
    fn a_failed_open_changes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"torn").unwrap();
        std::fs::remove_file(dir.path().join("seg").join(sidx_name(1, 1))).unwrap();
        let before = tree(dir.path());

        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(matches!(err, DbError::SegmentMissing { segment_id: 1, .. }));
        assert_eq!(tree(dir.path()), before);
    }

    /// Storage snapshots deliberately exclude the lock's diagnostic PID.
    fn storage_bytes(dir: &Path) -> Vec<(String, Vec<u8>)> {
        tree(dir)
            .into_iter()
            .filter_map(|name| {
                let path = dir.join(&name);
                path.is_file().then(|| (name, std::fs::read(path).unwrap()))
            })
            .collect()
    }

    #[test]
    fn a_same_length_corrupt_sidecar_preserves_storage_and_garbage() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        std::fs::write(dir.path().join("seg/garbage.tmp"), b"must stay").unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"must also stay").unwrap();
        let sidecar = dir.path().join("seg").join(sidx_name(1, 1));
        let mut bytes = std::fs::read(&sidecar).unwrap();
        // A section payload byte bypasses the shallow header/table check.
        bytes[64] ^= 1;
        std::fs::write(sidecar, bytes).unwrap();
        let before_tree = tree(dir.path());
        let before_bytes = storage_bytes(dir.path());
        // This regression checks the default eager whole-sidecar validation.
        let config = SegConfig {
            resident_metadata_bytes: None,
            ..config()
        };
        let err = try_open_core(
            dir.path(),
            config,
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(matches!(err, DbError::SegmentCorrupt { segment_id: 1, .. }));
        assert_eq!(tree(dir.path()), before_tree);
        assert_eq!(storage_bytes(dir.path()), before_bytes);
    }

    #[test]
    fn all_generation_structures_are_validated_before_recovery() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"must stay").unwrap();
        // The earlier generation has a recoverable bad tail. The later one
        // is structurally invalid, so even tail repair must not begin.
        use std::io::Write;
        let mut journal = std::fs::OpenOptions::new()
            .append(true)
            .open(
                dir.path()
                    .join("gen/0000000000000001/shard_000/000001.data"),
            )
            .unwrap();
        journal.write_all(b"torn tail").unwrap();
        drop(journal);
        std::fs::remove_dir_all(dir.path().join("gen/0000000000000002/shard_000")).unwrap();
        let before_tree = tree(dir.path());
        let before_bytes = storage_bytes(dir.path());
        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(matches!(err, DbError::GenerationMissing { gen_id: 2, .. }));
        assert_eq!(tree(dir.path()), before_tree);
        assert_eq!(storage_bytes(dir.path()), before_bytes);
    }

    #[test]
    fn encrypted_generation_metadata_is_rejected_before_recovery() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        std::fs::create_dir_all(dir.path().join("gen/00000000000000ff")).unwrap();
        std::fs::write(dir.path().join("seg/garbage.tmp"), b"must stay").unwrap();
        std::fs::write(dir.path().join(MANIFEST_TMP), b"must also stay").unwrap();
        // A later generation's incompatible metadata must be rejected before
        // recovering the earlier frozen generation's torn journal tail.
        use std::io::Write;
        let mut journal = std::fs::OpenOptions::new()
            .append(true)
            .open(
                dir.path()
                    .join("gen/0000000000000001/shard_000/000001.data"),
            )
            .unwrap();
        journal.write_all(b"torn tail").unwrap();
        drop(journal);
        let meta_path = dir.path().join("gen/0000000000000002/db.meta");
        let mut bytes = std::fs::read(&meta_path).unwrap();
        bytes[8] = 1; // Bitcask encryption flag; segmented journals are plaintext.
        std::fs::write(meta_path, bytes).unwrap();
        let before_tree = tree(dir.path());
        let before_bytes = storage_bytes(dir.path());
        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert_eq!(tree(dir.path()), before_tree);
        assert_eq!(storage_bytes(dir.path()), before_bytes);
        assert!(matches!(err, DbError::GenerationMissing { gen_id: 2, .. }));
    }

    #[test]
    fn a_missing_generation_fails_the_open_and_is_not_recreated() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        // The frozen generation holds tombstones for keys of the segment.
        std::fs::remove_dir_all(dir.path().join("gen/0000000000000001")).unwrap();
        let before = tree(dir.path());

        let err = try_open_core(
            dir.path(),
            config(),
            crate::seg::fs::real(),
            &TestClock::new(1),
        )
        .err()
        .unwrap();
        assert!(matches!(err, DbError::GenerationMissing { gen_id: 1, .. }));
        assert_eq!(tree(dir.path()), before);
    }

    #[test]
    fn the_shard_count_may_change_between_opens() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let wider = SegConfig {
            shard_count: 8,
            ..config()
        };
        let core = open_core(dir.path(), wider);
        assert_eq!(
            core.view().active.shard_count(),
            2,
            "an existing generation keeps its count"
        );
        for i in [0u64, 105, 150, 205, 250] {
            assert_eq!(core.get(&key_of(i)).unwrap(), expected(i), "key {i}");
        }
    }

    #[test]
    fn a_fenced_collection_still_reads() {
        let dir = tempfile::tempdir().unwrap();
        build_collection(dir.path());
        let core = open_core(dir.path(), config());
        core.check_writable().unwrap();
        let err = core.fence("test".into());
        assert!(matches!(
            err,
            DbError::CollectionFenced {
                collection: "test_seg",
                ..
            }
        ));
        assert!(matches!(
            core.check_writable(),
            Err(DbError::CollectionFenced { reason, .. }) if reason == "test"
        ));
        assert_eq!(core.fence_reason().as_deref(), Some("test"));
        assert_eq!(core.get(&key_of(150)).unwrap(), expected(150));

        // The first reason is kept.
        core.fence("later".into());
        assert_eq!(core.fence_reason().as_deref(), Some("test"));
    }

    #[test]
    fn a_failed_publication_is_reported_and_an_unknown_one_fences() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let core = try_open_core(dir.path(), config(), fs.clone(), &TestClock::new(1)).unwrap();

        fs.fail_on(FsOpKind::Rename, MANIFEST_NAME, 0);
        {
            let mut manifest = sync::lock(&core.manifest);
            let version = manifest.manifest_version;
            let (next, _) = manifest.reserve_segment_id().unwrap();
            assert!(core.publish_next(&mut manifest, next).is_err());
            assert_eq!(manifest.manifest_version, version, "nothing was published");
        }
        core.check_writable().unwrap();

        fs.fail_on(FsOpKind::SyncDir, "", 0);
        {
            let mut manifest = sync::lock(&core.manifest);
            let (next, _) = manifest.reserve_segment_id().unwrap();
            let err = core.publish_next(&mut manifest, next).unwrap_err();
            assert!(matches!(err, DbError::CollectionFenced { .. }));
        }
        assert!(core.check_writable().is_err());
    }
    #[derive(Clone, Copy)]
    struct TypedTreeKey([u8; 24]);
    impl Key for TypedTreeKey {
        const KEY_SCHEME: armour_core::KeyScheme = armour_core::KeyScheme::Typed(&[
            armour_core::KeyType::Fuid,
            armour_core::KeyType::Fuid,
            armour_core::KeyType::U64,
        ]);
        fn as_bytes(&self) -> &[u8] {
            &self.0
        }
        fn as_bytes_mut(&mut self) -> &mut [u8] {
            &mut self.0
        }
        fn from_bytes(bytes: &[u8]) -> Self {
            Self(bytes.try_into().unwrap())
        }
        fn zeroed() -> Self {
            Self([0; 24])
        }
    }

    #[test]
    fn tree_prefix_configuration_is_validated() {
        for lengths in [&[][..], &[8], &[16], &[8, 16]] {
            validate_prefix_filters::<TypedTreeKey>(lengths).unwrap();
        }
        for lengths in [&[0][..], &[24], &[7], &[16, 16]] {
            assert!(matches!(
                validate_prefix_filters::<TypedTreeKey>(lengths),
                Err(DbError::Config(_))
            ));
        }
        validate_prefix_filters::<testkit::RawTestKey>(&[7, 13, 31]).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("uncreated");
        assert!(matches!(
            testkit::try_open_tree_core(&path, SegConfig::test(), TestClock::new(1), &[0]),
            Err(DbError::Config(_))
        ));
        assert!(!path.exists());
    }

    #[test]
    fn tree_order_mismatch_has_no_repair_or_cleanup() {
        fn snapshot(dir: &Path) -> Vec<(PathBuf, Vec<u8>)> {
            let mut out = Vec::new();
            for entry in std::fs::read_dir(dir).unwrap() {
                let entry = entry.unwrap();
                if entry.file_type().unwrap().is_dir() {
                    out.extend(snapshot(&entry.path()));
                } else if entry.file_name() != "db.lock" {
                    out.push((entry.path(), std::fs::read(entry.path()).unwrap()));
                }
            }
            out.sort();
            out
        }
        for tree in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let config = SegConfig::test();
            let clock = TestClock::new(1_000);
            let core = if tree {
                testkit::open_tree_core(dir.path(), config.clone(), clock.clone(), &[])
            } else {
                open_core(dir.path(), config.clone())
            };
            core.put(&key_of(1), b"value").unwrap();
            let journal = core.view().active.dir().join("shard_000/000001.data");
            core.clean_shutdown().unwrap();
            drop(core);
            std::fs::OpenOptions::new()
                .append(true)
                .open(&journal)
                .unwrap()
                .write_all(b"repairable tail")
                .unwrap();
            std::fs::write(dir.path().join(MANIFEST_TMP), b"garbage manifest").unwrap();
            std::fs::create_dir(dir.path().join("gen/unreferenced")).unwrap();
            std::fs::write(
                dir.path().join("gen/unreferenced/keep"),
                b"garbage generation",
            )
            .unwrap();
            let before = snapshot(dir.path());
            let prefix_fs = TraceFs::new();
            let invalid = SegCore::<testkit::TestKey>::open_tree(
                dir.path(),
                testkit::meta(),
                &[0],
                config.clone(),
                OpenOptions {
                    fs: prefix_fs.clone(),
                    clock: clock.clock(),
                    worker: false,
                },
            );
            assert!(matches!(invalid, Err(DbError::Config(_))));
            assert!(prefix_fs.ops().is_empty());
            assert_eq!(snapshot(dir.path()), before);
            let fs = TraceFs::new();
            let options = OpenOptions {
                fs: fs.clone(),
                clock: clock.clock(),
                worker: false,
            };
            let result = if tree {
                SegCore::<testkit::TestKey>::open(dir.path(), testkit::meta(), config, options)
            } else {
                SegCore::<testkit::TestKey>::open_tree(
                    dir.path(),
                    testkit::meta(),
                    &[],
                    config,
                    options,
                )
            };
            assert!(matches!(result, Err(DbError::FormatMismatch(_))));
            assert_eq!(snapshot(dir.path()), before);
            assert!(
                fs.ops()
                    .iter()
                    .all(|op| op.kind() == FsOpKind::CreateDirAll && op.target() == dir.path())
            );
        }
    }

    #[test]
    fn tree_recovered_full_generation_preserves_admission() {
        let dir = tempfile::tempdir().unwrap();
        let config = SegConfig {
            seal_max_keys: 3,
            ..SegConfig::test()
        };
        let core =
            testkit::open_raw_tree_core(dir.path(), config.clone(), TestClock::new(1_000), &[8]);
        for i in 0..3 {
            core.put(&testkit::raw_ordered_key(i), b"v").unwrap();
        }
        let id = core.view().active.id();
        core.clean_shutdown().unwrap();
        drop(core);
        let config = SegConfig {
            shard_count: 8,
            ..config
        };
        let core = testkit::open_raw_tree_core(dir.path(), config, TestClock::new(2_000), &[16]);
        assert_eq!(core.prefix_filters, [16]);
        assert!(core.view().active.is_full());
        assert_eq!(core.view().active.shard_count(), 2);
        core.put(&testkit::raw_ordered_key(4), b"new").unwrap();
        assert_ne!(core.view().active.id(), id);
        assert_eq!(core.view().active.shard_count(), 8);
        assert_eq!(core.view().frozen[0].id(), id);
        assert_eq!(
            core.get(&testkit::raw_ordered_key(4)).unwrap(),
            Some(b"new".to_vec())
        );
    }

    #[test]
    fn physical_entries_count_tombstones_and_shadowed_versions() {
        let dir = tempfile::tempdir().unwrap();
        let core = testkit::open_tree_core(dir.path(), SegConfig::test(), TestClock::new(100), &[]);
        let k = testkit::ordered_key(1);
        core.put(&k, b"a").unwrap();
        core.seal().unwrap();
        core.seal_oldest().unwrap();
        core.put(&k, b"b").unwrap();
        core.delete(&testkit::ordered_key(2)).unwrap();
        // sealed: 1 entry; active: 2 keys (one live shadowing, one tombstone)
        assert_eq!(core.physical_entries(), 3);
        assert!(core.len() < 3 + 1);
    }
}