solistore 0.2.1

Embedded LSM key-value store for SoliDB: pure Rust, durable on every commit by default
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
//! The database: opening and recovery, column families, the commit path,
//! memtable switches and flushes, and point reads.
//!
//! # Commit path
//!
//! The protocol lives in [`crate::commit_queue`], where `loom` checks it;
//! this module does the work each step stands for. Writers queue up. The writer at the head of the queue becomes the leader,
//! takes every batch waiting behind it (up to [`MAX_GROUP_BYTES`]), gives each
//! a contiguous run of sequence numbers, writes all of them to the WAL with
//! one `write` and makes them durable with one `fdatasync`, then applies them
//! to the memtable and publishes the group's last sequence number. Writers
//! arriving meanwhile form the next group. N concurrent commits therefore
//! cost one fsync, not N.
//!
//! # Visibility
//!
//! Readers take the published sequence number as their snapshot and ignore
//! every entry above it. The leader publishes only after its whole group is
//! in the memtable, and there is one leader at a time, so a reader sees a
//! batch entirely or not at all.
//!
//! # Memtables and flushes
//!
//! When the memtable reaches `write_buffer_size`, the leader seals it, starts
//! a new WAL and a new memtable, and wakes the flush thread, which writes the
//! sealed memtable as level-0 tables, records them in the MANIFEST and
//! deletes the WALs nothing live is left in. If flushes fall
//! `max_immutable_memtables` behind, writers wait.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use arc_swap::ArcSwap;
use bytes::Bytes;
use parking_lot::{Condvar, Mutex, RwLock};

use crate::batch::{self, BatchOp, WriteBatch};
use crate::commit_queue::{GroupQueue, Publisher, Ticket, Turn};
use crate::compaction;
use crate::error::{Error, Result};
use crate::flush;
use crate::fs::{Fs, StdFs, WritableFile};
use crate::iter::{DbIterator, InternalIterator, IteratorMode, ReadOptions};
use crate::key::{self, Kind, MAX_SEQ};
use crate::log::{self, encode_record_parts, read_records};
use crate::manifest::{self, file_no_u32, Edit, ManifestState, ManifestWriter, DEFAULT_CF};
use crate::memtable::{self, Memtable};
use crate::sst::BlockCache;
use crate::version::{by_smallest, table_name, SuperVersion, TableFile, Version, NUM_LEVELS};

/// The most a commit group writes to the WAL at once. A leader stops taking
/// batches past this, so one huge group cannot hold every writer up.
pub const MAX_GROUP_BYTES: usize = 4 << 20;

/// A MANIFEST past this size is replaced by a snapshot of the state.
const MANIFEST_ROLL_BYTES: u64 = 64 << 20;

/// When a commit is acknowledged relative to the disk.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Durability {
    /// Every commit is fsynced before it returns: an acknowledged write
    /// survives power loss. Concurrent commits share one fsync.
    Full,
    /// Commits return once written to the OS; a background thread fsyncs
    /// every `sync_interval`, and a write with [`WriteOptions::sync`] waits
    /// for its own fsync. A crash of the process loses nothing; power loss
    /// can lose up to `sync_interval` of acknowledged writes, never a write
    /// without also losing every later one.
    Eventual { sync_interval: Duration },
}

#[derive(Clone)]
pub struct Options {
    pub create_if_missing: bool,
    pub error_if_exists: bool,
    pub durability: Durability,
    pub fs: Arc<dyn Fs>,
    /// Memtable size at which it is sealed and flushed.
    pub write_buffer_size: usize,
    /// Sealed memtables allowed to wait for a flush before writers stall.
    pub max_immutable_memtables: usize,
    /// Size at which a flush or compaction starts a new table file.
    pub target_file_size: u64,
    /// Level-0 files that start a compaction into the base level.
    pub level0_compaction_trigger: usize,
    /// Level-0 files at which each commit group is delayed by a millisecond.
    pub level0_slowdown_trigger: usize,
    /// Level-0 files at which writers wait for compaction.
    pub level0_stop_trigger: usize,
    /// Target size of the base level, into which level 0 compacts; each
    /// deeper level is `level_multiplier` times larger.
    pub max_bytes_for_level_base: u64,
    pub level_multiplier: u64,
    /// Set level targets from the bottom level, as RocksDB's option of the
    /// same name: the base level is the deepest whose target fits in
    /// `max_bytes_for_level_base`, and a small database keeps its data in
    /// the bottom level. Off, level 1 is the base level at
    /// `max_bytes_for_level_base`.
    ///
    /// A database written with it off drains its upper levels into the
    /// bottom once it is on, when level 0 leaves time for it; level 0
    /// keeps compacting into level 1 until level 1 is empty, so writes that
    /// never pause delay the drain. A database `ingest` loaded already has
    /// its data in the bottom level.
    pub level_compaction_dynamic_level_bytes: bool,
    /// Ranges a compaction is split into and merged in parallel.
    pub max_subcompactions: usize,
    /// Compactions that may run at once, on disjoint files.
    pub max_background_compactions: usize,
    /// Threads for background work in all: one flushes, the rest compact,
    /// subcompactions included. RocksDB's option of the same name.
    pub max_background_jobs: usize,
    /// Bytes of decoded data blocks kept in memory, shared by every table.
    pub block_cache_size: u64,
    /// Start writing compaction outputs back to the device as they are
    /// written, instead of at their final fsync (RocksDB's `bytes_per_sync`;
    /// any non-zero value turns it on, in 1 MiB steps). Off by default, as
    /// in RocksDB and SoliDB's profile.
    pub bytes_per_sync: u64,
    /// Dead WAL files kept to be written over instead of creating new ones
    /// (RocksDB's `recycle_log_file_num`; SoliDB's profile sets 3).
    pub recycle_wal_files: usize,
    /// In [`Durability::Eventual`], the background syncer also fsyncs the
    /// WAL as soon as this many bytes wait for it, not only every
    /// `sync_interval`. A synced write, or a crash, then finds at most
    /// about this much to flush: after a burst of writes, the first synced
    /// commit waited for the whole interval's backlog, tens of megabytes at
    /// load speed (60 ms after the 5M benchmark's load). RocksDB's
    /// `wal_bytes_per_sync` only starts the write-back; this makes the
    /// bytes durable, so it also narrows what power loss can take. 0 syncs
    /// on the interval alone.
    pub wal_bytes_per_sync: u64,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            create_if_missing: true,
            error_if_exists: false,
            durability: Durability::Full,
            fs: Arc::new(StdFs),
            write_buffer_size: 64 << 20,
            // Three memtables at most, as SoliDB's RocksDB profile
            // (max_write_buffer_number = 3).
            max_immutable_memtables: 2,
            target_file_size: 64 << 20,
            level0_compaction_trigger: 4,
            level0_slowdown_trigger: 20,
            level0_stop_trigger: 36,
            max_bytes_for_level_base: 512 << 20,
            level_multiplier: 10,
            level_compaction_dynamic_level_bytes: true,
            max_subcompactions: 4,
            // One at a time measured best at 5M documents: concurrent
            // compactions hold base-level files the next level-0 compaction
            // needs, and rewrote more in all (results/2026-10-14-nowb, with
            // fixed level targets).
            max_background_compactions: 1,
            max_background_jobs: 6,
            block_cache_size: 512 << 20,
            bytes_per_sync: 0,
            // One spare, where RocksDB in SoliDB's profile keeps three: a
            // reused file keeps the largest size it ever reached, and three of
            // them came to ~300 MB on the benchmark's disk measure.
            recycle_wal_files: 1,
            wal_bytes_per_sync: 1 << 20,
        }
    }
}

impl fmt::Debug for Options {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Options")
            .field("create_if_missing", &self.create_if_missing)
            .field("error_if_exists", &self.error_if_exists)
            .field("durability", &self.durability)
            .field("fs", &self.fs)
            .field("write_buffer_size", &self.write_buffer_size)
            .field("max_immutable_memtables", &self.max_immutable_memtables)
            .field("target_file_size", &self.target_file_size)
            .field("level0_compaction_trigger", &self.level0_compaction_trigger)
            .field("level0_slowdown_trigger", &self.level0_slowdown_trigger)
            .field("level0_stop_trigger", &self.level0_stop_trigger)
            .field("max_bytes_for_level_base", &self.max_bytes_for_level_base)
            .field("level_multiplier", &self.level_multiplier)
            .field(
                "level_compaction_dynamic_level_bytes",
                &self.level_compaction_dynamic_level_bytes,
            )
            .field("max_subcompactions", &self.max_subcompactions)
            .field(
                "max_background_compactions",
                &self.max_background_compactions,
            )
            .field("max_background_jobs", &self.max_background_jobs)
            .field("block_cache_size", &self.block_cache_size)
            .field("bytes_per_sync", &self.bytes_per_sync)
            .field("recycle_wal_files", &self.recycle_wal_files)
            .field("wal_bytes_per_sync", &self.wal_bytes_per_sync)
            .finish()
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub struct WriteOptions {
    /// Wait for this write's fsync even in [`Durability::Eventual`]. Always
    /// the case in [`Durability::Full`].
    pub sync: bool,
}

/// Counters since the database was opened: where writers waited, and how
/// much work the background did. A snapshot; see [`Db::stats`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Stats {
    /// Commit groups and the batches they carried.
    pub commit_groups: u64,
    pub committed_batches: u64,
    /// Bytes appended to WALs.
    pub wal_bytes: u64,
    /// WAL fsyncs made by commit groups (every group in `Full`, synced
    /// writes in `Eventual`).
    pub wal_fsyncs: u64,
    /// WAL fsyncs made by the eventual-mode syncer, on its interval or
    /// because `wal_bytes_per_sync` bytes were waiting. Counted once done.
    pub wal_background_fsyncs: u64,
    /// Groups delayed 1 ms because level 0 passed the slowdown trigger.
    pub l0_slowdowns: u64,
    /// Microseconds writers were stopped by level 0 at the stop trigger.
    pub l0_stop_micros: u64,
    /// Microseconds writers waited for a flush because too many sealed
    /// memtables were queued.
    pub memtable_wait_micros: u64,
    pub flushes: u64,
    pub flushed_bytes: u64,
    pub compactions: u64,
    pub compaction_read_bytes: u64,
    pub compaction_written_bytes: u64,
    pub compaction_micros: u64,
    /// The most bytes one WAL received before it was rotated.
    pub largest_wal_bytes: u64,
}

#[derive(Default)]
struct Counters {
    commit_groups: AtomicU64,
    committed_batches: AtomicU64,
    wal_bytes: AtomicU64,
    wal_fsyncs: AtomicU64,
    wal_background_fsyncs: AtomicU64,
    l0_slowdowns: AtomicU64,
    l0_stop_micros: AtomicU64,
    memtable_wait_micros: AtomicU64,
    flushes: AtomicU64,
    flushed_bytes: AtomicU64,
    compactions: AtomicU64,
    compaction_read_bytes: AtomicU64,
    compaction_written_bytes: AtomicU64,
    compaction_micros: AtomicU64,
    largest_wal_bytes: AtomicU64,
}

fn add(counter: &AtomicU64, n: u64) {
    counter.fetch_add(n, Ordering::Relaxed);
}

fn micros_since(start: Instant) -> u64 {
    start.elapsed().as_micros() as u64
}

/// What opening the database found in its logs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RecoveryReport {
    pub wal_files: usize,
    pub batches: u64,
    /// Bytes after the last intact record of a WAL. Non-zero after a crash
    /// that cut a write short: none of those batches had been acknowledged
    /// in `Full` mode.
    pub discarded_bytes: u64,
    /// Table files no MANIFEST named (a flush cut short), deleted.
    pub orphan_tables: usize,
    /// WALs not replayed, and deleted, because an earlier WAL lost writes
    /// they come after (see `log`): replaying them would keep a later write
    /// and lose an earlier one.
    pub dropped_wal_files: usize,
}

// ---------------------------------------------------------------- column families

/// A handle on a column family. Cheap to clone. Every handle on a column
/// family that has been dropped reports [`Error::ColumnFamilyDropped`], even
/// if one of the same name has been created since.
#[derive(Clone)]
pub struct ColumnFamily {
    inner: Arc<CfInner>,
}

struct CfInner {
    id: u32,
    name: String,
    dropped: AtomicBool,
}

impl ColumnFamily {
    fn new(id: u32, name: &str) -> Self {
        ColumnFamily {
            inner: Arc::new(CfInner {
                id,
                name: name.to_string(),
                dropped: AtomicBool::new(false),
            }),
        }
    }

    #[cfg(test)]
    pub(crate) fn for_tests(id: u32, name: &str) -> Self {
        Self::new(id, name)
    }

    pub fn name(&self) -> &str {
        &self.inner.name
    }

    pub(crate) fn id(&self) -> u32 {
        self.inner.id
    }

    fn check(&self) -> Result<()> {
        if self.inner.dropped.load(Ordering::Acquire) {
            Err(Error::ColumnFamilyDropped(self.inner.name.clone()))
        } else {
            Ok(())
        }
    }
}

impl fmt::Debug for ColumnFamily {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ColumnFamily({:?}, id {})",
            self.inner.name, self.inner.id
        )
    }
}

// ---------------------------------------------------------------- the database

/// An open database. Cheap to clone; closed when the last clone drops.
#[derive(Clone)]
pub struct Db {
    handle: Arc<Handle>,
}

/// Owns the background threads: dropping the last `Db` stops and joins them.
struct Handle {
    inner: Arc<Inner>,
    threads: Mutex<Vec<JoinHandle<()>>>,
}

struct Inner {
    dir: PathBuf,
    fs: Arc<dyn Fs>,
    durability: Durability,
    write_buffer_size: usize,
    max_imms: usize,
    target_file_size: u64,
    block_cache: Arc<BlockCache>,
    compaction: compaction::Config,
    l0_slowdown: usize,
    l0_stop: usize,
    /// Per level, the largest key last compacted out of it (round-robin).
    cursors: Mutex<Vec<Vec<u8>>>,
    cfs: RwLock<HashMap<String, ColumnFamily>>,
    structure: Mutex<Structure>,
    sv: ArcSwap<SuperVersion>,
    /// Serialises building and installing a new super version.
    sv_lock: Mutex<()>,
    /// Table files some compaction is working on; others leave them alone.
    compacting: Mutex<HashSet<u64>>,
    /// Compaction threads allowed in all, and in use (subcompactions count).
    compaction_threads: usize,
    compaction_threads_used: Mutex<usize>,
    /// The highest sequence number a reader may see, and the groups done
    /// but not yet visible.
    publisher: Publisher,
    commit: Mutex<CommitState>,
    /// Writers waiting to commit, and the leader's place.
    queue: GroupQueue<Pending, Slot>,
    /// Numbers of dead WAL files kept for reuse, and how many to keep.
    recycled_wals: Mutex<Vec<u64>>,
    recycle_wal_files: usize,
    /// The WAL being written, for the eventual-mode syncer.
    current_wal: Mutex<Arc<WalFile>>,
    /// What must be durable before the current WAL may be fsynced.
    barrier: Mutex<SyncBarrier>,
    /// Unsynced WAL bytes at which a leader wakes the syncer (0: never).
    wal_bytes_per_sync: u64,
    /// A leader asked the syncer for an fsync it has not started yet.
    sync_wanted: AtomicBool,
    /// The eventual-mode syncer, parked between fsyncs. Set before `open`
    /// returns, so every writer and the close find it.
    syncer: std::sync::OnceLock<std::thread::Thread>,
    /// Table files whose delete failed, retried by the background.
    graveyard: crate::version::Graveyard,
    /// A write, fsync or flush failed; see [`Error::Poisoned`].
    poisoned: AtomicBool,
    /// The first failure that poisoned the database, reported with every
    /// refusal after it: a background flush or compaction fails with no
    /// caller to tell, and writers only ever saw "poisoned".
    poison_cause: Mutex<Option<Arc<str>>>,
    bg: Mutex<Background>,
    bg_cv: Condvar,
    recovery: RecoveryReport,
    counters: Counters,
    _lock: Box<dyn Send + Sync>,
}

/// A memtable switch does not fsync the old WAL or the directory: that
/// would hold every writer behind the commit lock for a few milliseconds.
/// Instead, whatever fsyncs the current WAL first fsyncs what the switch
/// left behind, older WALs in order, then the directory (the new WAL's
/// name). A later write can then never be durable without every earlier
/// one, and an old WAL whose memtable is already flushed is dropped from
/// the list.
#[derive(Default)]
struct SyncBarrier {
    older: Vec<Arc<WalFile>>,
    dir_dirty: bool,
}

#[derive(Default)]
struct Background {
    shutdown: bool,
    flush_error: Option<Error>,
}

/// The MANIFEST and the state it describes, changed together.
struct Structure {
    writer: ManifestWriter,
    state: ManifestState,
}

struct WalFile {
    file: Arc<dyn WritableFile>,
    number: u64,
    /// Written since its last fsync.
    dirty: AtomicBool,
    /// Bytes appended to this WAL.
    written: AtomicU64,
    /// `written` when its last fsync started: the bytes past it may not be
    /// durable yet.
    synced: AtomicU64,
}

/// The leader's working state. Only the current leader locks it (and a
/// forced memtable switch).
struct CommitState {
    wal: Arc<WalFile>,
    /// The last sequence number handed out. Readers see up to
    /// `publisher.visible()`, which catches up as groups finish their inserts.
    last_seq: u64,
    buf: Vec<u8>,
}

struct Pending {
    batch: WriteBatch,
    sync: bool,
}

/// A writer's place in the commit queue (with `loom`, its `Arc` is loom's).
type Member = crate::sync::Arc<Ticket<Pending, Slot>>;

/// What a writer is told by its group's leader.
#[derive(Clone)]
enum Slot {
    /// In the WAL: insert into `group.mem` from this sequence number.
    Insert(Arc<Group>, u64),
    /// In the WAL, and the leader inserts it: wait for the group to be
    /// published.
    Wait(Arc<Group>),
    /// The leader of a group it inserts alone, with each member's first
    /// sequence number.
    InsertAll(Arc<Group>, Vec<u64>),
    Failed(Error),
}

/// Groups larger than this are inserted into the memtable by their leader
/// alone. Parallel inserts pay off when every member has a core; past
/// that, a member preempted between its insert and the group's
/// publication holds up every later group. SoliDB runs SDBQL writes on
/// tokio's blocking pool, 64 concurrent writers on 8 cores in the
/// benchmark, and spent most of its off-CPU time waiting for publication.
const MAX_PARALLEL_INSERT: usize = 8;

/// What a leader's WAL write hands back: the group, each member's first
/// sequence number, and whether the syncer is due (see `wal_bytes_per_sync`).
struct Written {
    group: Arc<Group>,
    firsts: Vec<u64>,
    wake_syncer: bool,
}

/// A commit group after its WAL write: its members insert in parallel, and
/// the last one to finish publishes it, after the group before it.
struct Group {
    mem: Arc<Memtable>,
    first: u64,
    last: u64,
    remaining: AtomicUsize,
}

pub(crate) fn wal_name(no: u64) -> String {
    format!("{no:06}.wal")
}

fn parse_wal_name(name: &str) -> Option<u64> {
    name.strip_suffix(".wal")?.parse().ok()
}

impl Db {
    pub fn open(path: impl AsRef<Path>, opts: Options) -> Result<Db> {
        let dir = path.as_ref().to_path_buf();
        let fs = opts.fs.clone();
        if opts.create_if_missing {
            fs.create_dir_all(&dir)?;
        }
        let lock = fs.lock(&dir.join("LOCK"))?;

        let mut state = match manifest::current(fs.as_ref(), &dir)? {
            Some(_) if opts.error_if_exists => {
                return Err(Error::InvalidArgument(format!(
                    "{} already exists",
                    dir.display()
                )))
            }
            Some(no) => manifest::read(fs.as_ref(), &dir, no)?,
            None if opts.create_if_missing => ManifestState::new_database(),
            None => {
                return Err(Error::InvalidArgument(format!(
                    "{} does not exist",
                    dir.display()
                )))
            }
        };
        let mut recovery = RecoveryReport::default();

        // Tables a crashed flush wrote but never recorded.
        let live: std::collections::HashSet<u64> = state
            .levels
            .iter()
            .flat_map(|l| l.keys().copied())
            .collect();
        let (highest, orphans) = flush::remove_orphans(fs.as_ref(), &dir, &|n| live.contains(&n))?;
        recovery.orphan_tables = orphans;
        state.next_file = state.next_file.max(highest + 1);

        // WALs below the log number were flushed; the rest may hold data.
        let mut wals: Vec<u64> = fs
            .list(&dir)?
            .iter()
            .filter_map(|name| parse_wal_name(name))
            .collect();
        wals.sort_unstable();
        let mut recycled = Vec::new();
        for no in wals.iter().filter(|no| **no < state.log_number) {
            if recycled.len() < opts.recycle_wal_files {
                recycled.push(*no);
            } else {
                fs.remove(&dir.join(wal_name(*no))).ok();
            }
        }
        wals.retain(|no| *no >= state.log_number);
        if let Some(last) = wals.last() {
            state.next_file = state.next_file.max(last + 1);
        }

        // A new WAL and a new MANIFEST for this run.
        let manifest_no = state.allocate_file();
        let wal_no = state.allocate_file();

        // Replay, oldest first, into the memtable this run starts with. With
        // everything flushed there is nothing to replay, and the sequence
        // resumes from what the MANIFEST and the tables record.
        let mem = Memtable::new(wals.first().copied().unwrap_or(wal_no));
        let mut last_seq = state.last_seq;
        for props in state.levels.iter().flat_map(|l| l.values()) {
            last_seq = last_seq.max(props.largest_seq);
        }
        for t in &state.tombstones {
            last_seq = last_seq.max(t.seq);
        }
        let mut cut = None;
        for (i, &no) in wals.iter().enumerate() {
            let data = fs.read(&dir.join(wal_name(no)))?;
            let log = read_records(&data, file_no_u32(no)?);
            if log.prev_last_seq.is_some_and(|prev| prev > last_seq) {
                cut = Some(i);
                break;
            }
            recovery.wal_files += 1;
            recovery.discarded_bytes += log.discarded as u64;
            for record in log.records {
                let decoded = batch::decode(record)?;
                recovery.batches += 1;
                let count = decoded.ops.len() as u64;
                last_seq = last_seq.max(decoded.first_seq + count.saturating_sub(1));
                apply(&mem, decoded.ops, decoded.first_seq, |cf| {
                    state.cfs.contains_key(&cf)
                });
            }
        }

        // Point-in-time: what follows a WAL that lost writes is dropped, and
        // its files deleted before anything new is written, so that a later
        // recovery does not stop there again and drop this run's writes.
        if let Some(i) = cut {
            for &no in &wals[i..] {
                let path = dir.join(wal_name(no));
                recovery.discarded_bytes += fs.read(&path).map(|d| d.len() as u64).unwrap_or(0);
                fs.remove(&path)?;
                recovery.dropped_wal_files += 1;
            }
            wals.truncate(i);
        }

        // What was replayed must be durable before the new WAL counts it:
        // after a process crash those bytes may still be only in the page
        // cache. The new WAL's header says every sequence number up to
        // `last_seq` is in the WALs before it, so a power loss that took
        // their tail would drop the new WAL, synced writes and all.
        for &no in &wals {
            fs.sync_file(&dir.join(wal_name(no)))?;
        }

        // The MANIFEST's install syncs the directory, which makes the new
        // WAL's name durable too, and the deletions above.
        let wal_file = fs.create(&dir.join(wal_name(wal_no)))?;
        let mut header = Vec::new();
        log::encode_header(&mut header, file_no_u32(wal_no)?, last_seq);
        wal_file.append(&header)?;
        let writer = ManifestWriter::install(fs.as_ref(), &dir, manifest_no, &state)?;
        for name in fs.list(&dir)? {
            if manifest::parse_manifest_name(&name).is_some_and(|no| no != manifest_no) {
                fs.remove(&dir.join(&name)).ok();
            }
        }

        let block_cache = Arc::new(BlockCache::new(opts.block_cache_size));
        let graveyard = crate::version::Graveyard::default();
        let mut version = Version::empty();
        for (level, files) in state.levels.iter().enumerate() {
            for (number, props) in files {
                version.levels[level].push(Arc::new(
                    TableFile::new(
                        fs.clone(),
                        block_cache.clone(),
                        &dir,
                        *number,
                        props.clone(),
                    )
                    .with_graveyard(graveyard.clone()),
                ));
            }
        }
        version.sort_level0();
        for level in &mut version.levels[1..] {
            level.sort_by(by_smallest);
        }
        version.tombstones = state.tombstones.clone();

        let cfs = state
            .cfs
            .iter()
            .map(|(id, name)| (name.clone(), ColumnFamily::new(*id, name)))
            .collect();
        let wal = Arc::new(WalFile {
            file: wal_file,
            number: wal_no,
            dirty: AtomicBool::new(false),
            written: AtomicU64::new(0),
            synced: AtomicU64::new(0),
        });
        let inner = Arc::new(Inner {
            dir,
            fs,
            durability: opts.durability,
            write_buffer_size: opts.write_buffer_size.max(1),
            max_imms: opts.max_immutable_memtables.max(1),
            target_file_size: opts.target_file_size.max(1),
            block_cache,
            compaction: compaction::Config {
                l0_trigger: opts.level0_compaction_trigger.max(1),
                level_base_bytes: opts.max_bytes_for_level_base.max(1),
                level_multiplier: opts.level_multiplier.max(2),
                dynamic: opts.level_compaction_dynamic_level_bytes,
                target_file_size: opts.target_file_size.max(1),
                subcompactions: opts.max_subcompactions.max(1),
                writeback: opts.bytes_per_sync > 0,
            },
            l0_slowdown: opts.level0_slowdown_trigger.max(1),
            l0_stop: opts
                .level0_stop_trigger
                .max(opts.level0_slowdown_trigger)
                .max(1),
            cursors: Mutex::new(vec![Vec::new(); NUM_LEVELS]),
            cfs: RwLock::new(cfs),
            structure: Mutex::new(Structure { writer, state }),
            sv: ArcSwap::from_pointee(SuperVersion {
                mem: Arc::new(mem),
                imms: Vec::new(),
                version: Arc::new(version),
            }),
            sv_lock: Mutex::new(()),
            compacting: Mutex::new(HashSet::new()),
            compaction_threads: opts.max_background_jobs.saturating_sub(1).max(1),
            compaction_threads_used: Mutex::new(0),
            publisher: Publisher::new(last_seq),
            commit: Mutex::new(CommitState {
                wal: wal.clone(),
                last_seq,
                buf: Vec::new(),
            }),
            queue: GroupQueue::default(),
            recycled_wals: Mutex::new(recycled),
            recycle_wal_files: opts.recycle_wal_files,
            current_wal: Mutex::new(wal),
            barrier: Mutex::new(SyncBarrier::default()),
            wal_bytes_per_sync: opts.wal_bytes_per_sync,
            sync_wanted: AtomicBool::new(false),
            syncer: std::sync::OnceLock::new(),
            graveyard,
            poisoned: AtomicBool::new(false),
            poison_cause: Mutex::new(None),
            bg: Mutex::new(Background::default()),
            bg_cv: Condvar::new(),
            recovery,
            counters: Counters::default(),
            _lock: lock,
        });

        let mut threads = Vec::new();
        let flusher = inner.clone();
        threads.push(
            std::thread::Builder::new()
                .name("solistore-flush".into())
                .spawn(move || flusher.flush_loop())
                .map_err(Error::from)?,
        );
        for i in 0..opts.max_background_compactions.max(1) {
            let compactor = inner.clone();
            threads.push(
                std::thread::Builder::new()
                    .name(format!("solistore-compact-{i}"))
                    .spawn(move || compactor.compaction_loop())
                    .map_err(Error::from)?,
            );
        }
        if let Durability::Eventual { sync_interval } = opts.durability {
            let syncer = inner.clone();
            let thread = std::thread::Builder::new()
                .name("solistore-wal-sync".into())
                .spawn(move || syncer.sync_loop(sync_interval))
                .map_err(Error::from)?;
            // Before any writer can look for it, and before a close could
            // need to wake it.
            inner
                .syncer
                .set(thread.thread().clone())
                .expect("one syncer per database");
            threads.push(thread);
        }
        Ok(Db {
            handle: Arc::new(Handle {
                inner,
                threads: Mutex::new(threads),
            }),
        })
    }

    fn inner(&self) -> &Inner {
        &self.handle.inner
    }

    pub fn path(&self) -> &Path {
        &self.inner().dir
    }

    pub fn recovery_report(&self) -> &RecoveryReport {
        &self.inner().recovery
    }

    pub fn stats(&self) -> Stats {
        let c = &self.inner().counters;
        let get = |a: &AtomicU64| a.load(Ordering::Relaxed);
        Stats {
            commit_groups: get(&c.commit_groups),
            committed_batches: get(&c.committed_batches),
            wal_bytes: get(&c.wal_bytes),
            wal_fsyncs: get(&c.wal_fsyncs),
            wal_background_fsyncs: get(&c.wal_background_fsyncs),
            l0_slowdowns: get(&c.l0_slowdowns),
            l0_stop_micros: get(&c.l0_stop_micros),
            memtable_wait_micros: get(&c.memtable_wait_micros),
            flushes: get(&c.flushes),
            flushed_bytes: get(&c.flushed_bytes),
            compactions: get(&c.compactions),
            compaction_read_bytes: get(&c.compaction_read_bytes),
            compaction_written_bytes: get(&c.compaction_written_bytes),
            compaction_micros: get(&c.compaction_micros),
            largest_wal_bytes: get(&c.largest_wal_bytes),
        }
    }

    /// Memory held by the memtables, approximately.
    pub fn memtable_bytes(&self) -> usize {
        let sv = self.inner().sv.load();
        std::iter::once(&sv.mem)
            .chain(&sv.imms)
            .map(|m| m.approximate_size())
            .sum()
    }

    /// Memory held by open tables' indexes and filters (charged against
    /// the block cache's budget).
    pub fn table_readers_bytes(&self) -> usize {
        self.inner().block_cache.pinned() as usize
    }

    /// Bytes held by the block cache.
    pub fn block_cache_usage(&self) -> u64 {
        self.inner().block_cache.usage()
    }

    /// Bytes of every live table file (RocksDB's `total-sst-files-size`).
    pub fn live_table_bytes(&self) -> u64 {
        self.inner()
            .sv
            .load()
            .version
            .files()
            .map(|f| f.props.size)
            .sum()
    }

    /// Approximate bytes on disk of the keys in `[start, end)` of `cf`:
    /// table files only, as RocksDB's `GetApproximateSizes` without the
    /// memtables. A file wholly inside the range counts in full; one that
    /// straddles an edge counts from its index, block by block.
    pub fn approximate_size(&self, cf: &ColumnFamily, start: &[u8], end: &[u8]) -> Result<u64> {
        cf.check()?;
        if start >= end {
            return Ok(0);
        }
        let lo = key::first_of(cf.id(), start);
        let hi = key::first_of(cf.id(), end);
        let sv = self.inner().sv.load();
        let mut total = 0;
        for file in sv.version.files() {
            let (smallest, largest) = (&file.props.smallest, &file.props.largest);
            if key::compare(largest, &lo).is_lt() || key::compare(smallest, &hi).is_ge() {
                continue;
            }
            if key::compare(smallest, &lo).is_ge() && key::compare(largest, &hi).is_lt() {
                total += file.props.size;
                continue;
            }
            let reader = file.reader()?;
            let from = reader.approximate_offset_of(&lo)?;
            let to = reader.approximate_offset_of(&hi)?;
            total += to.saturating_sub(from);
        }
        Ok(total)
    }

    /// Range tombstones some table file may still hold deleted data for.
    pub fn pending_range_tombstones(&self) -> usize {
        self.inner().sv.load().version.tombstones.len()
    }

    /// Table files per level.
    pub fn files_per_level(&self) -> Vec<usize> {
        self.inner()
            .sv
            .load()
            .version
            .levels
            .iter()
            .map(Vec::len)
            .collect()
    }

    // ------------------------------------------------------------ column families

    pub fn cf_handle(&self, name: &str) -> Option<ColumnFamily> {
        self.inner().cfs.read().get(name).cloned()
    }

    pub fn default_cf(&self) -> ColumnFamily {
        self.cf_handle(DEFAULT_CF)
            .expect("the default column family always exists")
    }

    pub fn cf_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.inner().cfs.read().keys().cloned().collect();
        names.sort();
        names
    }

    /// Create a column family. Durable when this returns.
    pub fn create_cf(&self, name: &str) -> Result<ColumnFamily> {
        if name.is_empty() {
            return Err(Error::InvalidArgument("empty column family name".into()));
        }
        let inner = self.inner();
        let mut structure = inner.structure.lock();
        if inner.cfs.read().contains_key(name) {
            return Err(Error::ColumnFamilyExists(name.to_string()));
        }
        let id = structure.state.next_cf_id;
        let next = id
            .checked_add(1)
            .ok_or_else(|| Error::InvalidArgument("column family ids exhausted".into()))?;
        inner.append_edits(
            &mut structure,
            &[
                Edit::CreateCf {
                    id,
                    name: name.to_string(),
                },
                Edit::NextCfId(next),
            ],
        )?;
        let cf = ColumnFamily::new(id, name);
        inner.cfs.write().insert(name.to_string(), cf.clone());
        Ok(cf)
    }

    /// Drop a column family. Its data becomes unreachable at once, and every
    /// handle on it fails from now on; its table files are deleted, and
    /// what is left of it in memtables is skipped when they are flushed.
    /// Durable when this returns.
    pub fn drop_cf(&self, name: &str) -> Result<()> {
        if name == DEFAULT_CF {
            return Err(Error::InvalidArgument(
                "the default column family cannot be dropped".into(),
            ));
        }
        let inner = self.inner();
        let cf = self
            .cf_handle(name)
            .ok_or_else(|| Error::ColumnFamilyNotFound(name.to_string()))?;
        let id = cf.id();
        inner.log_and_apply(
            |sv| {
                let mut edits = vec![Edit::DropCf { id }];
                let mut version = (*sv.version).clone();
                let mut retired = Vec::new();
                for (level, files) in version.levels.iter_mut().enumerate() {
                    files.retain(|f| {
                        let doomed = compaction::file_bounds(f).is_some_and(|(c, _, _)| c == id);
                        if doomed {
                            edits.push(Edit::DeleteFile {
                                level: level as u32,
                                number: f.number,
                            });
                            retired.push(f.clone());
                        }
                        !doomed
                    });
                }
                Ok(Some(VersionChange {
                    edits,
                    sv: SuperVersion {
                        mem: sv.mem.clone(),
                        imms: sv.imms.clone(),
                        version: Arc::new(version),
                    },
                    retired,
                }))
            },
            || {},
        )?;
        cf.inner.dropped.store(true, Ordering::Release);
        inner.cfs.write().remove(name);
        Ok(())
    }

    /// Compact the part of `cf` between `start` and `end` (whole column
    /// family when both are `None`): flush, merge what level 0 holds there,
    /// and rewrite every file that may still hold range-deleted data — the
    /// space a dropped collection held comes back. Waits until done.
    pub fn compact_range(
        &self,
        cf: &ColumnFamily,
        start: Option<&[u8]>,
        end: Option<&[u8]>,
    ) -> Result<()> {
        cf.check()?;
        self.flush()?;
        let inner = self.inner();
        let prefix = cf.id().to_be_bytes();
        let lo = [&prefix[..], start.unwrap_or_default()].concat();
        let hi = match end {
            Some(end) => [&prefix[..], end].concat(),
            None => cf
                .id()
                .checked_add(1)
                .map_or_else(|| vec![0xff; 5], |next| next.to_be_bytes().to_vec()),
        };
        let cfg = inner.compaction;
        let wanted = |v: &Version, busy: compaction::Busy<'_>| {
            compaction::pick_for_tombstones(v, &cfg, busy)
                .or_else(|| compaction::pick_level0_overlapping(v, &cfg, &lo, &hi, busy))
        };
        // Bounded: writes arriving meanwhile could otherwise keep it going.
        for _ in 0..10_000 {
            match inner.claim(wanted) {
                Some((c, version)) => {
                    let outcome = inner.compact(&c, &version);
                    inner.release(&c);
                    outcome?;
                }
                None => {
                    // Done, unless what is left is held by a background
                    // compaction: wait for it.
                    let version = inner.sv.load().version.clone();
                    if wanted(&version, &|_| false).is_none() {
                        break;
                    }
                    inner.check()?;
                    let mut bg = inner.bg.lock();
                    inner.bg_cv.wait_for(&mut bg, Duration::from_millis(10));
                }
            }
        }
        Ok(())
    }

    /// Load `cf`, which must be untouched (no entry, delete or range delete
    /// anywhere), from `entries`: user keys in strictly increasing order.
    /// The table files are written straight into the bottom level by
    /// `threads` threads and installed with one MANIFEST record: no WAL, no
    /// memtable, no compaction, each byte written once. RocksDB's ingestion
    /// of external files, for the case of a whole column family.
    ///
    /// Entries get sequence 0, as compaction gives entries at the bottom of
    /// the tree: nothing older can exist, since the column family was empty.
    /// The files are fsynced, then the directory, then the MANIFEST record;
    /// the load is durable when this returns and absent if it fails, its
    /// files removed. Nothing else may write to `cf` meanwhile: a write found
    /// there at install time fails the load.
    pub fn ingest<K, V, E>(
        &self,
        cf: &ColumnFamily,
        entries: impl IntoIterator<Item = std::result::Result<(K, V), E>>,
        threads: usize,
    ) -> Result<IngestReport>
    where
        K: AsRef<[u8]>,
        V: AsRef<[u8]>,
        E: fmt::Display,
    {
        cf.check()?;
        let inner = self.inner();
        inner.check()?;
        let id = cf.id();
        if !inner.untouched(&inner.sv.load(), id) {
            return Err(Error::InvalidArgument(format!(
                "ingest needs an untouched column family; {} holds entries, deletes or \
                 range deletes",
                cf.name()
            )));
        }
        let threads = threads.max(1);
        let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<(Vec<u8>, Vec<u8>)>>(threads);
        let rx = Mutex::new(rx);
        let written: Mutex<Vec<(u64, crate::sst::TableProps)>> = Mutex::new(Vec::new());
        let failed: Mutex<Option<Error>> = Mutex::new(None);
        let mut report = IngestReport::default();
        let read = std::thread::scope(|scope| {
            for _ in 0..threads {
                scope.spawn(|| loop {
                    let Ok(chunk) = rx.lock().recv() else {
                        return;
                    };
                    if failed.lock().is_some() {
                        continue; // drain what the reader already sent
                    }
                    match inner.ingest_chunk(id, &chunk) {
                        Ok(files) => written.lock().extend(files),
                        Err(e) => {
                            failed.lock().get_or_insert(e);
                        }
                    }
                });
            }
            let tx = tx;
            let mut chunk: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
            let mut size = 0usize;
            let mut last: Option<Vec<u8>> = None;
            for item in entries {
                let (k, v) =
                    item.map_err(|e| Error::InvalidArgument(format!("ingest source: {e}")))?;
                let (k, v) = (k.as_ref(), v.as_ref());
                match &mut last {
                    Some(l) if l.as_slice() >= k => {
                        return Err(Error::InvalidArgument(
                            "ingest keys must be strictly increasing".into(),
                        ));
                    }
                    Some(l) => {
                        l.clear();
                        l.extend_from_slice(k);
                    }
                    None => last = Some(k.to_vec()),
                }
                size += k.len() + v.len() + key::MIN_LEN;
                report.entries += 1;
                report.bytes += (k.len() + v.len()) as u64;
                chunk.push((key::encode(id, k, 0, Kind::Put), v.to_vec()));
                if size >= INGEST_CHUNK_BYTES {
                    size = 0;
                    if failed.lock().is_some() || tx.send(std::mem::take(&mut chunk)).is_err() {
                        break;
                    }
                }
            }
            if !chunk.is_empty() {
                let _ = tx.send(chunk);
            }
            Ok(())
        });
        let mut files = written.into_inner();
        let outcome = read
            .and_then(|()| failed.into_inner().map_or(Ok(()), Err))
            .and_then(|()| inner.install_ingested(id, &mut files));
        if let Err(e) = outcome {
            for (number, _) in &files {
                inner.fs.remove(&inner.dir.join(table_name(*number))).ok();
            }
            return Err(e);
        }
        report.files = files.len();
        Ok(report)
    }

    /// Write a consistent copy of the database to `path`, which must not
    /// exist: every memtable is flushed, then each live table file is hard
    /// linked (copied across file systems) and a fresh MANIFEST written. The
    /// copy holds everything committed before the call and opens like any
    /// database. On the same file system it costs no space until the source
    /// compacts the linked files away — which also means it is no protection
    /// against losing that file system.
    pub fn checkpoint(&self, path: impl AsRef<Path>) -> Result<()> {
        let target = path.as_ref();
        let inner = self.inner();
        if inner.fs.exists(target) {
            return Err(Error::InvalidArgument(format!(
                "{} already exists",
                target.display()
            )));
        }
        self.flush()?;
        // The pinned version keeps its files alive while they are linked.
        let sv = inner.sv.load_full();
        let mut state = ManifestState::empty();
        state.cfs = inner.structure.lock().state.cfs.clone();
        state.next_cf_id = inner.structure.lock().state.next_cf_id;
        state.tombstones = sv.version.tombstones.clone();
        let mut highest = 0;
        for (level, files) in sv.version.levels.iter().enumerate() {
            for f in files {
                state.levels[level].insert(f.number, f.props.clone());
                state.last_seq = state.last_seq.max(f.props.largest_seq);
                highest = highest.max(f.number);
            }
        }
        for t in &state.tombstones {
            state.last_seq = state.last_seq.max(t.seq);
        }
        state.next_file = highest + 1;
        state.log_number = state.next_file; // no WAL in a checkpoint

        inner.fs.create_dir_all(target)?;
        for f in sv.version.files() {
            inner.fs.link(
                &inner.dir.join(table_name(f.number)),
                &target.join(table_name(f.number)),
            )?;
        }
        let manifest_no = state.allocate_file();
        ManifestWriter::install(inner.fs.as_ref(), target, manifest_no, &state)?;
        Ok(())
    }

    // ------------------------------------------------------------ writes

    pub fn put(
        &self,
        cf: &ColumnFamily,
        key: impl AsRef<[u8]>,
        value: impl AsRef<[u8]>,
    ) -> Result<()> {
        let mut batch = WriteBatch::new();
        batch.put(cf, key, value);
        self.write(batch)
    }

    pub fn delete(&self, cf: &ColumnFamily, key: impl AsRef<[u8]>) -> Result<()> {
        let mut batch = WriteBatch::new();
        batch.delete(cf, key);
        self.write(batch)
    }

    pub fn write(&self, batch: WriteBatch) -> Result<()> {
        self.write_opt(batch, &WriteOptions::default())
    }

    /// Apply a batch atomically. Returns once it is visible to readers and
    /// as durable as the database's [`Durability`] (and `opts`) require.
    pub fn write_opt(&self, batch: WriteBatch, opts: &WriteOptions) -> Result<()> {
        if batch.is_empty() {
            return Ok(());
        }
        for cf in batch.column_families() {
            cf.check()?;
        }
        self.inner().commit(batch, opts.sync)
    }

    /// Fsync the WAL now: everything acknowledged so far becomes durable.
    pub fn sync_wal(&self) -> Result<()> {
        let inner = self.inner();
        inner.check()?;
        let wal = inner.current_wal.lock().clone();
        inner.sync_wal_file(&wal)
    }

    /// Write every memtable out as table files and wait until it is done.
    pub fn flush(&self) -> Result<()> {
        let inner = self.inner();
        {
            let mut commit = inner.commit.lock();
            if !inner.sv.load().mem.is_empty() {
                inner.switch_memtable(&mut commit)?;
            }
        }
        let mut bg = inner.bg.lock();
        loop {
            inner.check()?;
            if let Some(e) = &bg.flush_error {
                return Err(e.clone());
            }
            if inner.sv.load().imms.is_empty() {
                return Ok(());
            }
            inner.bg_cv.wait(&mut bg);
        }
    }

    // ------------------------------------------------------------ reads

    pub fn get(&self, cf: &ColumnFamily, key: impl AsRef<[u8]>) -> Result<Option<Bytes>> {
        cf.check()?;
        let inner = self.inner();
        // The super version first, then the snapshot: see `version`.
        let sv = inner.sv.load();
        let snapshot = inner.publisher.visible();
        sv.get(cf.id(), key.as_ref(), snapshot)
    }

    /// Several gets at one snapshot.
    pub fn multi_get<K: AsRef<[u8]>>(
        &self,
        cf: &ColumnFamily,
        keys: &[K],
    ) -> Result<Vec<Option<Bytes>>> {
        cf.check()?;
        let inner = self.inner();
        let sv = inner.sv.load();
        let snapshot = inner.publisher.visible();
        keys.iter()
            .map(|k| sv.get(cf.id(), k.as_ref(), snapshot))
            .collect()
    }

    pub fn iterator(&self, cf: &ColumnFamily, mode: IteratorMode<'_>) -> Result<DbIterator> {
        self.iterator_opt(cf, ReadOptions::default(), mode)
    }

    pub fn iterator_opt(
        &self,
        cf: &ColumnFamily,
        opts: ReadOptions,
        mode: IteratorMode<'_>,
    ) -> Result<DbIterator> {
        cf.check()?;
        let inner = self.inner();
        let sv = inner.sv.load_full();
        let snapshot = inner.publisher.visible();
        DbIterator::new(sv, cf.id(), snapshot, opts, mode)
    }
}

impl fmt::Debug for Db {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Db({})", self.inner().dir.display())
    }
}

impl Drop for Handle {
    fn drop(&mut self) {
        self.inner.bg.lock().shutdown = true;
        self.inner.bg_cv.notify_all();
        // The syncer sleeps on its own token, not on `bg_cv`. A token left
        // before it parks makes its park return at once, so it cannot miss
        // this.
        if let Some(syncer) = self.inner.syncer.get() {
            syncer.unpark();
        }
        for thread in self.threads.lock().drain(..) {
            thread.join().ok();
        }
        // A clean close leaves nothing for the next open to lose, and ends
        // the WAL with an end record.
        let wal = self.inner.current_wal.lock().clone();
        if !self.inner.poisoned.load(Ordering::Acquire) {
            let mut end = Vec::new();
            if let Ok(no) = file_no_u32(wal.number) {
                log::encode_end(&mut end, no);
                if wal.file.append(&end).is_ok() {
                    self.inner.sync_wal_file(&wal).ok();
                }
            }
        }
    }
}

/// Runs a closure when dropped: time an early-returning block.
struct Defer<F: FnMut()>(F);

impl<F: FnMut()> Drop for Defer<F> {
    fn drop(&mut self) {
        (self.0)()
    }
}

/// A structural change: its MANIFEST edits, the super version it leads to,
/// and the table files it removes.
/// What [`Db::ingest`] loaded.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IngestReport {
    pub entries: u64,
    /// Key and value bytes.
    pub bytes: u64,
    /// Table files written.
    pub files: usize,
}

/// Bytes of entries one [`Db::ingest`] thread turns into tables at a time.
/// With `threads` threads at work and as many chunks queued, the load holds
/// about `2 * threads` of these in memory.
const INGEST_CHUNK_BYTES: usize = 96 << 20;

struct VersionChange {
    edits: Vec<Edit>,
    sv: SuperVersion,
    retired: Vec<Arc<TableFile>>,
}

/// Finish a change against the range tombstones it leaves: drop every file
/// a tombstone deletes entirely, and every tombstone no file may hold
/// covered data for any more.
fn tidy(change: &mut VersionChange) {
    let mut version = (*change.sv.version).clone();
    for t in version.tombstones.clone() {
        for (level, files) in version.levels.iter_mut().enumerate() {
            files.retain(|f| {
                let doomed = compaction::fully_covered(f, &t);
                if doomed {
                    change.edits.push(Edit::DeleteFile {
                        level: level as u32,
                        number: f.number,
                    });
                    change.retired.push(f.clone());
                }
                !doomed
            });
        }
    }
    let files: Vec<Arc<TableFile>> = version.files().cloned().collect();
    version.tombstones.retain(|t| {
        let needed = files.iter().any(|f| compaction::may_hold_covered(f, t));
        if !needed {
            change.edits.push(Edit::RemoveRangeTombstone { seq: t.seq });
        }
        needed
    });
    change.sv.version = Arc::new(version);
}

/// Apply decoded ops to a memtable, numbering them from `first_seq`.
fn apply(mem: &Memtable, ops: Vec<BatchOp<'_>>, first_seq: u64, live: impl Fn(u32) -> bool) {
    // Each entry is written once, straight into its skiplist node.
    for (seq, op) in (first_seq..).zip(&ops) {
        match *op {
            BatchOp::Put { cf, key, value } if live(cf) => {
                mem.insert_entry(cf, key, seq, Kind::Put, value)
            }
            BatchOp::Delete { cf, key } if live(cf) => {
                mem.insert_entry(cf, key, seq, Kind::Delete, b"")
            }
            _ => {}
        }
    }
    let mut last = 0;
    for (seq, op) in (first_seq..).zip(ops) {
        if let BatchOp::DeleteRange { cf, start, end } = op {
            if live(cf) {
                mem.insert_range_tombstone(cf, start, end, seq);
            }
        }
        last = seq;
    }
    mem.account(last);
}

impl Inner {
    fn poison(&self) {
        self.poisoned.store(true, Ordering::Release);
        self.bg_cv.notify_all();
    }

    /// Poison, recording `cause` unless an earlier failure already did.
    fn poison_because(&self, cause: &Error) {
        self.poison_cause
            .lock()
            .get_or_insert_with(|| Arc::from(cause.to_string()));
        self.poison();
    }

    fn poisoned_error(&self) -> Error {
        Error::Poisoned(self.poison_cause.lock().clone())
    }

    fn check(&self) -> Result<()> {
        if self.poisoned.load(Ordering::Acquire) {
            Err(self.poisoned_error())
        } else {
            Ok(())
        }
    }

    /// Run an I/O step of the write path; any failure poisons the database.
    fn io<T>(&self, step: impl FnOnce() -> Result<T>) -> Result<T> {
        step().inspect_err(|e| self.poison_because(e))
    }

    /// Fsync `wal`, after the older WALs and the directory entries a
    /// memtable switch left unsynced (see [`SyncBarrier`]). Poisons the
    /// database on failure.
    fn sync_wal_file(&self, wal: &WalFile) -> Result<()> {
        // What is counted in `written` was appended before this fsync, so
        // it will be covered: from here on no leader asks again for it,
        // while the older WALs and the directory are synced first.
        Self::mark_syncing(wal);
        {
            let mut barrier = self.barrier.lock();
            // Every one, whatever its dirty flag says. A clear flag only
            // means another thread has started an fsync of it, not that the
            // fsync is done: the background syncer clears the flag before
            // syncing, and when a switch had set it again in between, a
            // synced write here skipped the WAL, was acknowledged, and a
            // crash before the other fsync finished lost it with that WAL's
            // tail. At most one fsync more per memtable switch.
            for old in std::mem::take(&mut barrier.older) {
                old.dirty.store(false, Ordering::Release);
                self.io(|| Ok(old.file.sync()?))?;
            }
            if barrier.dir_dirty {
                self.io(|| Ok(self.fs.sync_dir(&self.dir)?))?;
                barrier.dir_dirty = false;
            }
        }
        wal.dirty.store(false, Ordering::Release);
        self.io(|| Ok(wal.file.sync()?))
    }

    /// Record that an fsync covering everything counted in `written` so far
    /// has started. Only decides when the syncer is woken; a slower
    /// concurrent fsync must not move it back.
    fn mark_syncing(wal: &WalFile) {
        wal.synced
            .fetch_max(wal.written.load(Ordering::Acquire), Ordering::Release);
    }

    /// Whether `wal_bytes_per_sync` bytes of `wal` wait for an fsync no one
    /// has started. Checked by the leader after each unsynced group, under
    /// the commit lock; the wake-up itself waits for the lock's release.
    fn sync_due(&self, wal: &WalFile) -> bool {
        self.wal_bytes_per_sync > 0
            && wal
                .written
                .load(Ordering::Relaxed)
                .saturating_sub(wal.synced.load(Ordering::Relaxed))
                >= self.wal_bytes_per_sync
    }

    /// Ask the eventual-mode syncer for an fsync now. Waking it costs a
    /// futex call, paid once per request: until the syncer takes it, later
    /// callers find it pending and return.
    fn wake_syncer(&self) {
        let Some(syncer) = self.syncer.get() else {
            return; // Full durability: every group fsyncs itself
        };
        if !self.sync_wanted.load(Ordering::Relaxed)
            && !self.sync_wanted.swap(true, Ordering::AcqRel)
        {
            syncer.unpark();
        }
    }

    fn append_edits(&self, structure: &mut Structure, edits: &[Edit]) -> Result<()> {
        self.check()?;
        // A torn MANIFEST record would hide every later edit on replay.
        self.io(|| structure.writer.append(edits))?;
        for edit in edits {
            structure.state.apply(edit);
        }
        if structure.writer.size() > MANIFEST_ROLL_BYTES {
            // Start a new one holding just the current state.
            let old = structure.writer.number();
            let no = structure.state.allocate_file();
            let writer = self.io(|| {
                ManifestWriter::install(self.fs.as_ref(), &self.dir, no, &structure.state)
            })?;
            structure.writer = writer;
            self.fs
                .remove(&self.dir.join(manifest::manifest_name(old)))
                .ok();
        }
        Ok(())
    }

    /// Whether column family `id` has nothing anywhere: no entry or delete
    /// in a memtable or a table, no range delete.
    fn untouched(&self, sv: &SuperVersion, id: u32) -> bool {
        let cf_of = |k: &[u8]| key::parse(k).map(|p| p.cf);
        if sv.version.tombstones.iter().any(|t| t.cf == id) {
            return false;
        }
        for mem in std::iter::once(&sv.mem).chain(&sv.imms) {
            if mem.tombstones().iter().any(|t| t.cf == id) {
                return false;
            }
            let mut it = memtable::MemIter::new(mem.clone());
            it.seek_ge(&key::first_of(id, b""));
            if it.valid() && cf_of(it.key()) == Some(id) {
                return false;
            }
        }
        !sv.version.levels.iter().flatten().any(|f| {
            match (cf_of(&f.props.smallest), cf_of(&f.props.largest)) {
                (Some(lo), Some(hi)) => lo <= id && id <= hi,
                _ => true,
            }
        })
    }

    /// One chunk of an ingest, as table files: fsynced, directory synced.
    fn ingest_chunk(
        &self,
        id: u32,
        chunk: &[(Vec<u8>, Vec<u8>)],
    ) -> Result<Vec<(u64, crate::sst::TableProps)>> {
        let mut out =
            compaction::OutputFiles::new(self.fs.as_ref(), &self.dir, self.target_file_size, 0);
        let mut allocate = || self.allocate_file();
        for (k, v) in chunk {
            out.add(id, k, v, &mut allocate)?;
        }
        out.finish()
    }

    /// Put an ingest's files at the bottom level, in one MANIFEST record.
    fn install_ingested(&self, id: u32, files: &mut [(u64, crate::sst::TableProps)]) -> Result<()> {
        files.sort_by(|a, b| key::compare(&a.1.smallest, &b.1.smallest));
        if files.is_empty() {
            return Ok(());
        }
        let bottom = NUM_LEVELS - 1;
        let tables: Vec<Arc<TableFile>> = files
            .iter()
            .map(|(number, props)| {
                Arc::new(
                    TableFile::new(
                        self.fs.clone(),
                        self.block_cache.clone(),
                        &self.dir,
                        *number,
                        props.clone(),
                    )
                    .with_graveyard(self.graveyard.clone()),
                )
            })
            .collect();
        for table in &tables {
            table.reader()?;
        }
        self.log_and_apply(
            |sv| {
                if !self.untouched(sv, id) {
                    return Err(Error::InvalidArgument(
                        "the column family was written to during the ingest".into(),
                    ));
                }
                let edits = tables
                    .iter()
                    .map(|f| Edit::AddFile {
                        level: bottom as u32,
                        number: f.number,
                        props: f.props.clone(),
                    })
                    .collect();
                let mut version = (*sv.version).clone();
                version.levels[bottom].extend(tables.iter().cloned());
                version.levels[bottom].sort_by(by_smallest);
                Ok(Some(VersionChange {
                    edits,
                    sv: SuperVersion {
                        mem: sv.mem.clone(),
                        imms: sv.imms.clone(),
                        version: Arc::new(version),
                    },
                    retired: Vec::new(),
                }))
            },
            || {},
        )?;
        self.notify_background();
        Ok(())
    }

    fn allocate_file(&self) -> u64 {
        self.structure.lock().state.allocate_file()
    }

    fn install(&self, change: impl FnOnce(&SuperVersion) -> SuperVersion) {
        let _guard = self.sv_lock.lock();
        let current = self.sv.load_full();
        self.sv.store(Arc::new(change(&current)));
    }

    fn notify_background(&self) {
        let _bg = self.bg.lock();
        self.bg_cv.notify_all();
    }

    // ------------------------------------------------------------ commit

    fn commit(&self, batch: WriteBatch, sync: bool) -> Result<()> {
        // Only reached by unwinding out of the WAL write: the members learn
        // the database is poisoned.
        let abandoned = || {
            self.poison();
            Slot::Failed(self.poisoned_error())
        };
        let gather = self.durability == Durability::Full || sync;
        let turn = self.queue.enter(
            Pending { batch, sync },
            gather,
            MAX_GROUP_BYTES,
            |p| p.batch.size_in_bytes(),
            &abandoned,
        );
        let (slot, me) = match turn {
            Turn::Followed(slot, me) => (slot, me),
            Turn::Lead(lead) => {
                let written = self.write_group(&lead.group);
                let leader_inserts = lead.group.len() > MAX_PARALLEL_INSERT;
                let (slot, members) = lead.finish(|i, _| match &written {
                    Ok(w) if leader_inserts => {
                        if i == 0 {
                            Slot::InsertAll(w.group.clone(), w.firsts.clone())
                        } else {
                            Slot::Wait(w.group.clone())
                        }
                    }
                    Ok(w) => Slot::Insert(w.group.clone(), w.firsts[i]),
                    Err(e) => Slot::Failed(e.clone()),
                });
                // Out of the commit lock and the leader's place: the futex
                // call delays neither the members nor the next group.
                if written.as_ref().is_ok_and(|w| w.wake_syncer) {
                    self.wake_syncer();
                }
                if let Slot::InsertAll(g, firsts) = &slot {
                    for (member, &first) in members.iter().zip(firsts) {
                        apply(&g.mem, member.item.batch.ops(), first, |_| true);
                    }
                    self.publisher.publish(g.first, g.last);
                    return Ok(());
                }
                // `finish` returns the group with the leader's ticket first.
                let me = members
                    .into_iter()
                    .next()
                    .expect("the leader heads its group");
                (slot, me)
            }
        };
        match slot {
            Slot::Failed(e) => Err(e),
            Slot::Insert(group, first) => {
                self.insert_and_publish(&me.item.batch, &group, first);
                Ok(())
            }
            Slot::Wait(group) => {
                self.publisher.wait(group.last);
                Ok(())
            }
            Slot::InsertAll(..) => unreachable!("only the leader inserts a whole group"),
        }
    }

    /// Give the group its sequence numbers and write it to the WAL, fsynced
    /// if the durability asks for it. Returns the group, each member's
    /// first sequence number, and whether to wake the syncer.
    fn write_group(&self, group: &[Member]) -> Result<Written> {
        self.check()?;
        let mut commit = self.commit.lock();
        self.throttle()?;
        // A switch leaves the old WAL's tail and the new name to the syncer:
        // have it run now, unless it is to keep to its interval.
        let mut wake_syncer = false;
        if self.sv.load().mem.approximate_size() >= self.write_buffer_size {
            self.switch_memtable(&mut commit)?;
            wake_syncer = self.wal_bytes_per_sync > 0;
        }
        let CommitState { wal, last_seq, buf } = &mut *commit;
        let wal_no = file_no_u32(wal.number)?;
        buf.clear();
        let mut seq = *last_seq;
        let mut firsts = Vec::with_capacity(group.len());
        for member in group {
            let batch = &member.item.batch;
            firsts.push(seq + 1);
            let header = batch.header(seq + 1);
            encode_record_parts(buf, wal_no, &[&header, batch.ops_bytes()]);
            seq += batch.len() as u64;
        }
        if seq > MAX_SEQ {
            return Err(Error::InvalidArgument("sequence numbers exhausted".into()));
        }

        let sync = self.durability == Durability::Full || group.iter().any(|m| m.item.sync);
        self.io(|| Ok(wal.file.append(buf)?))?;
        // Release: whoever reads this count reads it after the bytes were
        // appended, and may fsync them as counted (see `sync_wal_file`).
        wal.written.fetch_add(buf.len() as u64, Ordering::Release);
        add(&self.counters.wal_bytes, buf.len() as u64);
        add(&self.counters.commit_groups, 1);
        add(&self.counters.committed_batches, group.len() as u64);
        if sync {
            add(&self.counters.wal_fsyncs, 1);
            self.sync_wal_file(wal)?;
        } else {
            wal.dirty.store(true, Ordering::Release);
            wake_syncer |= self.sync_due(wal);
        }
        if buf.capacity() > 2 * MAX_GROUP_BYTES {
            *buf = Vec::new();
        }
        let first = *last_seq + 1;
        *last_seq = seq;
        // Switches happen under the commit lock, and wait for every group
        // already handed out to be published: this memtable stays the one
        // this group belongs in until it is.
        let mem = self.sv.load().mem.clone();
        Ok(Written {
            group: Arc::new(Group {
                mem,
                first,
                last: seq,
                remaining: AtomicUsize::new(group.len()),
            }),
            firsts,
            wake_syncer,
        })
    }

    /// Insert one member's batch; the group's last member to finish
    /// publishes it once every earlier group is published. Returns when the
    /// group is visible, so a writer always reads its own write.
    fn insert_and_publish(&self, batch: &WriteBatch, group: &Group, first: u64) {
        apply(&group.mem, batch.ops(), first, |_| true);
        if group.remaining.fetch_sub(1, Ordering::AcqRel) == 1 {
            self.publisher.publish(group.first, group.last);
        } else {
            self.publisher.wait(group.last);
        }
    }

    /// Hold writes back while level 0 has more files than compaction keeps
    /// up with: a little past the slowdown trigger, entirely at the stop one.
    /// Reads slow down with every level-0 file, so this bounds them too.
    fn throttle(&self) -> Result<()> {
        let l0 = self.sv.load().version.levels[0].len();
        if l0 >= self.l0_stop {
            let start = Instant::now();
            let _count = Defer(|| add(&self.counters.l0_stop_micros, micros_since(start)));
            let mut bg = self.bg.lock();
            while self.sv.load().version.levels[0].len() >= self.l0_stop {
                self.check()?;
                if let Some(e) = &bg.flush_error {
                    return Err(e.clone());
                }
                if bg.shutdown {
                    return Err(Error::InvalidArgument("the database is closing".into()));
                }
                self.bg_cv.wait(&mut bg);
            }
        } else if l0 >= self.l0_slowdown {
            add(&self.counters.l0_slowdowns, 1);
            std::thread::sleep(Duration::from_millis(1));
        }
        Ok(())
    }

    /// Seal the memtable and start a new one with a new WAL. Called with the
    /// commit lock held. Waits while too many memtables are waiting to flush.
    fn switch_memtable(&self, commit: &mut CommitState) -> Result<()> {
        {
            let start = Instant::now();
            let _count = Defer(|| add(&self.counters.memtable_wait_micros, micros_since(start)));
            let mut bg = self.bg.lock();
            while self.sv.load().imms.len() >= self.max_imms {
                self.check()?;
                if let Some(e) = &bg.flush_error {
                    return Err(e.clone());
                }
                if bg.shutdown {
                    return Err(Error::InvalidArgument("the database is closing".into()));
                }
                self.bg_cv.wait(&mut bg);
            }
        }
        // A flush must not start on a memtable still being inserted into.
        self.publisher.wait(commit.last_seq);
        // Everything in the old WAL must be durable before anything lands in
        // the new one: a crash may not keep a later write and lose an
        // earlier one.
        let written = commit.wal.written.load(Ordering::Relaxed);
        self.counters
            .largest_wal_bytes
            .fetch_max(written, Ordering::Relaxed);
        // The old WAL is closed with an end record, so its reused file's old
        // bytes are not mistaken for a torn write when it is replayed.
        let mut end = Vec::new();
        log::encode_end(&mut end, file_no_u32(commit.wal.number)?);
        self.io(|| Ok(commit.wal.file.append(&end)?))?;
        commit.wal.dirty.store(true, Ordering::Release);
        let number = self.allocate_file();
        let new_path = self.dir.join(wal_name(number));
        // The recycled list stays locked until the file is renamed: a flush
        // lists the directory under the same lock, and seeing the old name
        // after it left the list would put it back.
        let file = {
            let mut recycled = self.recycled_wals.lock();
            match recycled.pop() {
                Some(old) => {
                    self.io(|| Ok(self.fs.reuse(&self.dir.join(wal_name(old)), &new_path)?))?
                }
                None => self.io(|| Ok(self.fs.create(&new_path)?))?,
            }
        };
        // Everything up to `last_seq` is in older WALs or tables.
        let mut header = Vec::new();
        log::encode_header(&mut header, file_no_u32(number)?, commit.last_seq);
        self.io(|| Ok(file.append(&header)?))?;
        {
            let mut barrier = self.barrier.lock();
            barrier.older.push(commit.wal.clone());
            barrier.dir_dirty = true;
        }
        let wal = Arc::new(WalFile {
            file,
            number,
            dirty: AtomicBool::new(false),
            written: AtomicU64::new(0),
            synced: AtomicU64::new(0),
        });
        commit.wal = wal.clone();
        *self.current_wal.lock() = wal;

        self.install(|sv| SuperVersion {
            mem: Arc::new(Memtable::new(number)),
            imms: std::iter::once(sv.mem.clone())
                .chain(sv.imms.iter().cloned())
                .collect(),
            version: sv.version.clone(),
        });
        self.notify_background();
        Ok(())
    }

    // ------------------------------------------------------------ background

    fn flush_loop(&self) {
        loop {
            let imm = {
                let mut bg = self.bg.lock();
                loop {
                    if bg.shutdown || self.poisoned.load(Ordering::Acquire) {
                        return;
                    }
                    if let Some(imm) = self.sv.load().imms.last() {
                        break imm.clone();
                    }
                    self.bg_cv.wait(&mut bg);
                }
            };
            if let Err(e) = self.flush_memtable(&imm) {
                self.poison_because(&e);
                self.bg.lock().flush_error = Some(e);
                self.notify_background();
                return;
            }
        }
    }

    /// Change the database's structure: compute the edits and the new super
    /// version from the current ones, log the edits, run `after_log`,
    /// install, and retire the files the change dropped. One change at a
    /// time, so a change computed from the current version is still valid
    /// when it is installed. `None` from `change` means nothing to do.
    fn log_and_apply(
        &self,
        change: impl FnOnce(&SuperVersion) -> Result<Option<VersionChange>>,
        after_log: impl FnOnce(),
    ) -> Result<bool> {
        let _guard = self.sv_lock.lock();
        let current = self.sv.load_full();
        let Some(mut change) = change(&current)? else {
            return Ok(false);
        };
        tidy(&mut change);
        {
            let mut structure = self.structure.lock();
            let next_file = structure.state.next_file;
            change.edits.push(Edit::NextFile(next_file));
            self.append_edits(&mut structure, &change.edits)?;
        }
        after_log();
        self.sv.store(Arc::new(change.sv));
        // Deleted once the last reader holding an older version is done.
        change.retired.iter().for_each(|f| f.mark_obsolete());
        crate::version::retry_deletes(self.fs.as_ref(), &self.graveyard);
        Ok(true)
    }

    fn live_cfs(&self) -> HashSet<u32> {
        self.structure.lock().state.cfs.keys().copied().collect()
    }

    /// Write the oldest sealed memtable as level-0 tables and retire it.
    fn flush_memtable(&self, imm: &Arc<Memtable>) -> Result<()> {
        let tombstones = imm.tombstones();
        let (next_wal, watermark) = {
            let sv = self.sv.load();
            // WALs before the next memtable's first one hold nothing unflushed.
            let at = sv
                .imms
                .iter()
                .position(|m| Arc::ptr_eq(m, imm))
                .expect("the memtable being flushed");
            let next_wal = if at == 0 {
                sv.mem.first_wal()
            } else {
                sv.imms[at - 1].first_wal()
            };
            let watermark = sv
                .version
                .tombstones
                .iter()
                .chain(&tombstones)
                .map(|t| t.seq)
                .max()
                .unwrap_or(0);
            (next_wal, watermark)
        };
        let live = self.live_cfs();
        let files = flush::write_tables(
            self.fs.as_ref(),
            &self.dir,
            imm,
            &|cf| live.contains(&cf),
            self.target_file_size,
            watermark,
            || self.allocate_file(),
        )?;

        add(&self.counters.flushes, 1);
        add(
            &self.counters.flushed_bytes,
            files.iter().map(|(_, p)| p.size).sum(),
        );
        let tables: Vec<Arc<TableFile>> = files
            .iter()
            .map(|(number, props)| {
                Arc::new(
                    TableFile::new(
                        self.fs.clone(),
                        self.block_cache.clone(),
                        &self.dir,
                        *number,
                        props.clone(),
                    )
                    .with_graveyard(self.graveyard.clone()),
                )
            })
            .collect();
        // Open the new tables here, on the flush thread, so the first
        // readers after the install do not each pay for it.
        for table in &tables {
            table.reader()?;
        }
        self.log_and_apply(
            |sv| {
                let mut edits: Vec<Edit> = files
                    .iter()
                    .map(|(number, props)| Edit::AddFile {
                        level: 0,
                        number: *number,
                        props: props.clone(),
                    })
                    .collect();
                edits.extend(tombstones.iter().cloned().map(Edit::AddRangeTombstone));
                edits.push(Edit::LogNumber(next_wal));
                edits.push(Edit::LastSeq(imm.max_seq()));
                let mut version = (*sv.version).clone();
                version.levels[0].extend(tables);
                version.sort_level0();
                version.tombstones.extend(tombstones.iter().cloned());
                Ok(Some(VersionChange {
                    edits,
                    sv: SuperVersion {
                        mem: sv.mem.clone(),
                        imms: sv
                            .imms
                            .iter()
                            .filter(|m| !Arc::ptr_eq(m, imm))
                            .cloned()
                            .collect(),
                        version: Arc::new(version),
                    },
                    retired: Vec::new(),
                }))
            },
            // The LogNumber edit is durable: the old WALs can go, before the
            // new version is visible to anyone waiting for this flush.
            || {
                // Their memtable is in table files now: nothing to fsync.
                self.barrier.lock().older.retain(|w| w.number >= next_wal);
                let mut recycled = self.recycled_wals.lock();
                for name in self.fs.list(&self.dir).unwrap_or_default() {
                    let Some(no) = parse_wal_name(&name).filter(|no| *no < next_wal) else {
                        continue;
                    };
                    if recycled.contains(&no) {
                        continue;
                    }
                    if recycled.len() < self.recycle_wal_files {
                        recycled.push(no);
                    } else {
                        self.fs.remove(&self.dir.join(&name)).ok();
                    }
                }
            },
        )?;
        self.notify_background();
        Ok(())
    }

    /// Take up to `want` compaction threads, at least one: a compaction
    /// splits into as many subcompactions as the budget has room for.
    fn reserve_threads(&self, want: usize) -> usize {
        let mut used = self.compaction_threads_used.lock();
        let granted = want
            .min(self.compaction_threads.saturating_sub(*used))
            .max(1);
        *used += granted;
        granted
    }

    fn release_threads(&self, n: usize) {
        let mut used = self.compaction_threads_used.lock();
        *used = used.saturating_sub(n);
    }

    /// Pick a compaction with `choose` and reserve its files, atomically
    /// with respect to every other compaction.
    fn claim(
        &self,
        choose: impl FnOnce(&Version, compaction::Busy<'_>) -> Option<compaction::Compaction>,
    ) -> Option<(compaction::Compaction, Arc<Version>)> {
        let mut busy = self.compacting.lock();
        let version = self.sv.load().version.clone();
        let picked = choose(&version, &|n| busy.contains(&n))?;
        busy.extend(picked.all_inputs().map(|(_, f)| f.number));
        Some((picked, version))
    }

    fn release(&self, c: &compaction::Compaction) {
        let mut busy = self.compacting.lock();
        for (_, f) in c.all_inputs() {
            busy.remove(&f.number);
        }
        drop(busy);
        self.notify_background();
    }

    fn compaction_loop(&self) {
        loop {
            let (picked, version) = {
                let mut bg = self.bg.lock();
                loop {
                    if bg.shutdown || self.poisoned.load(Ordering::Acquire) {
                        return;
                    }
                    let cursors = self.cursors.lock().clone();
                    if let Some(claimed) =
                        self.claim(|v, busy| compaction::pick(v, &cursors, &self.compaction, busy))
                    {
                        break claimed;
                    }
                    // Wake now and then even without work, to retry deletes
                    // that failed.
                    if self
                        .bg_cv
                        .wait_for(&mut bg, Duration::from_secs(1))
                        .timed_out()
                    {
                        crate::version::retry_deletes(self.fs.as_ref(), &self.graveyard);
                    }
                }
            };
            let outcome = self.compact(&picked, &version);
            self.release(&picked);
            if let Err(e) = outcome {
                self.poison_because(&e);
                self.bg.lock().flush_error = Some(e);
                self.notify_background();
                return;
            }
        }
    }

    /// Run one compaction picked from `version`, its files reserved. If the
    /// inputs changed meanwhile (a range delete dropped one), the result is
    /// discarded.
    fn compact(&self, c: &compaction::Compaction, version: &Version) -> Result<()> {
        let start = Instant::now();
        let output_level = c.output_level;
        let outputs = if c.is_trivial_move() {
            Vec::new()
        } else {
            let live = self.live_cfs();
            let threads = self.reserve_threads(self.compaction.subcompactions);
            let cfg = compaction::Config {
                subcompactions: threads,
                ..self.compaction
            };
            let outcome = compaction::run(
                c,
                version,
                &|cf| live.contains(&cf),
                self.fs.as_ref(),
                &self.dir,
                &cfg,
                &|| self.allocate_file(),
            );
            self.release_threads(threads);
            outcome?
        };
        let new_tables: Vec<Arc<TableFile>> = if c.is_trivial_move() {
            vec![c.inputs[0].clone()]
        } else {
            outputs
                .iter()
                .map(|(number, props)| {
                    Arc::new(
                        TableFile::new(
                            self.fs.clone(),
                            self.block_cache.clone(),
                            &self.dir,
                            *number,
                            props.clone(),
                        )
                        .with_graveyard(self.graveyard.clone()),
                    )
                })
                .collect()
        };
        // Opened before they are installed, as the flush does.
        for table in &new_tables {
            table.reader()?;
        }
        let applied = self.log_and_apply(
            |sv| {
                let current = c
                    .all_inputs()
                    .all(|(level, f)| sv.version.levels[level].iter().any(|g| Arc::ptr_eq(g, f)));
                if !current {
                    return Ok(None);
                }
                let mut edits: Vec<Edit> = c
                    .all_inputs()
                    .map(|(level, f)| Edit::DeleteFile {
                        level: level as u32,
                        number: f.number,
                    })
                    .collect();
                edits.extend(new_tables.iter().map(|f| Edit::AddFile {
                    level: output_level as u32,
                    number: f.number,
                    props: f.props.clone(),
                }));
                let mut version = (*sv.version).clone();
                for (level, f) in c.all_inputs() {
                    version.levels[level].retain(|g| !Arc::ptr_eq(g, f));
                }
                version.levels[output_level].extend(new_tables.iter().cloned());
                version.levels[output_level].sort_by(by_smallest);
                let retired = if c.is_trivial_move() {
                    Vec::new()
                } else {
                    c.all_inputs().map(|(_, f)| f.clone()).collect()
                };
                Ok(Some(VersionChange {
                    edits,
                    sv: SuperVersion {
                        mem: sv.mem.clone(),
                        imms: sv.imms.clone(),
                        version: Arc::new(version),
                    },
                    retired,
                }))
            },
            || {},
        )?;
        add(&self.counters.compactions, 1);
        add(&self.counters.compaction_micros, micros_since(start));
        if !c.is_trivial_move() {
            add(
                &self.counters.compaction_read_bytes,
                c.all_inputs().map(|(_, f)| f.props.size).sum(),
            );
            add(
                &self.counters.compaction_written_bytes,
                outputs.iter().map(|(_, p)| p.size).sum(),
            );
        }
        if !applied && !c.is_trivial_move() {
            // Deleted as they are dropped, after their readers are closed.
            new_tables.iter().for_each(|t| t.mark_obsolete());
        }
        if c.output_level > c.level {
            self.cursors.lock()[c.level] = c.largest();
        }
        self.notify_background();
        Ok(())
    }

    /// Eventual mode's background fsync: every `interval`, and at once when
    /// a leader asks (`wal_bytes_per_sync` bytes waiting, or a memtable
    /// switch). It sleeps on its own park token: on the shared `bg_cv` every
    /// flush and compaction woke it. Every request comes with an `unpark`,
    /// so a request made while it syncs makes the next park return at once.
    fn sync_loop(&self, interval: Duration) {
        loop {
            std::thread::park_timeout(interval);
            let wal = self.current_wal.lock().clone();
            // The mark first, then the flag: a leader asks again only for
            // bytes past what this round covers, not for the same bytes
            // while the older WALs and the directory are synced first.
            Self::mark_syncing(&wal);
            self.sync_wanted.store(false, Ordering::Release);
            if self.bg.lock().shutdown || self.poisoned.load(Ordering::Acquire) {
                return;
            }
            let behind = !self.barrier.lock().older.is_empty();
            if wal.dirty.load(Ordering::Acquire) || behind {
                if self.sync_wal_file(&wal).is_err() {
                    return;
                }
                add(&self.counters.wal_background_fsyncs, 1);
            }
        }
    }
}