armdb 0.2.0

sharded bitcask key-value storage optimized for NVMe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
use std::mem::size_of;
use std::ops::Bound;
use std::sync::Arc;

use crate::Key;

use crate::byte_view::ByteView;
use crate::cache::{BlockCache, BlockKey};
use crate::compaction::{CompactionIndex, compact_shard};
use crate::config::Config;
use crate::disk_loc::DiskLoc;
use crate::engine::Engine;
use crate::error::{DbError, DbResult};
use crate::hook::{NoHook, WriteHook};
use crate::io::aligned_buf::AlignedBuf;
use crate::recovery::recover_var_tree;
use crate::shard::ShardInner;
use crate::skiplist::node::{SkipNode, VarNode, random_height};
use crate::skiplist::{InsertResult, SkipList};
use crate::sync::MutexGuard;

const MAX_STALE_RETRIES: usize = 3;

/// A tree with fixed-size keys and variable-length values.
/// Values are stored as `ByteView` (inline ≤20 bytes, heap with ref counting for larger).
/// Disk reads are cached at 4096-byte block granularity via `BlockCache`.
///
/// Each `VarTree` owns its storage engine — one tree = one database directory.
///
/// # Usage
///
/// ```ignore
/// let tree = VarTree::<16>::open("data/messages", Config::default())?;
/// tree.put(&key, b"hello world")?;
/// tree.close()?;
/// ```
///
/// # Iteration
///
/// `iter()`, `range()`, and `prefix_iter()` all return [`VarIter`] which
/// implements `Iterator + DoubleEndedIterator` with `Item = (K, ByteView)`.
/// Each `next()` / `next_back()` may perform disk I/O on a block-cache miss.
///
/// ```ignore
/// let latest = tree.prefix_iter(&group_id).take(50).collect::<Vec<_>>();
/// let oldest = tree.prefix_iter(&group_id).rev().take(10);  // DoubleEndedIterator
/// ```
pub struct VarTree<K: Key, H: WriteHook<K> = NoHook> {
    index: SkipList<VarNode<K>>,
    engine: Engine,
    cache: BlockCache,
    compaction_threshold: f64,
    shard_prefix_bits: usize,
    reversed: bool,
    hook: H,
}

impl<K: Key> VarTree<K> {
    /// Open or create a `VarTree` at the given path.
    /// Recovers the index from existing data files on disk.
    pub fn open(path: impl AsRef<std::path::Path>, config: Config) -> DbResult<Self> {
        Self::open_inner(path, config, NoHook)
    }
}

impl<K: Key, H: WriteHook<K>> VarTree<K, H> {
    /// Open or create a `VarTree` with a write hook for secondary index maintenance.
    pub fn open_hooked(
        path: impl AsRef<std::path::Path>,
        config: Config,
        hook: H,
    ) -> DbResult<Self> {
        Self::open_inner(path, config, hook)
    }

    fn open_inner(path: impl AsRef<std::path::Path>, config: Config, hook: H) -> DbResult<Self> {
        let compaction_threshold = config.compaction_threshold;
        let shard_prefix_bits = config.shard_prefix_bits;
        let reversed = config.reversed;
        let cache = BlockCache::new(&config.cache);
        let engine = Engine::open(path, config)?;

        let tree = Self {
            index: SkipList::new(reversed),
            engine,
            cache,
            compaction_threshold,
            shard_prefix_bits,
            reversed,
            hook,
        };

        // Recover index from disk
        let shard_dirs = tree.engine.shard_dirs();
        let shard_dir_refs = Engine::shard_dir_refs(&shard_dirs);
        let shard_ids = tree.engine.shard_ids();

        let hints = tree.engine.hints();
        let outcome = recover_var_tree::<K>(
            &shard_dir_refs,
            &shard_ids,
            tree.index(),
            hints,
            #[cfg(feature = "encryption")]
            tree.engine.cipher(),
        )?;
        for tail in &outcome.active_tails {
            tree.engine.shards()[tail.shard_idx].apply_recovery_tail(tail)?;
        }
        for (shard_idx, dead) in outcome.shard_dead_bytes {
            tree.engine.shards()[shard_idx].install_dead_bytes(dead);
        }
        let max_gsn = outcome.max_gsn;

        tree.engine
            .gsn()
            .fetch_max(max_gsn + 1, std::sync::atomic::Ordering::Relaxed);
        if hints {
            for shard in tree.engine.shards().iter() {
                shard.set_key_len(size_of::<K>());
            }
        }
        tracing::info!(
            key_size = size_of::<K>(),
            entries = tree.len(),
            "var_tree recovered"
        );

        Ok(tree)
    }

    /// Graceful shutdown: write hint files (if enabled), flush write buffers + fsync.
    pub fn close(self) -> DbResult<()> {
        if self.engine.hints() {
            self.sync_hints()?;
        }
        self.engine.flush()
    }

    /// Flush all shard write buffers to disk (without fsync).
    pub fn flush_buffers(&self) -> DbResult<()> {
        self.engine.flush_buffers()
    }

    /// Get the database configuration.
    pub fn config(&self) -> &Config {
        self.engine.config()
    }
}

impl<K: Key, H: WriteHook<K>> CompactionIndex<K> for VarTree<K, H> {
    fn update_if_match(&self, key: &K, old_loc: DiskLoc, new_loc: DiskLoc) -> bool {
        let guard = self.index.collector().enter();
        if let Some(node) = self.index.get(key.as_bytes(), &guard) {
            let current_ptr = node.load_disk_ptr();
            let current_disk = unsafe { *current_ptr };
            if current_disk == old_loc {
                let new_disk_ptr = Box::into_raw(Box::new(new_loc));
                match node.compare_exchange_disk(current_ptr, new_disk_ptr) {
                    Ok(old_ptr) => {
                        unsafe {
                            self.index
                                .collector()
                                .retire(old_ptr, seize::reclaim::boxed::<DiskLoc>);
                        }
                        return true;
                    }
                    Err(_) => {
                        // Concurrent put changed the DiskLoc — entry is no longer
                        // at old_loc, treat as dead in the compacted file.
                        unsafe {
                            drop(Box::from_raw(new_disk_ptr));
                        }
                        return false;
                    }
                }
            }
        }
        false
    }

    fn invalidate_blocks(&self, shard_id: u8, file_id: u32, total_bytes: u64) {
        self.cache.invalidate_file(shard_id, file_id, total_bytes);
    }

    fn contains_key(&self, key: &K) -> bool {
        self.contains(key)
    }
}

impl<K: Key, H: WriteHook<K>> VarTree<K, H> {
    /// Trigger a background compaction pass across all shards.
    pub fn compact(&self) -> DbResult<usize> {
        let mut total_compacted = 0;
        for shard in self.engine.shards().iter() {
            total_compacted += compact_shard(shard, self, self.compaction_threshold)?;
        }
        Ok(total_compacted)
    }

    /// Get a value by key. Checks block cache first, then reads from disk.
    pub fn get(&self, key: &K) -> Option<ByteView> {
        metrics::counter!("armdb.ops", "op" => "get", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.get");
        let guard = self.index.collector().enter();
        let node = match self.index.get(key.as_bytes(), &guard) {
            Some(n) => n,
            None => {
                #[cfg(feature = "hot-path-tracing")]
                tracing::error!(
                    "VarTree get error: index.get returned None for key {:?}",
                    key.as_bytes()
                );
                return None;
            }
        };
        self.read_value_cached(node, &guard)
    }

    /// Get a value by key, returning `Err(KeyNotFound)` if absent.
    pub fn get_or_err(&self, key: &K) -> DbResult<ByteView> {
        self.get(key).ok_or(DbError::KeyNotFound)
    }

    /// Insert or update a key-value pair.
    pub fn put(&self, key: &K, value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "put", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.put");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let guard = self.index.collector().enter();
        let old_value = if H::NEEDS_OLD_VALUE {
            if let Some(node) = self.index.get(key.as_bytes(), &guard) {
                let disk = *node.load_disk();
                Some(self.read_value_locked_result(&disk, &inner)?)
            } else {
                None
            }
        } else {
            None
        };
        self.put_locked(shard_id, &mut inner, &guard, key, value)?;
        drop(inner);
        self.hook.on_write(key, old_value.as_deref(), Some(value));
        Ok(())
    }

    /// Insert a key-value pair only if the key does not exist.
    /// Returns `Err(KeyExists)` if the key is already present.
    pub fn insert(&self, key: &K, value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "insert", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.insert");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let guard = self.index.collector().enter();
        self.insert_locked(shard_id, &mut inner, &guard, key, value)?;
        drop(inner);
        self.hook.on_write(key, None, Some(value));
        Ok(())
    }

    /// Delete a key. Returns `true` if the key existed.
    pub fn delete(&self, key: &K) -> DbResult<bool> {
        metrics::counter!("armdb.ops", "op" => "delete", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.delete");
        let shard_id = self.shard_for(key);
        let mut inner = self.engine.shards()[shard_id].lock();
        let guard = self.index.collector().enter();
        let old_value = if H::NEEDS_OLD_VALUE {
            if let Some(node) = self.index.get(key.as_bytes(), &guard) {
                let disk = *node.load_disk();
                Some(self.read_value_locked_result(&disk, &inner)?)
            } else {
                None
            }
        } else {
            None
        };
        let existed = self.delete_locked(shard_id, &mut inner, &guard, key)?;
        drop(inner);
        if existed {
            self.hook.on_write(key, old_value.as_deref(), None);
        }
        Ok(existed)
    }

    /// Atomically execute multiple operations on a single shard.
    /// All keys must route to the same shard as `shard_key`.
    /// The closure must be short — shard lock is held for its duration.
    pub fn atomic<R>(
        &self,
        shard_key: &K,
        f: impl FnOnce(&mut VarShard<'_, K, H>) -> DbResult<R>,
    ) -> DbResult<R> {
        let shard_id = self.shard_for(shard_key);
        let inner = self.engine.shards()[shard_id].lock();
        let guard = self.index.collector().enter();
        let mut shard = VarShard {
            tree: self,
            inner,
            shard_id,
            guard,
        };
        f(&mut shard)
    }

    fn put_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        guard: &seize::LocalGuard<'_>,
        key: &K,
        value: &[u8],
    ) -> DbResult<()> {
        let (disk_loc, _gsn) = inner.append_entry(shard_id as u8, key.as_bytes(), value, false)?;

        // Fast path: key exists — atomic swap, no write_lock, no node allocation
        if let Some(existing) = self.index.get(key.as_bytes(), guard) {
            let new_disk = Box::into_raw(Box::new(disk_loc));
            let old_disk_ptr = existing.swap_disk(new_disk);
            let old_disk = unsafe { *old_disk_ptr };
            inner.add_dead_bytes(
                old_disk.file_id,
                crate::entry::entry_size(size_of::<K>(), old_disk.len),
            );
            unsafe {
                self.index
                    .collector()
                    .retire(old_disk_ptr, seize::reclaim::boxed::<DiskLoc>);
            }
            return Ok(());
        }

        // Slow path: new key — allocate node + take write_lock via insert
        let height = random_height();
        let node_ptr = VarNode::alloc(*key, disk_loc, height);

        match self.index.insert(node_ptr, guard) {
            InsertResult::Inserted => {}
            InsertResult::Exists(existing) => {
                // Race: another shard inserted same key between get and insert
                let new_disk = Box::into_raw(Box::new(disk_loc));
                let old_disk_ptr = existing.swap_disk(new_disk);
                let old_disk = unsafe { *old_disk_ptr };
                inner.add_dead_bytes(
                    old_disk.file_id,
                    crate::entry::entry_size(size_of::<K>(), old_disk.len),
                );
                unsafe {
                    self.index
                        .collector()
                        .retire(old_disk_ptr, seize::reclaim::boxed::<DiskLoc>);
                }
                unsafe {
                    (*node_ptr)
                        .disk
                        .store(std::ptr::null_mut(), std::sync::atomic::Ordering::Relaxed);
                    VarNode::<K>::dealloc_node(node_ptr);
                }
            }
        }

        Ok(())
    }

    fn insert_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        guard: &seize::LocalGuard<'_>,
        key: &K,
        value: &[u8],
    ) -> DbResult<()> {
        if self.index.get(key.as_bytes(), guard).is_some() {
            return Err(DbError::KeyExists);
        }

        let (disk_loc, _gsn) = inner.append_entry(shard_id as u8, key.as_bytes(), value, false)?;
        let height = random_height();
        let node_ptr = VarNode::alloc(*key, disk_loc, height);

        match self.index.insert(node_ptr, guard) {
            InsertResult::Inserted => Ok(()),
            InsertResult::Exists(_existing) => {
                // Race: another path inserted this key after our `get` check and
                // before `index.insert`. Account for the entry we already appended
                // as dead bytes, free the unpublished node, and report KeyExists.
                inner.add_dead_bytes(
                    disk_loc.file_id,
                    crate::entry::entry_size(size_of::<K>(), disk_loc.len),
                );
                // SAFETY: node_ptr was just allocated by VarNode::alloc and has
                // not been published into the SkipList. It uniquely owns its
                // freshly-allocated DiskLoc box.
                unsafe { VarNode::<K>::dealloc_node(node_ptr) };
                Err(DbError::KeyExists)
            }
        }
    }

    fn delete_locked(
        &self,
        shard_id: usize,
        inner: &mut ShardInner,
        guard: &seize::LocalGuard<'_>,
        key: &K,
    ) -> DbResult<bool> {
        if self.index.get(key.as_bytes(), guard).is_none() {
            return Ok(false);
        }

        inner.append_entry(shard_id as u8, key.as_bytes(), &[], true)?;

        let removed = self.index.remove(key.as_bytes(), guard);

        if let Some(node_ptr) = removed {
            let disk = *unsafe { &*node_ptr }.load_disk();
            inner.add_dead_bytes(
                disk.file_id,
                crate::entry::entry_size(size_of::<K>(), disk.len),
            );
        }

        Ok(removed.is_some())
    }

    /// Check if a key exists.
    pub fn contains(&self, key: &K) -> bool {
        let guard = self.index.collector().enter();
        self.index.get(key.as_bytes(), &guard).is_some()
    }

    /// Encoded value byte length for `key`, or `None` if absent.
    /// Reads only the in-memory index entry (`DiskLoc::len`); no disk I/O.
    pub fn entry_len(&self, key: &K) -> Option<u32> {
        let guard = self.index.collector().enter();
        self.index
            .get(key.as_bytes(), &guard)
            .map(|node| node.load_disk().len)
    }

    /// Return the first entry in index order, or `None` if empty.
    /// With `reversed=true` (default): the entry with the largest key.
    /// O(1) index lookup. May perform disk I/O on block-cache miss.
    pub fn first(&self) -> Option<(K, ByteView)> {
        let guard = self.index.collector().enter();
        let mut ptr = crate::skiplist::strip_mark(unsafe {
            (*self.index.head_ptr())
                .tower(0)
                .load(std::sync::atomic::Ordering::Acquire)
        });
        while !ptr.is_null() {
            let node = unsafe { &*ptr };
            if !node.is_marked() {
                return self.read_value_cached(node, &guard).map(|v| (node.key, v));
            }
            ptr = crate::skiplist::strip_mark(
                node.tower(0).load(std::sync::atomic::Ordering::Acquire),
            );
        }
        None
    }

    /// Return the last entry in index order, or `None` if empty.
    /// With `reversed=true` (default): the entry with the smallest key.
    /// May perform disk I/O on block-cache miss.
    pub fn last(&self) -> Option<(K, ByteView)> {
        self.iter().next_back()
    }

    // -- Range helpers (front/back pointer positioning) -------------------------

    fn resolve_front(&self, bound: &Bound<&K>, guard: &seize::LocalGuard<'_>) -> *mut VarNode<K> {
        match bound {
            Bound::Included(k) => self.index.find_first_ge(k.as_bytes(), guard),
            Bound::Excluded(k) => {
                let ge = self.index.find_first_ge(k.as_bytes(), guard);
                if !ge.is_null()
                    && !unsafe { &*ge }.is_marked()
                    && unsafe { &*ge }.key_bytes() == k.as_bytes()
                {
                    crate::skiplist::strip_mark(unsafe {
                        (*ge).tower(0).load(std::sync::atomic::Ordering::Acquire)
                    })
                } else {
                    ge
                }
            }
            Bound::Unbounded => crate::skiplist::strip_mark(unsafe {
                (*self.index.head_ptr())
                    .tower(0)
                    .load(std::sync::atomic::Ordering::Acquire)
            }),
        }
    }

    fn prefix_bounds(&self, prefix: &[u8]) -> (K, Bound<K>) {
        if self.reversed {
            let mut search = K::zeroed();
            search.as_bytes_mut().fill(0xFF);
            search.as_bytes_mut()[..prefix.len()].copy_from_slice(prefix);
            let mut end_key = K::zeroed();
            end_key.as_bytes_mut()[..prefix.len()].copy_from_slice(prefix);
            (search, Bound::Included(end_key))
        } else {
            let mut search = K::zeroed();
            search.as_bytes_mut()[..prefix.len()].copy_from_slice(prefix);
            let end = prefix_to_end_bound::<K>(prefix);
            (search, end)
        }
    }

    /// Iterate entries whose keys start with `prefix`.
    ///
    /// `reversed=true` (default): yields matching keys in DESC order.
    /// `next()` is O(1), `next_back()` is O(log n). Both may perform disk I/O on cache miss.
    pub fn prefix_iter(&self, prefix: &[u8]) -> VarIter<'_, K, H> {
        let guard = self.index.collector().enter();
        let (search_key, end) = self.prefix_bounds(prefix);
        let front = self.index.find_first_ge(search_key.as_bytes(), &guard);
        VarIter {
            tree: self,
            front,
            back: None,
            end,
            start: Bound::Included(search_key),
            reversed: self.reversed,
            done: false,
            _guard: guard,
        }
    }

    /// Iterate all entries in index order.
    ///
    /// `reversed=true` (default): DESC. `reversed=false`: ASC.
    /// `next()` is O(1), `next_back()` is O(log n). Both may perform disk I/O on cache miss.
    pub fn iter(&self) -> VarIter<'_, K, H> {
        let guard = self.index.collector().enter();
        let front = crate::skiplist::strip_mark(unsafe {
            (*self.index.head_ptr())
                .tower(0)
                .load(std::sync::atomic::Ordering::Acquire)
        });
        VarIter {
            tree: self,
            front,
            back: None,
            end: Bound::Unbounded,
            start: Bound::Unbounded,
            reversed: self.reversed,
            done: false,
            _guard: guard,
        }
    }

    /// Iterate entries in `[start, end)` — start inclusive, end exclusive.
    ///
    /// `reversed=true` (default): DESC within range. `reversed=false`: ASC.
    /// `next()` is O(1), `next_back()` is O(log n). Both may perform disk I/O on cache miss.
    pub fn range(&self, start: &K, end: &K) -> VarIter<'_, K, H> {
        self.range_bounds(Bound::Included(start), Bound::Excluded(end))
    }

    /// Iterate entries in range defined by `start` and `end` bounds.
    ///
    /// Unlike [`range()`](Self::range), allows `Included`, `Excluded`, or `Unbounded`
    /// for each bound independently.
    ///
    /// `reversed=true` (default): DESC within range. `reversed=false`: ASC.
    /// `next()` is O(1), `next_back()` is O(log n). Both may perform disk I/O on cache miss.
    pub fn range_bounds(&self, start: Bound<&K>, end: Bound<&K>) -> VarIter<'_, K, H> {
        let guard = self.index.collector().enter();
        if self.reversed {
            let front = self.resolve_front(&end, &guard);
            VarIter {
                tree: self,
                front,
                back: None,
                end: bound_owned(&start),
                start: bound_owned(&end),
                reversed: true,
                done: false,
                _guard: guard,
            }
        } else {
            let front = self.resolve_front(&start, &guard);
            VarIter {
                tree: self,
                front,
                back: None,
                end: bound_owned(&end),
                start: bound_owned(&start),
                reversed: false,
                done: false,
                _guard: guard,
            }
        }
    }

    pub fn len(&self) -> usize {
        self.index.len()
    }

    pub fn is_empty(&self) -> bool {
        self.index.is_empty()
    }

    /// Write hint files for all active shard files. Call during graceful shutdown.
    pub fn sync_hints(&self) -> DbResult<()> {
        for shard in self.engine.shards().iter() {
            shard.write_active_hint(size_of::<K>())?;
        }
        Ok(())
    }

    /// Pre-populate the block cache with blocks containing live values.
    ///
    /// Walks the index to collect unique block offsets, sorts them for sequential I/O,
    /// then reads each block into the cache. Only blocks with live data are loaded —
    /// dead entries and garbage are skipped.
    pub fn warmup(&self) -> DbResult<()> {
        use std::collections::BTreeSet;

        let guard = self.index.collector().enter();

        // Collect unique (shard_id, file_id, block_offset) from live index entries
        let mut blocks: BTreeSet<(u8, u32, u64)> = BTreeSet::new();
        let mut current = crate::skiplist::strip_mark(unsafe {
            (*self.index.head_ptr())
                .tower(0)
                .load(std::sync::atomic::Ordering::Acquire)
        });
        while !current.is_null() {
            let node = unsafe { &*current };
            current = crate::skiplist::strip_mark(
                node.tower(0).load(std::sync::atomic::Ordering::Acquire),
            );
            if node.is_marked() {
                continue;
            }
            let disk = *node.load_disk();
            let block_offset = disk.offset as u64 & !4095;
            blocks.insert((disk.shard_id, disk.file_id, block_offset));
        }
        drop(guard);

        // Read blocks in sorted order (sequential I/O per shard/file)
        for (shard_id, file_id, block_offset) in &blocks {
            let key = BlockKey {
                shard_id: *shard_id,
                file_id: *file_id,
                block_offset: *block_offset,
            };
            if self.cache.get(&key).is_some() {
                continue;
            }
            let shard = &self.engine.shards()[*shard_id as usize];
            let (buf, is_full_block) = shard.read_block(*file_id, *block_offset)?;
            if is_full_block {
                self.cache.insert(key, Arc::new(buf));
            }
        }

        Ok(())
    }

    pub(crate) fn index(&self) -> &SkipList<VarNode<K>> {
        &self.index
    }

    /// Iterate all entries and optionally mutate them. Call once at startup.
    ///
    /// The callback receives each (key, value_bytes) and returns `MigrateAction`:
    /// - `Keep` — no change (fires `on_init` if `H::NEEDS_INIT`); not counted
    /// - `Update(new_value)` — replace value (hook-free write, fires `on_init`)
    /// - `Delete` — remove entry (hook-free tombstone, no hooks)
    ///
    /// `on_write` is NEVER fired during migrate — see `docs/hooks.md` in the armdb crate.
    /// Returns the number of mutated entries.
    pub fn migrate(
        &self,
        f: impl Fn(&K, &[u8]) -> crate::MigrateAction<ByteView>,
    ) -> DbResult<usize> {
        use crate::MigrateAction;

        let guard = self.index.collector().enter();
        let mut current = crate::skiplist::strip_mark(unsafe {
            (*self.index.head_ptr())
                .tower(0)
                .load(std::sync::atomic::Ordering::Acquire)
        });
        let mut count = 0;
        while !current.is_null() {
            let node = unsafe { &*current };
            current = crate::skiplist::strip_mark(
                node.tower(0).load(std::sync::atomic::Ordering::Acquire),
            );
            if node.is_marked() {
                continue;
            }
            let value = match self.read_value_cached(node, &guard) {
                Some(v) => v,
                None => {
                    tracing::warn!(
                        key = ?node.key.as_bytes(),
                        "var_tree migrate: skipping entry — value read failed"
                    );
                    continue;
                }
            };
            match f(&node.key, &value) {
                MigrateAction::Keep => {
                    if H::NEEDS_INIT {
                        self.hook.on_init(&node.key, &value);
                    }
                }
                MigrateAction::Update(new_value) => {
                    let shard_id = self.shard_for(&node.key);
                    {
                        let mut inner = self.engine.shards()[shard_id].lock();
                        self.put_locked(shard_id, &mut inner, &guard, &node.key, &new_value)?;
                    }
                    if H::NEEDS_INIT {
                        self.hook.on_init(&node.key, &new_value);
                    }
                    count += 1;
                }
                MigrateAction::Delete => {
                    let shard_id = self.shard_for(&node.key);
                    let mut inner = self.engine.shards()[shard_id].lock();
                    self.delete_locked(shard_id, &mut inner, &guard, &node.key)?;
                    count += 1;
                }
            }
        }

        tracing::info!(mutations = count, "var_tree migration complete");
        Ok(count)
    }

    /// Replay `on_init` for every live entry. Used when no migration runs
    /// (Db calls this after `run_migration` returns `false`). Public users
    /// should invoke `migrate(|_, _| MigrateAction::Keep)` instead.
    pub(crate) fn replay_init(&self) {
        if !H::NEEDS_INIT {
            return;
        }
        let guard = self.index.collector().enter();
        let mut current = crate::skiplist::strip_mark(unsafe {
            (*self.index.head_ptr())
                .tower(0)
                .load(std::sync::atomic::Ordering::Acquire)
        });
        let mut count = 0usize;
        while !current.is_null() {
            let node = unsafe { &*current };
            current = crate::skiplist::strip_mark(
                node.tower(0).load(std::sync::atomic::Ordering::Acquire),
            );
            if node.is_marked() {
                continue;
            }
            let value = match self.read_value_cached(node, &guard) {
                Some(v) => v,
                None => {
                    tracing::warn!(
                        key = ?node.key.as_bytes(),
                        "var_tree replay_init: skipping entry — value read failed"
                    );
                    continue;
                }
            };
            self.hook.on_init(&node.key, &value);
            count += 1;
        }
        tracing::debug!(replayed = count, "var_tree replay_init complete");
    }

    /// Lock-free read body. Returns `Ok(v)` on success, `Err(StaleDiskLoc)` if
    /// compaction removed the file referenced by `disk` between the caller's
    /// snapshot and the read. Other `DbError`s indicate I/O or decryption
    /// failure.
    fn read_value_cached_inner(&self, disk: &DiskLoc) -> DbResult<ByteView> {
        let len = disk.len as usize;
        let start = (disk.offset & 4095) as usize;

        // Large values (>2 blocks) bypass the cached path. This check MUST
        // sit before the cache lookup: a warm first block would otherwise
        // route a large value into `extract_from_block`, which only supports
        // two blocks and would panic on `next[..second_len]` when
        // `second_len > 4096`. StaleDiskLoc propagates so the outer retry
        // loop (`read_value_cached`) takes a fresh DiskLoc snapshot.
        if start + len > 8192 {
            let shard = &self.engine.shards()[disk.shard_id as usize];
            let inner = shard.lock();
            return self.read_value_locked_result(disk, &inner);
        }

        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };

        // 1. Block Cache (lock-free)
        if let Some(block) = self.cache.get(&cache_key) {
            metrics::counter!("armdb.cache.hit").increment(1);
            return Self::extract_from_block(&block, start, len, || {
                self.get_or_read_block(disk.shard_id, disk.file_id, block_offset + 4096)
            });
        }

        // 2. Write buffer — for unflushed data in active file (brief shard lock)
        {
            let shard = &self.engine.shards()[disk.shard_id as usize];
            let inner = shard.lock();
            if inner.active.file_id == disk.file_id
                && let Some(bytes) = inner.write_buf.read(disk.offset as u64, len)
            {
                return Ok(ByteView::new(bytes));
            }
        }

        // 3. Disk read + cache
        metrics::counter!("armdb.cache.miss").increment(1);
        let block = self.get_or_read_block(disk.shard_id, disk.file_id, block_offset)?;
        Self::extract_from_block(&block, start, len, || {
            self.get_or_read_block(disk.shard_id, disk.file_id, block_offset + 4096)
        })
    }

    /// Lock-free read with bounded retry on compaction race.
    ///
    /// The caller must hold a `seize::LocalGuard` for the duration of the
    /// call (passed by reference so it cannot be dropped early); `node` must
    /// have been obtained from this tree's index under the same guard. The
    /// guard's lifetime, encoded in the parameter signature, prevents the
    /// retire collector from reclaiming `node` between retry iterations.
    fn read_value_cached(
        &self,
        node: &VarNode<K>,
        _guard: &seize::LocalGuard<'_>,
    ) -> Option<ByteView> {
        for _ in 0..MAX_STALE_RETRIES {
            let disk = *node.load_disk();
            match self.read_value_cached_inner(&disk) {
                Ok(v) => return Some(v),
                Err(DbError::StaleDiskLoc) => {
                    metrics::counter!("armdb.read.stale_retry", "tree" => "var_tree").increment(1);
                    continue;
                }
                Err(_e) => {
                    #[cfg(feature = "hot-path-tracing")]
                    tracing::error!("VarTree read_value_cached error: {:?}", _e);
                    return None;
                }
            }
        }
        None
    }

    fn extract_from_block(
        block: &AlignedBuf,
        start: usize,
        len: usize,
        next_block: impl FnOnce() -> DbResult<Arc<AlignedBuf>>,
    ) -> DbResult<ByteView> {
        debug_assert!(
            start + len <= 8192,
            "extract_from_block supports at most 2 blocks (8192 bytes)"
        );
        if start + len <= 4096 {
            Ok(ByteView::new(&block[start..start + len]))
        } else {
            let next = next_block()?;
            let first_part = &block[start..];
            let second_len = len - first_part.len();
            let mut combined = Vec::with_capacity(len);
            combined.extend_from_slice(first_part);
            combined.extend_from_slice(&next[..second_len]);
            Ok(ByteView::from_vec(combined))
        }
    }

    /// Get a block from cache, or read it from disk and cache it.
    fn get_or_read_block(
        &self,
        shard_id: u8,
        file_id: u32,
        block_offset: u64,
    ) -> DbResult<Arc<AlignedBuf>> {
        let key = BlockKey {
            shard_id,
            file_id,
            block_offset,
        };
        if let Some(cached) = self.cache.get(&key) {
            return Ok(cached);
        }
        let shard = &self.engine.shards()[shard_id as usize];
        let (buf, is_full_block) = shard.read_block(file_id, block_offset)?;
        let arc = Arc::new(buf);
        // Only cache full blocks (entirely within the file's data region).
        // Partial blocks at the end of a file have zero-padded tails that
        // would become stale after file rotation or further writes.
        if is_full_block {
            self.cache.insert(key, arc.clone());
        }
        Ok(arc)
    }

    /// Compare-and-swap: if current value == expected, replace with new_value.
    /// Returns `Ok(())` on success, `Err(CasMismatch)` if current != expected,
    /// `Err(KeyNotFound)` if key doesn't exist.
    ///
    /// **Caveat:** Holds the shard lock while reading the current value. On a
    /// block-cache miss this performs disk I/O under the lock, blocking all
    /// writes to the same shard. Pre-warm the cache to avoid latency spikes.
    pub fn cas(&self, key: &K, expected: &[u8], new_value: &[u8]) -> DbResult<()> {
        metrics::counter!("armdb.ops", "op" => "cas", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.cas");
        let shard_id = self.shard_for(key);
        let shard = &self.engine.shards()[shard_id];
        let mut inner = shard.lock();

        let guard = self.index.collector().enter();
        let existing = self
            .index
            .get(key.as_bytes(), &guard)
            .ok_or(DbError::KeyNotFound)?;

        let disk = *existing.load_disk();
        let current = self
            .read_value_locked(&disk, &inner)
            .ok_or(DbError::KeyNotFound)?;
        if current.as_ref() != expected {
            return Err(DbError::CasMismatch);
        }

        let (new_disk_loc, _gsn) =
            inner.append_entry(shard_id as u8, key.as_bytes(), new_value, false)?;

        let new_disk = Box::into_raw(Box::new(new_disk_loc));
        let old_disk_ptr = existing.swap_disk(new_disk);
        let old_disk = unsafe { *old_disk_ptr };
        inner.add_dead_bytes(
            old_disk.file_id,
            crate::entry::entry_size(size_of::<K>(), old_disk.len),
        );
        unsafe {
            self.index
                .collector()
                .retire(old_disk_ptr, seize::reclaim::boxed::<DiskLoc>);
        }

        drop(inner);
        self.hook.on_write(
            key,
            if H::NEEDS_OLD_VALUE {
                Some(&*current)
            } else {
                None
            },
            Some(new_value),
        );
        Ok(())
    }

    /// Atomically read-modify-write. Returns `Some(new_value)` if key existed, `None` otherwise.
    /// The closure receives the current value and returns a new ByteView.
    /// The closure must not be heavy (shard lock is held).
    ///
    /// **Caveat:** Holds the shard lock while reading the current value. On a
    /// block-cache miss this performs disk I/O under the lock, blocking all
    /// writes to the same shard. Pre-warm the cache to avoid latency spikes.
    pub fn update(&self, key: &K, f: impl FnOnce(&[u8]) -> ByteView) -> DbResult<Option<ByteView>> {
        self.update_inner(key, f, false)
    }

    /// Like [`update()`](Self::update), but returns `Some(old_value)` instead of the new one.
    pub fn fetch_update(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> ByteView,
    ) -> DbResult<Option<ByteView>> {
        self.update_inner(key, f, true)
    }

    pub(crate) fn try_update_inner(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> DbResult<Option<ByteView>>,
        return_old: bool,
    ) -> DbResult<Option<ByteView>> {
        metrics::counter!("armdb.ops", "op" => "update", "tree" => "var_tree").increment(1);
        #[cfg(feature = "hot-path-tracing")]
        tracing::trace!("var_tree.update");
        let shard_id = self.shard_for(key);
        let shard = &self.engine.shards()[shard_id];
        let mut inner = shard.lock();

        let guard = self.index.collector().enter();
        let existing = match self.index.get(key.as_bytes(), &guard) {
            Some(n) => n,
            None => return Ok(None),
        };

        let disk = *existing.load_disk();
        let current = match self.read_value_locked(&disk, &inner) {
            Some(v) => v,
            None => return Ok(None),
        };

        let new_value = match f(&current)? {
            Some(v) => v,
            None => return Ok(Some(current)),
        };

        let (new_disk_loc, _gsn) =
            inner.append_entry(shard_id as u8, key.as_bytes(), &new_value, false)?;

        let new_disk = Box::into_raw(Box::new(new_disk_loc));
        let old_disk_ptr = existing.swap_disk(new_disk);
        let old_disk = unsafe { *old_disk_ptr };
        inner.add_dead_bytes(
            old_disk.file_id,
            crate::entry::entry_size(size_of::<K>(), old_disk.len),
        );
        unsafe {
            self.index
                .collector()
                .retire(old_disk_ptr, seize::reclaim::boxed::<DiskLoc>);
        }

        drop(inner);
        self.hook.on_write(
            key,
            if H::NEEDS_OLD_VALUE {
                Some(&*current)
            } else {
                None
            },
            Some(&*new_value),
        );
        Ok(Some(if return_old { current } else { new_value }))
    }

    fn update_inner(
        &self,
        key: &K,
        f: impl FnOnce(&[u8]) -> ByteView,
        return_old: bool,
    ) -> DbResult<Option<ByteView>> {
        self.try_update_inner(key, |bytes| Ok(Some(f(bytes))), return_old)
    }

    /// Read value when shard lock is already held, propagating `DbError`.
    /// Used by both `read_value_locked` (Option wrapper) and the large-value
    /// fallback in `read_value_cached_inner`.
    fn read_value_locked_result(&self, disk: &DiskLoc, inner: &ShardInner) -> DbResult<ByteView> {
        let len = disk.len as usize;

        // 1. Write buffer (for unflushed data)
        if inner.active.file_id == disk.file_id
            && let Some(bytes) = inner.write_buf.read(disk.offset as u64, len)
        {
            return Ok(ByteView::new(bytes));
        }

        // 2. Block cache (lock-free, single-block fast path)
        let block_offset = disk.offset as u64 & !4095;
        let start = (disk.offset & 4095) as usize;
        if start + len <= 4096 {
            let cache_key = BlockKey {
                shard_id: disk.shard_id,
                file_id: disk.file_id,
                block_offset,
            };
            if let Some(block) = self.cache.get(&cache_key) {
                return Ok(ByteView::new(&block[start..start + len]));
            }

            // 2b. Cache miss — read block under held lock, populate cache
            let (buf, is_full_block) = inner.read_block_locked(disk.file_id, block_offset)?;
            let arc = Arc::new(buf);
            if is_full_block {
                self.cache.insert(cache_key, arc.clone());
            }
            return Ok(ByteView::new(&arc[start..start + len]));
        }

        // 3. Multi-block: disk read via encryption-aware helper (no cache).
        let bytes = inner.read_value_from_disk_locked(disk)?;
        Ok(ByteView::new(&bytes))
    }

    /// Read value when shard lock is already held. Used by CAS/update.
    ///
    /// Thin `Option` wrapper around `read_value_locked_result` that preserves
    /// the existing call-site contract: `StaleDiskLoc` is logged at error
    /// level and collapsed to `None`; other errors collapse to `None` silently.
    fn read_value_locked(&self, disk: &DiskLoc, inner: &ShardInner) -> Option<ByteView> {
        match self.read_value_locked_result(disk, inner) {
            Ok(v) => Some(v),
            Err(DbError::StaleDiskLoc) => {
                tracing::error!(
                    file_id = disk.file_id,
                    shard_id = disk.shard_id,
                    "stale DiskLoc under shard lock - programming bug",
                );
                None
            }
            Err(_) => None,
        }
    }

    pub fn shard_for(&self, key: &K) -> usize {
        crate::shard_for_key(key, self.shard_prefix_bits, self.engine.shards().len())
    }
}

#[cfg(feature = "replication")]
impl<K: Key, H: WriteHook<K>> crate::replication::ReplicationTarget for VarTree<K, H> {
    fn apply_entry(
        &self,
        _shard_inner: &mut crate::shard::ShardInner,
        shard_id: u8,
        file_id: u32,
        entry_offset: u64,
        header: &crate::entry::EntryHeader,
        key: &[u8],
        _value: &[u8],
    ) -> DbResult<crate::replication::ApplyOutcome> {
        use crate::replication::ApplyOutcome;

        let key: K = K::from_bytes(key);

        let value_offset =
            entry_offset + size_of::<crate::entry::EntryHeader>() as u64 + size_of::<K>() as u64;
        let disk = DiskLoc::new(shard_id, file_id, value_offset as u32, header.value_len);

        if header.is_tombstone() {
            let guard = self.index.collector().enter();
            let removed = self.index.remove(key.as_bytes(), &guard);
            match removed {
                Some(node_ptr) => {
                    let old_disk = *unsafe { &*node_ptr }.load_disk();
                    Ok(ApplyOutcome::TombstoneRemoved(old_disk))
                }
                None => Ok(ApplyOutcome::Inserted), // no-op tombstone — no dead bytes
            }
        } else {
            let guard = self.index.collector().enter();
            let height = random_height();
            let node_ptr = VarNode::alloc(key, disk, height);
            match self.index.insert(node_ptr, &guard) {
                InsertResult::Inserted => Ok(ApplyOutcome::Inserted),
                InsertResult::Exists(existing) => {
                    let new_disk_ptr = Box::into_raw(Box::new(disk));
                    let old_disk_ptr = existing.swap_disk(new_disk_ptr);
                    let old_disk = unsafe { *old_disk_ptr };
                    unsafe {
                        self.index
                            .collector()
                            .retire(old_disk_ptr, seize::reclaim::boxed::<DiskLoc>);
                    }
                    // Deallocate the unused node
                    unsafe {
                        (*node_ptr)
                            .disk
                            .store(std::ptr::null_mut(), std::sync::atomic::Ordering::Relaxed);
                        VarNode::<K>::dealloc_node(node_ptr);
                    }
                    Ok(ApplyOutcome::Replaced(old_disk))
                }
            }
        }
    }

    fn try_apply_entry(
        &self,
        shard_inner: &mut crate::shard::ShardInner,
        shard_id: u8,
        file_id: u32,
        entry_offset: u64,
        header: &crate::entry::EntryHeader,
        raw_after_header: &[u8],
    ) -> DbResult<crate::replication::ApplyOutcome> {
        use crate::replication::ApplyOutcome;

        if raw_after_header.len() < size_of::<K>() + header.value_len as usize {
            return Ok(ApplyOutcome::NotMatched);
        }
        let key = &raw_after_header[..size_of::<K>()];
        let value = &raw_after_header[size_of::<K>()..size_of::<K>() + header.value_len as usize];
        let crc = crate::entry::compute_crc32(header.gsn, header.value_len, key, value);
        if crc != header.crc32 {
            return Ok(ApplyOutcome::NotMatched);
        }
        self.apply_entry(
            shard_inner,
            shard_id,
            file_id,
            entry_offset,
            header,
            key,
            value,
        )
    }

    fn key_len(&self) -> usize {
        size_of::<K>()
    }
}

#[cfg(feature = "replication")]
impl<K: Key, H: WriteHook<K>> VarTree<K, H> {
    /// Install SPSC replication producers into every shard and start a
    /// `ReplicationServer` bound to `bind_addr`.
    ///
    /// # Single-call contract
    ///
    /// Each call installs fresh SPSC producers, replacing any previously
    /// installed ones. Call this at most once per `VarTree` instance — a
    /// second call will orphan the in-flight producer of any active streaming
    /// connection on the first server, which will then observe an empty ring
    /// buffer and silently stop forwarding entries.
    pub fn start_replication_server(
        &self,
        bind_addr: std::net::SocketAddr,
        signal: crate::shutdown::ShutdownSignal,
    ) -> crate::error::DbResult<crate::replication::ReplicationServer> {
        let consumers = self.install_replication_producers()?;
        crate::replication::ReplicationServer::start(
            bind_addr,
            self.engine.shards().clone(),
            consumers,
            self.engine.config().max_file_size,
            signal,
        )
    }

    pub fn start_replication_server_with_options(
        &self,
        bind_addr: std::net::SocketAddr,
        signal: crate::shutdown::ShutdownSignal,
        options: crate::replication::ReplicationServerOptions,
    ) -> crate::error::DbResult<crate::replication::ReplicationServer> {
        let consumers = self.install_replication_producers()?;
        crate::replication::ReplicationServer::start_with_options(
            bind_addr,
            self.engine.shards().clone(),
            consumers,
            self.engine.config().max_file_size,
            signal,
            options,
        )
    }

    fn install_replication_producers(
        &self,
    ) -> crate::error::DbResult<Vec<rtrb::Consumer<crate::replication::ReplicationEntry>>> {
        const SPSC_CAPACITY: usize = 4096;
        let shards = self.engine.shards();
        let mut consumers = Vec::with_capacity(shards.len());
        for shard in shards.iter() {
            let (p, c) = rtrb::RingBuffer::new(SPSC_CAPACITY);
            shard.set_replication_producer(p);
            consumers.push(c);
        }
        Ok(consumers)
    }

    /// Start a `ReplicationClient` that streams entries from `leader_addr`
    /// into `registry`. Symmetric to [`Self::start_replication_server`].
    ///
    /// `key_len` is derived from `size_of::<K>()`.
    pub fn start_replication_client(
        &self,
        leader_addr: std::net::SocketAddr,
        registry: std::sync::Arc<crate::replication::ReplicationRegistry>,
        signal: crate::shutdown::ShutdownSignal,
    ) -> crate::error::DbResult<crate::replication::ReplicationClient> {
        crate::replication::ReplicationClient::start(
            leader_addr,
            self.engine.shards().clone(),
            registry,
            size_of::<K>() as u16,
            signal,
        )
    }

    pub fn start_replication_client_with_options(
        &self,
        leader_addr: std::net::SocketAddr,
        registry: std::sync::Arc<crate::replication::ReplicationRegistry>,
        signal: crate::shutdown::ShutdownSignal,
        options: crate::replication::ReplicationClientOptions,
    ) -> crate::error::DbResult<crate::replication::ReplicationClient> {
        crate::replication::ReplicationClient::start_with_options(
            leader_addr,
            self.engine.shards().clone(),
            registry,
            size_of::<K>() as u16,
            signal,
            options,
        )
    }
}

#[cfg(feature = "replication")]
impl<K, H> VarTree<K, H>
where
    K: Key + Send + Sync + 'static,
    H: WriteHook<K> + Send + Sync + 'static,
{
    /// Wrap a shared handle to this tree as a `Box<dyn ReplicationTarget>`.
    ///
    /// The returned box holds an `Arc` clone — the caller retains full read
    /// access to the original tree through the `Arc` while the registry owns
    /// the box. This is the intended pattern for follower-side wiring:
    ///
    /// ```ignore
    /// let follower = Arc::new(VarTree::<[u8; 8]>::open(path, cfg)?);
    /// let registry = ReplicationRegistry::new(follower.as_replication_target());
    /// // `follower` remains usable for .get() etc.
    /// ```
    pub fn as_replication_target(
        self: &std::sync::Arc<Self>,
    ) -> Box<dyn crate::replication::ReplicationTarget> {
        Box::new(std::sync::Arc::clone(self))
    }
}

/// Handle for atomic multi-key operations within a single shard.
/// Obtained via [`VarTree::atomic`]. The shard lock is held for the
/// lifetime of this struct — keep the closure short.
pub struct VarShard<'a, K: Key, H: WriteHook<K> = NoHook> {
    tree: &'a VarTree<K, H>,
    inner: MutexGuard<'a, ShardInner>,
    shard_id: usize,
    guard: seize::LocalGuard<'a>,
}

impl<K: Key, H: WriteHook<K>> VarShard<'_, K, H> {
    pub fn put(&mut self, key: &K, value: &[u8]) -> DbResult<()> {
        self.check_shard(key)?;
        self.tree
            .put_locked(self.shard_id, &mut self.inner, &self.guard, key, value)
    }

    pub fn insert(&mut self, key: &K, value: &[u8]) -> DbResult<()> {
        self.check_shard(key)?;
        self.tree
            .insert_locked(self.shard_id, &mut self.inner, &self.guard, key, value)
    }

    pub fn delete(&mut self, key: &K) -> DbResult<bool> {
        self.check_shard(key)?;
        self.tree
            .delete_locked(self.shard_id, &mut self.inner, &self.guard, key)
    }

    pub fn get(&self, key: &K) -> Option<ByteView> {
        let node = self.tree.index.get(key.as_bytes(), &self.guard)?;
        let disk = *node.load_disk();
        self.tree.read_value_locked(&disk, &self.inner)
    }

    pub fn get_or_err(&self, key: &K) -> DbResult<ByteView> {
        self.get(key).ok_or(DbError::KeyNotFound)
    }

    pub fn contains(&self, key: &K) -> bool {
        self.tree.index.get(key.as_bytes(), &self.guard).is_some()
    }

    fn check_shard(&self, key: &K) -> DbResult<()> {
        if self.tree.shard_for(key) != self.shard_id {
            return Err(DbError::ShardMismatch);
        }
        Ok(())
    }
}

fn bound_owned<K: Copy>(b: &Bound<&K>) -> Bound<K> {
    match b {
        Bound::Included(k) => Bound::Included(**k),
        Bound::Excluded(k) => Bound::Excluded(**k),
        Bound::Unbounded => Bound::Unbounded,
    }
}

fn prefix_to_end_bound<K: Key>(prefix: &[u8]) -> Bound<K> {
    let mut incremented = prefix.to_vec();
    let mut carry = true;
    for byte in incremented.iter_mut().rev() {
        if carry {
            if *byte == 0xFF {
                *byte = 0x00;
            } else {
                *byte += 1;
                carry = false;
                break;
            }
        }
    }
    if carry {
        Bound::Unbounded
    } else {
        let mut end = K::zeroed();
        end.as_bytes_mut()[..incremented.len()].copy_from_slice(&incremented);
        Bound::Excluded(end)
    }
}

/// Iterator over entries in a `VarTree`. Returned by `iter()`, `range()`, and `prefix_iter()`.
///
/// Weakly-consistent: concurrent inserts/updates may be visible during iteration.
/// Deleted entries are skipped. The `seize` guard prevents use-after-free.
/// Each `next()` may perform disk I/O on a block-cache miss.
pub struct VarIter<'a, K: Key, H: WriteHook<K> = NoHook> {
    tree: &'a VarTree<K, H>,
    front: *mut VarNode<K>,
    /// `None` = not yet resolved (lazy). Computed on first `next_back()` call.
    back: Option<*mut VarNode<K>>,
    end: Bound<K>,
    start: Bound<K>,
    reversed: bool,
    done: bool,
    _guard: seize::LocalGuard<'a>,
}

impl<K: Key, H: WriteHook<K>> Iterator for VarIter<'_, K, H> {
    type Item = (K, ByteView);

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if self.done || self.front.is_null() {
                return None;
            }
            let node = unsafe { &*self.front };
            let converged = self.back.is_some_and(|back| std::ptr::eq(self.front, back));
            self.front = crate::skiplist::strip_mark(
                node.tower(0).load(std::sync::atomic::Ordering::Acquire),
            );
            if converged {
                self.done = true;
            }
            if node.is_marked() {
                if converged {
                    return None;
                }
                continue;
            }
            if !self.check_end(&node.key) {
                self.done = true;
                return None;
            }
            match self.tree.read_value_cached(node, &self._guard) {
                Some(value) => return Some((node.key, value)),
                None => {
                    if converged {
                        return None;
                    }
                    continue;
                }
            }
        }
    }
}

impl<K: Key, H: WriteHook<K>> DoubleEndedIterator for VarIter<'_, K, H> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.back.is_none() {
            self.back = Some(self.resolve_back());
            if self.front.is_null() {
                self.done = true;
            }
        }
        loop {
            let back = self.back.unwrap_or(std::ptr::null_mut());
            if self.done || back.is_null() {
                return None;
            }
            let node = unsafe { &*back };
            let key = node.key;
            let converged = std::ptr::eq(self.front, back);
            self.back = Some(self.tree.index().find_last_lt(key.as_bytes(), &self._guard));
            if converged {
                self.done = true;
            }
            if node.is_marked() {
                if converged {
                    return None;
                }
                continue;
            }
            if !self.check_start(&key) {
                self.done = true;
                return None;
            }
            match self.tree.read_value_cached(node, &self._guard) {
                Some(value) => return Some((key, value)),
                None => {
                    if converged {
                        return None;
                    }
                    continue;
                }
            }
        }
    }
}

impl<K: Key, H: WriteHook<K>> VarIter<'_, K, H> {
    /// Lazily resolve the back pointer for DoubleEndedIterator.
    fn resolve_back(&self) -> *mut VarNode<K> {
        let index = self.tree.index();
        match &self.end {
            Bound::Unbounded => index.find_last(&self._guard),
            Bound::Excluded(k) => index.find_last_lt(k.as_bytes(), &self._guard),
            Bound::Included(k) => {
                let ge = index.find_first_ge(k.as_bytes(), &self._guard);
                if !ge.is_null()
                    && !unsafe { &*ge }.is_marked()
                    && unsafe { &*ge }.key_bytes() == k.as_bytes()
                {
                    ge
                } else {
                    index.find_last_lt(k.as_bytes(), &self._guard)
                }
            }
        }
    }

    #[inline(always)]
    fn check_end(&self, key: &K) -> bool {
        match &self.end {
            Bound::Unbounded => true,
            Bound::Excluded(end) => {
                if self.reversed {
                    key.as_bytes() > end.as_bytes()
                } else {
                    key.as_bytes() < end.as_bytes()
                }
            }
            Bound::Included(end) => {
                if self.reversed {
                    key.as_bytes() >= end.as_bytes()
                } else {
                    key.as_bytes() <= end.as_bytes()
                }
            }
        }
    }

    #[inline(always)]
    fn check_start(&self, key: &K) -> bool {
        match &self.start {
            Bound::Unbounded => true,
            Bound::Excluded(s) => {
                if self.reversed {
                    key.as_bytes() < s.as_bytes()
                } else {
                    key.as_bytes() > s.as_bytes()
                }
            }
            Bound::Included(s) => {
                if self.reversed {
                    key.as_bytes() <= s.as_bytes()
                } else {
                    key.as_bytes() >= s.as_bytes()
                }
            }
        }
    }
    /// Collect only the keys. Convenience for backward compatibility.
    pub fn collect_keys(&mut self) -> Vec<K> {
        self.map(|(k, _)| k).collect()
    }

    /// Collect all remaining entries. Convenience for backward compatibility.
    pub fn collect_entries(&mut self) -> Vec<(K, ByteView)> {
        self.collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Config;
    use crate::compaction::compact_shard;
    use tempfile::tempdir;

    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

    /// Test hook with counters for on_write / on_init calls and the last observed new value for
    /// on_write. NEEDS_INIT and NEEDS_OLD_VALUE are parameterized by const generics.
    #[derive(Default)]
    struct CountingHook<const NEEDS_INIT: bool, const NEEDS_OLD: bool> {
        writes: AtomicUsize,
        writes_with_old: AtomicUsize,
        inits: AtomicUsize,
        last_write_new: crate::sync::Mutex<Option<Vec<u8>>>,
        last_init_value: crate::sync::Mutex<Option<Vec<u8>>>,
    }

    impl<const NEEDS_INIT: bool, const NEEDS_OLD: bool> WriteHook<[u8; 8]>
        for CountingHook<NEEDS_INIT, NEEDS_OLD>
    {
        const NEEDS_OLD_VALUE: bool = NEEDS_OLD;
        const NEEDS_INIT: bool = NEEDS_INIT;

        fn on_write(&self, _key: &[u8; 8], old: Option<&[u8]>, new: Option<&[u8]>) {
            self.writes.fetch_add(1, AtomicOrdering::Relaxed);
            if old.is_some() {
                self.writes_with_old.fetch_add(1, AtomicOrdering::Relaxed);
            }
            *crate::sync::lock(&self.last_write_new) = new.map(<[u8]>::to_vec);
        }

        fn on_init(&self, _key: &[u8; 8], value: &[u8]) {
            self.inits.fetch_add(1, AtomicOrdering::Relaxed);
            *crate::sync::lock(&self.last_init_value) = Some(value.to_vec());
        }
    }

    fn open_test_tree(dir: &std::path::Path) -> VarTree<[u8; 8]> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        VarTree::open(dir, cfg).expect("open test tree")
    }

    fn open_test_tree_hooked<const NEEDS_INIT: bool, const NEEDS_OLD: bool>(
        dir: &std::path::Path,
        hook: CountingHook<NEEDS_INIT, NEEDS_OLD>,
    ) -> VarTree<[u8; 8], CountingHook<NEEDS_INIT, NEEDS_OLD>> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        VarTree::open_hooked(dir, cfg, hook).expect("open hooked test tree")
    }

    fn put_until_compactable(tree: &VarTree<[u8; 8]>, key: [u8; 8]) -> DiskLoc {
        // Capture the DiskLoc after the first put — this points to an early
        // file that will be erased by compaction (all later puts overwrite
        // the index, leaving this entry dead in its file).
        tree.put(&key, &[0u8; 256]).expect("first put");
        let snap = {
            let guard = tree.index.collector().enter();
            let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
            *node.load_disk()
        };
        // Each put is 280 bytes (16 header + 8 key + 256 value, 8-byte aligned).
        // With max_file_size=8192, ~30 puts cross the first rotation boundary.
        // Use 65 puts so the snap file is sealed as immutable AND fully dead.
        for i in 1..65u8 {
            tree.put(&key, &[i; 256]).expect("put");
        }
        tree.put(&key, b"final-value-payload-XX")
            .expect("final put");
        snap
    }

    #[test]
    fn read_value_cached_inner_returns_stale_after_compaction() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 7u64.to_be_bytes();
        let snap = put_until_compactable(&tree, key);

        let shard = &tree.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        match tree.read_value_cached_inner(&snap) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn read_value_cached_returns_some_after_compaction() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 11u64.to_be_bytes();
        let _snap = put_until_compactable(&tree, key);
        let shard = &tree.engine.shards()[0];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let v = tree
            .read_value_cached(node, &guard)
            .expect("post-compaction value must be readable");
        assert_eq!(v.as_bytes(), b"final-value-payload-XX");
    }

    #[test]
    fn get_during_compaction_returns_some() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 13u64.to_be_bytes();
        let _snap = put_until_compactable(&tree, key);
        let shard = &tree.engine.shards()[0];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let v = tree.get(&key).expect("post-compaction get");
        assert_eq!(v.as_bytes(), b"final-value-payload-XX");
    }

    #[test]
    fn iter_during_compaction_yields_all_live_keys() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        for k in 1u64..=3 {
            put_until_compactable(&tree, k.to_be_bytes());
        }
        let shard = &tree.engine.shards()[0];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let collected: std::collections::BTreeMap<[u8; 8], Vec<u8>> = tree
            .iter()
            .map(|(k, v)| (k, v.as_bytes().to_vec()))
            .collect();
        assert_eq!(collected.len(), 3);
        for k in 1u64..=3 {
            let bytes = collected
                .get(&k.to_be_bytes())
                .expect("every original key must remain");
            assert_eq!(bytes.as_slice(), b"final-value-payload-XX");
        }
    }

    #[test]
    fn get_or_read_block_returns_stale_for_unknown_file_id() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        match tree.get_or_read_block(0, 9999, 0) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(_) => panic!("expected StaleDiskLoc, got Ok"),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn extract_from_block_propagates_next_block_error() {
        let block = AlignedBuf::zeroed(4096);
        let start = 4090;
        let len = 32;
        let result: DbResult<ByteView> =
            VarTree::<[u8; 8]>::extract_from_block(&block, start, len, || {
                Err(DbError::StaleDiskLoc)
            });
        match result {
            Err(DbError::StaleDiskLoc) => {}
            Ok(_) => panic!("expected StaleDiskLoc, got Ok"),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn extract_from_block_multi_block_first_cached_second_stale() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 21u64.to_be_bytes();
        let value = vec![0xCDu8; 4073];
        tree.put(&key, &value).expect("initial put");

        // Capture the multi-block DiskLoc BEFORE overwriting.
        let snap = {
            let guard = tree.index.collector().enter();
            let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
            *node.load_disk()
        };

        // Make the initial entry dead by overwriting many times so compaction
        // erases the file containing `snap` (need enough writes to force file
        // rotation past max_file_size=8192 and seal the file as immutable).
        // 65 overwrites ensures the snap file is fully dead after two rotations.
        for i in 0..65u8 {
            tree.put(&key, &[i; 256]).expect("overwrite");
        }
        tree.put(&key, b"final").expect("final");

        let shard = &tree.engine.shards()[0];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let block_offset = snap.offset as u64 & !4095;
        let first_block = AlignedBuf::zeroed(4096);
        let cache_key = BlockKey {
            shard_id: snap.shard_id,
            file_id: snap.file_id,
            block_offset,
        };
        tree.cache.insert(cache_key, Arc::new(first_block));

        match tree.read_value_cached_inner(&snap) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(_) => panic!("expected StaleDiskLoc from second block, got Ok"),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    #[test]
    fn retry_limit_returns_none_on_persistent_stale() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 99u64.to_be_bytes();
        tree.put(&key, b"payload").expect("put");

        // Force every read_value_cached_inner call to see Stale by manually
        // clearing inner.immutable AND moving the active.file_id out of the
        // way. node.load_disk() still points at the original (now-unreachable)
        // file_id, so each retry hits Shard::read_block, which returns
        // StaleDiskLoc.
        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let snap = *node.load_disk();
        drop(guard);

        {
            let shard = &tree.engine.shards()[snap.shard_id as usize];
            let mut inner = shard.lock();
            inner.immutable = Vec::new();
            // Reassign active.file_id to a sentinel value that does not match
            // snap.file_id, so the active-file branch in Shard::read_block
            // never matches either.
            inner.active.file_id = u32::MAX;
        }

        let guard = tree.index.collector().enter();
        let node = tree
            .index
            .get(key.as_bytes(), &guard)
            .expect("still indexed");
        assert!(
            tree.read_value_cached(node, &guard).is_none(),
            "MAX_STALE_RETRIES must terminate the loop and return None"
        );
    }

    #[test]
    fn var_tree_replay_init_fires_on_init_per_live_key_raw() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        for i in 0u64..5 {
            tree.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        // Delete one — replay_init must not see it.
        tree.delete(&3u64.to_be_bytes()).expect("delete");

        // Reset counters so we measure only the effect of replay_init.
        tree.hook.writes.store(0, AtomicOrdering::Relaxed);
        tree.hook.inits.store(0, AtomicOrdering::Relaxed);

        tree.replay_init();

        assert_eq!(
            tree.hook.inits.load(AtomicOrdering::Relaxed),
            4,
            "4 live keys"
        );
        assert_eq!(
            tree.hook.writes.load(AtomicOrdering::Relaxed),
            0,
            "no on_write"
        );
    }

    #[test]
    fn var_tree_replay_init_no_hook_is_noop() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        for i in 0u64..3 {
            tree.put(&i.to_be_bytes(), &[i as u8; 8]).expect("put");
        }
        // Must finish instantly with no effects.
        tree.replay_init();
        // sanity: tree is intact.
        assert!(tree.get(&0u64.to_be_bytes()).is_some());
    }

    #[test]
    fn var_tree_migrate_keep_fires_on_init_not_on_write_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        for i in 0u64..4 {
            tree.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        tree.hook.writes.store(0, AtomicOrdering::Relaxed);
        tree.hook.inits.store(0, AtomicOrdering::Relaxed);

        let mutated = tree.migrate(|_, _| MigrateAction::Keep).expect("migrate");

        assert_eq!(mutated, 0);
        assert_eq!(
            tree.hook.inits.load(AtomicOrdering::Relaxed),
            4,
            "4 keeps -> 4 on_init"
        );
        assert_eq!(
            tree.hook.writes.load(AtomicOrdering::Relaxed),
            0,
            "Keep must not fire on_write"
        );
    }

    #[test]
    fn var_tree_migrate_update_fires_on_init_with_new_value_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 42u64.to_be_bytes();
        tree.put(&key, b"old-value").expect("put");
        tree.hook.writes.store(0, AtomicOrdering::Relaxed);
        tree.hook.inits.store(0, AtomicOrdering::Relaxed);

        let new = ByteView::new(b"new-value");
        let mutated = tree
            .migrate(move |_, _| MigrateAction::Update(new.clone()))
            .expect("migrate");

        assert_eq!(mutated, 1);
        assert_eq!(tree.hook.inits.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(
            crate::sync::lock(&tree.hook.last_init_value).as_deref(),
            Some(b"new-value".as_ref()),
            "on_init must receive the NEW value"
        );
        assert_eq!(
            tree.hook.writes.load(AtomicOrdering::Relaxed),
            0,
            "Update must NOT fire on_write (was double-firing through self.put)"
        );
        assert_eq!(tree.get(&key).unwrap().as_bytes(), b"new-value");
    }

    #[test]
    fn var_tree_migrate_delete_fires_no_hooks_raw() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 7u64.to_be_bytes();
        tree.put(&key, b"x").expect("put");
        tree.hook.writes.store(0, AtomicOrdering::Relaxed);
        tree.hook.inits.store(0, AtomicOrdering::Relaxed);

        let mutated = tree.migrate(|_, _| MigrateAction::Delete).expect("migrate");

        assert_eq!(mutated, 1);
        assert_eq!(tree.hook.inits.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(tree.hook.writes.load(AtomicOrdering::Relaxed), 0);
        assert!(tree.get(&key).is_none());
    }

    #[test]
    fn var_tree_migrate_no_init_hook_is_silent_for_keep_and_update() {
        use crate::MigrateAction;
        let dir = tempdir().unwrap();
        // NEEDS_INIT = false: on_init must never be called regardless of action.
        let tree = open_test_tree_hooked::<false, false>(dir.path(), CountingHook::default());

        for i in 0u64..3 {
            tree.put(&i.to_be_bytes(), &[i as u8; 16]).expect("put");
        }
        tree.hook.writes.store(0, AtomicOrdering::Relaxed);
        tree.hook.inits.store(0, AtomicOrdering::Relaxed);

        // Keep
        tree.migrate(|_, _| MigrateAction::Keep)
            .expect("migrate keep");
        assert_eq!(
            tree.hook.inits.load(AtomicOrdering::Relaxed),
            0,
            "Keep with NEEDS_INIT=false"
        );
        assert_eq!(tree.hook.writes.load(AtomicOrdering::Relaxed), 0);

        // Update
        let new = ByteView::new(b"new");
        tree.migrate(move |_, _| MigrateAction::Update(new.clone()))
            .expect("migrate update");
        assert_eq!(
            tree.hook.inits.load(AtomicOrdering::Relaxed),
            0,
            "Update with NEEDS_INIT=false"
        );
        assert_eq!(
            tree.hook.writes.load(AtomicOrdering::Relaxed),
            0,
            "Update must not fire on_write either"
        );
    }

    #[test]
    fn var_tree_public_put_still_fires_on_write_once() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        tree.put(&1u64.to_be_bytes(), b"v").expect("put");
        assert_eq!(tree.hook.writes.load(AtomicOrdering::Relaxed), 1);
    }

    #[test]
    fn var_tree_atomic_does_not_fire_hooks() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree_hooked::<true, false>(dir.path(), CountingHook::default());

        let key = 1u64.to_be_bytes();
        tree.atomic(&key, |shard| {
            shard.put(&key, b"a")?;
            shard.delete(&key)?;
            Ok(())
        })
        .expect("atomic");

        assert_eq!(tree.hook.writes.load(AtomicOrdering::Relaxed), 0);
        assert_eq!(tree.hook.inits.load(AtomicOrdering::Relaxed), 0);
    }

    /// `_result` returns Ok when the value sits in the active write buffer.
    #[test]
    fn read_value_locked_result_ok_from_write_buf() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 1u64.to_be_bytes();
        let payload = b"in-write-buffer-value";
        tree.put(&key, payload).expect("put");

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let disk = *node.load_disk();
        drop(guard);

        let shard = &tree.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        let v = tree
            .read_value_locked_result(&disk, &inner)
            .expect("write-buf read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// `_result` returns Ok when the value is on an immutable file and the
    /// entry sits within a single 4 KiB block.
    #[test]
    fn read_value_locked_result_ok_from_disk_immutable() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 2u64.to_be_bytes();
        let payload = b"single-block-immutable";
        tree.put(&key, payload).expect("put");
        // Force rotation so the entry moves out of the active write buffer.
        // Each put is 280 bytes; with max_file_size=8192, need >30 puts to
        // cross the rotation boundary. Use keys 100..135 to avoid overwriting key 2.
        for i in 100u64..135 {
            tree.put(&i.to_be_bytes(), &[i as u8; 256])
                .expect("rotator");
        }

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let disk = *node.load_disk();
        drop(guard);

        // `open_test_tree` uses the default CacheConfig (max_size = 0), so the
        // cache is disabled and step 2 (single-block cache lookup) returns
        // None unconditionally — the read naturally exercises step 3 (disk).

        let shard = &tree.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        // Sanity: the entry must NOT be in the write buffer anymore — the rotator
        // loop above is sized to force rotation past max_file_size=8192.
        assert_ne!(
            disk.file_id, inner.active.file_id,
            "test setup failed: key=2 entry is still in the active file's write buffer",
        );
        let v = tree
            .read_value_locked_result(&disk, &inner)
            .expect("disk read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// `_result` propagates `StaleDiskLoc` from the disk read.
    #[test]
    fn read_value_locked_result_propagates_stale_disk_loc() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 3u64.to_be_bytes();
        let snap = put_until_compactable(&tree, key);

        let shard = &tree.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let inner = shard.lock();
        match tree.read_value_locked_result(&snap, &inner) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }
    }

    /// Backward-compat: the `Option` wrapper still returns `None` on
    /// `StaleDiskLoc`, so callers like `cas`/`update` keep their contract.
    /// We intentionally do NOT assert on the tracing output (no capture
    /// helper exists in this crate); the `None` is the load-bearing
    /// invariant.
    #[test]
    fn read_value_locked_returns_none_on_stale() {
        let dir = tempdir().unwrap();
        let tree = open_test_tree(dir.path());

        let key = 4u64.to_be_bytes();
        let snap = put_until_compactable(&tree, key);

        let shard = &tree.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        let inner = shard.lock();
        assert!(tree.read_value_locked(&snap, &inner).is_none());
    }

    /// Pins the "size check sits before cache lookup" invariant.
    ///
    /// Manually inject the first 4 KiB block of a large value into the
    /// cache. Without the early `start + len > 8192` check, the cached path
    /// would call `extract_from_block`, which only supports two blocks and
    /// would panic on `next[..second_len]` for `second_len > 4096`.
    ///
    /// With the early check, the call routes to the locked path and returns
    /// the correct bytes.
    #[test]
    fn large_value_with_first_block_cached_uses_fallback() {
        let dir = tempdir().unwrap();
        // Custom geometry: write_buffer_size big enough for 20 KiB entry,
        // max_file_size == write_buffer_size (required by Config::validate);
        // rotation is forced explicitly via rotate_active_for_test.
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        // Enable the block cache so `cache.insert` actually takes effect.
        // Default `CacheConfig::default` has `max_size = 0` which makes the
        // cache a no-op; we need real inserts to set up the warm-cache scenario.
        cfg.cache.max_size = 1 << 20;
        let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg).expect("open");

        let key = 42u64.to_be_bytes();
        // Build a value whose body spans ~5 blocks: > 8192 bytes.
        let payload: Vec<u8> = (0..20_000u32).map(|i| i as u8).collect();
        tree.put(&key, &payload).expect("put large");
        // Force rotation so the large entry moves to an immutable file.
        tree.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let disk = *node.load_disk();
        drop(guard);

        // Sanity: this is a multi-block large value.
        let start = (disk.offset & 4095) as usize;
        assert!(
            start + disk.len as usize > 8192,
            "test precondition: large value must span >2 blocks",
        );

        // Inject the first block (zeroes) into the cache to ensure the cache
        // lookup would succeed for the first block — exactly the warm-cache
        // scenario that would have triggered the old panic.
        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };
        tree.cache
            .insert(cache_key, Arc::new(AlignedBuf::zeroed(4096)));
        // Sanity: insert took effect.
        assert!(
            tree.cache.get(&cache_key).is_some(),
            "cache must be enabled for warm-cache scenario",
        );

        let v = tree
            .read_value_cached_inner(&disk)
            .expect("large value must read via locked fallback");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    /// Value entirely in one block: `start + len <= 4096`.
    #[test]
    fn extract_from_block_single_block() {
        let mut block = AlignedBuf::zeroed(4096);
        for (i, byte) in block.iter_mut().enumerate() {
            *byte = i as u8;
        }
        let v = VarTree::<[u8; 8]>::extract_from_block(&block, 100, 50, || {
            panic!("next_block must not be called for single-block reads")
        })
        .expect("ok");
        let expected: Vec<u8> = (100u8..150u8).collect();
        assert_eq!(v.as_bytes(), expected.as_slice());
    }

    /// Value ends exactly at the second block's end: `start + len == 8192`.
    #[test]
    fn extract_from_block_two_blocks_exact() {
        let mut first = AlignedBuf::zeroed(4096);
        for byte in first.iter_mut() {
            *byte = 0xAA;
        }
        let mut second = AlignedBuf::zeroed(4096);
        for byte in second.iter_mut() {
            *byte = 0xBB;
        }
        // start = 4096 - 1 (last byte of first block); len = 4097.
        // start + len = 8192 — the boundary that must remain supported.
        let v = VarTree::<[u8; 8]>::extract_from_block(&first, 4095, 4097, || Ok(Arc::new(second)))
            .expect("ok");
        let bytes = v.as_bytes();
        assert_eq!(bytes.len(), 4097);
        assert_eq!(bytes[0], 0xAA);
        assert_eq!(bytes[1], 0xBB);
        assert_eq!(bytes[4096], 0xBB);
    }

    /// Value spans two blocks partially: `4096 < start + len < 8192`.
    #[test]
    fn extract_from_block_two_blocks_partial() {
        let mut first = AlignedBuf::zeroed(4096);
        for byte in first.iter_mut() {
            *byte = 0x11;
        }
        let mut second = AlignedBuf::zeroed(4096);
        for byte in second.iter_mut() {
            *byte = 0x22;
        }
        // start = 4000, len = 200 -> first 96 bytes from first, next 104 from second.
        let v = VarTree::<[u8; 8]>::extract_from_block(&first, 4000, 200, || Ok(Arc::new(second)))
            .expect("ok");
        let bytes = v.as_bytes();
        assert_eq!(bytes.len(), 200);
        assert!(bytes[..96].iter().all(|b| *b == 0x11));
        assert!(bytes[96..].iter().all(|b| *b == 0x22));
    }

    /// Fixed geometry that forces large entries onto an immutable file:
    /// `write_buffer_size` fits the 50 KiB entry; rotation is done explicitly
    /// via `rotate_active_for_test` so max_file_size == write_buffer_size
    /// satisfies Config::validate.
    fn open_large_value_tree(dir: &std::path::Path) -> VarTree<[u8; 8]> {
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        VarTree::open(dir, cfg).expect("open large-value test tree")
    }

    fn build_large_payload(seed: u8) -> Vec<u8> {
        (0..50_000u32)
            .map(|i| (i as u8).wrapping_add(seed))
            .collect()
    }

    /// End-to-end: 50 KiB value, force rotation to immutable, then `get`
    /// must return correct bytes via read_value_from_disk_locked.
    ///
    /// `open_large_value_tree` uses the default CacheConfig (max_size = 0),
    /// so the block cache is disabled and the read goes through the
    /// large-value locked fallback → disk read on every call.
    #[test]
    fn large_value_read_via_locked_fallback() {
        let dir = tempdir().unwrap();
        let tree = open_large_value_tree(dir.path());

        let key = 100u64.to_be_bytes();
        let payload = build_large_payload(0);
        tree.put(&key, &payload).expect("put large");
        tree.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let v = tree
            .read_value_cached(node, &guard)
            .expect("read must succeed via locked fallback");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn large_value_read_encrypted() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        cfg.encryption_key = Some([7u8; 32]);
        // Cache stays at default (max_size = 0, disabled). The locked
        // fallback always goes to step 3 -> read_value_from_disk_locked,
        // which routes to pread_value_encrypted under this feature gate.
        let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg).expect("open enc");

        let key = 101u64.to_be_bytes();
        let payload = build_large_payload(0xAB);
        tree.put(&key, &payload).expect("put encrypted large");
        tree.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate");

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let v = tree
            .read_value_cached(node, &guard)
            .expect("encrypted large read must succeed via pread_value_encrypted");
        assert_eq!(v.as_bytes(), payload.as_slice());
    }

    /// Deterministic stale-DiskLoc test for large values: build a large
    /// entry, capture its DiskLoc, overwrite enough to make the file fully
    /// dead, compact (removes the file), then the captured DiskLoc must
    /// surface as StaleDiskLoc via the locked fallback. The public
    /// retry path then returns the live value.
    #[test]
    fn large_value_stale_disk_loc_deterministic() {
        let dir = tempdir().unwrap();
        let tree = open_large_value_tree(dir.path());

        let key = 102u64.to_be_bytes();
        let payload = build_large_payload(0x42);
        tree.put(&key, &payload).expect("first large put");

        // Snapshot the DiskLoc of the first put — points at the file we
        // will erase via compaction.
        let snap = {
            let guard = tree.index.collector().enter();
            let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
            *node.load_disk()
        };

        // Rotate the active file so the large entry moves to an immutable file.
        tree.engine.shards()[0]
            .rotate_active_for_test(8)
            .expect("rotate after large put");

        // Overwrite many times with small payloads to move the live pointer off
        // the original file (making it 100% dead so compaction erases it).
        for i in 1..20u8 {
            tree.put(&key, &[i; 256]).expect("overwrite");
        }
        tree.put(&key, b"live-after-compaction").expect("final put");

        let shard = &tree.engine.shards()[snap.shard_id as usize];
        let _ = compact_shard(shard, &tree, 0.0).expect("compaction");

        // Direct call on the stale snapshot — must propagate StaleDiskLoc
        // through the large-value locked fallback.
        match tree.read_value_cached_inner(&snap) {
            Err(DbError::StaleDiskLoc) => {}
            Ok(v) => panic!("expected StaleDiskLoc, got Ok({:?})", v.as_bytes()),
            Err(e) => panic!("expected StaleDiskLoc, got Err({e})"),
        }

        // Public retry path picks up the live value.
        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let v = tree
            .read_value_cached(node, &guard)
            .expect("public path must retry and return live value");
        assert_eq!(v.as_bytes(), b"live-after-compaction");
    }

    /// `_result` step 2: single-block cache fast path.
    /// Writes a value, snapshots its DiskLoc, manually inserts the matching
    /// 4 KiB block into the cache, then calls `_result` and verifies the
    /// cache-hit path returns the correct bytes.
    #[test]
    fn read_value_locked_result_ok_from_cache_single_block() {
        let dir = tempdir().unwrap();
        // Enable the cache so `cache.insert` actually takes effect.
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 8192;
        cfg.write_buffer_size = 8192;
        cfg.compaction_threshold = 0.0;
        cfg.cache.max_size = 1 << 20;
        let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg).expect("open");

        let key = 9u64.to_be_bytes();
        let payload = b"small-single-block-value";
        tree.put(&key, payload).expect("put");
        // Force rotation so the entry leaves the active write buffer (otherwise
        // step 1 short-circuits and step 2 never runs). Need enough writes to
        // push write_offset past max_file_size=8192.
        for i in 100u64..135 {
            tree.put(&i.to_be_bytes(), &[i as u8; 256])
                .expect("rotator");
        }

        let guard = tree.index.collector().enter();
        let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
        let disk = *node.load_disk();
        drop(guard);

        // Sanity: this value fits in a single block (step 2 only runs when
        // start + len <= 4096).
        let start = (disk.offset & 4095) as usize;
        let len = disk.len as usize;
        assert!(
            start + len <= 4096,
            "test precondition: value must fit in a single block",
        );

        // Pre-warm the cache BEFORE acquiring the shard lock.
        // get_or_read_block → shard.read_block → sync::lock(&inner), so it
        // must not be called while the shard lock is already held.
        let block_offset = disk.offset as u64 & !4095;
        let cache_key = BlockKey {
            shard_id: disk.shard_id,
            file_id: disk.file_id,
            block_offset,
        };
        let block = tree
            .get_or_read_block(disk.shard_id, disk.file_id, block_offset)
            .expect("read block");
        tree.cache.insert(cache_key, block);
        assert!(
            tree.cache.get(&cache_key).is_some(),
            "cache must contain the block for step 2 to fire",
        );

        let shard = &tree.engine.shards()[disk.shard_id as usize];
        let inner = shard.lock();
        assert_ne!(
            disk.file_id, inner.active.file_id,
            "test setup failed: key entry is still in the active write buffer",
        );

        let v = tree
            .read_value_locked_result(&disk, &inner)
            .expect("cache-hit read must succeed");
        assert_eq!(v.as_bytes(), payload);
    }

    /// End-to-end roundtrip with file_id above u16::MAX.
    ///
    /// Uses write_buffer_size=128 KiB so a single 512-byte entry fits in one
    /// flush cycle; max_file_size=4096 forces per-entry rotation; cache
    /// enabled so the fast path is also exercised.  After bumping
    /// next_file_id to 70_000 and rotating, the active file gets an id that
    /// exceeds u16::MAX.  The entry is flushed + rotated to make it
    /// immutable, then `get` must return the correct bytes via the locked
    /// disk-read path.  Before the file_id u32 widening this would either
    /// panic or return wrong bytes because the high bits were truncated.
    #[test]
    fn var_tree_get_with_file_id_above_u16() {
        let dir = tempdir().unwrap();
        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        cfg.cache.max_size = 1 << 20;
        let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg).expect("open");

        let shard = &tree.engine.shards()[0];

        // Bump file id well past u16::MAX and rotate so the next active file
        // carries the new id.
        shard.set_next_file_id(70_000);
        shard.rotate_active_for_test(8).expect("first rotate");
        assert!(
            shard.active_file_id() >= 70_000,
            "active_file_id should be >= 70_000 after rotation"
        );

        let key = 42u64.to_be_bytes();
        let value = vec![0xC3u8; 512];
        tree.put(&key, &value).expect("put");

        // Confirm the DiskLoc has file_id > u16::MAX.
        {
            let guard = tree.index.collector().enter();
            let node = tree.index.get(key.as_bytes(), &guard).expect("indexed");
            let disk = *node.load_disk();
            assert!(
                disk.file_id > u16::MAX as u32,
                "DiskLoc.file_id must be above u16::MAX, got {}",
                disk.file_id,
            );
        }

        // Flush the write buffer and rotate so the entry lands on an
        // immutable file — reads will go through Shard::read_block.
        shard.flush().expect("flush");
        shard.rotate_active_for_test(8).expect("second rotate");

        let got = tree.get(&key).expect("get must return Some");
        assert_eq!(got.as_bytes(), value.as_slice());
    }

    /// Recovery roundtrip with file_id above u16::MAX.
    ///
    /// Phase A: open, bump next_file_id past u16::MAX, rotate once (so the
    /// active file gets an id > 65535), write entries, close.  `close()` calls
    /// `sync_hints()` which flushes the write buffer and writes the hint file
    /// with the correct key length (8), then `engine.flush()` fsyncs.
    /// Phase B: reopen from the same tempdir, read every entry back, confirm
    /// at least one on-disk file_id still exceeds u16::MAX.
    ///
    /// Before the file_id u32 widening the high bits were truncated during
    /// hint-file serialization and recovery; this test pins that code path so
    /// a future regression cannot go undetected.
    #[test]
    fn recovery_handles_file_id_above_u16() {
        let dir = tempdir().unwrap();

        let mut cfg = Config::test();
        cfg.shard_count = 1;
        cfg.max_file_size = 128 * 1024;
        cfg.write_buffer_size = 128 * 1024;
        cfg.compaction_threshold = 0.0;
        cfg.cache.max_size = 1 << 20;

        // --- Phase A: open, bump file_id past u16, write, close ---
        {
            let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg.clone()).expect("open A");
            let shard = &tree.engine.shards()[0];

            // Bump the id counter and rotate so the active file gets id 70_000.
            shard.set_next_file_id(70_000);
            shard
                .rotate_active_for_test(8)
                .expect("rotate to file_id 70_000");
            assert!(
                shard.active_file_id() >= 70_000,
                "active_file_id should be >= 70_000 after rotation"
            );

            for i in 0u64..4 {
                let key = i.to_be_bytes();
                let value = vec![i as u8; 200];
                tree.put(&key, &value).expect("put phase A");
            }

            tree.close().expect("close phase A");
        }

        // --- Phase B: reopen, read entries, assert wide file_id persists ---
        {
            let tree: VarTree<[u8; 8]> = VarTree::open(dir.path(), cfg).expect("open B");

            assert_eq!(tree.len(), 4, "all 4 entries must survive recovery");

            for i in 0u64..4 {
                let key = i.to_be_bytes();
                let expected = vec![i as u8; 200];
                let got = tree
                    .get(&key)
                    .unwrap_or_else(|| panic!("key {i} not found after recovery"));
                assert_eq!(
                    got.as_bytes(),
                    expected.as_slice(),
                    "value mismatch for key {i} after recovery"
                );
            }

            // Verify at least one on-disk file_id exceeded u16::MAX so that
            // the test actually exercises the wide-id path.
            let shard = &tree.engine.shards()[0];
            let max_fid = shard.file_ids().into_iter().max().expect("non-empty");
            assert!(
                max_fid > u16::MAX as u32,
                "max file_id should exceed u16::MAX after recovery (got {})",
                max_fid
            );
        }
    }
}