coordinode-lsm-tree 7.2.0

Embedded LSM-tree storage engine in pure Rust, no C/C++ dependency. MVCC snapshots, BuRR filters, zstd dictionary compression, columnar PAX blocks, AES-256-GCM at rest, self-healing per-block ECC, compaction on a near-full disk, no_std support.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024-present, fjall-rs
// Copyright (c) 2026-present, Dmitry Prudnikov

//! Pluggable filesystem abstraction for I/O backends.
//!
//! The [`Fs`](crate::fs::Fs) trait is intended to abstract the filesystem operations
//! that lsm-tree performs, allowing alternative backends such as
//! `io_uring`, in-memory filesystems for deterministic testing, or cloud
//! blob storage. Call-site migration is tracked in separate issues.
//!
//! The default implementation [`StdFs`](crate::fs::StdFs) delegates to [`std::fs`] and
//! is a zero-sized type, so it adds no runtime overhead when used as a
//! monomorphized generic parameter.
//!
//! # Platform-specific backends
//!
//! - **Linux 5.6+**: `IoUringFs` - batched SQE submission via `io_uring`
//!   (feature-gated: `io-uring`)
//! - **Windows**: IOCP (`IoCompletionPort`) could provide similar batched
//!   completion semantics - not yet implemented, tracked for when Windows
//!   becomes a production target
//! - **macOS / BSD**: no batched I/O API exists (`dispatch_io` and `kqueue`
//!   do not help for storage I/O patterns); [`StdFs`](crate::fs::StdFs) is the correct choice

mod aligned_buf;
mod counting_fs;
// `direct_io` is std-only (touches `std::fs::OpenOptions`). It is
// gated behind the `std` feature so a `no_std + alloc` build of
// this crate does not even attempt to compile it. The wider
// `fs::*` backend (Fs / FsFile traits, std_fs, io_uring_fs)
// still depends on `std::io::{Read, Write, Seek}` + `std::path::Path`
// - those have no `core::*` equivalents, so feature-gating just
// this submodule does not yet make a no-std build work end-to-end.
// Porting the traits off std::io / std::path is tracked as #311
// (prerequisite); the wider no-std migration epic is #274. This
// gate is the first concrete step.
#[cfg(feature = "std")]
mod open_flags;
// `std_fs` (std::fs) is genuinely std-bound and gated out of a `no_std` build.
// `mem_fs` is the no_std-capable reference backend (spin + hashbrown over the
// `crate::io` `Fs` trait): it stays unconditional so a `no_std` consumer has a
// working `Fs` implementation to use and to copy for a real backend.
mod mem_fs;
// Programmable fault-injection backend for crash / error-path testing.
// std-gated test/dev surface: it wraps an inner Fs and implements the std
// `io::{Read, Write, Seek}` traits on its file handle (which under `std` ARE
// the `crate::io` trait aliases), so it does not participate in a no_std build.
#[cfg(feature = "std")]
mod fault_fs;
// Power-loss crash simulator: rolls files back to their last-synced content on
// `crash()`. Same std-gated test/dev rationale as `fault_fs`.
#[cfg(feature = "std")]
mod crash_fs;
#[cfg(feature = "std")]
mod std_fs;

pub use aligned_buf::AlignedBuf;
pub use counting_fs::{
    CountingFs, DirectoryWrites, FileWrites, WriteIoSnapshot, WriteIoStats, WriteOrigin,
};

#[cfg(all(target_os = "linux", feature = "io-uring"))]
mod io_uring_fs;

// Pure-Rust `no_std` io_uring driver core on raw Linux syscalls (#346).
#[cfg(all(target_os = "linux", feature = "io-uring-raw"))]
mod io_uring_raw;

// The batched-read tests every backend that reads by descriptor passes.
#[cfg(all(
    test,
    feature = "std",
    target_os = "linux",
    any(feature = "io-uring", feature = "io-uring-raw")
))]
mod batch_conformance;

#[cfg(feature = "std")]
pub use crash_fs::CrashFs;
#[cfg(all(test, feature = "std"))]
pub(crate) use fault_fs::ReadHook;
#[cfg(feature = "std")]
pub use fault_fs::{Fault, FaultFs, FaultInjector, FaultOp, FaultRule, SyncKind};
pub use mem_fs::MemFs;
#[cfg(feature = "std")]
pub use std_fs::StdFs;
#[cfg(feature = "std")]
pub(crate) use std_fs::is_cross_device;

#[cfg(all(target_os = "linux", feature = "io-uring"))]
pub use io_uring_fs::{IoUringFs, is_io_uring_available};

// Raw-syscall `no_std` io_uring driver (#346): the driver core (`IoUringRaw`),
// the [`FsFile`] handle (`IoUringRawFile`), and the [`Fs`] backend
// (`IoUringRawFs`) that opens files on a shared ring and handles directory
// operations via plain blocking syscalls — all pure syscalls, no `io-uring`
// crate and no `std::fs`.
#[cfg(all(target_os = "linux", feature = "io-uring-raw"))]
pub use io_uring_raw::{
    IoUringRaw, IoUringRawFile, IoUringRawFs, O_CREAT, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY,
    close_raw, open_raw,
};

// `Read` / `Write` / `Seek` come from `crate::io`, the local mirror
// of `std::io` that compiles under `no_std + alloc`. Under `feature =
// "std"` the blanket impls in `crate::io` forward to `std::io::*`, so
// existing std-backed backends (`std_fs`, `io_uring_fs`) satisfy
// these bounds without any change to their own impls.
//
// `io::{Result, Error, ErrorKind}` come from `crate::io` (the local mirror of
// `std::io`): under `std` they bridge to/from `std::io` via `From`, so std
// backends' `?`-chains convert transparently; under `no_std` they are the
// native types. `Path`/`PathBuf` come from `crate::path` (a re-export of
// `std::path` under `std`, a `str`-key newtype under `no_std`).
use crate::io::{self, Read, Seek, Write};
use crate::path::{Path, PathBuf};
#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, string::String, vec::Vec};

/// Options for opening a file through the [`Fs`] trait.
///
/// Mirrors the builder API of [`std::fs::OpenOptions`].
#[expect(
    clippy::struct_excessive_bools,
    reason = "mirrors std::fs::OpenOptions which uses bool flags for each mode"
)]
// `non_exhaustive` paired with the `direct_io` field landing in the
// same release. The new field already breaks struct-literal
// callers; bundling `non_exhaustive` in the same semver-major bump
// confines the break to one release and lets every future field
// land as semver-minor. Builder methods (`.read()`, `.write()`, …,
// `.direct_io()`) cover every field, so callers using the builder
// API are unaffected.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct FsOpenOptions {
    /// Open for reading.
    pub read: bool,
    /// Open for writing.
    pub write: bool,
    /// Create the file if it does not exist.
    pub create: bool,
    /// Create a new file and fail if it already exists.
    pub create_new: bool,
    /// Truncate the file to zero length on open.
    pub truncate: bool,
    /// Open in append mode, so writes go to the end of the file.
    pub append: bool,
    /// Bypass the kernel page cache for this file (`O_DIRECT` on Linux).
    ///
    /// When set, the caller is responsible for issuing reads and writes
    /// at offsets aligned to the filesystem's logical block size, with
    /// userspace buffers aligned to the same boundary and lengths that
    /// are a multiple of that block size.
    ///
    /// `direct_io` is a HINT, not a guarantee. The flag is honoured only
    /// on Linux and Android, with the target architecture's own `O_DIRECT`
    /// bit, and the raw `io_uring` backend does not wire it. Other
    /// platforms - macOS (would need `F_NOCACHE` post-open via `fcntl`, not
    /// wired here), Windows (would need `FILE_FLAG_NO_BUFFERING` at
    /// `CreateFile` time, not wired here), other Unixes - silently drop the
    /// flag.
    ///
    /// Callers must therefore treat `direct_io` as best-effort:
    /// correctness must not depend on cache bypass being in effect, and
    /// any alignment requirements imposed by the kernel only apply when
    /// the flag is actually honoured (you cannot tell from this API
    /// alone whether it was). See [`AlignedBuf`] for an aligned heap
    /// buffer suitable for `O_DIRECT` reads and writes when the flag is
    /// honoured.
    pub direct_io: bool,
    /// Do not follow a symbolic link at the path's last component. On Unix
    /// the open fails (`O_NOFOLLOW`); on Windows the link itself is opened
    /// (`FILE_FLAG_OPEN_REPARSE_POINT`), which is not a regular file. A
    /// backend without symbolic links has nothing to follow.
    pub no_follow: bool,
    /// Do not wait in the open itself: a named pipe at the path with no
    /// reader fails the open on Unix rather than block it (`O_NONBLOCK`,
    /// cleared once the file is open, so its reads and writes block as
    /// usual). A backend without named pipes has nothing to wait for.
    pub no_wait: bool,
    /// What the file is written for, so a counting backend such as
    /// [`CountingFs`] charges its writes to that origin. Advisory: it never
    /// changes what the open or the file does.
    pub write_origin: Option<WriteOrigin>,
}

impl Default for FsOpenOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl FsOpenOptions {
    /// Creates a new set of options with everything disabled.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            read: false,
            write: false,
            create: false,
            create_new: false,
            truncate: false,
            append: false,
            direct_io: false,
            no_follow: false,
            no_wait: false,
            write_origin: None,
        }
    }

    /// Sets the `read` flag.
    #[must_use]
    pub const fn read(mut self, read: bool) -> Self {
        self.read = read;
        self
    }

    /// Sets the `write` flag.
    #[must_use]
    pub const fn write(mut self, write: bool) -> Self {
        self.write = write;
        self
    }

    /// Sets the `create` flag.
    #[must_use]
    pub const fn create(mut self, create: bool) -> Self {
        self.create = create;
        self
    }

    /// Sets the `create_new` flag.
    #[must_use]
    pub const fn create_new(mut self, create_new: bool) -> Self {
        self.create_new = create_new;
        self
    }

    /// Sets the `truncate` flag.
    #[must_use]
    pub const fn truncate(mut self, truncate: bool) -> Self {
        self.truncate = truncate;
        self
    }

    /// Sets the `append` flag.
    #[must_use]
    pub const fn append(mut self, append: bool) -> Self {
        self.append = append;
        self
    }

    /// Sets the `direct_io` flag.
    #[must_use]
    pub const fn direct_io(mut self, direct_io: bool) -> Self {
        self.direct_io = direct_io;
        self
    }

    /// Sets the `no_follow` flag.
    #[must_use]
    pub const fn no_follow(mut self, no_follow: bool) -> Self {
        self.no_follow = no_follow;
        self
    }

    /// Sets the `no_wait` flag.
    #[must_use]
    pub const fn no_wait(mut self, no_wait: bool) -> Self {
        self.no_wait = no_wait;
        self
    }

    /// Sets what the file is written for (see [`Self::write_origin`]).
    #[must_use]
    pub const fn write_origin(mut self, origin: WriteOrigin) -> Self {
        self.write_origin = Some(origin);
        self
    }
}

/// Metadata about a file or directory.
#[derive(Clone, Debug)]
pub struct FsMetadata {
    /// Size in bytes. For directories the value is platform-dependent.
    pub len: u64,
    /// Whether this entry is a directory.
    pub is_dir: bool,
    /// Whether this entry is a regular file.
    pub is_file: bool,
}

/// Static capability profile of a filesystem backend.
///
/// Different filesystems offer different guarantees - per-block integrity
/// checks, copy-on-write semantics, O(1) reflink clones, native snapshots.
/// The storage engine queries [`Fs::capabilities`] to make FS-aware decisions
/// (skip redundant checksums where the FS already verifies, disable `CoW` on
/// write-once SST files, prefer reflink over hard-link for checkpoints).
///
/// The [`Default`] is conservative: every field `false`, i.e. "assume the
/// backend offers no special guarantees". A backend opts into an optimization
/// only by reporting the corresponding capability `true`, so an unknown or
/// third-party backend is always treated safely.
//
// no-std: pure data type - `Copy` struct of `bool`s, no allocator needed.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
#[expect(
    clippy::struct_excessive_bools,
    reason = "a capability profile is a flat set of independent yes/no FS guarantees; \
              each flag is queried on its own, so distinct bools read clearer than \
              bitflags or a state machine (same rationale as FsOpenOptions)"
)]
pub struct FsCapabilities {
    /// The filesystem detects single-byte corruption on read and returns an
    /// I/O error (EIO) rather than silently handing back wrong bytes. True for
    /// ZFS, Btrfs, `ReFS`, and S3-backed backends (service-side validation).
    ///
    /// When set, the engine may skip computing its own file checksum on the
    /// read path and rely on the FS surfacing corruption.
    pub per_block_integrity_on_read: bool,

    /// The filesystem has a background scrub mechanism (`zfs scrub`,
    /// `btrfs scrub`) that detects and repairs latent corruption out-of-band.
    pub background_scrub: bool,

    /// The filesystem is inherently copy-on-write (Btrfs, ZFS, APFS). Implies
    /// atomic full-file rewrite, but a fragmentation penalty on the
    /// append-then-read SST access pattern - the engine can disable per-file
    /// `CoW` on write-once SSTs to recover throughput.
    pub copy_on_write: bool,

    /// The filesystem supports an O(1) reflink data clone (`FICLONE` on Linux,
    /// `clonefile(2)` on macOS/APFS, block cloning on `ReFS`). A reflinked file
    /// shares blocks copy-on-write yet has an independent inode.
    pub reflink: bool,

    /// The filesystem supports instant native snapshots (Btrfs subvolume
    /// snapshot, ZFS snapshot, APFS snapshot).
    pub native_snapshot: bool,

    /// The filesystem can deallocate a byte range *inside* a file, freeing its
    /// physical blocks while leaving the logical length unchanged (a hole that
    /// reads back as zeros): `fallocate(FALLOC_FL_PUNCH_HOLE)` on Linux,
    /// `fcntl(F_PUNCHHOLE)` on macOS/APFS. True for ext4 / xfs / btrfs / zfs /
    /// tmpfs / apfs; false for network mounts and any backend that cannot
    /// reclaim mid-file extents.
    ///
    /// Enables the opt-in tight-space incremental-reclaim compaction mode, which
    /// frees consumed input extents in place as the merged output grows. When
    /// false the mode is unavailable and the engine falls back to whole-output
    /// compaction.
    pub punch_hole: bool,

    /// Syncing a directory does nothing on this backend (Windows has no
    /// directory fsync; an entry is as durable as the platform makes it
    /// without one). Work whose only gain is a directory sync it saves, such
    /// as the table file pool, is then skipped: it would cost and save
    /// nothing.
    pub directory_sync_noop: bool,
}

/// A directory entry returned by [`Fs::read_dir`].
#[derive(Clone, Debug)]
pub struct FsDirEntry {
    /// Full path to the entry.
    pub path: PathBuf,
    /// File name component (without parent path).
    // String (not OsString) - lsm-tree uses numeric file names for tables/blobs.
    // StdFs::read_dir returns InvalidData for non-UTF-8 names (not lossy) since
    // any such name indicates filesystem corruption for this crate's usage.
    pub file_name: String,
    /// Whether this entry is a directory.
    pub is_dir: bool,
}

/// Access-pattern hint passed to [`FsFile::hint`].
///
/// Backends translate it to the platform's nearest equivalent
/// (`posix_fadvise` on Linux, no-op on macOS / Windows for now). The
/// hint is advisory - backends are free to ignore it - and only
/// influences kernel readahead / page-cache eviction heuristics, not
/// correctness.
///
/// Used at SST/blob open sites to tell the OS what we're about to do
/// with the file (sequential scan, random point read, write-once-and-
/// evict, …). Picking the right hint cuts page-cache double-buffering
/// on cold-path compaction reads and prevents readahead waste on
/// point-read SST files.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FileHint {
    /// No hint - leave the kernel's default caching / readahead policy in
    /// place. Use when the access pattern is unknown or genuinely mixed.
    #[default]
    Default,

    /// File will be read mostly forward, in order
    /// (`POSIX_FADV_SEQUENTIAL`). Tells the kernel to ramp up readahead
    /// and evict already-read pages aggressively. Use for compaction
    /// input files and full-range scans.
    Sequential,

    /// File will be read at scattered offsets with no useful prefetch
    /// pattern (`POSIX_FADV_RANDOM`). Tells the kernel to disable
    /// readahead so it doesn't waste bandwidth speculatively loading
    /// pages we won't touch. Use for SST files opened for point-read
    /// service.
    Random,

    /// File is being written and we won't need it cached afterwards -
    /// drop pages from the page cache when the write completes
    /// (`POSIX_FADV_DONTNEED`). Use for compaction output and memtable
    /// flush output to keep them from evicting hot pages of files we're
    /// still reading from.
    WriteOnce,
}

/// How long the data written through a file is expected to live before it is
/// overwritten or deleted.
///
/// Passed to [`FsFile::set_write_lifetime`] so a device that groups data by
/// lifetime (`NVMe` streams or flexible data placement) keeps data that dies
/// together in the same erase units. Advisory: it changes where a device
/// places data, never what a read returns.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WriteLifetime {
    /// Expected to be overwritten soon.
    Short,
    /// Between short and long.
    Medium,
    /// Expected to outlive most other data.
    Long,
    /// Expected to be kept for the life of the store.
    Extreme,
}

/// Durability level for a sync (fsync) operation.
///
/// The distinction is only observable on macOS, where Rust's
/// [`std::fs::File::sync_all`] / [`sync_data`](std::fs::File::sync_data)
/// both issue `fcntl(F_FULLFSYNC)` - a full hardware barrier that flushes
/// the drive's write cache to the platters (~4 ms on a modern SSD). On
/// every other platform `sync_all` is already a plain `fsync` and both
/// variants behave identically.
///
/// [`Self::Normal`] is the default: it matches the durability that
/// `RocksDB` and `SQLite` give out of the box (plain `fsync`, which on macOS
/// reaches the drive cache but not necessarily the platters). [`Self::Full`]
/// opts into `F_FULLFSYNC` on macOS for callers that need power-loss
/// durability at the cost of a much slower flush.
//
// no-std: pure data type - `Copy` enum, no allocator needed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SyncMode {
    /// Plain `fsync` on every platform. On macOS this does NOT issue
    /// `F_FULLFSYNC`, so it is dramatically faster but only guarantees the
    /// data reached the drive's write cache (same as `RocksDB` / `SQLite`
    /// defaults). The default.
    #[default]
    Normal,

    /// Full durability. On macOS this issues `fcntl(F_FULLFSYNC)` so the
    /// data survives power loss; elsewhere it is identical to
    /// [`Self::Normal`]. Slower - opt in only when the workload needs
    /// power-loss durability without an external journal.
    Full,

    /// Ordered durability. On macOS this issues `fcntl(F_BARRIERFSYNC)`
    /// (about 0.7 ms against `F_FULLFSYNC`'s 5.7 ms): the writes synced on a
    /// device reach its medium in the order they were synced, and all of them
    /// are durable once a later [`Fs::sync_device`] of that device returns
    /// `Ok`. The last sync of a transition on one device before a step on
    /// another is issued as [`Self::Full`], so a step never outlives one on
    /// another device it depends on. Elsewhere it is identical to
    /// [`Self::Normal`], where `fsync` already reaches the medium.
    Barrier,
}

/// Filesystem operations on an open file handle.
///
/// Extends [`Read`] + [`Write`] + [`Seek`] with persistence and
/// metadata operations needed by the storage engine.
pub trait FsFile: Read + Write + Seek + Send + Sync {
    /// Flushes all OS-internal buffers and metadata to durable storage.
    ///
    /// Equivalent to [`sync_all_with`](Self::sync_all_with) with
    /// [`SyncMode::Full`] - the strongest durability the platform offers
    /// (`F_FULLFSYNC` on macOS).
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_all(&self) -> io::Result<()>;

    /// Flushes file data, and the metadata a later read of that data needs
    /// (the file size), to durable storage; other metadata (timestamps) need
    /// not be. This is POSIX `fdatasync` (IEEE Std 1003.1, "synchronized I/O
    /// data integrity completion"), and the engine relies on it: an appended
    /// log is synced this way, and a size left behind would lose the append.
    ///
    /// Equivalent to [`sync_data_with`](Self::sync_data_with) with
    /// [`SyncMode::Full`].
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_data(&self) -> io::Result<()>;

    /// Flushes all buffers and metadata at the requested durability
    /// [`SyncMode`].
    ///
    /// The default implementation ignores `mode` and delegates to
    /// [`sync_all`](Self::sync_all) (full durability); backends where the
    /// mode is observable (the std `File` backend on macOS) override this.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_all_with(&self, mode: SyncMode) -> io::Result<()> {
        let _ = mode;
        self.sync_all()
    }

    /// Flushes file data, and the file size, at the requested durability
    /// [`SyncMode`], with the same contract as [`sync_data`](Self::sync_data).
    ///
    /// The default implementation ignores `mode` and delegates to
    /// [`sync_data`](Self::sync_data).
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_data_with(&self, mode: SyncMode) -> io::Result<()> {
        let _ = mode;
        self.sync_data()
    }

    /// Returns metadata for this open file handle.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if metadata cannot be retrieved.
    fn metadata(&self) -> io::Result<FsMetadata>;

    /// Returns the number of directory entries (hard links) referring to this
    /// file's underlying object.
    ///
    /// In-place mutation paths consult this before writing through a path:
    /// a count above 1 means another name (typically a checkpoint) shares the
    /// same bytes, and writing in place would silently rewrite that snapshot
    /// too.
    ///
    /// Backends with no hard-link concept ([`MemFs`], whose
    /// [`Fs::hard_link`] copies) override this to return 1. The Unix file
    /// backends report the real count from the inode's link field (`StdFs` via
    /// `nlink`, the raw `io_uring` backend via `statx` `stx_nlink`). Backends that
    /// CAN share inodes but cannot determine the count keep the default error, so
    /// in-place mutation paths fail closed (treat the file as shared) instead
    /// of overwriting a snapshot through an unrecognized link.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the link count cannot be retrieved; the
    /// default returns [`ErrorKind::Unsupported`](crate::io::ErrorKind).
    fn hard_link_count(&self) -> io::Result<u64> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "hard-link count unavailable",
        ))
    }

    /// Truncates or extends the file to the specified length.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the length change fails.
    fn set_len(&self, size: u64) -> io::Result<()>;

    /// Reads bytes from the file at the given offset without changing the
    /// file cursor position.
    ///
    /// Equivalent to `pread(2)` on Unix. Multiple threads can call this
    /// concurrently on the same file handle without synchronization.
    ///
    /// Implementations must provide *fill-or-EOF* semantics: on success,
    /// this method either fills `buf` completely and returns
    /// `Ok(buf.len())`, or returns `Ok(n)` with `n < buf.len()` only if
    /// the read has reached EOF. Callers may rely on a short read
    /// indicating EOF and therefore do not need a retry loop.
    ///
    /// Implementations are responsible for handling OS-level short reads
    /// and interrupts internally (for example, by retrying on `EINTR`)
    /// so that the above guarantee holds unless an error is returned.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the read fails.
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;

    /// Reads several disjoint `(offset, buf)` regions in one batched operation,
    /// filling each `buf` completely (the regions are block reads of known size,
    /// so a short read is treated as an error, not EOF).
    ///
    /// The default implementation reads the regions serially via
    /// [`read_at`](Self::read_at). Backends with batched / asynchronous I/O
    /// override this to submit every read at once and wait for all completions,
    /// so a multi-block read (a `multi_get` over cold SST blocks) overlaps in
    /// flight and costs one submission instead of one blocking read per block.
    ///
    /// # Errors
    ///
    /// Returns the first failing region's I/O error (a partial read of any region
    /// is reported as [`io::ErrorKind::UnexpectedEof`]). On error the contents of
    /// every `buf` are unspecified.
    fn read_many(&self, regions: &mut [(u64, &mut [u8])]) -> io::Result<()> {
        for (offset, buf) in regions.iter_mut() {
            let n = self.read_at(buf, *offset)?;
            if n != buf.len() {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "read_many: short read on a fixed-size block region",
                ));
            }
        }
        Ok(())
    }

    /// The raw OS file descriptor backing this handle, or `None`.
    ///
    /// `None` for backends with no descriptor (in-memory) or where it is not
    /// meaningful. [`Fs::read_blocks_batched`] uses it to submit reads across
    /// several files to one shared `io_uring` ring; a handle returning `None`
    /// is read serially instead.
    fn backing_fd(&self) -> Option<i32> {
        None
    }

    /// Acquires an exclusive (write) lock on this file.
    ///
    /// Blocks until the lock is acquired.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if locking fails or is unsupported.
    fn lock_exclusive(&self) -> io::Result<()>;

    /// Tries to acquire an exclusive (write) lock on this file WITHOUT blocking.
    ///
    /// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if another holder
    /// (typically another process) currently owns it. Used for the cross-process
    /// directory lock acquired at [`Config::open`](crate::Config::open) /
    /// [`Config::repair`](crate::Config::repair): a second opener must fail fast
    /// (`Ok(false)` → `Error::Locked`), not hang on a blocking acquire.
    ///
    /// The default implementation **fails closed**: it returns an
    /// [`io::ErrorKind::Unsupported`] error so a backend that has not opted in
    /// cannot silently bypass the cross-process directory lock. A disk-backed
    /// backend that forgot to override this would otherwise let two processes
    /// race on the same tree's manifest. Real on-disk backends override this
    /// with a non-blocking OS lock (`flock` `LOCK_NB` / `LockFileEx`
    /// `LOCKFILE_FAIL_IMMEDIATELY`); intentionally single-process backends
    /// (e.g. in-memory) override it to return `Ok(true)` (exclusivity is
    /// vacuous when there is only one process).
    ///
    /// # Errors
    ///
    /// [`io::ErrorKind::Unsupported`] from the default (un-opted-in) impl, or an
    /// I/O error if a real lock operation fails (a held lock is reported as
    /// `Ok(false)`, not an error).
    fn try_lock_exclusive(&self) -> io::Result<bool> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "FsFile::try_lock_exclusive is not implemented for this backend; \
             override it (real lock, or Ok(true) for single-process backends) \
             or disable the directory lock via Config::with_directory_lock(false)",
        ))
    }

    /// Advise the kernel about the expected access pattern for this file.
    ///
    /// Implementations translate the [`FileHint`] to the platform's
    /// closest primitive (`posix_fadvise` on Linux, no-op on macOS /
    /// Windows / in-memory backends for now). The default trait impl
    /// is a no-op so backends that have nothing useful to do here
    /// don't need to override it.
    ///
    /// The hint is advisory - backends may ignore it - and only
    /// influences kernel readahead / page-cache eviction heuristics, not
    /// correctness.
    ///
    /// # Errors
    ///
    /// Returns an I/O error only if the underlying syscall fails with a
    /// non-`EINVAL` error. A backend that doesn't support the requested
    /// hint should treat the call as a no-op and return `Ok(())` rather
    /// than fail - the hint is a performance lever, not a correctness
    /// requirement.
    fn hint(&self, _hint: FileHint) -> io::Result<()> {
        Ok(())
    }

    /// Starts writing back the `len` bytes written at `offset` without
    /// waiting for them: a later sync then has little left to write, and a
    /// large file does not hold the device for one long flush at its end.
    ///
    /// It makes nothing durable; only a sync does. The default is a no-op;
    /// the std backend issues `sync_file_range(SYNC_FILE_RANGE_WRITE)` on
    /// Linux.
    ///
    /// # Errors
    ///
    /// Returns the error of the system call.
    fn start_writeback(&self, offset: u64, len: u64) -> io::Result<()> {
        let _ = (offset, len);
        Ok(())
    }

    /// Tells the device how long the data written through this handle is
    /// expected to live (see [`WriteLifetime`]).
    ///
    /// The default is a no-op; the std backend issues
    /// `fcntl(F_SET_RW_HINT)` on Linux.
    ///
    /// # Errors
    ///
    /// Returns the error of the system call. The hint is advisory, so a
    /// caller treats a refusal as "no hint", never as a failed write.
    fn set_write_lifetime(&self, lifetime: WriteLifetime) -> io::Result<()> {
        let _ = lifetime;
        Ok(())
    }
}

/// Asks `file` to start writing back `len` bytes at `offset` for a writer that
/// writes back every `writeback_bytes`. The request is a hint: a refusal turns
/// writeback off for the file (`*writeback_bytes = 0`) instead of failing the
/// write, since the file's final sync still writes it and reports a failed
/// write. On Linux `sync_file_range` without `SYNC_FILE_RANGE_WAIT_AFTER` does
/// not consume the file's writeback error, so that sync still sees it.
pub(crate) fn hint_writeback(file: &dyn FsFile, offset: u64, len: u64, writeback_bytes: &mut u64) {
    if let Err(error) = file.start_writeback(offset, len) {
        log::warn!("writeback hint refused, the file is written back by its final sync: {error}");
        *writeback_bytes = 0;
    }
}

/// One block-read request for [`Fs::read_blocks_batched`]: fill `buf` with
/// `buf.len()` bytes from `file` at `offset`.
///
/// Different requests may target different files (different SSTs, and on a
/// multi-device layout different devices), which is the point: one batched
/// submission across all of them.
pub struct BlockRead<'a> {
    /// File to read from.
    pub file: &'a dyn FsFile,
    /// Byte offset within `file`.
    pub offset: u64,
    /// Destination; filled completely on success.
    pub buf: BlockBuf<'a>,
}

/// The destination of one [`BlockRead`]: the bytes to fill, plus a count of how
/// much of it an implementation actually filled.
///
/// The count exists because `Fs` is a public, SAFE trait. "Fills every request
/// or fails" is a documented promise, and an implementation that reports
/// success having written nothing is wrong but not `unsafe`; a caller that
/// decoded whatever was in the buffer would be taking its results on that
/// promise. So the count is not something an implementation asserts, it is
/// something it does: it advances by writing, through [`append`](Self::append),
/// or by filling [`unfilled_mut`](Self::unfilled_mut) and saying how much with
/// [`advance`](Self::advance). The caller checks [`is_full`](Self::is_full) and
/// refuses a short request.
///
/// The memory is INITIALIZED, and this type is entirely safe. Handing out
/// uninitialized bytes would save the caller a memset per block, but they would
/// have to reach [`FsFile::read_at`], which takes a `&mut [u8]` and is itself
/// safe and publicly implementable: forming that reference over uninitialized
/// memory is undefined behaviour on its own, and an otherwise valid
/// implementation is entitled to read its input buffer before writing to it.
/// Nothing on this side can close that, so the memset is paid, and what this
/// type buys is the counting.
pub struct BlockBuf<'a> {
    buf: &'a mut [u8],
    filled: usize,
}

impl<'a> BlockBuf<'a> {
    /// Wraps a buffer as an empty destination.
    #[must_use]
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, filled: 0 }
    }

    /// How many bytes the request wants.
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.buf.len()
    }

    /// How many bytes have been written so far.
    #[must_use]
    pub fn filled(&self) -> usize {
        self.filled
    }

    /// Whether the request has been filled completely.
    #[must_use]
    pub fn is_full(&self) -> bool {
        self.filled == self.buf.len()
    }

    /// The bytes written so far: the whole block once [`is_full`](Self::is_full).
    #[must_use]
    pub fn filled_bytes(&self) -> &[u8] {
        #[expect(
            clippy::indexing_slicing,
            reason = "filled <= buf.len() is the type's invariant"
        )]
        &self.buf[..self.filled]
    }

    /// Copies `bytes` into the unfilled part and counts them.
    ///
    /// The safe way to fill a request. Returns the number of bytes taken, which
    /// is `bytes.len()` unless the request had less room left.
    pub fn append(&mut self, bytes: &[u8]) -> usize {
        let room = self.buf.len() - self.filled;
        let n = room.min(bytes.len());
        for (slot, byte) in self
            .buf
            .iter_mut()
            .skip(self.filled)
            .zip(bytes.iter().take(n))
        {
            *slot = *byte;
        }
        self.filled += n;
        n
    }

    /// The part still to be filled.
    ///
    /// For an implementation that reads into the destination rather than
    /// through a buffer of its own: read into this, then say how much arrived
    /// with [`advance`](Self::advance). Both the pointer and the length of a
    /// read must come from THIS slice; taking the length from
    /// [`capacity`](Self::capacity) instead would describe a region starting at
    /// the fill point and running to the end of the whole buffer, which is
    /// longer than what is left whenever anything has been written.
    pub fn unfilled_mut(&mut self) -> &mut [u8] {
        let filled = self.filled;
        #[expect(
            clippy::indexing_slicing,
            reason = "filled <= buf.len() is the type's invariant"
        )]
        &mut self.buf[filled..]
    }

    /// Counts `n` more bytes as filled.
    ///
    /// Over-counting cannot break memory safety here, since the bytes were
    /// initialized to begin with; it makes the request look complete when it is
    /// not, and the block decoded from it then fails its checksum. Clamped at
    /// the capacity so the fill point stays inside the buffer.
    pub fn advance(&mut self, n: usize) {
        // Clamp BEFORE adding: `filled + n` computed first would panic in
        // debug builds and wrap `filled` backwards in release builds for an
        // oversized `n`.
        let remaining = self.buf.len() - self.filled;
        self.filled += n.min(remaining);
    }
}

/// One read handed to a [`ReadQueue`]: `buf.len()` bytes of `file` from
/// `offset`.
///
/// The queue owns the buffer from [`submit`](ReadQueue::submit) until it hands
/// the read back in a [`ReadDone`], so a read still in flight can never have
/// its destination freed under it.
pub struct QueuedRead {
    /// The caller's name for the read, handed back with its completion.
    pub tag: usize,
    /// File to read from.
    pub file: alloc::sync::Arc<dyn FsFile>,
    /// Byte offset within `file`.
    pub offset: u64,
    /// Destination, exactly as long as the read.
    pub buf: Vec<u8>,
}

/// A [`QueuedRead`] the queue is done with: its buffer, and whether every byte
/// of it arrived.
pub struct ReadDone {
    /// The tag the read was submitted with.
    pub tag: usize,
    /// The destination; the whole block when `result` is `Ok`.
    pub buf: Vec<u8>,
    /// `Ok` once every byte was read; a short read is
    /// [`io::ErrorKind::UnexpectedEof`].
    pub result: io::Result<()>,
}

/// Reads submitted one after another and handed back as they finish, so a
/// caller can issue a read that depends on a finished one while others are
/// still in flight. Obtained from [`Fs::read_queue`].
///
/// # Examples
///
/// ```
/// use lsm_tree::fs::{Fs, FsFile, FsOpenOptions, MemFs, QueuedRead};
/// use std::io::Write;
/// use std::path::Path;
/// use std::sync::Arc;
///
/// let fs = MemFs::new();
/// fs.create_dir_all(Path::new("/d"))?;
/// let path = Path::new("/d/f");
/// fs.open(path, &FsOpenOptions::new().write(true).create(true))?
///     .write_all(b"hello, world")?;
/// let file: Arc<dyn FsFile> = Arc::from(fs.open(path, &FsOpenOptions::new().read(true))?);
///
/// let mut queue = fs.read_queue();
/// queue.submit(QueuedRead { tag: 7, file, offset: 7, buf: vec![0; 5] });
/// let mut read = Vec::new();
/// queue.wait(1, &mut |done| read.push((done.tag, done.buf, done.result.is_ok())));
/// assert_eq!(read, [(7, b"world".to_vec(), true)]);
/// # Ok::<(), lsm_tree::io::Error>(())
/// ```
#[diagnostic::on_unimplemented(
    message = "`{Self}` is not a read queue",
    label = "this type does not implement `ReadQueue`",
    note = "`Fs::read_queue` provides one for every backend; implement `ReadQueue` only for a backend that can take reads while others are in flight"
)]
pub trait ReadQueue {
    /// Queues `read`. A backend may issue it at once or hold it until the
    /// next [`wait`](Self::wait); either way the reads submitted between two
    /// waits travel together.
    fn submit(&mut self, read: QueuedRead);

    /// Reads submitted and not yet handed back.
    fn outstanding(&self) -> usize;

    /// Reads among the [`outstanding`](Self::outstanding) ones that only a
    /// [`wait`](Self::wait) for at least one read carries out: none of them
    /// finishes on its own, so a caller does not sleep on a
    /// [`ReadWake`] for them. The default counts every outstanding read, as
    /// for a queue that reads only while it is waited on.
    fn held(&self) -> usize {
        self.outstanding()
    }

    /// Whether a [`wait`](Self::wait) for none issues the reads submitted
    /// since the last wait, rather than leave them for a wait for some. A
    /// wrapper that takes each read through checks of its own as it is issued
    /// passes the reads on at such a wait only when this is `true`.
    ///
    /// The default, `false`, matches a queue that reads only while it is
    /// waited on for at least one read. `io_uring` answers `true`.
    fn issues_at_wait_for_none(&self) -> bool {
        false
    }

    /// Hands back the reads the last [`wait`](Self::wait) for none was given
    /// and kept rather than issued (a ring with no room for them), in the
    /// order they were submitted: the queue no longer holds them. A wrapper
    /// that takes each read through checks of its own as it is issued takes
    /// these back and passes them on again at a later wait, the one that
    /// issues them.
    ///
    /// The default hands back none, as for a queue that issues at a wait for
    /// none every read it is given there.
    fn take_kept(&mut self) -> Vec<QueuedRead> {
        Vec::new()
    }

    /// Issues every read not yet issued, then hands reads to `on_done` as they
    /// finish, each once, until at least `min` have been handed over in this
    /// call or none is left outstanding. A read that has finished by then is
    /// handed over too, so `min = 0` collects what is ready without waiting.
    fn wait(&mut self, min: usize, on_done: &mut dyn FnMut(ReadDone));

    /// Asks the queue to call `wake` each time a read it issued finishes off
    /// the calling thread, after the read is ready for [`wait`](Self::wait)
    /// to hand over, so a caller reading through several queues can sleep
    /// until any of them has a read back. Returns whether it will, for every
    /// read it issues: a queue may decline once reads are in flight.
    ///
    /// The default declines: a queue that reads only while it is waited on
    /// has nothing finishing in between.
    fn set_wake(&mut self, wake: alloc::sync::Arc<dyn ReadWake>) -> bool {
        drop(wake);
        false
    }
}

/// Told by a [`ReadQueue`] that one of its reads is back: see
/// [`ReadQueue::set_wake`]. Called from whatever thread finished the read.
///
/// That thread can be a backend's I/O thread (the `io_uring` ring thread), so
/// an implementation returns promptly and does not panic: a blocking `wake`
/// stalls every read of the backend, and a panic on the ring thread aborts the
/// process.
#[diagnostic::on_unimplemented(
    message = "`{Self}` cannot be woken by a read queue",
    label = "this type does not implement `ReadWake`",
    note = "a caller waiting on several `ReadQueue`s implements `ReadWake` to learn that one of them has a read back"
)]
pub trait ReadWake: Send + Sync {
    /// A read is ready to be handed over.
    fn wake(&self);
}

/// The [`ReadQueue`] of a backend that cannot take reads while others are in
/// flight: the reads submitted since the last wait for at least one are read
/// in one [`Fs::read_blocks_batched_each`] call, which a backend overriding
/// it still batches.
struct BatchedReadQueue<'a, F: Fs + ?Sized> {
    fs: &'a F,
    submitted: Vec<QueuedRead>,
}

impl<F: Fs + ?Sized> ReadQueue for BatchedReadQueue<'_, F> {
    fn submit(&mut self, read: QueuedRead) {
        self.submitted.push(read);
    }

    fn outstanding(&self) -> usize {
        self.submitted.len()
    }

    fn wait(&mut self, min: usize, on_done: &mut dyn FnMut(ReadDone)) {
        // Nothing finishes between waits here, so a wait for none has
        // nothing to hand over, and reading would block the caller polling.
        if min == 0 || self.submitted.is_empty() {
            return;
        }
        let mut reads = core::mem::take(&mut self.submitted);
        let mut filled = alloc::vec![false; reads.len()];
        let outcome = {
            let mut reqs: Vec<BlockRead<'_>> = reads
                .iter_mut()
                .map(|read| BlockRead {
                    file: read.file.as_ref(),
                    offset: read.offset,
                    buf: BlockBuf::new(&mut read.buf[..]),
                })
                .collect();
            self.fs
                .read_blocks_batched_each(&mut reqs, &mut |index, _| {
                    if let Some(slot) = filled.get_mut(index) {
                        *slot = true;
                    }
                })
        };
        // A read not handed over failed: a failed call leaves the contents of
        // every buffer it did not hand over unspecified, even one it filled.
        // The first such read carries the call's error, the others its kind.
        // With no error, a read not handed over was reported read without
        // being filled.
        let (mut failure, kind, message) = match outcome {
            Ok(()) => (
                None,
                io::ErrorKind::UnexpectedEof,
                "read queue: a read reported done was left unfilled",
            ),
            Err(error) => {
                let kind = error.kind();
                (
                    Some(error),
                    kind,
                    "read queue: a read of a batch that failed",
                )
            }
        };
        for (read, filled) in reads.into_iter().zip(filled) {
            let result = if filled {
                Ok(())
            } else {
                Err(failure
                    .take()
                    .unwrap_or_else(|| io::Error::new(kind, message)))
            };
            on_done(ReadDone {
                tag: read.tag,
                buf: read.buf,
                result,
            });
        }
    }
}

/// Pluggable filesystem abstraction.
///
/// Intended to cover all filesystem operations that lsm-tree performs.
/// The default implementation [`StdFs`] delegates to [`std::fs`].
///
/// # Object safety
///
/// `Fs` is object-safe and can be used as `Arc<dyn Fs>` directly:
/// ```
/// # use lsm_tree::fs::{Fs, StdFs};
/// # use std::sync::Arc;
/// let _: Arc<dyn Fs> = Arc::new(StdFs);
/// ```
pub trait Fs: Send + Sync + 'static {
    /// Opens a file at `path` with the given options.
    ///
    /// Returns a boxed file handle. For syscall-backed implementations
    /// like [`StdFs`], the allocation and dynamic dispatch overhead is
    /// typically negligible compared to the underlying I/O operations.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the file cannot be opened.
    // Box<dyn FsFile> is intentionally 'static (the default) - file handles are
    // owned values that do not borrow from the Fs instance that created them.
    fn open(&self, path: &Path, opts: &FsOpenOptions) -> io::Result<Box<dyn FsFile>>;

    /// Reads several blocks, possibly from DIFFERENT files, in one batched
    /// operation. The default reads each serially via [`FsFile::read_at`];
    /// `io_uring` overrides it to submit every read across all the files to its
    /// one shared ring, so reads from many SSTs (and, on a multi-device layout,
    /// many devices) coalesce into one submission and overlap in flight, with
    /// the kernel fanning each read out to its file's underlying device.
    ///
    /// Fills each [`BlockBuf`] completely (block reads are fixed-size); a short
    /// read on any block is an error, leaving every buffer's contents
    /// unspecified. A destination that arrives partly filled is COMPLETED: it
    /// already owns the block's first `filled` bytes, so the read covers the
    /// unfilled suffix starting at `offset + filled` in the file.
    ///
    /// The destination is initialized memory whose fill count starts at zero,
    /// so an implementation that reports success without filling a request
    /// leaves that request short rather than making stale bytes look read: see
    /// [`BlockBuf`]. The caller rejects a short request, which is why this
    /// contract does not have to be trusted.
    ///
    /// # Errors
    ///
    /// Returns the first failing block's I/O error (a partial read of any block
    /// is reported as [`io::ErrorKind::UnexpectedEof`]).
    fn read_blocks_batched(&self, reqs: &mut [BlockRead<'_>]) -> io::Result<()> {
        for req in reqs.iter_mut() {
            // A destination that arrives partly filled already owns the
            // block's first `filled` bytes; the read owes the unfilled
            // suffix, which starts `filled` bytes into the block on disk.
            let offset = req
                .offset
                .checked_add(req.buf.filled() as u64)
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "read_blocks_batched: request offset overflows",
                    )
                })?;
            let dst = req.buf.unfilled_mut();
            let want = dst.len();
            let n = req.file.read_at(dst, offset)?;
            req.buf.advance(n);
            if n != want {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "read_blocks_batched: short read on a fixed-size block",
                ));
            }
        }
        Ok(())
    }

    /// [`read_blocks_batched`](Self::read_blocks_batched), handing each
    /// request to `on_read` with its index as soon as it has been filled, so
    /// the caller can work on a finished block while others are still being
    /// read.
    ///
    /// `on_read` sees only completely filled requests, each once, in the order
    /// they finish; when a request fails it is not called for it. Calls can
    /// arrive while the reads of other requests are still in flight, so the
    /// order is the implementation's: the default fills the whole batch first
    /// and then hands the requests over in index order; `io_uring` hands each
    /// over as its read completes.
    ///
    /// # Errors
    ///
    /// Returns the error of the lowest-indexed request whose read failed. A
    /// request handed to `on_read` has succeeded whatever the call returns.
    fn read_blocks_batched_each(
        &self,
        reqs: &mut [BlockRead<'_>],
        on_read: &mut dyn FnMut(usize, &BlockRead<'_>),
    ) -> io::Result<()> {
        self.read_blocks_batched(reqs)?;
        // An implementation can report success without filling a request (see
        // `BlockBuf`); such a request is not handed over, and the caller finds
        // it short.
        for (index, req) in reqs.iter().enumerate().filter(|(_, r)| r.buf.is_full()) {
            on_read(index, req);
        }
        Ok(())
    }

    /// A queue that takes reads one after another and hands each back when it
    /// finishes, so a read that depends on a finished one can be issued while
    /// others are still in flight: see [`ReadQueue`].
    ///
    /// The default queue reads what was submitted since the last wait in one
    /// [`read_blocks_batched_each`](Self::read_blocks_batched_each) call, so a
    /// backend that overrides only the batched read keeps its batching.
    /// `io_uring` issues each read to its ring as the queue is waited on and
    /// hands it back the moment it completes.
    fn read_queue(&self) -> Box<dyn ReadQueue + '_> {
        Box::new(BatchedReadQueue {
            fs: self,
            submitted: Vec::new(),
        })
    }

    /// Whether [`read_blocks_batched`](Self::read_blocks_batched),
    /// [`read_blocks_batched_each`](Self::read_blocks_batched_each) and
    /// [`read_queue`](Self::read_queue) read a file whose
    /// [`FsFile::backing_fd`] is `Some` through that descriptor, never calling
    /// its [`FsFile::read_at`]. A wrapper that observes reads at `read_at`
    /// (fault injection, accounting) has to observe these in the batch call
    /// instead.
    ///
    /// The default, `false`, matches the default batched read, which reads
    /// every request through `read_at`. `io_uring` answers `true`.
    ///
    /// A backend answering `true` validates every descriptor-backed request
    /// of a batch (its `offset` plus the bytes already filled fits a `u64`)
    /// before it issues any descriptor read: a wrapper screens the batch as
    /// a whole, and a batch it would refuse must read nothing.
    fn reads_by_descriptor(&self) -> bool {
        false
    }

    /// Refuses `reqs` as a backend that reads by descriptor refuses a batch
    /// whole, before it reads any of it: the error it would return for the
    /// first request it cannot take by descriptor, judged as that request
    /// stands now. A wrapper that takes each read through checks of its own
    /// asks this first, so no check is spent on a batch that reads nothing.
    ///
    /// The default refuses nothing. `io_uring` refuses an offset that
    /// overflows and a request longer than one read submits.
    ///
    /// # Errors
    ///
    /// Returns the error the batch would fail with.
    fn check_descriptor_batch(&self, reqs: &[BlockRead<'_>]) -> io::Result<()> {
        let _ = reqs;
        Ok(())
    }

    /// Recursively creates all directories leading to `path`.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if directory creation fails.
    fn create_dir_all(&self, path: &Path) -> io::Result<()>;

    /// Atomically creates a single directory at `path`.
    ///
    /// Unlike [`create_dir_all`](Self::create_dir_all), this method must
    /// FAIL with [`io::ErrorKind::AlreadyExists`] when `path` already
    /// exists - it is the POSIX `mkdir(2)` primitive used by
    /// [`AbstractTree::create_checkpoint`](crate::AbstractTree::create_checkpoint) to
    /// claim its target directory without a TOCTOU window.
    ///
    /// The parent directory must already exist; this method does not
    /// recurse.
    ///
    /// # Default implementation
    ///
    /// Returns [`io::ErrorKind::Unsupported`]. Backends that want to be
    /// usable as a checkpoint target MUST override this method.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::AlreadyExists`] if `path` already exists,
    /// [`io::ErrorKind::NotFound`] if the parent directory does not
    /// exist, or another I/O error if creation fails for backend-specific
    /// reasons.
    fn create_dir(&self, path: &Path) -> io::Result<()> {
        let _ = path;
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "Fs::create_dir is not implemented for this backend",
        ))
    }

    /// Returns all entries in a directory (order is unspecified).
    ///
    /// Returns a `Vec` rather than a streaming iterator because
    /// `read_dir` is a cold-path operation (recovery, compaction file
    /// listing) where directory sizes are expected to remain small.
    /// Callers that need a specific order must sort the result.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the directory cannot be read or if any
    /// individual entry fails.
    fn read_dir(&self, path: &Path) -> io::Result<Vec<FsDirEntry>>;

    /// Removes a single file.
    ///
    /// If the file does not exist, implementations must return
    /// [`io::ErrorKind::NotFound`]. Callers such as version GC rely on
    /// this to perform idempotent deletes.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the file cannot be removed.
    fn remove_file(&self, path: &Path) -> io::Result<()>;

    /// Recursively removes a directory and all of its contents.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the directory cannot be removed.
    fn remove_dir_all(&self, path: &Path) -> io::Result<()>;

    /// Removes an empty directory, and only an empty one: unlike
    /// [`Fs::remove_dir_all`] it never takes what someone else put there.
    ///
    /// # Errors
    ///
    /// Returns [`io::ErrorKind::NotFound`] if the directory does not exist,
    /// and an error if it holds anything or cannot be removed. The default
    /// returns [`io::ErrorKind::Unsupported`]: a backend without it keeps
    /// every directory.
    fn remove_dir(&self, path: &Path) -> io::Result<()> {
        let _ = path;
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "this backend cannot remove a single empty directory",
        ))
    }

    /// Whether `a` and `b` name the SAME physical file within this backend's
    /// namespace (aliases: symlinked spellings, `..` traversals, case folding).
    ///
    /// The default is literal path equality — correct for virtual backends
    /// ([`MemFs`]), whose distinct path strings are distinct files by
    /// construction; resolving them through the HOST filesystem would let a
    /// host symlink alias two unrelated virtual files. Kernel-backed backends
    /// ([`StdFs`]) override this with filesystem OBJECT identity (Unix
    /// device + inode) — canonical spellings alone miss bind-mount aliases,
    /// which keep their two mount-point spellings over one underlying file.
    ///
    /// # Errors
    ///
    /// A probe that cannot DECIDE (an identity stat failure on either side)
    /// must return the error rather than guessing: callers use `false` to
    /// authorize duplicate deletion, so a fabricated "distinct" verdict lets
    /// a transient fault delete the alias of a file the caller keeps —
    /// unlinking the very directory entry it retained.
    fn same_file(&self, a: &Path, b: &Path) -> io::Result<bool> {
        Ok(a == b)
    }

    /// The target named by `path` when `path` is itself a symbolic link, read
    /// without following it; `None` when `path` is anything else or does not
    /// exist. A relative target is returned as stored, relative to the
    /// directory holding `path`.
    ///
    /// The default answers `None`: a backend without symbolic links
    /// ([`MemFs`]) has nothing to report.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if `path` cannot be inspected.
    fn read_link(&self, path: &Path) -> io::Result<Option<PathBuf>> {
        let _ = path;
        Ok(None)
    }

    /// Makes `link` a symbolic link to `target`, stored as given: the inverse
    /// of [`read_link`](Self::read_link), for a backend that reports links.
    /// `to_dir` is the kind a platform that tells links to directories from
    /// links to files (Windows) records, as
    /// [`symlink_to_dir`](Self::symlink_to_dir) reports it; others ignore it.
    ///
    /// The default refuses with [`io::ErrorKind::Unsupported`]: a backend
    /// without symbolic links ([`MemFs`]) has none to make.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the link cannot be made.
    fn symlink(&self, target: &Path, link: &Path, to_dir: bool) -> io::Result<()> {
        let _ = (target, link, to_dir);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "this backend has no symbolic links",
        ))
    }

    /// Whether the symbolic link `path` was made as a link to a directory,
    /// the kind Windows records with the link whatever its target is now;
    /// `false` on a platform that records no kind.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if `path` cannot be inspected.
    fn symlink_to_dir(&self, path: &Path) -> io::Result<bool> {
        let _ = path;
        Ok(false)
    }

    /// Renames a file from `from` to `to`.
    ///
    /// If `to` already exists as a regular file, it is atomically replaced —
    /// on EVERY supported platform. `std::fs::rename` (the [`StdFs`] backend)
    /// honors this on Windows too via replace-existing semantics; only a
    /// destination DIRECTORY fails there, and a destination file that other
    /// handles hold open is still replaceable because the standard library
    /// opens files with full sharing (including delete). Every temp-then-rename
    /// publish in the crate (restriction sidecars, heal attestations, detached
    /// heal copies, salvaged blobs) relies on this contract; implementations
    /// must preserve it. This is required by
    /// [`rewrite_atomic`](crate::file::rewrite_atomic).
    ///
    /// lsm-tree only renames files (table files, sidecars), never
    /// directories. [`MemFs`] rejects directory renames with `InvalidInput`.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the rename fails.
    fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;

    /// Returns metadata for the file or directory at `path`.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if metadata cannot be retrieved.
    fn metadata(&self, path: &Path) -> io::Result<FsMetadata>;

    /// Ensures directory metadata is persisted to durable storage.
    ///
    /// On platforms that do not support directory fsync (e.g. Windows),
    /// this may be a no-op.
    ///
    /// Implementations must accept `.` (the current / implicit root
    /// directory): callers syncing the new entry of a bare relative file pass
    /// it, because an empty [`Path::parent`] is not a syncable name. A
    /// backend that admits a file creation must be able to sync the entry it
    /// created.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_directory(&self, path: &Path) -> io::Result<()>;

    /// Ensures directory metadata is persisted at the requested durability
    /// [`SyncMode`].
    ///
    /// The default implementation ignores `mode` and delegates to
    /// [`sync_directory`](Self::sync_directory); backends where the mode is
    /// observable (the std backend on macOS) override this.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the sync operation fails.
    fn sync_directory_with(&self, path: &Path, mode: SyncMode) -> io::Result<()> {
        let _ = mode;
        self.sync_directory(path)
    }

    /// Makes durable everything synced on the device holding `path` before
    /// the call, including what [`SyncMode::Barrier`] synced only in order.
    ///
    /// The default is a no-op, for a backend whose syncs already reach the
    /// medium; the std backend issues one `fcntl(F_FULLFSYNC)` on macOS.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if `path` cannot be opened or the flush fails.
    fn sync_device(&self, path: &Path) -> io::Result<()> {
        let _ = path;
        Ok(())
    }

    /// Returns `Ok(true)` if a file or directory exists at `path`.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the existence of `path` cannot be determined
    /// (for example, due to permission issues or transient backend failures).
    fn exists(&self, path: &Path) -> io::Result<bool>;

    /// Creates a hard link `dst` that refers to the same inode as `src`.
    ///
    /// Used by [`AbstractTree::create_checkpoint`](crate::AbstractTree::create_checkpoint)
    /// to snapshot SST and blob files in O(1) per file without duplicating
    /// data on disk. After the link is created, deleting either path leaves
    /// the other intact; the inode is reclaimed only after the last link
    /// is removed.
    ///
    /// # Cross-filesystem behaviour
    ///
    /// Hard links cannot span filesystems. `hard_link` is a PURE link: on a
    /// cross-device situation (Unix `EXDEV` / [`io::ErrorKind::CrossesDevices`])
    /// implementations surface the error rather than silently byte-copying.
    /// Callers that want a cross-filesystem copy use the checkpoint driver's
    /// `link_or_copy_cross_fs`, which detects the cross-device (and
    /// `Unsupported` / `NotFound`) error and performs a `SyncMode`-aware
    /// streamed copy. Keeping the copy in one place means the copied file's
    /// durability honors `Config::sync_mode` instead of an unconditional
    /// barrier hidden inside `hard_link`.
    ///
    /// In-memory backends ([`MemFs`]) have no inodes; they implement this
    /// as a byte copy that produces an independent file with the same
    /// contents (their "link" semantics).
    ///
    /// # Default implementation
    ///
    /// Returns [`io::ErrorKind::Unsupported`]. Backends are free to leave
    /// this default in place: the checkpoint driver's
    /// `link_or_copy_cross_fs` helper treats `Unsupported` (and `NotFound`)
    /// as a signal to fall back to a streamed byte copy, so snapshots
    /// still succeed - they just lose the O(1) hard-link optimisation
    /// and pay full-bytes worth of disk on the target volume. Backends
    /// that DO support real hard links (most kernel filesystems) should
    /// override this for the inode-sharing benefit.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if `src` does not exist, `dst` already exists,
    /// the destination's parent directory is missing, or `src` and `dst`
    /// are on different filesystems (cross-device - surfaced, not copied).
    fn hard_link(&self, src: &Path, dst: &Path) -> io::Result<()> {
        let _ = (src, dst);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "Fs::hard_link is not implemented for this backend",
        ))
    }

    /// Identifies the **path namespace** this backend resolves against.
    ///
    /// Two `Fs` values may safely participate in a cross-backend
    /// [`Fs::hard_link`] call only if their `backend_id()` values are
    /// both `Some` and equal: that contract states "we resolve paths
    /// against the same underlying inode table, so a hard link from
    /// `src` here to `dst` there links the SAME file we'd see by
    /// reading `src` through `Self`."
    ///
    /// Examples of equal backend IDs:
    /// - All [`crate::fs::StdFs`] instances on the same host (one
    ///   shared kernel filesystem).
    /// - An `IoUringFs` and a [`crate::fs::StdFs`] on the
    ///   same host (the uring backend delegates path resolution to the
    ///   kernel).
    ///
    /// Examples of distinct backend IDs:
    /// - Two independent [`crate::fs::MemFs`] instances (each has its
    ///   own in-memory tree).
    /// - A [`crate::fs::MemFs`] vs any kernel-backed backend (a
    ///   hard-link attempt would resolve `src` against the host
    ///   filesystem and silently capture an unrelated file if one
    ///   happens to exist at the same path - a checkpoint correctness
    ///   bug).
    ///
    /// The default returns `None`, meaning "no shared-namespace
    /// guarantee" - safe-by-default for third-party backends that have
    /// not opted in. Callers MUST treat `None` as a veto on
    /// cross-backend [`Fs::hard_link`] and stream-copy instead, even
    /// when both sides return `None`.
    fn backend_id(&self) -> Option<u64> {
        None
    }

    /// Identifies the **physical volume** (free-space pool) backing `path`.
    ///
    /// Distinct from [`backend_id`](Self::backend_id), which identifies the path
    /// *namespace* (inode table) and is therefore the SAME for every `StdFs`
    /// path on a host even across different mounts. This instead identifies the
    /// *mount / device* `path` lives on (Unix `st_dev`), so two paths can be
    /// compared for sharing one free-space pool.
    ///
    /// The storage-admission gate uses it to decide whether a routed SST
    /// destination and the blob folder land on independent volumes (budget each
    /// separately) or the same filesystem (budget their combined transient peak,
    /// or it can `ENOSPC`). `level_routes` maps levels to paths but does NOT
    /// prove a separate mount.
    ///
    /// Two paths with the same `Some(id)` share a volume; two with different
    /// `Some(id)` are provably independent. `None` means the backend cannot
    /// prove independence — callers MUST conservatively assume the paths share a
    /// volume (combine budgets), even when both sides return `None`.
    ///
    /// # Default implementation
    ///
    /// Returns `None` (independence unknown → callers combine).
    fn volume_id(&self, path: &Path) -> Option<u64> {
        let _ = path;
        None
    }

    /// Reports the [`FsCapabilities`] of the filesystem backing `path`.
    ///
    /// Capabilities are a property of the *mount* `path` lives on, not of the
    /// backend as a whole: one [`StdFs`] can serve a data directory on Btrfs and
    /// a WAL on ext4. Callers pass the directory whose mount they care about
    /// (typically the tree's data dir).
    ///
    /// The default is conservative - every capability `false`, i.e. "assume no
    /// special FS guarantees". A backend overrides this to opt into FS-aware
    /// optimizations (skip redundant checksums, disable `CoW` on SSTs, reflink
    /// checkpoints). Unknown / third-party backends keep the safe default.
    fn capabilities(&self, path: &Path) -> FsCapabilities {
        let _ = path;
        FsCapabilities::default()
    }

    /// Requests that per-file copy-on-write be disabled for the file at `path`.
    ///
    /// On `CoW` filesystems (Btrfs) write-once SST files gain no benefit from `CoW`
    /// and suffer a fragmentation penalty; clearing the per-file `CoW` flag
    /// (`FS_NOCOW_FL` via `FS_IOC_SETFLAGS`) recovers throughput. The flag only
    /// takes effect on a file with no data blocks yet, so callers invoke this
    /// immediately after creating the (empty) SST file and before writing.
    ///
    /// Path-based (rather than handle-based) so the trait stays object-safe and
    /// portable: backends with no fd concept ([`MemFs`], a future Windows
    /// backend) implement it as a no-op.
    ///
    /// # Default implementation
    ///
    /// No-op returning `Ok(())`. Backends on non-`CoW` filesystems, or that
    /// cannot express the request, correctly leave this default in place -
    /// disabling `CoW` is a throughput optimization, never a correctness
    /// requirement.
    ///
    /// # Errors
    ///
    /// Returns an I/O error only if the backend supports the operation and the
    /// underlying syscall fails for a reason other than "not applicable".
    fn try_disable_cow(&self, path: &Path) -> io::Result<()> {
        let _ = path;
        Ok(())
    }

    /// Deallocates `len` bytes starting at `offset` inside the file at `path`,
    /// freeing the physical blocks while leaving the file's logical length
    /// unchanged: the punched range reads back as zeros. `fallocate(fd,
    /// FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, ...)` on Linux,
    /// `fcntl(F_PUNCHHOLE)` on macOS/APFS.
    ///
    /// This is the in-place reclaim primitive for tight-space incremental
    /// compaction: as merged output becomes durable, the consumed input prefix
    /// is punched to return its extents to the filesystem without rewriting or
    /// truncating the input file (which concurrent readers may still hold).
    ///
    /// Callers MUST gate this on [`FsCapabilities::punch_hole`] for the mount
    /// (via [`capabilities`](Self::capabilities)); a backend that cannot punch
    /// returns [`io::ErrorKind::Unsupported`] from the default below.
    ///
    /// # Default implementation
    ///
    /// Returns [`io::ErrorKind::Unsupported`]. Only backends whose
    /// `capabilities().punch_hole` is true override it.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the backend does not support hole punching, or if
    /// the underlying syscall fails (e.g. the mount reports `EOPNOTSUPP`).
    fn punch_hole(&self, path: &Path, offset: u64, len: u64) -> io::Result<()> {
        let _ = (path, offset, len);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "punch_hole is not supported by this backend",
        ))
    }

    /// Clones the file at `src` to `dst` with O(1) reflink semantics when the
    /// backend supports it (`FICLONE` on Linux, `clonefile(2)` on macOS/APFS,
    /// `ReFS` block cloning on Windows).
    ///
    /// A reflinked clone shares data blocks copy-on-write but has an
    /// independent inode: later modifications to either path do not affect the
    /// other, and there is no max-links-per-inode constraint. This makes it a
    /// safer, cheaper alternative to [`hard_link`](Self::hard_link) for
    /// checkpoint / backup tooling.
    ///
    /// # Default implementation
    ///
    /// Falls back to a streamed byte copy through this backend's own
    /// [`open`](Self::open) - correct on every backend, just without the O(1)
    /// block-sharing benefit. `dst` is created with `create_new`, so the call
    /// fails if it already exists. Backends that support real reflink override
    /// this for the O(1) path.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if `src` cannot be read, `dst` already exists or
    /// cannot be created, or the clone / copy fails.
    fn reflink_file(&self, src: &Path, dst: &Path) -> io::Result<()> {
        copy_file_streamed(self, src, dst)
    }

    /// Returns the data blocks of the file at `path` to the filesystem,
    /// leaving a zero-length file in place.
    ///
    /// This is the synchronous half of obsolete-file reclaim: it frees the
    /// space immediately (so a `walkdir + sum(len)` footprint scan reflects the
    /// reclaim at once) and is O(1) — a metadata operation, not a data rewrite
    /// — while the directory-entry `unlink` can be deferred to a background
    /// deleter. Reclaim is split this way so a caller measuring disk usage
    /// right after a logical delete sees the drop without the foreground thread
    /// blocking on the unlink.
    ///
    /// # Default implementation
    ///
    /// Opens the file for writing and sets its length to zero. Portable across
    /// every backend. A backend MAY override with a filesystem-specific
    /// primitive when one is genuinely cheaper (none beats `set_len(0)` for the
    /// length-based footprint today; the hook exists so an FS that grows one —
    /// reported via [`Fs::capabilities`] — can plug it in without touching the
    /// call sites). [`MemFs`] truncates its in-memory buffer.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the file cannot be opened or truncated.
    fn truncate_file(&self, path: &Path) -> io::Result<()> {
        self.open(path, &FsOpenOptions::new().write(true))?
            .set_len(0)
    }

    /// The counters what is written through this backend is counted into,
    /// when it counts (see [`CountingFs`]): a tree records there the bytes of
    /// the files it installs on this backend.
    ///
    /// # Default implementation
    ///
    /// `None`: a backend that counts nothing. A backend wrapping another
    /// returns the inner one's, so a counting backend under it is still
    /// found.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsm_tree::fs::{CountingFs, Fs, MemFs};
    /// use std::sync::Arc;
    ///
    /// assert!(MemFs::new().write_io_stats().is_none());
    /// let counted = CountingFs::new(Arc::new(MemFs::new()));
    /// assert!(counted.write_io_stats().is_some());
    /// ```
    fn write_io_stats(&self) -> Option<&alloc::sync::Arc<WriteIoStats>> {
        None
    }

    /// The write budget of the medium this backend writes to, when one is set
    /// (see [`CountingFs::with_budget`]): a compaction writing its output
    /// here reserves the bytes it expects from it before it runs.
    ///
    /// # Default implementation
    ///
    /// `None`: no budget. A backend wrapping another returns the inner one's.
    ///
    /// # Examples
    ///
    /// ```
    /// use lsm_tree::fs::{CountingFs, Fs, MemFs, WriteIoStats};
    /// use lsm_tree::write_budget::{Allowance, WriteBudget};
    /// use std::sync::Arc;
    /// use std::time::Duration;
    ///
    /// let budget = Arc::new(WriteBudget::new(
    ///     Arc::new(WriteIoStats::default()),
    ///     Allowance::new(8 << 30, Duration::from_secs(86_400)),
    /// ));
    /// let medium = CountingFs::with_budget(Arc::new(MemFs::new()), Arc::clone(&budget));
    /// assert!(medium.write_budget().is_some_and(|b| Arc::ptr_eq(b, &budget)));
    /// // It counts into the budget's ledger.
    /// assert!(medium.write_io_stats().is_some_and(|s| Arc::ptr_eq(s, budget.ledger())));
    /// ```
    fn write_budget(&self) -> Option<&alloc::sync::Arc<crate::write_budget::WriteBudget>> {
        None
    }

    /// Number of hard links to the file at `path` (the inode's link count).
    ///
    /// Used to keep [`Self::truncate_file`] safe: truncation frees the inode's
    /// blocks for **every** hard link, so a file a checkpoint has linked (via
    /// [`Self::hard_link`]) must not be truncated — only unlinked. A caller
    /// truncates only when this returns `Ok(1)` (it owns the sole link).
    ///
    /// # Default implementation
    ///
    /// Returns an `Unsupported` error so a backend that cannot report link
    /// counts makes callers conservatively skip truncation (correctness over
    /// the reclaim optimization). [`StdFs`] overrides it on Unix via `nlink`.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the count cannot be determined (including the
    /// `Unsupported` default).
    fn hard_link_count(&self, path: &Path) -> io::Result<u64> {
        let _ = path;
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "hard_link_count is not supported by this backend",
        ))
    }

    /// Best-effort free space, in bytes, on the filesystem backing `path`.
    ///
    /// Reports bytes available to an unprivileged process (Unix `statvfs`
    /// `f_bavail * f_frsize`), which the storage-admission gate uses to defend
    /// against the *physical* disk filling, alongside any configured byte
    /// quota. Best-effort by nature: the disk is shared with other processes,
    /// so the figure is a reservation hint, not a guarantee — the atomic
    /// single-transaction commit model still prevents corruption if a physical
    /// `ENOSPC` slips through. Callers should sample it (e.g. at flush /
    /// compaction boundaries) and cache it, never probe per write.
    ///
    /// # Default implementation
    ///
    /// Returns `u64::MAX` ("treat as unbounded"), so a backend that cannot
    /// report free space never drives the tree read-only on a phantom
    /// disk-pressure signal. Real backends override it.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the underlying probe fails on a backend that
    /// supports it.
    fn available_space(&self, path: &Path) -> io::Result<u64> {
        let _ = path;
        Ok(u64::MAX)
    }

    /// Physically ALLOCATED bytes of the file at `path` (blocks actually backed
    /// by storage), or `None` when the backend cannot report it.
    ///
    /// Differs from the file's logical length ([`FsMetadata::len`]) when the
    /// file is SPARSE: a hole-punched range (via [`punch_hole`](Self::punch_hole))
    /// frees physical blocks while the logical length is unchanged, so
    /// `allocated_size < len`. Manifest repair uses this to recognize a
    /// tight-space-punched SST (whose consumed prefix data blocks were reclaimed)
    /// that a rebuilt manifest would otherwise open as an unrestricted table,
    /// letting reads traverse the punched (zero-reading) blocks and fail.
    ///
    /// # Default implementation
    ///
    /// Returns `Ok(None)` ("cannot tell"): a backend that does not track physical
    /// allocation (and thus never punches) reports nothing, and repair treats the
    /// file as unpunched — its current behaviour. Backends that support hole
    /// punching override it.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the underlying probe fails on a backend that
    /// supports it.
    fn allocated_size(&self, path: &Path) -> io::Result<Option<u64>> {
        let _ = path;
        Ok(None)
    }

    /// Whether `[offset, offset + len)` of `path` is entirely a HOLE — an
    /// unallocated range that reads back as zeros.
    ///
    /// This is the extent-local counterpart to [`allocated_size`](Self::allocated_size),
    /// and the only one of the two that can attribute a hole to a specific
    /// range. A file-wide allocation total says nothing about WHERE the missing
    /// bytes are, and it is not even proof of a hole: a filesystem with
    /// transparent compression reports an ordinary, fully-written file as using
    /// fewer physical bytes than its length. Manifest repair uses this to tell a
    /// reclaimed (punched) data block from one destroyed by corruption — both
    /// read as zeros, and only the first may be skipped.
    ///
    /// # Default implementation
    ///
    /// Returns `Ok(None)` ("cannot tell"). A backend that cannot answer leaves
    /// the hole unproven, and a caller that needs the proof must treat the zeros
    /// as content. Backends that support hole punching override it.
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the underlying probe fails on a backend that
    /// supports it.
    fn extent_is_hole(&self, path: &Path, offset: u64, len: u64) -> io::Result<Option<bool>> {
        let _ = (path, offset, len);
        Ok(None)
    }

    /// Whether `[offset, offset + len)` CONTAINS a filesystem hole —
    /// `Some(true)` if any part of the range is unallocated, `Some(false)` if
    /// the whole range is backed by allocated blocks, `None` if the backend
    /// cannot tell.
    ///
    /// The companion of [`extent_is_hole`](Self::extent_is_hole) for punches
    /// whose extents are NOT filesystem-block-aligned: `punch_hole` on such a
    /// range deallocates only the wholly-contained blocks and zero-fills the
    /// edges, so the punched range is a hole in its interior while its
    /// boundary pages stay allocated — an `extent_is_hole` over the full range
    /// answers `false` there. Manifest repair probes a zeroed run with this to
    /// prove the run was reclaimed rather than destroyed; the implicit
    /// all-files-end-in-a-hole EOF state must NOT count as a contained hole.
    ///
    /// # Default implementation
    ///
    /// Returns `Ok(None)` ("cannot tell"), leaving the punch unproven exactly
    /// like the default [`extent_is_hole`](Self::extent_is_hole).
    ///
    /// # Errors
    ///
    /// Returns an I/O error if the underlying probe fails on a backend that
    /// supports it.
    fn extent_contains_hole(&self, path: &Path, offset: u64, len: u64) -> io::Result<Option<bool>> {
        let _ = (path, offset, len);
        Ok(None)
    }
}

/// Bytes available to an unprivileged process on the filesystem backing
/// `path`, via POSIX `statvfs(3)`: `f_bavail * f_frsize`.
///
/// `f_bavail` (blocks free to non-root) is used rather than `f_bfree` (total
/// free, including the root reserve) so the figure matches what a normal write
/// can actually consume. Shared by the std and `io_uring` (libc) backends; the
/// raw `io_uring` backend uses a direct `statfs` syscall instead (no libc).
#[cfg(all(unix, feature = "std"))]
#[allow(
    clippy::unnecessary_cast,
    clippy::cast_lossless,
    reason = "statvfs field widths vary by platform (e.g. fsblkcnt_t is u32 on \
              macOS, u64 on Linux); `as u64` is the portable widening that is a \
              no-op where the field is already u64"
)]
pub(crate) fn statvfs_available_space(path: &Path) -> std::io::Result<u64> {
    use core::mem::MaybeUninit;
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;

    let c = CString::new(path.as_os_str().as_bytes()).map_err(|_| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "path contains an interior NUL byte",
        )
    })?;
    let mut buf = MaybeUninit::<libc::statvfs>::uninit();
    // SAFETY: `c` is a valid NUL-terminated C string; on success (rc == 0)
    // the kernel fully initializes the `statvfs` buffer.
    #[expect(unsafe_code, reason = "statvfs FFI to read filesystem free space")]
    let rc = unsafe { libc::statvfs(c.as_ptr(), buf.as_mut_ptr()) };
    if rc != 0 {
        return Err(std::io::Error::last_os_error());
    }
    // SAFETY: statvfs returned 0, so `buf` is initialized.
    #[expect(unsafe_code, reason = "read initialized statvfs fields")]
    let st = unsafe { buf.assume_init() };
    // Saturate the product so an implausible value can never wrap.
    let frsize = st.f_frsize as u64;
    let bavail = st.f_bavail as u64;
    Ok(bavail.saturating_mul(frsize))
}

/// The [`Fs::backend_id`] of every backend that resolves paths against the host
/// kernel's file system table: `StdFs` and the `io_uring` backends. Two such
/// backends can hard-link across instances because both resolve their paths
/// through the same kernel namespace.
#[cfg(any(feature = "std", all(target_os = "linux", feature = "io-uring-raw")))]
pub(crate) const KERNEL_BACKEND_ID: u64 = 0x4b45_524e_454c_5f46; // "KERNEL_F"

/// The capabilities of a Linux file system by its `statfs(2)` `f_type` magic,
/// shared by every backend that reads it. Btrfs / ZFS get the full profile;
/// XFS gets copy-on-write plus reflink (reflink is only present on
/// `reflink=1` volumes, which a clone handles by falling back to a copy).
/// `fallocate(PUNCH_HOLE)` is supported by every common local file system
/// (ext4 / xfs / btrfs / zfs / tmpfs); unknown and network mounts get the
/// conservative default, so a runtime `EOPNOTSUPP` never surprises the
/// tight-space compaction gate.
///
/// Built where a backend reads `f_type`: 64-bit `StdFs`, and the raw backend
/// on the targets whose `statfs` layout it declares.
#[cfg(all(
    target_os = "linux",
    any(
        all(feature = "std", target_pointer_width = "64"),
        all(
            feature = "io-uring-raw",
            any(target_arch = "x86_64", target_arch = "aarch64")
        )
    )
))]
pub(crate) fn linux_fs_type_capabilities(f_type: i64) -> FsCapabilities {
    // statfs f_type magic numbers (stable kernel ABI, arch-independent).
    const BTRFS: i64 = 0x9123_683E;
    const ZFS: i64 = 0x2FC1_2FC1;
    const XFS: i64 = 0x5846_5342;
    const EXT_FAMILY: i64 = 0x0000_EF53; // ext2/3/4 share this magic
    const TMPFS: i64 = 0x0102_1994;

    match f_type {
        BTRFS | ZFS => FsCapabilities {
            per_block_integrity_on_read: true,
            background_scrub: true,
            copy_on_write: true,
            reflink: true,
            native_snapshot: true,
            punch_hole: true,
            ..FsCapabilities::default()
        },
        XFS => FsCapabilities {
            copy_on_write: true,
            reflink: true,
            punch_hole: true,
            ..FsCapabilities::default()
        },
        EXT_FAMILY | TMPFS => FsCapabilities {
            punch_hole: true,
            ..FsCapabilities::default()
        },
        _ => FsCapabilities::default(),
    }
}

/// The device id (`st_dev`) of the mount backing `path`, the
/// [`Fs::volume_id`] basis for the std and `io_uring` (libc) backends. Two
/// paths on the same mount share `st_dev` (one free-space pool); different
/// mounts have different `st_dev`. `None` if `path` cannot be stat-ed (e.g. it
/// does not exist yet) — independence is then unproven and callers combine.
#[cfg(all(unix, feature = "std"))]
pub(crate) fn unix_volume_id(path: &Path) -> Option<u64> {
    use std::os::unix::fs::MetadataExt;
    std::fs::metadata(path).ok().map(|m| m.dev())
}

/// Physically allocated bytes of `path` via `stat(2)`'s `st_blocks`
/// (`blocks * 512`, the POSIX-fixed block unit — unrelated to the filesystem's
/// I/O block size). Less than the logical length for a sparse / hole-punched
/// file. Shared by the std and `io_uring` (libc) backends.
///
/// A stat FAILURE is PROPAGATED as `Err`, never mapped to `None`: manifest
/// repair reads `Ok(None)` as "allocation-unaware backend" and hence "unpunched",
/// so swallowing the error on a genuinely punched file would drop its restriction
/// and expose the zeroed prefix. Every unix file has `st_blocks`, so a successful
/// stat always yields `Ok(Some(_))`.
#[cfg(all(unix, feature = "std"))]
pub(crate) fn unix_allocated_size(path: &Path) -> std::io::Result<Option<u64>> {
    use std::os::unix::fs::MetadataExt;
    // `st_blocks` is always in 512-byte units per POSIX, regardless of the
    // filesystem block size; multiply to bytes. `blocks()` is u64.
    Ok(Some(std::fs::metadata(path)?.blocks() * 512))
}

/// Streamed independent copy of `src` to `dst` through `fs`'s own [`Fs::open`].
///
/// The fallback for [`Fs::reflink_file`] on backends without O(1) reflink, and
/// the slow path a real reflink takes when the FS declines the clone (non-CoW
/// mount, cross-device). `dst` is created with `create_new`, so an existing
/// target is an error rather than a silent overwrite. The copy is fsynced so a
/// clone is durable on return.
pub(crate) fn copy_file_streamed<F: Fs + ?Sized>(fs: &F, src: &Path, dst: &Path) -> io::Result<()> {
    let mut src_file = fs.open(src, &FsOpenOptions::new().read(true))?;
    let mut dst_file = fs.open(dst, &FsOpenOptions::new().write(true).create_new(true))?;
    // Heap buffer (not a 64 KiB stack array) - keeps the cold-path clone off
    // the stack and satisfies the large-stack-array lint.
    let mut buf = vec![0u8; 64 * 1024].into_boxed_slice();

    // Run the copy in a closure so any failure leaves the original error AND
    // lets us best-effort remove the partial `dst` before propagating —
    // otherwise a mid-copy ENOSPC/EIO leaves a partial file and a retry trips
    // `create_new`'s AlreadyExists for an unrelated reason. Reads retry on
    // EINTR so a signal during the copy doesn't spuriously fail it. Mirrors
    // `checkpoint::link_or_copy_cross_fs`'s streamed-copy contract.
    let result: io::Result<()> = (|| {
        loop {
            let n = match src_file.read(&mut buf) {
                Ok(0) => break,
                Ok(n) => n,
                #[cfg(feature = "std")]
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                #[cfg(not(feature = "std"))]
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e.into()),
            };
            let chunk = buf.get(..n).ok_or_else(|| {
                io::Error::other("read returned more bytes than the buffer holds")
            })?;
            dst_file.write_all(chunk)?;
        }
        dst_file.sync_all()?;
        Ok(())
    })();

    if let Err(e) = result {
        drop(dst_file);
        let _ = fs.remove_file(dst);
        return Err(e);
    }
    Ok(())
}

#[cfg(test)]
mod block_buf_tests;

#[cfg(test)]
mod read_queue_tests;

#[cfg(all(
    test,
    target_os = "linux",
    any(
        all(feature = "std", target_pointer_width = "64"),
        all(
            feature = "io-uring-raw",
            any(target_arch = "x86_64", target_arch = "aarch64")
        )
    )
))]
mod fs_type_tests;