pagedb 0.1.0-beta.6

Encrypted, portable, embedded page store with B+ tree and segment-file surfaces.
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
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
//! Integration tests for snapshot_to / restore_from / promote_to_follower /
//! apply_incremental / snapshot_incremental_to.

use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

use crate::options::RetainPolicy;
use crate::snapshot::export::{
    SnapshotManifest, decode_manifest, derive_snapshot_hk_key, encode_manifest, open_manifest,
};
use crate::txn::db::VisibilityTestHook;
use crate::vfs::tokio_backend::{TokioFile, TokioLockHandle, TokioVfs};
use crate::vfs::{OpenMode, ReadReq, Vfs, VfsFile, WriteReq};
use crate::{
    ApplyStats, CommitId, Db, DbMode, OpenOptions, PagedbError, RealmId, SegmentKind,
    SegmentPageKind, SnapshotStats, run_deep_walk,
};

const PAGE: usize = 4096;
const KEK: [u8; 32] = [7u8; 32];
const REALM: RealmId = RealmId::new([1u8; 16]);

fn tempdir() -> std::path::PathBuf {
    tempfile::Builder::new()
        .prefix("pagedb-snap-")
        .tempdir()
        .unwrap()
        .keep()
}

async fn make_db(root: &std::path::Path) -> Db<TokioVfs> {
    let vfs = TokioVfs::new(root);
    Db::open(vfs, KEK, PAGE, REALM, OpenOptions::default())
        .await
        .unwrap()
}

/// A `TokioVfs` whose renames can be made to fail, per destination class.
///
/// An apply renames twice: once to swap its staged image over `main.db` — its
/// commit point — and once per segment during journal replay, which is only
/// reachable when that swap already succeeded. The two are separately
/// selectable so a test can name the boundary it is interrupting.
#[derive(Clone)]
struct RenameFaultVfs {
    inner: TokioVfs,
    fail_renames: Arc<AtomicBool>,
    fail_main_db_renames: Arc<AtomicBool>,
}

impl RenameFaultVfs {
    fn new(root: &std::path::Path) -> Self {
        Self {
            inner: TokioVfs::new(root),
            fail_renames: Arc::new(AtomicBool::new(false)),
            fail_main_db_renames: Arc::new(AtomicBool::new(false)),
        }
    }

    fn fail_renames(&self, fail: bool) {
        self.fail_renames.store(fail, Ordering::SeqCst);
    }

    fn fail_main_db_renames(&self, fail: bool) {
        self.fail_main_db_renames.store(fail, Ordering::SeqCst);
    }
}

impl Vfs for RenameFaultVfs {
    type File = TokioFile;
    type LockHandle = TokioLockHandle;

    async fn open(&self, path: &str, mode: OpenMode) -> crate::Result<Self::File> {
        self.inner.open(path, mode).await
    }

    async fn remove(&self, path: &str) -> crate::Result<()> {
        self.inner.remove(path).await
    }

    async fn rename(&self, from: &str, to: &str) -> crate::Result<()> {
        let destination = to.trim_start_matches('/');
        let refused = (destination.starts_with("seg/") && self.fail_renames.load(Ordering::SeqCst))
            || (destination == "main.db" && self.fail_main_db_renames.load(Ordering::SeqCst));
        if refused {
            return Err(PagedbError::Io(std::io::Error::other(
                "injected persistent rename failure",
            )));
        }
        self.inner.rename(from, to).await
    }

    async fn list_dir(&self, path: &str) -> crate::Result<Vec<String>> {
        self.inner.list_dir(path).await
    }

    async fn mkdir_all(&self, path: &str) -> crate::Result<()> {
        self.inner.mkdir_all(path).await
    }

    async fn sync_dir(&self, path: &str) -> crate::Result<()> {
        self.inner.sync_dir(path).await
    }

    async fn lock_exclusive(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_exclusive(path).await
    }

    async fn lock_shared(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_shared(path).await
    }

    fn root_path(&self) -> Option<&std::path::Path> {
        Some(self.inner.root_path())
    }
}

async fn make_db_with_options(root: &std::path::Path, options: OpenOptions) -> Db<TokioVfs> {
    let vfs = TokioVfs::new(root);
    Db::open(vfs, KEK, PAGE, REALM, options).await.unwrap()
}

fn hex_lower(bytes: &[u8; 16]) -> String {
    use std::fmt::Write as _;

    let mut out = String::with_capacity(32);
    for byte in bytes {
        write!(&mut out, "{byte:02x}").unwrap();
    }
    out
}

fn create_stale_snapshot_sidecar(snapshot_dir: &std::path::Path) {
    let stale_seg_dir = snapshot_dir.join("seg");
    std::fs::create_dir_all(&stale_seg_dir).unwrap();
    std::fs::write(
        stale_seg_dir.join("00000000000000000000000000000001"),
        b"stale",
    )
    .unwrap();
}

#[derive(Clone)]
struct FailStagingSyncTokioVfs {
    inner: TokioVfs,
    fail_staging_sync: Arc<AtomicBool>,
}

impl FailStagingSyncTokioVfs {
    fn new(root: impl Into<std::path::PathBuf>) -> Self {
        Self {
            inner: TokioVfs::new(root),
            fail_staging_sync: Arc::new(AtomicBool::new(false)),
        }
    }

    fn fail_next_staging_sync(&self) {
        self.fail_staging_sync.store(true, Ordering::SeqCst);
    }
}

impl Vfs for FailStagingSyncTokioVfs {
    type File = TokioFile;
    type LockHandle = TokioLockHandle;

    async fn open(&self, path: &str, mode: OpenMode) -> crate::Result<Self::File> {
        self.inner.open(path, mode).await
    }

    async fn remove(&self, path: &str) -> crate::Result<()> {
        self.inner.remove(path).await
    }

    async fn rename(&self, from: &str, to: &str) -> crate::Result<()> {
        self.inner.rename(from, to).await
    }

    async fn list_dir(&self, path: &str) -> crate::Result<Vec<String>> {
        self.inner.list_dir(path).await
    }

    async fn mkdir_all(&self, path: &str) -> crate::Result<()> {
        self.inner.mkdir_all(path).await
    }

    async fn sync_dir(&self, path: &str) -> crate::Result<()> {
        if path == "seg/.staging" && self.fail_staging_sync.swap(false, Ordering::SeqCst) {
            return Err(PagedbError::Io(std::io::Error::other(
                "injected staging sync fault",
            )));
        }
        self.inner.sync_dir(path).await
    }

    async fn lock_exclusive(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_exclusive(path).await
    }

    async fn lock_shared(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_shared(path).await
    }

    fn root_path(&self) -> Option<&std::path::Path> {
        Some(self.inner.root_path())
    }
}

#[test]
fn tempdir_helper_allocates_unique_roots() {
    let dirs: Vec<_> = (0..128).map(|_| tempdir()).collect();
    let mut paths = dirs.clone();
    paths.sort();
    paths.dedup();
    assert_eq!(paths.len(), dirs.len());

    for dir in dirs {
        std::fs::remove_dir_all(dir).ok();
    }
}

// ---------------------------------------------------------------------------
// Test 1: full snapshot then restore reads data back.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn full_snapshot_then_restore_reads_data() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"key1", b"value1").await.unwrap();
        t.put(b"key2", b"value2").await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert!(stats.bytes > 0);

    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    assert_eq!(restored.mode(), DbMode::ReadOnly);

    let rtxn = restored.begin_read().await.unwrap();
    let v1 = rtxn.get(b"key1").await.unwrap();
    let v2 = rtxn.get(b"key2").await.unwrap();
    assert_eq!(v1.as_deref(), Some(b"value1" as &[u8]));
    assert_eq!(v2.as_deref(), Some(b"value2" as &[u8]));

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 2: restore yields a ReadOnly Db; begin_write returns ReadOnly error.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_yields_readonly_db() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db_with_options(
        &src_dir,
        OpenOptions::default().with_commit_history_retain(RetainPolicy::Unbounded),
    )
    .await;
    db.snapshot_to(&snap_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    assert_eq!(restored.mode(), DbMode::ReadOnly);

    // begin_write must be refused, naming the mode that would have served it.
    let err = restored.begin_write().await.err().unwrap();
    assert!(
        matches!(
            err,
            PagedbError::WrongMode {
                operation: "begin_write",
                required: DbMode::Standalone,
                actual: DbMode::ReadOnly,
            }
        ),
        "expected WrongMode naming Standalone, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 3: restore_from rejects corrupt active-root main.db pages.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_corrupt_active_root_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&snap_dir).await.unwrap();

    let manifest = open_manifest(&snap_dir.join("manifest"), &KEK)
        .await
        .unwrap();
    assert_ne!(
        manifest.target_active_root_page_id, 0,
        "test setup must produce a non-empty active tree"
    );
    let main_path = snap_dir.join("main.db");
    let mut bytes = std::fs::read(&main_path).unwrap();
    let corrupt_at = manifest.target_active_root_page_id as usize * PAGE + 128;
    assert!(
        bytes.len() > corrupt_at,
        "test setup must include the active root page in full snapshot main.db"
    );
    bytes[corrupt_at] ^= 0xFF;
    std::fs::write(&main_path, bytes).unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject corrupt active-root pages"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected page authentication failure, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 4: failed restore leaves the destination reusable.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_failure_leaves_destination_reusable() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&snap_dir).await.unwrap();

    let manifest = open_manifest(&snap_dir.join("manifest"), &KEK)
        .await
        .unwrap();
    let main_path = snap_dir.join("main.db");
    let original_main = std::fs::read(&main_path).unwrap();
    let mut corrupt_main = original_main.clone();
    let corrupt_at = manifest.target_active_root_page_id as usize * PAGE + 128;
    assert!(
        corrupt_main.len() > corrupt_at,
        "test setup must include the active root page in full snapshot main.db"
    );
    corrupt_main[corrupt_at] ^= 0xFF;
    std::fs::write(&main_path, corrupt_main).unwrap();

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("corrupt snapshot must fail restore"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected page authentication failure, got {err:?}"
    );

    std::fs::write(&main_path, original_main).unwrap();
    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .expect("failed restore must leave the destination reusable");
    let rtxn = restored.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    drop(rtxn);
    drop(restored);
    drop(db);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 5: restore_from rejects non-empty destination directories.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_non_empty_destination() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&snap_dir).await.unwrap();
    drop(db);

    let stale_seg = dst_dir.join("seg");
    std::fs::create_dir_all(&stale_seg).unwrap();
    std::fs::write(stale_seg.join("00000000000000000000000000000000"), b"stale").unwrap();

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject a non-empty destination"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(_)),
        "expected Io for non-empty destination, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 5: restore_from rejects a manifest whose root fields do not match main.db.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_manifest_active_root_mismatch() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&snap_dir).await.unwrap();

    let manifest_path = snap_dir.join("manifest");
    let mut manifest = open_manifest(&manifest_path, &KEK).await.unwrap();
    assert_ne!(
        manifest.target_active_root_page_id, 0,
        "test setup must produce a non-empty active tree"
    );
    let hk_key = derive_snapshot_hk_key(&KEK, &manifest.kek_salt, manifest.mk_epoch).unwrap();
    manifest.target_active_root_page_id = 0;
    std::fs::write(manifest_path, encode_manifest(&manifest, &hk_key)).unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject manifest/header root mismatch"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_)
                | PagedbError::SnapshotIncompatible {
                    field: "target_active_root_page_id"
                }
        ),
        "expected identity/corruption failure for manifest/header mismatch, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 6: restore_from rejects an incremental snapshot manifest.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_incremental_snapshot_manifest() {
    let src_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"later", b"value").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&delta_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject an incremental snapshot manifest"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_) | PagedbError::SnapshotIncompatible { field: "kind" }
        ),
        "expected Corruption for incremental snapshot manifest, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_manifest_with_trailing_bytes() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&snap_dir).await.unwrap();

    let manifest_path = snap_dir.join("manifest");
    let mut bytes = std::fs::read(&manifest_path).unwrap();
    bytes.push(0xAA);
    std::fs::write(&manifest_path, bytes).unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject non-canonical manifest length"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for manifest trailing bytes, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 4: promote_to_follower allows applying a real incremental.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn promote_to_follower_allows_apply() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut txn = db.begin_write().await.unwrap();
        txn.put(b"base", b"before-snapshot").await.unwrap();
        txn.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    // Advance the source after the full snapshot and export c1 -> c2.
    {
        let mut txn = db.begin_write().await.unwrap();
        txn.put(b"changed", b"after-snapshot").await.unwrap();
        txn.commit().await.unwrap();
    }
    let c2 = db.latest_commit();
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();

    let follower = restored.promote_to_follower().await.unwrap();
    assert_eq!(follower.mode(), DbMode::Follower);
    assert!(follower.can_apply_incremental());

    let stats = follower.apply_incremental(&delta_dir).await.unwrap();
    assert!(stats.pages_applied > 0);
    assert_eq!(follower.latest_commit(), c2);

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"changed").await.unwrap().as_deref(),
        Some(b"after-snapshot".as_slice())
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

/// An incremental apply seals the follower's own relocated metadata into the
/// staged image and writes no header until the swap, so — like a compaction
/// rebuild — that whole run draws nonces from one anchor window.
///
/// The delta pages are copied verbatim and cost no nonces, so the only thing
/// that makes this path consume any is the follower's own bookkeeping:
/// `stage_reclaimed_free_list` rewrites the *complete* chain, one page per 252
/// entries, and its entry set is `base-reader-visible − target-reachable`. A
/// fixture whose target still reaches everything the base did therefore reclaims
/// nothing and seals a single page — which an unbounded implementation would
/// pass just as happily. So the source deletes the bulk of an overflow-backed
/// tree between the base and the target: ~1500 pages that were live at the base
/// and are not live at the target, which is six-plus chain pages the follower
/// must seal in one flush.
///
/// The assertion is that the anchor ends more than a whole budget above where it
/// started. One window carries at most `budget` nonces, so nothing but a refresh
/// *during* the apply can satisfy it — widening the window cannot.
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_is_not_bounded_by_the_anchor_budget() {
    const BUDGET: u64 = 2;
    const ROWS: u32 = 1600;
    const KEPT: u32 = 100;
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    // Values above a quarter page each take an overflow page, so the base tree
    // is roughly one page per row — the supply the deletion below turns into
    // reclaimed ids.
    let spilled = vec![0xA7u8; 3000];
    for chunk in 0..4u32 {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0..(ROWS / 4) {
            txn.put(
                format!("row-{:05}", chunk * (ROWS / 4) + index).as_bytes(),
                &spilled,
            )
            .await
            .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let base = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    // Everything dropped here is a page the base commit reached and the target
    // does not, which is exactly the follower's reclaim set.
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in KEPT..ROWS {
            txn.delete(format!("row-{index:05}").as_bytes())
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let target = db.latest_commit();
    db.snapshot_incremental_to(base, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(
        &snap_dir,
        &dst_dir,
        OpenOptions::default().with_anchor_budget(BUDGET),
        KEK,
    )
    .await
    .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let before = follower.pager.durable_anchor();
    follower
        .apply_incremental(&delta_dir)
        .await
        .expect("an apply must not be bounded by the anchor budget");
    let after = follower.pager.durable_anchor();
    assert_eq!(follower.latest_commit(), target);
    assert!(
        after > before.saturating_add(BUDGET),
        "the staging flush must advance the anchor past a whole window; it moved \
         from {before} to {after} with a budget of {BUDGET}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"row-00000").await.unwrap().as_deref(),
        Some(spilled.as_slice()),
        "a surviving row must read back after the apply"
    );
    assert!(
        rtxn.get(b"row-01599").await.unwrap().is_none(),
        "a deleted row must not survive the apply"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

/// A writer that recycles pages between the base and target commits still
/// produces an applicable delta.
///
/// Page reuse is the steady state of the free-list design, not an edge case: the
/// reclamation floor exists so freed pages come back. A page id below the base
/// commit's allocation cursor therefore proves nothing on its own — what matters
/// is whether the page was *live* at the base. Treating the cursor as a liveness
/// boundary rejects healthy snapshots from any database that has ever deleted
/// anything, which is why this walks a full delete-and-refill cycle rather than
/// only appending.
#[tokio::test(flavor = "current_thread")]
async fn incremental_round_trip_survives_page_reuse_below_the_base_cursor() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;

    // Grow the tree well past a single page, so deleting most of it frees
    // interior pages rather than just trimming one leaf.
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0u16..512 {
            txn.put(format!("reuse-{index:04}").as_bytes(), &[index as u8; 64])
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    // Free most of those pages. They stay on the durable free list, below the
    // allocation cursor the base commit will record.
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0u16..480 {
            txn.delete(format!("reuse-{index:04}").as_bytes())
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let base = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    // Refill. The allocator draws from the free list, so the target tree is
    // reachable through pages whose ids sit below `base`'s cursor.
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0u16..480 {
            txn.put(format!("refill-{index:04}").as_bytes(), &[0xC7; 64])
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let target = db.latest_commit();
    let base_next_page_id = {
        let txn = db.begin_read_at(base).await.unwrap();
        txn.next_page_id()
    };

    db.snapshot_incremental_to(base, &delta_dir)
        .await
        .expect("page reuse below the base cursor must still export");
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    let stats = follower
        .apply_incremental(&delta_dir)
        .await
        .expect("a delta carrying recycled page ids must still apply");
    assert!(stats.pages_applied > 0);
    assert_eq!(follower.latest_commit(), target);

    // The scenario is only meaningful if reuse actually happened; otherwise this
    // silently degrades into the append-only case the other tests already cover.
    let rtxn = follower.begin_read().await.unwrap();
    assert!(
        rtxn.next_page_id() <= base_next_page_id.saturating_add(64),
        "expected the refill to recycle freed pages rather than extend the file: \
         base cursor {base_next_page_id}, target cursor {}",
        rtxn.next_page_id()
    );
    for index in 0u16..480 {
        assert_eq!(
            rtxn.get(format!("refill-{index:04}").as_bytes())
                .await
                .unwrap()
                .as_deref(),
            Some([0xC7; 64].as_slice()),
            "refilled key {index} missing after apply"
        );
        assert_eq!(
            rtxn.get(format!("reuse-{index:04}").as_bytes())
                .await
                .unwrap(),
            None,
            "deleted key {index} came back after apply"
        );
    }

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_surfaces_staging_dir_sync_failure_then_retry_succeeds() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"stable").await.unwrap();
        t.commit().await.unwrap();
    }
    let base = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    let meta = {
        let mut s = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        s.append_page(SegmentPageKind::Data, b"post-base segment")
            .await
            .unwrap();
        s.seal().await.unwrap()
    };
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("post-base.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(base, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    drop(restored);

    let vfs = FailStagingSyncTokioVfs::new(&dst_dir);
    let restored = Db::open_read_only(vfs.clone(), KEK, PAGE, REALM, OpenOptions::default())
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    vfs.fail_next_staging_sync();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must surface failed staging directory syncs");
    assert!(
        matches!(err, PagedbError::Io(_)),
        "expected staging sync I/O error, got {err:?}"
    );
    assert_eq!(
        follower.latest_commit(),
        base,
        "failed staging sync must leave the follower on the base commit"
    );
    {
        let rtxn = follower.begin_read().await.unwrap();
        assert_eq!(
            rtxn.get(b"base").await.unwrap().as_deref(),
            Some(b"stable" as &[u8])
        );
        assert!(
            rtxn.open_segment("post-base.seg").await.is_err(),
            "failed apply must not expose the target segment"
        );
    }

    let stats = follower
        .apply_incremental(&delta_dir)
        .await
        .expect("retry after transient staging sync fault must succeed");
    assert_eq!(stats.segments_promoted, 1);
    assert!(
        follower.latest_commit() > base,
        "successful retry must advance the follower commit"
    );
    let rtxn = follower.begin_read().await.unwrap();
    let reader = rtxn.open_segment("post-base.seg").await.unwrap();
    let page = reader.read_page(1).await.unwrap();
    assert!(page.starts_with(b"post-base segment"));

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 5: incremental carries only changed pages.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn incremental_carries_only_changed_pages() {
    let src_dir = tempdir();
    let snap1_dir = tempdir();
    let snap2_dir = tempdir();

    let db = make_db_with_options(
        &src_dir,
        OpenOptions::default().with_commit_history_retain(RetainPolicy::Unbounded),
    )
    .await;
    // Write a small base that does not create free pages before the base
    // cursor; reused below-base pages are covered by the dedicated rejection
    // regression below.
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"key000", b"init").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    let full_stats: SnapshotStats = db.snapshot_to(&snap1_dir).await.unwrap();

    // Write more data to advance the commit.
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new000", b"added").await.unwrap();
        t.commit().await.unwrap();
    }

    let inc_stats: SnapshotStats = db.snapshot_incremental_to(c1, &snap2_dir).await.unwrap();

    // Incremental should have fewer pages than the full snapshot.
    assert!(
        inc_stats.pages_written < full_stats.pages_written,
        "incremental pages {} should be < full pages {}",
        inc_stats.pages_written,
        full_stats.pages_written
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap1_dir).ok();
    std::fs::remove_dir_all(&snap2_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 6: incremental snapshots require a readable base commit.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn incremental_snapshot_rejects_missing_base_commit() {
    let src_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }

    let missing_base = CommitId::new(99);
    let err = db
        .snapshot_incremental_to(missing_base, &delta_dir)
        .await
        .expect_err("incremental snapshots must reject an unreadable base commit");
    assert!(
        matches!(err, PagedbError::CommitGone { .. }),
        "expected CommitGone for missing base commit, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 7: apply_incremental advances commit and data matches.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_advances_commit() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    // Write initial data.
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    // Write more data after c1.
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    let c2 = db.latest_commit();

    // Incremental from c1 to c2.
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    // Restore and promote.
    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    // Apply incremental.
    let _stats: ApplyStats = follower.apply_incremental(&delta_dir).await.unwrap();

    // The follower's latest_commit should equal c2 after applying.
    let follower_commit = follower.latest_commit();
    assert_eq!(follower_commit, c2, "follower commit should match c2");

    // The applied delta must advance the data tree: the key written after the
    // base snapshot is now readable, and the base key still resolves.
    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"new_key").await.unwrap().as_deref(),
        Some(b"new_val".as_slice()),
        "incrementally-applied key must be readable on the follower"
    );
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice()),
        "base key must survive the incremental apply"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 8: apply_incremental rejects a delta when the follower is past its base.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_delta_when_follower_not_at_base_commit() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    follower.apply_incremental(&delta_dir).await.unwrap();
    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject a delta whose base is not the follower commit");
    assert!(
        matches!(
            err,
            PagedbError::SnapshotIncompatible {
                field: "base_commit"
            }
        ),
        "expected a base-commit identity failure, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn incremental_snapshot_rejects_missing_changed_main_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }

    std::fs::OpenOptions::new()
        .write(true)
        .open(src_dir.join("main.db"))
        .unwrap()
        .set_len((PAGE * 2) as u64)
        .unwrap();

    let err = db
        .snapshot_incremental_to(c1, &delta_dir)
        .await
        .expect_err("incremental snapshot must reject missing changed main.db pages");
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::UnexpectedEof),
        "expected UnexpectedEof for missing changed main page, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

/// Export succeeds when the target reaches pages below the base allocation
/// cursor, and actually ships them.
///
/// The cursor is an allocation watermark, not a liveness boundary. A page that
/// was on the free list at the base commit is legitimately reallocated for the
/// target, and shipping it is safe precisely because nothing reachable from the
/// base points at it. Rejecting on the cursor would make incremental snapshots
/// unusable for any database that has ever deleted anything.
///
/// The complementary end-to-end case — that such a delta also *applies* — is
/// `incremental_round_trip_survives_page_reuse_below_the_base_cursor`.
#[tokio::test(flavor = "current_thread")]
async fn incremental_snapshot_exports_reused_pages_below_base_cursor() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();

    let options = OpenOptions::default().with_commit_history_retain(RetainPolicy::Count(2));
    let db = make_db_with_options(&src_dir, options.clone()).await;
    {
        let mut t = db.begin_write().await.unwrap();
        for i in 0u32..48 {
            t.put(format!("old-{i:03}").as_bytes(), &vec![i as u8; PAGE * 2])
                .await
                .unwrap();
        }
        t.commit().await.unwrap();
    }
    {
        let mut t = db.begin_write().await.unwrap();
        for i in 0u32..48 {
            t.delete(format!("old-{i:03}").as_bytes()).await.unwrap();
        }
        t.commit().await.unwrap();
    }
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base-marker", b"retained").await.unwrap();
        t.commit().await.unwrap();
    }
    let base = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    let new_value = vec![0xC7; PAGE * 2];
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"reused-after-base", &new_value).await.unwrap();
        t.commit().await.unwrap();
    }
    let base_next_page_id = {
        let txn = db.begin_read_at(base).await.unwrap();
        txn.next_page_id()
    };
    let stats = db
        .snapshot_incremental_to(base, &delta_dir)
        .await
        .expect("reused pages below the base cursor must still export");
    assert!(stats.pages_written > 0);

    // Prove the scenario is the intended one: at least one shipped record names
    // a page id below the base cursor. Without this the test would still pass on
    // an implementation that only ever appends.
    let delta = std::fs::read(delta_dir.join("pages.delta")).unwrap();
    let record_size = 8 + PAGE;
    assert_eq!(delta.len() % record_size, 0, "delta must be whole records");
    let recycled = delta
        .chunks_exact(record_size)
        .map(|record| u64::from_be_bytes(record[..8].try_into().unwrap()))
        .filter(|page_id| *page_id < base_next_page_id)
        .count();
    assert!(
        recycled > 0,
        "expected the refill to recycle freed pages below the base cursor \
         ({base_next_page_id}); the delta shipped none"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 9: apply_incremental rejects a truncated delta stream.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_truncated_delta_stream() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }

    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    let delta_path = delta_dir.join("pages.delta");
    assert!(
        std::fs::metadata(&delta_path).unwrap().len() > 8,
        "test setup must produce a non-empty delta stream"
    );
    std::fs::write(&delta_path, [0xAA]).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject a truncated delta stream");
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for truncated delta stream, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    assert_eq!(rtxn.get(b"new_key").await.unwrap().as_deref(), None);
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 9: apply_incremental rejects delta records for header pages.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_header_page_delta_record() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let mut delta = Vec::with_capacity(8 + PAGE);
    delta.extend_from_slice(&0u64.to_be_bytes());
    delta.extend_from_slice(&vec![0xAA; PAGE]);
    std::fs::write(delta_dir.join("pages.delta"), delta).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject header-page delta records");
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for header-page delta record, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 10: apply_incremental rejects delta records beyond the target page range.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_delta_record_at_target_next_page_id() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let manifest = std::fs::read(delta_dir.join("manifest")).unwrap();
    let target_next_page_id = u64::from_le_bytes(manifest[74..82].try_into().unwrap());
    let mut delta = Vec::with_capacity(8 + PAGE);
    delta.extend_from_slice(&target_next_page_id.to_be_bytes());
    delta.extend_from_slice(&vec![0xAA; PAGE]);
    std::fs::write(delta_dir.join("pages.delta"), delta).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject out-of-range delta records");
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for out-of-range delta record, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 11: apply_incremental rejects delta records below the base next-page id.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
/// A delta record naming a page the base still holds live is refused, and the
/// refusal leaves the base intact.
///
/// The injected id is the base snapshot's own active root — a page the follower
/// is still reading through. What makes it inadmissible is that it is base-live,
/// not that it sorts below some allocation cursor: recycled ids below that
/// cursor are ordinary and are covered by
/// `incremental_snapshot_exports_reused_pages_below_base_cursor`.
async fn apply_incremental_refuses_to_overwrite_a_base_live_page_without_mutating_base() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();
    let base_manifest = open_manifest(&snap_dir.join("manifest"), &KEK)
        .await
        .unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let stale_page_id = base_manifest.target_active_root_page_id;
    assert!(
        stale_page_id >= 2 && stale_page_id < base_manifest.next_page_id_at_target,
        "test setup needs an existing non-header base page"
    );
    let delta_path = delta_dir.join("pages.delta");
    let original_delta = std::fs::read(&delta_path).unwrap();
    let mut malicious_delta = Vec::with_capacity(original_delta.len() + 8 + PAGE);
    malicious_delta.extend_from_slice(&stale_page_id.to_be_bytes());
    malicious_delta.extend_from_slice(&vec![0xAA; PAGE]);
    malicious_delta.extend_from_slice(&original_delta);
    std::fs::write(&delta_path, malicious_delta).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must refuse to overwrite a base-live page");
    assert!(
        matches!(
            err,
            PagedbError::SnapshotBasePageReused { page_id } if page_id == stale_page_id
        ),
        "expected SnapshotBasePageReused naming page {stale_page_id}, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    let base = rtxn
        .get(b"base")
        .await
        .expect("failed apply must not corrupt existing base pages");
    assert_eq!(base.as_deref(), Some(b"data".as_slice()));
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 12: apply_incremental rejects duplicate delta records.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_duplicate_delta_page_records() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let delta_path = delta_dir.join("pages.delta");
    let original_delta = std::fs::read(&delta_path).unwrap();
    assert!(
        original_delta.len() >= 8 + PAGE,
        "test setup must produce at least one delta page"
    );
    let duplicate_page_id = u64::from_be_bytes(original_delta[..8].try_into().unwrap());
    let mut duplicated_delta = Vec::with_capacity(original_delta.len() + 8 + PAGE);
    duplicated_delta.extend_from_slice(&original_delta);
    duplicated_delta.extend_from_slice(&duplicate_page_id.to_be_bytes());
    duplicated_delta.extend_from_slice(&vec![0xAA; PAGE]);
    std::fs::write(delta_path, duplicated_delta).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject duplicate delta records");
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for duplicate delta record, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 12: apply_incremental rejects corrupt target active-root delta pages.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_corrupt_target_active_root_delta_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let manifest = std::fs::read(delta_dir.join("manifest")).unwrap();
    let target_active_root_page_id = u64::from_le_bytes(manifest[102..110].try_into().unwrap());
    let delta_path = delta_dir.join("pages.delta");
    let mut delta = std::fs::read(&delta_path).unwrap();
    let record_len = 8 + PAGE;
    let mut corrupted = false;
    for record in delta.chunks_exact_mut(record_len) {
        let page_id = u64::from_be_bytes(record[..8].try_into().unwrap());
        if page_id == target_active_root_page_id {
            record[8 + 128] ^= 0xFF;
            corrupted = true;
            break;
        }
    }
    assert!(
        corrupted,
        "test setup must include target active root page {target_active_root_page_id} in pages.delta"
    );
    std::fs::write(&delta_path, delta).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject corrupt target active-root delta pages");
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected page authentication failure, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    assert_eq!(
        rtxn.get(b"new_key").await.unwrap().as_deref(),
        None,
        "failed incremental apply must not advance the active root"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 12: apply_incremental rejects a full snapshot manifest.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_full_snapshot_manifest() {
    let src_dir = tempdir();
    let base_snap_dir = tempdir();
    let full_snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&base_snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"later", b"value").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_to(&full_snap_dir).await.unwrap();
    drop(db);

    let restored =
        Db::<TokioVfs>::restore_from(&base_snap_dir, &dst_dir, OpenOptions::default(), KEK)
            .await
            .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&full_snap_dir)
        .await
        .expect_err("apply_incremental must reject a full snapshot manifest");
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_) | PagedbError::SnapshotIncompatible { field: "kind" }
        ),
        "expected Corruption for full snapshot manifest, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&base_snap_dir).ok();
    std::fs::remove_dir_all(&full_snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_manifest_with_trailing_bytes() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"later", b"value").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let manifest_path = delta_dir.join("manifest");
    let mut bytes = std::fs::read(&manifest_path).unwrap();
    bytes.push(0xAA);
    std::fs::write(&manifest_path, bytes).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject non-canonical manifest length");
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for manifest trailing bytes, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 13: apply_incremental rejects a correctly MACed wrong-realm manifest.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_wrong_realm_manifest() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let manifest_path = delta_dir.join("manifest");
    let mut manifest = open_manifest(&manifest_path, &KEK).await.unwrap();
    let hk_key = derive_snapshot_hk_key(&KEK, &manifest.kek_salt, manifest.mk_epoch).unwrap();
    manifest.realm_id = [2u8; 16];
    std::fs::write(manifest_path, encode_manifest(&manifest, &hk_key)).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject a wrong-realm incremental manifest");
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_) | PagedbError::SnapshotIncompatible { field: "realm_id" }
        ),
        "expected identity failure for wrong-realm manifest, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    assert_eq!(
        rtxn.get(b"new_key").await.unwrap().as_deref(),
        None,
        "failed incremental apply must not advance the active root"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 13: apply_incremental rejects target commits that do not advance.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_non_advancing_target_commit() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();

    let manifest_path = delta_dir.join("manifest");
    let mut manifest = open_manifest(&manifest_path, &KEK).await.unwrap();
    let hk_key = derive_snapshot_hk_key(&KEK, &manifest.kek_salt, manifest.mk_epoch).unwrap();
    manifest.target_commit = manifest.base_commit;
    std::fs::write(manifest_path, encode_manifest(&manifest, &hk_key)).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject non-advancing target commits");
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_)
                | PagedbError::SnapshotIncompatible {
                    field: "target_commit"
                }
        ),
        "expected identity/corruption failure for non-advancing target commit, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    assert_eq!(
        rtxn.get(b"new_key").await.unwrap().as_deref(),
        None,
        "failed incremental apply must not install new content under the base commit id"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 14: standalone db calling apply_incremental is refused as a wrong mode.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_on_standalone() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    db.snapshot_to(&snap_dir).await.unwrap();

    let err = db.apply_incremental(&snap_dir).await.err().unwrap();
    assert!(
        matches!(
            err,
            PagedbError::WrongMode {
                operation: "apply_incremental",
                required: DbMode::Follower,
                actual: DbMode::Standalone,
            }
        ),
        "expected WrongMode naming Follower, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 14: snapshot includes segments; restored db can read segment.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_includes_segments() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        let meta = w.seal().await.unwrap();
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("my.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let rtxn = restored.begin_read().await.unwrap();
    let reader = rtxn.open_segment("my.seg").await.unwrap();
    let page = reader.read_page(1).await.unwrap();
    assert!(page.starts_with(b"seg-content"));

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 15: snapshot_to rejects a catalog segment whose file is missing.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_to_rejects_missing_catalog_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    let meta = {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        w.seal().await.unwrap()
    };
    let segment_path = src_dir.join("seg").join(hex_lower(&meta.segment_id));
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("missing-source.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }
    assert!(
        segment_path.is_file(),
        "test setup must create the linked live segment file"
    );
    std::fs::remove_file(&segment_path).unwrap();

    let err = match db.snapshot_to(&snap_dir).await {
        Ok(_) => panic!("snapshot_to must reject a catalog segment whose file is missing"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound),
        "expected NotFound for missing catalog segment file, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 16: snapshot_to rejects non-empty output directories.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_to_rejects_non_empty_destination() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    create_stale_snapshot_sidecar(&snap_dir);

    let err = match db.snapshot_to(&snap_dir).await {
        Ok(_) => panic!("snapshot_to must reject a non-empty destination"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::AlreadyExists),
        "expected AlreadyExists for non-empty snapshot destination, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 17: failed snapshot_to leaves the destination reusable.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_to_failure_leaves_destination_reusable() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    let meta = {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        w.seal().await.unwrap()
    };
    let segment_path = src_dir.join("seg").join(hex_lower(&meta.segment_id));
    let backup_path = segment_path.with_extension("bak");
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("retry-full.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }
    std::fs::rename(&segment_path, &backup_path).unwrap();

    let err = match db.snapshot_to(&snap_dir).await {
        Ok(_) => panic!("snapshot_to must reject a catalog segment whose file is missing"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound),
        "expected NotFound for missing catalog segment file, got {err:?}"
    );

    std::fs::rename(&backup_path, &segment_path).unwrap();
    let stats = db
        .snapshot_to(&snap_dir)
        .await
        .expect("failed snapshot_to must leave the destination reusable");
    assert_eq!(stats.segments_written, 1);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn snapshot_to_rejects_missing_main_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"full-missing-page", b"value").await.unwrap();
        t.commit().await.unwrap();
    }

    std::fs::OpenOptions::new()
        .write(true)
        .open(src_dir.join("main.db"))
        .unwrap()
        .set_len((PAGE * 2) as u64)
        .unwrap();

    let err = db
        .snapshot_to(&snap_dir)
        .await
        .expect_err("snapshot_to must reject missing main.db pages");
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::UnexpectedEof),
        "expected UnexpectedEof for missing main.db page, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn snapshot_to_rejects_missing_header_referenced_main_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();

    let db = make_db(&src_dir).await;
    let second_value = vec![0xB2; PAGE * 3];
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"overflow-a", &vec![0xA1; PAGE * 3]).await.unwrap();
        t.put(b"overflow-b", &second_value).await.unwrap();
        t.commit().await.unwrap();
    }
    let rtxn = db.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"overflow-b").await.unwrap().as_deref(),
        Some(second_value.as_slice()),
        "test setup must make the committed payload readable before truncation"
    );
    drop(rtxn);

    db.snapshot_to(&snap_dir).await.unwrap();
    let manifest = open_manifest(&snap_dir.join("manifest"), &KEK)
        .await
        .unwrap();
    std::fs::remove_dir_all(&snap_dir).unwrap();

    let highest_root_page = manifest
        .target_active_root_page_id
        .max(manifest.target_catalog_root_page_id);
    let truncated_len = (highest_root_page + 1) * PAGE as u64;
    let main_path = src_dir.join("main.db");
    let original_len = std::fs::metadata(&main_path).unwrap().len();
    assert!(
        original_len > truncated_len,
        "test setup must allocate header-referenced pages beyond the root/catalog watermark"
    );
    std::fs::OpenOptions::new()
        .write(true)
        .open(&main_path)
        .unwrap()
        .set_len(truncated_len)
        .unwrap();

    let err = db
        .snapshot_to(&snap_dir)
        .await
        .expect_err("snapshot_to must reject missing header-referenced pages");
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::UnexpectedEof),
        "expected UnexpectedEof for missing header-referenced page, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 18: snapshot_incremental_to rejects a new segment whose file is missing.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_incremental_to_rejects_missing_new_segment_file() {
    let src_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();

    let meta = {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        w.seal().await.unwrap()
    };
    let segment_path = src_dir.join("seg").join(hex_lower(&meta.segment_id));
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("missing-incremental.seg", &meta)
            .await
            .unwrap();
        t.commit().await.unwrap();
    }
    assert!(
        segment_path.is_file(),
        "test setup must create the linked live segment file"
    );
    std::fs::remove_file(&segment_path).unwrap();

    let err = match db.snapshot_incremental_to(c1, &delta_dir).await {
        Ok(_) => panic!("snapshot_incremental_to must reject a new segment whose file is missing"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound),
        "expected NotFound for missing new segment file, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 19: snapshot_incremental_to rejects non-empty output directories.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_incremental_to_rejects_non_empty_destination() {
    let src_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"new_key", b"new_val").await.unwrap();
        t.commit().await.unwrap();
    }
    create_stale_snapshot_sidecar(&delta_dir);

    let err = match db.snapshot_incremental_to(c1, &delta_dir).await {
        Ok(_) => panic!("snapshot_incremental_to must reject a non-empty destination"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::AlreadyExists),
        "expected AlreadyExists for non-empty incremental destination, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 20: failed snapshot_incremental_to leaves the destination reusable.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn snapshot_incremental_to_failure_leaves_destination_reusable() {
    let src_dir = tempdir();
    let delta_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    let meta = {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        w.seal().await.unwrap()
    };
    let segment_path = src_dir.join("seg").join(hex_lower(&meta.segment_id));
    let backup_path = segment_path.with_extension("bak");
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("retry-incremental.seg", &meta)
            .await
            .unwrap();
        t.commit().await.unwrap();
    }
    std::fs::rename(&segment_path, &backup_path).unwrap();

    let err = match db.snapshot_incremental_to(c1, &delta_dir).await {
        Ok(_) => panic!("snapshot_incremental_to must reject a new segment whose file is missing"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Io(ref io) if io.kind() == std::io::ErrorKind::NotFound),
        "expected NotFound for missing new segment file, got {err:?}"
    );

    std::fs::rename(&backup_path, &segment_path).unwrap();
    let stats = db
        .snapshot_incremental_to(c1, &delta_dir)
        .await
        .expect("failed snapshot_incremental_to must leave the destination reusable");
    assert_eq!(stats.segments_written, 1);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 21: apply_incremental rejects renamed segment sidecars.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_renamed_manifest_declared_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let meta = {
            let mut s = db
                .create_segment(REALM, SegmentKind::Unspecified)
                .await
                .unwrap();
            s.append_page(SegmentPageKind::Data, b"segment-after-base")
                .await
                .unwrap();
            s.set_manifest(b"mf").unwrap();
            s.seal().await.unwrap()
        };
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("renamed.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(delta_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one incremental segment sidecar"
    );
    let original_sidecar = &seg_files[0];
    let fake_sidecar = delta_dir
        .join("seg")
        .join("cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd");
    std::fs::rename(original_sidecar, fake_sidecar).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject renamed manifest-declared segment files");
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_)
                | PagedbError::SnapshotIncompatible {
                    field: "segments_count"
                }
        ),
        "expected Corruption for renamed segment sidecar, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert!(
        rtxn.open_segment("renamed.seg").await.is_err(),
        "failed incremental apply must not advance the catalog"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// Test 18: restore_from rejects missing manifest-declared segment files.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_missing_manifest_declared_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        let meta = w.seal().await.unwrap();
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("missing-full.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(snap_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one full-snapshot segment sidecar"
    );
    for file in seg_files {
        std::fs::remove_file(file).unwrap();
    }
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject missing manifest-declared segment files"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_)
                | PagedbError::SnapshotIncompatible {
                    field: "segments_count"
                }
        ),
        "expected Corruption for missing full-snapshot segment sidecar, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 19: restore_from rejects renamed manifest-declared segment files.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_renamed_manifest_declared_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        let meta = w.seal().await.unwrap();
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("renamed-full.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(snap_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one full-snapshot segment sidecar"
    );
    let fake_sidecar = snap_dir
        .join("seg")
        .join("efefefefefefefefefefefefefefefef");
    std::fs::rename(&seg_files[0], fake_sidecar).unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject renamed manifest-declared segment files"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for renamed full-snapshot segment sidecar, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 20: restore_from rejects corrupt segment data pages.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_corrupt_segment_data_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        let meta = w.seal().await.unwrap();
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("corrupt.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(snap_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one full-snapshot segment sidecar"
    );
    let mut bytes = std::fs::read(&seg_files[0]).unwrap();
    assert!(
        bytes.len() > PAGE + 128,
        "test setup must include a data page to corrupt"
    );
    bytes[PAGE + 128] ^= 0xFF;
    std::fs::write(&seg_files[0], bytes).unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject corrupt segment data pages"),
        Err(err) => err,
    };
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected segment authentication failure, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 21: restore_from rejects extra manifest-undeclared segment files.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn restore_rejects_extra_manifest_undeclared_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut w = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        w.append_page(SegmentPageKind::Data, b"seg-content")
            .await
            .unwrap();
        w.set_manifest(b"mf").unwrap();
        let meta = w.seal().await.unwrap();
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("my.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_to(&snap_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    std::fs::write(
        snap_dir
            .join("seg")
            .join("abababababababababababababababab"),
        b"manifest-undeclared segment",
    )
    .unwrap();
    drop(db);

    let err = match Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
    {
        Ok(_) => panic!("restore_from must reject manifest-undeclared segment files"),
        Err(err) => err,
    };
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption for extra full-snapshot segment sidecar, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 22: apply_incremental rejects missing manifest-declared segment files.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_missing_manifest_declared_segment_file() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let meta = {
            let mut s = db
                .create_segment(REALM, SegmentKind::Unspecified)
                .await
                .unwrap();
            s.append_page(SegmentPageKind::Data, b"segment-after-base")
                .await
                .unwrap();
            s.set_manifest(b"mf").unwrap();
            s.seal().await.unwrap()
        };
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("missing.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(delta_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one incremental segment sidecar"
    );
    for file in seg_files {
        std::fs::remove_file(file).unwrap();
    }
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject missing manifest-declared segment files");
    assert!(
        matches!(
            err,
            PagedbError::Corruption(_)
                | PagedbError::SnapshotIncompatible {
                    field: "segments_count"
                }
        ),
        "expected Corruption for missing segment sidecar, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert_eq!(
        rtxn.get(b"base").await.unwrap().as_deref(),
        Some(b"data".as_slice())
    );
    assert!(
        rtxn.open_segment("missing.seg").await.is_err(),
        "failed incremental apply must not advance the catalog"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_delta_depending_on_leftover_future_pages() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let meta = {
            let mut s = db
                .create_segment(REALM, SegmentKind::Unspecified)
                .await
                .unwrap();
            s.append_page(SegmentPageKind::Data, b"segment-after-base")
                .await
                .unwrap();
            s.set_manifest(b"mf").unwrap();
            s.seal().await.unwrap()
        };
        let mut t = db.begin_write().await.unwrap();
        t.put(b"later", b"value").await.unwrap();
        t.link_segment("leftover.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let original_delta = std::fs::read(delta_dir.join("pages.delta")).unwrap();
    assert!(
        original_delta.len() > PAGE,
        "test setup must produce at least one changed main-db page"
    );
    let seg_files: Vec<_> = std::fs::read_dir(delta_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one segment sidecar"
    );
    let saved_segments: Vec<_> = seg_files
        .iter()
        .map(|path| (path.clone(), std::fs::read(path).unwrap()))
        .collect();

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    for (path, bytes) in &saved_segments {
        assert!(
            bytes.len() > PAGE + 128,
            "test setup must include a segment data page to corrupt"
        );
        let mut corrupt = bytes.clone();
        corrupt[PAGE + 128] ^= 0xFF;
        std::fs::write(path, corrupt).unwrap();
    }
    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("first apply must fail after writing delta pages");
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected corrupt sidecar authentication failure, got {err:?}"
    );
    assert_eq!(
        follower.latest_commit(),
        c1,
        "failed apply must not advance the follower header"
    );

    for (path, bytes) in &saved_segments {
        std::fs::write(path, bytes).unwrap();
    }
    let manifest = std::fs::read(delta_dir.join("manifest")).unwrap();
    let target_active_root_page_id = u64::from_le_bytes(manifest[102..110].try_into().unwrap());
    let mut corrupt_retry_delta = original_delta;
    let mut corrupted = false;
    for record in corrupt_retry_delta.chunks_exact_mut(8 + PAGE) {
        let page_id = u64::from_be_bytes(record[..8].try_into().unwrap());
        if page_id == target_active_root_page_id {
            record[8 + 128] ^= 0xFF;
            corrupted = true;
            break;
        }
    }
    assert!(
        corrupted,
        "test setup must include the target active root in pages.delta"
    );
    std::fs::write(delta_dir.join("pages.delta"), corrupt_retry_delta).unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("retry must authenticate rewritten pages instead of using cached leftovers");
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected authentication failure for a corrupt retry over leftover future pages, got {err:?}"
    );
    assert_eq!(
        follower.latest_commit(),
        c1,
        "incomplete retry must not advance the follower header"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 23: apply_incremental rejects corrupt new segment sidecars.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_corrupt_new_segment_sidecar() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let meta = {
            let mut s = db
                .create_segment(REALM, SegmentKind::Unspecified)
                .await
                .unwrap();
            s.append_page(SegmentPageKind::Data, b"segment-after-base")
                .await
                .unwrap();
            s.set_manifest(b"mf").unwrap();
            s.seal().await.unwrap()
        };
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("corrupt-new.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }

    let stats = db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    assert_eq!(stats.segments_written, 1);
    let seg_files: Vec<_> = std::fs::read_dir(delta_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .map(|entry| entry.path())
        .collect();
    assert_eq!(
        seg_files.len(),
        1,
        "test setup must produce exactly one incremental segment sidecar"
    );
    let mut bytes = std::fs::read(&seg_files[0]).unwrap();
    assert!(
        bytes.len() > PAGE + 128,
        "test setup must include a data page to corrupt"
    );
    bytes[PAGE + 128] ^= 0xFF;
    std::fs::write(&seg_files[0], bytes).unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let err = follower
        .apply_incremental(&delta_dir)
        .await
        .expect_err("apply_incremental must reject corrupt new segment sidecars");
    assert!(
        matches!(
            err,
            PagedbError::ChecksumFailure | PagedbError::Corruption(_)
        ),
        "expected segment authentication failure, got {err:?}"
    );

    let rtxn = follower.begin_read().await.unwrap();
    assert!(
        rtxn.open_segment("corrupt-new.seg").await.is_err(),
        "failed incremental apply must not advance the catalog"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 24: apply_incremental tombstones segments removed by the target catalog.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_tombstones_segment_removed_by_target_catalog() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    let meta = {
        let mut s = db
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        s.append_page(SegmentPageKind::Data, b"segment-before-unlink")
            .await
            .unwrap();
        s.set_manifest(b"mf").unwrap();
        s.seal().await.unwrap()
    };
    {
        let mut t = db.begin_write().await.unwrap();
        t.link_segment("removed.seg", &meta).await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut t = db.begin_write().await.unwrap();
        t.unlink_segment("removed.seg").await.unwrap();
        t.commit().await.unwrap();
    }
    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    let live_path = dst_dir.join("seg").join(hex_lower(&meta.segment_id));
    assert!(
        live_path.is_file(),
        "base restore must contain the segment before the unlink delta is applied"
    );

    let stats = follower
        .apply_incremental(&delta_dir)
        .await
        .expect("unlink delta should apply successfully");
    assert_eq!(
        stats.segments_tombstoned, 1,
        "apply_incremental must report the removed segment tombstone"
    );
    assert!(
        !live_path.exists(),
        "removed segment must not remain at its live path after apply"
    );
    let tombstone_dir = dst_dir.join("seg").join(".tombstone");
    let tombstone_count = std::fs::read_dir(&tombstone_dir)
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().is_file())
        .count();
    assert_eq!(tombstone_count, 1);

    let rtxn = follower.begin_read().await.unwrap();
    assert!(
        rtxn.open_segment("removed.seg").await.is_err(),
        "applied target catalog must no longer expose the removed segment"
    );
    drop(rtxn);

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// Test 25: manifest corruption detected.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn manifest_corruption_detected() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    db.snapshot_to(&snap_dir).await.unwrap();
    drop(db);

    // Corrupt the last byte of the manifest (the HK-MAC).
    let manifest_path = snap_dir.join("manifest");
    let mut bytes = std::fs::read(&manifest_path).unwrap();
    let last = bytes.len() - 1;
    bytes[last] ^= 0xFF;
    std::fs::write(&manifest_path, &bytes).unwrap();

    let err = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .err()
        .unwrap();
    assert!(
        matches!(err, PagedbError::Corruption(_)),
        "expected Corruption, got {err:?}"
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

// ---------------------------------------------------------------------------
// An incremental delta may carry an arbitrary number of new segments. Applying
// it must promote every staged segment, regardless of how many there are — the
// apply journal that records the promotions must represent a promotion set that
// does not fit in a single page. A live set larger than one journal page's
// worth of actions is ordinary for any segment-heavy engine (HNSW shards,
// columnar blocks, FTS postings), so this is common usage, not a corner case.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_promotes_segment_set_larger_than_one_journal_page() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut t = db.begin_write().await.unwrap();
        t.put(b"base", b"data").await.unwrap();
        t.commit().await.unwrap();
    }
    let c1 = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();

    // Link more segments than fit in a single journal page's worth of promote
    // actions, so the promotion set must span multiple journal pages.
    const SEGMENTS: u32 = 300;
    for i in 0..SEGMENTS {
        let meta = {
            let mut s = db
                .create_segment(REALM, SegmentKind::Unspecified)
                .await
                .unwrap();
            s.append_page(SegmentPageKind::Data, &[0xAA; 256])
                .await
                .unwrap();
            s.seal().await.unwrap()
        };
        let mut w = db.begin_write().await.unwrap();
        w.link_segment(&format!("seg-{i:05}"), &meta).await.unwrap();
        w.commit().await.unwrap();
    }

    db.snapshot_incremental_to(c1, &delta_dir).await.unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let stats: ApplyStats = follower
        .apply_incremental(&delta_dir)
        .await
        .expect("apply_incremental must promote a multi-page promotion set");
    assert_eq!(
        stats.segments_promoted, SEGMENTS,
        "every staged segment must be promoted"
    );

    // Every staged segment must have been promoted from `seg/.staging/` to its
    // live `seg/<hex(id)>` path — the journal must carry the whole promotion
    // set, not just the fraction that fit one page. Verify at the filesystem level
    // (the live `seg/` dir holds exactly the promoted files), and that nothing
    // is left behind in staging. A single-page journal could only carry a
    // fraction of the set, so this fails unless the journal spans pages.
    let live_count = std::fs::read_dir(dst_dir.join("seg"))
        .unwrap()
        .filter_map(std::result::Result::ok)
        .filter(|e| e.path().is_file())
        .count();
    assert_eq!(
        live_count as u32, SEGMENTS,
        "all {SEGMENTS} staged segments must be promoted to live paths"
    );
    let staging = dst_dir.join("seg").join(".staging");
    let staging_left = std::fs::read_dir(&staging)
        .map(|rd| {
            rd.filter_map(std::result::Result::ok)
                .filter(|e| e.path().is_file())
                .count()
        })
        .unwrap_or(0);
    assert_eq!(staging_left, 0, "no staged segment may be left unpromoted");

    // The applied delta must advance the catalog: every promoted segment is
    // reachable by name and readable through the follower's catalog, not just
    // present on disk.
    let rtxn = follower.begin_read().await.unwrap();
    for i in (0..SEGMENTS).step_by(73) {
        let name = format!("seg-{i:05}");
        let reader = rtxn
            .open_segment(&name)
            .await
            .unwrap_or_else(|e| panic!("segment {name} unreachable via catalog: {e:?}"));
        let page = reader.read_page(1).await.unwrap();
        assert!(
            page.starts_with(&[0xAA; 256]),
            "segment {name} content wrong"
        );
    }

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn deferred_apply_journal_blocks_next_apply_until_gc_drains_reader_pin() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    let meta = {
        let mut writer = source
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        writer
            .append_page(SegmentPageKind::Data, b"base-segment")
            .await
            .unwrap();
        writer.seal().await.unwrap()
    };
    {
        let mut write = source.begin_write().await.unwrap();
        write.link_segment("removed", &meta).await.unwrap();
        write.commit().await.unwrap();
    }
    let base = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();
    {
        let mut write = source.begin_write().await.unwrap();
        write.unlink_segment("removed").await.unwrap();
        write.commit().await.unwrap();
    }
    source
        .snapshot_incremental_to(base, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    let base_reader = follower.begin_read().await.unwrap();

    assert!(matches!(
        follower.apply_incremental(&delta_dir).await,
        Err(PagedbError::ReadersPinningTruncatedRange)
    ));
    assert!(follower.list_segments(REALM, "").await.unwrap().is_empty());
    assert!(matches!(
        follower.apply_incremental(&delta_dir).await,
        Err(PagedbError::ReadersPinningTruncatedRange)
    ));

    drop(base_reader);
    follower.gc_now().await.unwrap();

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

#[tokio::test(flavor = "current_thread")]
async fn failed_apply_promote_poisoned_handle_reopens_and_replays_journal_before_reads() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut write = source.begin_write().await.unwrap();
        write.put(b"base", b"before-snapshot").await.unwrap();
        write.commit().await.unwrap();
    }
    let base = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();
    let meta = {
        let mut writer = source
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        writer
            .append_page(SegmentPageKind::Data, b"promoted-after-reopen")
            .await
            .unwrap();
        writer.seal().await.unwrap()
    };
    {
        let mut write = source.begin_write().await.unwrap();
        write.link_segment("promoted", &meta).await.unwrap();
        write.commit().await.unwrap();
    }
    source
        .snapshot_incremental_to(base, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    drop(restored);

    let vfs = RenameFaultVfs::new(&dst_dir);
    let read_only = Db::open_read_only(vfs.clone(), KEK, PAGE, REALM, OpenOptions::default())
        .await
        .unwrap();
    let follower = read_only.promote_to_follower().await.unwrap();
    vfs.fail_renames(true);

    assert!(matches!(
        follower.apply_incremental(&delta_dir).await,
        Err(PagedbError::DurablyCommittedButUnpublished { .. })
    ));
    assert!(matches!(
        follower.list_segments(REALM, "").await,
        Err(PagedbError::DurablyCommittedButUnpublished { .. })
    ));

    vfs.fail_renames(false);
    drop(follower);
    let reopened = Db::open_existing(vfs, KEK, PAGE, REALM).await.unwrap();
    let segment = reopened.open_segment(REALM, "promoted").await.unwrap();
    assert!(
        segment
            .read_page(1)
            .await
            .unwrap()
            .starts_with(b"promoted-after-reopen")
    );

    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

async fn follower_with_segment_incremental() -> (Db<TokioVfs>, Vec<std::path::PathBuf>, u64) {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut write = source.begin_write().await.unwrap();
        write.put(b"base", b"value").await.unwrap();
        write.commit().await.unwrap();
    }
    let base_commit = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();

    {
        let mut write = source.begin_write().await.unwrap();
        write.put(b"after-base", b"value").await.unwrap();
        write.commit().await.unwrap();
    }
    let meta = {
        let mut writer = source
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        writer
            .append_page(SegmentPageKind::Data, b"manifest-validation")
            .await
            .unwrap();
        writer.seal().await.unwrap()
    };
    {
        let mut write = source.begin_write().await.unwrap();
        write
            .link_segment("manifest-validation", &meta)
            .await
            .unwrap();
        write.commit().await.unwrap();
    }
    let target_commit = source.latest_commit().value();
    source
        .snapshot_incremental_to(base_commit, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    (
        follower,
        vec![src_dir, snap_dir, delta_dir, dst_dir],
        target_commit,
    )
}

fn original_manifest(path: &std::path::Path) -> [u8; 240] {
    std::fs::read(path.join("manifest"))
        .unwrap()
        .try_into()
        .unwrap()
}

fn rewrite_manifest(
    path: &std::path::Path,
    original: &[u8; 240],
    hk: &[u8; 32],
    edit: impl FnOnce(&mut SnapshotManifest),
) {
    let mut manifest = decode_manifest(original, hk).unwrap();
    edit(&mut manifest);
    std::fs::write(path.join("manifest"), encode_manifest(&manifest, hk)).unwrap();
}

fn directory_contents(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    fn collect(
        root: &std::path::Path,
        current: &std::path::Path,
        out: &mut Vec<std::path::PathBuf>,
    ) {
        for entry in std::fs::read_dir(current).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            let relative = path.strip_prefix(root).unwrap().to_owned();
            out.push(relative);
            if path.is_dir() {
                collect(root, &path, out);
            }
        }
    }

    let mut entries = Vec::new();
    collect(root, root, &mut entries);
    entries.sort();
    entries
}

async fn assert_refusal_preserves_follower(
    follower: &Db<TokioVfs>,
    delta_dir: &std::path::Path,
    dst_dir: &std::path::Path,
    expected_field: &'static str,
    commit_before: u64,
    headers_before: &[u8],
    directory_before: &[std::path::PathBuf],
) {
    let error = follower.apply_incremental(delta_dir).await.unwrap_err();
    assert!(matches!(
        error,
        PagedbError::SnapshotIncompatible { field } if field == expected_field
    ));
    assert_eq!(follower.latest_commit().value(), commit_before);
    assert_eq!(
        &std::fs::read(dst_dir.join("main.db")).unwrap()[..PAGE * 2],
        headers_before
    );
    assert_eq!(directory_contents(dst_dir), directory_before);
}

struct ManifestRejectionContext {
    follower: Db<TokioVfs>,
    paths: Vec<std::path::PathBuf>,
    original: [u8; 240],
    hk: [u8; 32],
    commit_before: u64,
    headers_before: Vec<u8>,
    directory_before: Vec<std::path::PathBuf>,
}

impl ManifestRejectionContext {
    async fn reject_manifest_change(
        &self,
        expected_field: &'static str,
        edit: impl FnOnce(&mut SnapshotManifest),
    ) {
        rewrite_manifest(&self.paths[2], &self.original, &self.hk, edit);
        assert_refusal_preserves_follower(
            &self.follower,
            &self.paths[2],
            &self.paths[3],
            expected_field,
            self.commit_before,
            &self.headers_before,
            &self.directory_before,
        )
        .await;
    }
}

#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_rejects_incompatible_manifests_without_mutation() {
    let (follower, paths, _) = follower_with_segment_incremental().await;
    let original = original_manifest(&paths[2]);
    let mut salt = [0u8; 16];
    salt.copy_from_slice(&original[53..69]);
    let mut epoch = [0u8; 8];
    epoch.copy_from_slice(&original[45..53]);
    let hk = derive_snapshot_hk_key(&KEK, &salt, u64::from_le_bytes(epoch)).unwrap();
    let commit_before = follower.latest_commit().value();
    let main_db = std::fs::read(paths[3].join("main.db")).unwrap();
    let headers_before = main_db[..PAGE * 2].to_vec();
    let directory_before = directory_contents(&paths[3]);
    let context = ManifestRejectionContext {
        follower,
        paths,
        original,
        hk,
        commit_before,
        headers_before,
        directory_before,
    };

    context
        .reject_manifest_change("kind", |manifest| manifest.kind = 0)
        .await;
    context
        .reject_manifest_change("base_commit", |manifest| manifest.base_commit += 1)
        .await;
    context
        .reject_manifest_change("target_commit", |manifest| {
            manifest.target_commit = manifest.base_commit
        })
        .await;
    context
        .reject_manifest_change("file_id", |manifest| manifest.file_id[0] ^= 1)
        .await;
    context
        .reject_manifest_change("realm_id", |manifest| manifest.realm_id[0] ^= 1)
        .await;
    context
        .reject_manifest_change("cipher_id", |manifest| manifest.cipher_id ^= 1)
        .await;
    context
        .reject_manifest_change("mk_epoch", |manifest| manifest.mk_epoch += 1)
        .await;
    context
        .reject_manifest_change("kek_salt", |manifest| manifest.kek_salt[0] ^= 1)
        .await;
    context
        .reject_manifest_change("page_size", |manifest| {
            manifest.page_size = (PAGE * 2) as u32
        })
        .await;
    context
        .reject_manifest_change("version", |manifest| manifest.version = 2)
        .await;
    context
        .reject_manifest_change("target_active_root_page_id", |manifest| {
            manifest.target_active_root_page_id = manifest.next_page_id_at_target
        })
        .await;
    context
        .reject_manifest_change("target_catalog_root_page_id", |manifest| {
            manifest.target_catalog_root_page_id = 1
        })
        .await;
    context
        .reject_manifest_change("segments_count", |manifest| manifest.segments_count += 1)
        .await;

    drop(context.follower);
    for path in context.paths {
        std::fs::remove_dir_all(path).ok();
    }
}

#[tokio::test(flavor = "current_thread")]
async fn concurrent_incremental_applies_are_serialized_before_raw_page_writes() {
    let (follower, paths, target_commit) = follower_with_segment_incremental().await;
    let delta_dir = &paths[2];
    assert!(
        std::fs::metadata(delta_dir.join("pages.delta"))
            .unwrap()
            .len()
            > 0
    );
    let (first, second) = tokio::join!(
        follower.apply_incremental(delta_dir),
        follower.apply_incremental(delta_dir),
    );

    let results = [first, second];
    assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1);
    assert!(results.iter().any(|result| {
        matches!(
            result,
            Err(PagedbError::SnapshotIncompatible {
                field: "base_commit"
            })
        )
    }));
    assert_eq!(follower.latest_commit().value(), target_commit);

    drop(follower);
    for path in paths {
        std::fs::remove_dir_all(path).ok();
    }
}

/// Applying an incremental delta installs whole pages by absolute id, bypassing
/// the normal write-txn path that the free-list accounting relies on elsewhere.
/// That makes it its own place where a page could end up reachable from neither
/// a live root nor the free list — a leak the deep walk's orphan check exists to
/// catch.
#[tokio::test(flavor = "current_thread")]
async fn apply_incremental_leaves_no_orphan_pages_on_the_follower() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..200 {
            write
                .put(format!("k{i:05}").as_bytes(), &[1u8; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    let base = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();

    // Several more commits after the base snapshot, overwriting the same key
    // set each time so copy-on-write both allocates fresh pages and recycles
    // superseded ones, exercising both halves of the delta.
    for generation in 0u8..5 {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..200 {
            write
                .put(format!("k{i:05}").as_bytes(), &[generation; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    source
        .snapshot_incremental_to(base, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    follower.apply_incremental(&delta_dir).await.unwrap();

    let report = run_deep_walk(&follower).await.unwrap();
    assert!(
        report.orphan_page_ids.is_empty(),
        "snapshot apply must not leave leaked pages on the follower, got {} orphans: {:?}",
        report.orphan_page_ids.len(),
        report.orphan_page_ids
    );
    assert!(
        report.is_clean(),
        "follower deep-walk report should be clean after apply_incremental: {report:?}"
    );

    drop(follower);
    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

/// An apply allocates ids the producer never had — the rewritten free-list
/// chain, and the commit-history tree when a delta claims the pages hosting it
/// — so the follower's visible `next_page_id` can end up ahead of the producer's
/// own cursor. A follower that runs ahead must still be able to take the next
/// delta: nothing about a smaller `next_page_id_at_target` makes a delta
/// inapplicable, because the published cursor is the larger of the two. Apply
/// two deltas back-to-back, the second chained onto the first delta's own target
/// commit, to prove that door stays open.
#[tokio::test(flavor = "current_thread")]
async fn chained_incremental_applies_keep_the_follower_able_to_advance() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_one_dir = tempdir();
    let delta_two_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..200 {
            write
                .put(format!("k{i:05}").as_bytes(), &[1u8; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    let base = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();

    // First run of overwrite-generations: supersedes and recycles pages,
    // exactly like the single-delta orphan test, then export delta one.
    for generation in 0u8..5 {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..200 {
            write
                .put(format!("k{i:05}").as_bytes(), &[generation; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    let delta_one_target = source.latest_commit();
    source
        .snapshot_incremental_to(base, &delta_one_dir)
        .await
        .unwrap();

    // More overwrite-generations on top, so delta two chains onto delta
    // one's own target commit rather than the original base.
    for generation in 5u8..10 {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..200 {
            write
                .put(format!("k{i:05}").as_bytes(), &[generation; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    let delta_two_target = source.latest_commit();
    source
        .snapshot_incremental_to(delta_one_target, &delta_two_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    follower
        .apply_incremental(&delta_one_dir)
        .await
        .expect("first chained delta must apply");
    assert_eq!(follower.latest_commit(), delta_one_target);
    {
        let report = run_deep_walk(&follower).await.unwrap();
        assert!(
            report.orphan_page_ids.is_empty(),
            "no orphans expected after the first delta, got {:?}",
            report.orphan_page_ids
        );
        let rtxn = follower.begin_read().await.unwrap();
        for i in 0u32..200 {
            assert_eq!(
                rtxn.get(format!("k{i:05}").as_bytes())
                    .await
                    .unwrap()
                    .as_deref(),
                Some(vec![4u8; 128].as_slice()),
                "key k{i:05} should reflect generation 4 after the first delta"
            );
        }
    }

    // This is the assertion that catches the cursor-runahead hazard: if
    // folding delta one's reclaimed chain into the follower's free list
    // bump-allocated the follower's next_page_id past the producer's own
    // cursor at delta_one_target, validate_incremental_manifest would reject
    // this second delta as stale even though it correctly chains onto the
    // commit the follower is sitting at.
    follower.apply_incremental(&delta_two_dir).await.expect(
        "second chained delta must apply without the follower's cursor outrunning the producer",
    );
    assert_eq!(follower.latest_commit(), delta_two_target);
    {
        let report = run_deep_walk(&follower).await.unwrap();
        assert!(
            report.orphan_page_ids.is_empty(),
            "no orphans expected after the second delta, got {:?}",
            report.orphan_page_ids
        );
        assert!(
            report.is_clean(),
            "follower deep-walk report should be clean after both chained deltas: {report:?}"
        );
        let rtxn = follower.begin_read().await.unwrap();
        for i in 0u32..200 {
            assert_eq!(
                rtxn.get(format!("k{i:05}").as_bytes())
                    .await
                    .unwrap()
                    .as_deref(),
                Some(vec![9u8; 128].as_slice()),
                "key k{i:05} should reflect generation 9 after the second delta"
            );
        }
    }

    drop(follower);
    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&delta_one_dir).ok();
    std::fs::remove_dir_all(&delta_two_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
}

/// The follower keeps its own free-list chain and commit-history tree across an
/// apply, and those pages are invisible to the producer, which can neither
/// predict nor avoid them. When the producer's allocator later recycles one of
/// those same ids into its own live tree, the resulting delta ships that id by
/// number.
///
/// That used to be inapplicable by construction: pages went straight into the
/// live `main.db` before the header swap, so overwriting one would have
/// destroyed base state while the only durable header still pointed at it, and
/// the apply refused rather than risk it. The target is now assembled in a
/// staged image and this handle's own metadata is relocated out of the incoming
/// page space before the swap, so the delta applies — and this proves it applies
/// *correctly*: the follower lands on the target commit, every key reads back as
/// the source has it, its page graph deep-walks clean, and it agrees with a
/// follower built from a full snapshot of the same commit.
#[tokio::test(flavor = "current_thread")]
async fn a_delta_that_recycles_follower_private_page_ids_applies_cleanly() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();
    let delta_dir = tempdir();
    let full_snap_dir = tempdir();
    let full_dst_dir = tempdir();

    let source = make_db(&src_dir).await;

    // A large working set, so deletes free interior pages, not just one leaf.
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..512 {
            write
                .put(format!("k{i:05}").as_bytes(), &[0xAA; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    source.snapshot_to(&snap_dir).await.unwrap();

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let base = source.latest_commit();

    // Free half the working set -- interior pages go onto the source's
    // durable free list.
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..256 {
            write.delete(format!("k{i:05}").as_bytes()).await.unwrap();
        }
        write.commit().await.unwrap();
    }
    // Re-insert, forcing the allocator to draw the just-freed ids back off the
    // free list -- among them, with overwhelming likelihood given 512 keys
    // reused down to 256 ids, some id the follower is holding for its own
    // chain or commit-history pages.
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..256 {
            write
                .put(format!("k{i:05}").as_bytes(), &[0xBB; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    let target = source.latest_commit();
    source
        .snapshot_incremental_to(base, &delta_dir)
        .await
        .expect("exporting the delta itself must succeed");

    follower
        .apply_incremental(&delta_dir)
        .await
        .expect("a delta that recycles a follower-private page id must apply");

    assert_eq!(
        follower.latest_commit(),
        target,
        "the apply must land on the delta's target commit"
    );
    {
        let rtxn = follower.begin_read().await.unwrap();
        for i in 0u32..256 {
            assert_eq!(
                rtxn.get(format!("k{i:05}").as_bytes())
                    .await
                    .unwrap()
                    .as_deref(),
                Some(vec![0xBBu8; 128].as_slice()),
                "refilled key k{i:05} must reflect the source's current state"
            );
        }
        for i in 256u32..512 {
            assert_eq!(
                rtxn.get(format!("k{i:05}").as_bytes())
                    .await
                    .unwrap()
                    .as_deref(),
                Some(vec![0xAAu8; 128].as_slice()),
                "untouched key k{i:05} must reflect the source's current state"
            );
        }
    }
    let report = run_deep_walk(&follower).await.unwrap();
    assert!(
        report.orphan_page_ids.is_empty(),
        "an applied delta must not leave orphan pages, got {:?}",
        report.orphan_page_ids
    );
    assert!(
        report.is_clean(),
        "an applied delta must leave the follower's deep-walk report clean: {report:?}"
    );
    // The commit-history tree the follower carries is relocated when the delta
    // claims its pages; either way it must still be walkable afterwards.
    assert!(matches!(
        follower.begin_read_at(base).await,
        Ok(_) | Err(PagedbError::CommitGone { .. })
    ));
    assert!(
        !dst_dir.join("main.db.applying").exists(),
        "a completed apply must leave no staged image behind"
    );

    // The same commit reached the other way round: a full snapshot. The two
    // followers must agree key for key.
    source.snapshot_to(&full_snap_dir).await.unwrap();
    let full_restored =
        Db::<TokioVfs>::restore_from(&full_snap_dir, &full_dst_dir, OpenOptions::default(), KEK)
            .await
            .unwrap();
    let full_follower = full_restored.promote_to_follower().await.unwrap();
    assert_eq!(full_follower.latest_commit(), target);
    {
        let delta_read = follower.begin_read().await.unwrap();
        let full_read = full_follower.begin_read().await.unwrap();
        for i in 0u32..512 {
            let key = format!("k{i:05}");
            assert_eq!(
                delta_read.get(key.as_bytes()).await.unwrap(),
                full_read.get(key.as_bytes()).await.unwrap(),
                "delta-applied and full-snapshot followers disagree on {key}"
            );
        }
    }
    let full_report = run_deep_walk(&full_follower).await.unwrap();
    assert!(
        full_report.is_clean(),
        "full-snapshot follower must deep-walk clean: {full_report:?}"
    );

    drop(full_follower);
    drop(follower);
    drop(source);
    std::fs::remove_dir_all(&src_dir).ok();
    std::fs::remove_dir_all(&snap_dir).ok();
    std::fs::remove_dir_all(&dst_dir).ok();
    std::fs::remove_dir_all(&delta_dir).ok();
    std::fs::remove_dir_all(&full_snap_dir).ok();
    std::fs::remove_dir_all(&full_dst_dir).ok();
}

/// Chaining deltas is not a two-delta trick: an ordinary write-churn workload
/// must keep replicating by delta indefinitely.
///
/// Each round frees half the working set, refills it, and overwrites the
/// surviving half in place — the shape that recycles page ids fastest, including
/// the ids hosting the follower's own free-list chain and commit-history tree.
/// Every round must apply, land on that round's commit, read back that round's
/// generation, and deep-walk clean. A single refusal fails the test: needing a
/// full snapshot to get past ordinary churn is the defect this asserts against.
#[tokio::test(flavor = "current_thread")]
async fn chained_deltas_survive_many_rounds_of_delete_and_refill_churn() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;

    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..512 {
            write
                .put(format!("k{i:05}").as_bytes(), &[0xAA; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    source.snapshot_to(&snap_dir).await.unwrap();

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let mut delta_target = source.latest_commit();
    let mut cleanup_dirs = vec![src_dir.clone(), snap_dir.clone(), dst_dir.clone()];

    for round in 0u32..12 {
        let round_base = delta_target;
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 0u32..256 {
                write.delete(format!("k{i:05}").as_bytes()).await.unwrap();
            }
            write.commit().await.unwrap();
        }
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 0u32..256 {
                write
                    .put(format!("k{i:05}").as_bytes(), &[round as u8; 128])
                    .await
                    .unwrap();
            }
            write.commit().await.unwrap();
        }
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 256u32..512 {
                write
                    .put(format!("k{i:05}").as_bytes(), &[round as u8; 128])
                    .await
                    .unwrap();
            }
            write.commit().await.unwrap();
        }

        delta_target = source.latest_commit();
        let delta_dir = tempdir();
        cleanup_dirs.push(delta_dir.clone());
        source
            .snapshot_incremental_to(round_base, &delta_dir)
            .await
            .unwrap_or_else(|e| panic!("round {round}: incremental export must succeed: {e:?}"));

        follower
            .apply_incremental(&delta_dir)
            .await
            .unwrap_or_else(|e| panic!("round {round}: chained delta must apply: {e:?}"));

        assert_eq!(
            follower.latest_commit(),
            delta_target,
            "round {round}: the apply must land on the delta's target commit"
        );
        let report = run_deep_walk(&follower).await.unwrap();
        assert!(
            report.orphan_page_ids.is_empty(),
            "round {round}: no orphan pages, got {:?}",
            report.orphan_page_ids
        );
        assert!(
            report.is_clean(),
            "round {round}: deep-walk report must be clean: {report:?}"
        );
        let rtxn = follower.begin_read().await.unwrap();
        for i in 0u32..512 {
            assert_eq!(
                rtxn.get(format!("k{i:05}").as_bytes())
                    .await
                    .unwrap()
                    .as_deref(),
                Some(vec![round as u8; 128].as_slice()),
                "round {round}: key k{i:05} should reflect this round's generation"
            );
        }
        drop(rtxn);
        assert!(
            !dst_dir.join("main.db.applying").exists(),
            "round {round}: a completed apply must leave no staged image behind"
        );

        // Re-applying a delta the follower has already absorbed must fail on the
        // manifest's base commit, not silently redo the work.
        let replay = follower.apply_incremental(&delta_dir).await;
        assert!(
            matches!(
                replay,
                Err(PagedbError::SnapshotIncompatible { field }) if field == "base_commit"
            ),
            "round {round}: replaying a completed delta must fail on base_commit, got {replay:?}"
        );
    }

    drop(follower);
    drop(source);
    for dir in cleanup_dirs {
        std::fs::remove_dir_all(&dir).ok();
    }
}

/// A replication client's error handling must survive being right either way.
///
/// `SnapshotBasePageReused` is still a reachable refusal -- a delta record that
/// names a page the base commit is still reading through is not something any
/// well-formed export produces, and it is refused before anything is staged.
/// Ordinary churn is no longer a cause of it (see
/// `chained_deltas_survive_many_rounds_of_delete_and_refill_churn`, which
/// requires every round to apply), so a client that treats the refusal as fatal
/// and a client that falls back to a full snapshot must both stay consistent.
/// This test drives 12 rounds of that churn and, on every round, accepts exactly
/// two outcomes -- clean apply, or refusal-plus-full-snapshot-remedy -- and
/// fails loudly on anything else, so the fallback path keeps being exercised
/// end-to-end without pinning which branch a given build takes.
#[tokio::test(flavor = "current_thread")]
async fn a_follower_stays_consistent_across_churn_by_falling_back_to_a_full_snapshot() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;

    // A large working set, so deletes free interior pages, not just one leaf.
    {
        let mut write = source.begin_write().await.unwrap();
        for i in 0u32..512 {
            write
                .put(format!("k{i:05}").as_bytes(), &[0xAA; 128])
                .await
                .unwrap();
        }
        write.commit().await.unwrap();
    }
    source.snapshot_to(&snap_dir).await.unwrap();

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let mut follower = restored.promote_to_follower().await.unwrap();

    let mut delta_target = source.latest_commit();
    let mut cleanup_dirs = vec![src_dir.clone(), snap_dir.clone(), dst_dir.clone()];
    let mut ok_rounds = 0u32;
    let mut refused_rounds = 0u32;

    for round in 0u32..12 {
        let round_base = delta_target;

        // Pre-round follower state, needed only if this round's delta gets
        // refused -- the refusal must be a pure no-op.
        let pre_round_commit = follower.latest_commit();
        let pre_round_values: Vec<(String, Option<bytes::Bytes>)> = {
            let rtxn = follower.begin_read().await.unwrap();
            let mut values = Vec::with_capacity(512);
            for i in 0u32..512 {
                let key = format!("k{i:05}");
                let value = rtxn.get(key.as_bytes()).await.unwrap();
                values.push((key, value));
            }
            values
        };

        // Ordinary churn: free half the working set, refill it with this
        // round's generation, and overwrite the surviving half in place. Both
        // the refill and the in-place overwrite draw on/recycle freed pages,
        // which is exactly the condition that can hit a follower-held id.
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 0u32..256 {
                write.delete(format!("k{i:05}").as_bytes()).await.unwrap();
            }
            write.commit().await.unwrap();
        }
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 0u32..256 {
                write
                    .put(format!("k{i:05}").as_bytes(), &[round as u8; 128])
                    .await
                    .unwrap();
            }
            write.commit().await.unwrap();
        }
        {
            let mut write = source.begin_write().await.unwrap();
            for i in 256u32..512 {
                write
                    .put(format!("k{i:05}").as_bytes(), &[round as u8; 128])
                    .await
                    .unwrap();
            }
            write.commit().await.unwrap();
        }

        delta_target = source.latest_commit();
        let delta_dir = tempdir();
        cleanup_dirs.push(delta_dir.clone());
        source
            .snapshot_incremental_to(round_base, &delta_dir)
            .await
            .unwrap_or_else(|e| panic!("round {round}: incremental export must succeed: {e:?}"));

        match follower.apply_incremental(&delta_dir).await {
            Ok(_) => {
                ok_rounds += 1;
                assert_eq!(
                    follower.latest_commit(),
                    delta_target,
                    "round {round}: a successful apply must land on the delta's target commit"
                );
                let report = run_deep_walk(&follower).await.unwrap();
                assert!(
                    report.orphan_page_ids.is_empty(),
                    "round {round}: a successful apply must leave no orphan pages, got {:?}",
                    report.orphan_page_ids
                );
                assert!(
                    report.is_clean(),
                    "round {round}: a successful apply must leave a clean deep-walk report: {report:?}"
                );
                let rtxn = follower.begin_read().await.unwrap();
                for i in 0u32..512 {
                    assert_eq!(
                        rtxn.get(format!("k{i:05}").as_bytes())
                            .await
                            .unwrap()
                            .as_deref(),
                        Some(vec![round as u8; 128].as_slice()),
                        "round {round}: key k{i:05} should reflect this round's generation after a successful apply"
                    );
                }
            }
            Err(PagedbError::SnapshotBasePageReused { .. }) => {
                refused_rounds += 1;

                // The refusal must be a pure no-op on the follower that was
                // asked to apply the delta.
                assert_eq!(
                    follower.latest_commit(),
                    pre_round_commit,
                    "round {round}: a refused apply must not advance the follower's commit"
                );
                {
                    let rtxn = follower.begin_read().await.unwrap();
                    for (key, expected) in &pre_round_values {
                        assert_eq!(
                            &rtxn.get(key.as_bytes()).await.unwrap(),
                            expected,
                            "round {round}: key {key} must read back exactly as before the refused apply"
                        );
                    }
                }
                let report = run_deep_walk(&follower).await.unwrap();
                assert!(
                    report.orphan_page_ids.is_empty(),
                    "round {round}: a refused apply must not leave orphan pages, got {:?}",
                    report.orphan_page_ids
                );
                assert!(
                    report.is_clean(),
                    "round {round}: a refused apply must leave a clean deep-walk report: {report:?}"
                );

                // The documented remedy: fall back to a full snapshot and keep
                // going with a brand-new follower built from it.
                let full_snap_dir = tempdir();
                let full_dst_dir = tempdir();
                cleanup_dirs.push(full_snap_dir.clone());
                cleanup_dirs.push(full_dst_dir.clone());

                source
                    .snapshot_to(&full_snap_dir)
                    .await
                    .unwrap_or_else(|e| {
                        panic!("round {round}: full-snapshot remedy export must succeed: {e:?}")
                    });
                let full_restored = Db::<TokioVfs>::restore_from(
                    &full_snap_dir,
                    &full_dst_dir,
                    OpenOptions::default(),
                    KEK,
                )
                .await
                .unwrap_or_else(|e| {
                    panic!("round {round}: full-snapshot remedy restore must succeed: {e:?}")
                });
                let new_follower = full_restored
                    .promote_to_follower()
                    .await
                    .unwrap_or_else(|e| {
                        panic!("round {round}: full-snapshot remedy promotion must succeed: {e:?}")
                    });

                assert_eq!(
                    new_follower.latest_commit(),
                    delta_target,
                    "round {round}: the remedy follower must land on the source's current commit"
                );
                let report = run_deep_walk(&new_follower).await.unwrap();
                assert!(
                    report.orphan_page_ids.is_empty(),
                    "round {round}: the remedy follower must have no orphan pages, got {:?}",
                    report.orphan_page_ids
                );
                assert!(
                    report.is_clean(),
                    "round {round}: the remedy follower must deep-walk clean: {report:?}"
                );
                let rtxn = new_follower.begin_read().await.unwrap();
                for i in 0u32..512 {
                    assert_eq!(
                        rtxn.get(format!("k{i:05}").as_bytes())
                            .await
                            .unwrap()
                            .as_deref(),
                        Some(vec![round as u8; 128].as_slice()),
                        "round {round}: key k{i:05} should reflect this round's generation on the remedy follower"
                    );
                }
                drop(rtxn);

                drop(follower);
                follower = new_follower;
            }
            Err(other) => panic!(
                "round {round}: unexpected error, only Ok or SnapshotBasePageReused are acceptable outcomes of chaining a delta: {other:?}"
            ),
        }
    }

    // Neither branch is required to occur. Which rounds apply and which are
    // refused depends on the ids the producer's allocator happens to recycle,
    // and that shifts with build configuration. Asserting a count here would pin
    // a scheduling accident, so this test asserts only the property that must
    // hold either way — every round ends applied-and-clean or
    // refused-and-unchanged, never anything else, and the follower is
    // consistent at the end. Each branch is proved deterministically on its own:
    // the clean apply by `chained_deltas_survive_many_rounds_of_delete_and_refill_churn`,
    // the refusal by
    // `apply_incremental_refuses_to_overwrite_a_base_live_page_without_mutating_base`.
    assert_eq!(
        ok_rounds + refused_rounds,
        12,
        "every round must end in one of the two acceptable outcomes"
    );

    drop(follower);
    drop(source);
    for dir in cleanup_dirs {
        std::fs::remove_dir_all(&dir).ok();
    }
}

/// A `TokioVfs` whose A/B header slots — in `main.db` or in the staged image an
/// apply builds beside it — can be made unwritable.
///
/// The delta pages and relocated metadata an incremental apply writes land at
/// page 4 and above, so rejecting writes below that boundary stops an apply
/// exactly between "the target image is fully assembled" and "its header names
/// the target", which is the last durable boundary before the swap.
#[derive(Clone)]
struct HeaderFaultVfs {
    inner: TokioVfs,
    fail_header_writes: Arc<AtomicBool>,
}

impl HeaderFaultVfs {
    fn new(root: &std::path::Path) -> Self {
        Self {
            inner: TokioVfs::new(root),
            fail_header_writes: Arc::new(AtomicBool::new(false)),
        }
    }

    fn fail_header_writes(&self, fail: bool) {
        self.fail_header_writes.store(fail, Ordering::SeqCst);
    }

    fn injected() -> PagedbError {
        PagedbError::Io(std::io::Error::other("injected header swap interruption"))
    }
}

impl Vfs for HeaderFaultVfs {
    type File = HeaderFaultFile;
    type LockHandle = TokioLockHandle;

    async fn open(&self, path: &str, mode: OpenMode) -> crate::Result<Self::File> {
        Ok(HeaderFaultFile {
            inner: self.inner.open(path, mode).await?,
            is_main_db: path == "/main.db" || path == "/main.db.applying",
            fail_header_writes: self.fail_header_writes.clone(),
        })
    }

    async fn remove(&self, path: &str) -> crate::Result<()> {
        self.inner.remove(path).await
    }

    async fn rename(&self, from: &str, to: &str) -> crate::Result<()> {
        self.inner.rename(from, to).await
    }

    async fn list_dir(&self, path: &str) -> crate::Result<Vec<String>> {
        self.inner.list_dir(path).await
    }

    async fn mkdir_all(&self, path: &str) -> crate::Result<()> {
        self.inner.mkdir_all(path).await
    }

    async fn sync_dir(&self, path: &str) -> crate::Result<()> {
        self.inner.sync_dir(path).await
    }

    async fn lock_exclusive(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_exclusive(path).await
    }

    async fn lock_shared(&self, path: &str) -> crate::Result<Self::LockHandle> {
        self.inner.lock_shared(path).await
    }

    fn root_path(&self) -> Option<&std::path::Path> {
        Some(self.inner.root_path())
    }
}

struct HeaderFaultFile {
    inner: TokioFile,
    is_main_db: bool,
    fail_header_writes: Arc<AtomicBool>,
}

impl HeaderFaultFile {
    /// A single-page write into slot A or B. The length test matters: cloning
    /// the base into the staged image also writes over those offsets, in
    /// multi-page chunks, and that copy is not the boundary under test.
    fn rejects(&self, offset: u64, len: usize) -> bool {
        self.is_main_db
            && self.fail_header_writes.load(Ordering::SeqCst)
            && offset < 2 * PAGE as u64
            && len == PAGE
    }
}

impl VfsFile for HeaderFaultFile {
    async fn read_at(&self, offset: u64, buf: &mut [u8]) -> crate::Result<usize> {
        self.inner.read_at(offset, buf).await
    }

    async fn read_at_vectored(&self, reqs: &mut [ReadReq<'_>]) -> crate::Result<()> {
        self.inner.read_at_vectored(reqs).await
    }

    async fn write_at(&mut self, offset: u64, buf: &[u8]) -> crate::Result<usize> {
        if self.rejects(offset, buf.len()) {
            return Err(HeaderFaultVfs::injected());
        }
        self.inner.write_at(offset, buf).await
    }

    async fn write_at_vectored(&mut self, reqs: &[WriteReq<'_>]) -> crate::Result<()> {
        if reqs
            .iter()
            .any(|req| self.rejects(req.offset, req.buf.len()))
        {
            return Err(HeaderFaultVfs::injected());
        }
        self.inner.write_at_vectored(reqs).await
    }

    async fn sync(&mut self) -> crate::Result<()> {
        self.inner.sync().await
    }

    async fn truncate(&mut self, len: u64) -> crate::Result<()> {
        self.inner.truncate(len).await
    }

    async fn len(&self) -> crate::Result<u64> {
        self.inner.len().await
    }

    async fn is_empty(&self) -> crate::Result<bool> {
        self.inner.is_empty().await
    }

    fn supports_direct_io(&self) -> bool {
        self.inner.supports_direct_io()
    }
}

/// An apply interrupted at its commit point — the rename of the fully sealed
/// staged image over `main.db` — leaves the follower wholly at the base commit.
///
/// This is the boundary that matters most: on the far side of it the target is
/// complete on disk, header and all, and only the rename decides which of the
/// two states the store is. Nothing of the target may be observable until it
/// lands, and the retry must be able to run the whole apply again from the base.
#[tokio::test(flavor = "current_thread")]
async fn apply_interrupted_at_the_image_swap_stays_at_the_base_commit_then_retries_through() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut txn = source.begin_write().await.unwrap();
        txn.put(b"base", b"base-value").await.unwrap();
        txn.commit().await.unwrap();
    }
    let base_commit = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();
    {
        let mut txn = source.begin_write().await.unwrap();
        txn.put(b"target", b"target-value").await.unwrap();
        txn.commit().await.unwrap();
    }
    let target_commit = source.latest_commit();
    source
        .snapshot_incremental_to(base_commit, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    drop(restored);

    let fault_vfs = RenameFaultVfs::new(&dst_dir);
    let follower = Db::open_read_only(fault_vfs.clone(), KEK, PAGE, REALM, OpenOptions::default())
        .await
        .unwrap()
        .promote_to_follower()
        .await
        .unwrap();
    fault_vfs.fail_main_db_renames(true);
    assert!(
        follower.apply_incremental(&delta_dir).await.is_err(),
        "a refused image swap must fail the apply"
    );
    fault_vfs.fail_main_db_renames(false);
    drop(follower);

    let reopened = Db::<TokioVfs>::open_read_only(
        TokioVfs::new(&dst_dir),
        KEK,
        PAGE,
        REALM,
        OpenOptions::default(),
    )
    .await
    .unwrap();
    assert_eq!(
        reopened.latest_commit(),
        base_commit,
        "an unswapped image leaves the follower at its base commit"
    );
    {
        let read = reopened.begin_read().await.unwrap();
        assert_eq!(
            read.get(b"base").await.unwrap().as_deref(),
            Some(b"base-value".as_slice())
        );
        assert!(
            read.get(b"target").await.unwrap().is_none(),
            "no part of the target commit may be observable before the swap"
        );
    }
    let report = run_deep_walk(&reopened).await.unwrap();
    assert!(
        report.is_clean(),
        "interrupted apply left the follower unsound: {report:?}"
    );

    let retried = reopened.promote_to_follower().await.unwrap();
    retried.apply_incremental(&delta_dir).await.unwrap();
    assert_eq!(
        retried.latest_commit(),
        target_commit,
        "the retry must carry the follower to the delta's target"
    );
    {
        let read = retried.begin_read().await.unwrap();
        assert_eq!(
            read.get(b"target").await.unwrap().as_deref(),
            Some(b"target-value".as_slice())
        );
        assert_eq!(
            read.get(b"base").await.unwrap().as_deref(),
            Some(b"base-value".as_slice())
        );
    }
    let report = run_deep_walk(&retried).await.unwrap();
    assert!(
        report.is_clean(),
        "completed apply after an interrupted swap: {report:?}"
    );
    assert!(
        !dst_dir.join("main.db.applying").exists(),
        "a completed apply must leave no staged image behind"
    );

    drop(retried);
    for dir in [&src_dir, &snap_dir, &delta_dir, &dst_dir] {
        std::fs::remove_dir_all(dir).ok();
    }
}

/// An incremental apply interrupted while sealing its staged image leaves the
/// follower wholly at the base commit, and a later apply of the very same delta
/// carries it all the way to the target.
///
/// The whole target is already assembled in the scratch when its header write is
/// refused — the last durable boundary before the rename that commits it — so
/// the two halves of the property are what matter: nothing of the target may be
/// observable while no durable header names it, and the scratch left behind must
/// not block the retry that finishes the transfer.
#[tokio::test(flavor = "current_thread")]
async fn apply_interrupted_at_the_header_swap_stays_at_the_base_commit_then_retries_through() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    {
        let mut txn = source.begin_write().await.unwrap();
        txn.put(b"base", b"base-value").await.unwrap();
        txn.commit().await.unwrap();
    }
    let base_commit = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();
    {
        let mut txn = source.begin_write().await.unwrap();
        txn.put(b"target", b"target-value").await.unwrap();
        txn.commit().await.unwrap();
    }
    let target_commit = source.latest_commit();
    source
        .snapshot_incremental_to(base_commit, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    drop(restored);

    // Refuse the header swap the apply ends with, after its delta pages and
    // journal sidecar are already durable.
    let fault_vfs = HeaderFaultVfs::new(&dst_dir);
    let follower = Db::open_read_only(fault_vfs.clone(), KEK, PAGE, REALM, OpenOptions::default())
        .await
        .unwrap()
        .promote_to_follower()
        .await
        .unwrap();
    fault_vfs.fail_header_writes(true);
    assert!(
        follower.apply_incremental(&delta_dir).await.is_err(),
        "a refused header swap must fail the apply"
    );
    fault_vfs.fail_header_writes(false);
    drop(follower);

    let reopened = Db::<TokioVfs>::open_read_only(
        TokioVfs::new(&dst_dir),
        KEK,
        PAGE,
        REALM,
        OpenOptions::default(),
    )
    .await
    .unwrap();
    assert_eq!(
        reopened.latest_commit(),
        base_commit,
        "an unswapped header leaves the follower at its base commit"
    );
    {
        let read = reopened.begin_read().await.unwrap();
        assert_eq!(
            read.get(b"base").await.unwrap().as_deref(),
            Some(b"base-value".as_slice())
        );
        assert!(
            read.get(b"target").await.unwrap().is_none(),
            "no part of the target commit may be observable before its header is durable"
        );
    }
    let report = run_deep_walk(&reopened).await.unwrap();
    assert!(
        report.is_clean(),
        "interrupted apply left the follower unsound: {report:?}"
    );

    let retried = reopened.promote_to_follower().await.unwrap();
    retried.apply_incremental(&delta_dir).await.unwrap();
    assert_eq!(
        retried.latest_commit(),
        target_commit,
        "the retry must carry the follower to the delta's target"
    );
    {
        let read = retried.begin_read().await.unwrap();
        assert_eq!(
            read.get(b"target").await.unwrap().as_deref(),
            Some(b"target-value".as_slice())
        );
        assert_eq!(
            read.get(b"base").await.unwrap().as_deref(),
            Some(b"base-value".as_slice())
        );
    }
    let report = run_deep_walk(&retried).await.unwrap();
    assert!(
        report.is_clean(),
        "completed apply after an interruption: {report:?}"
    );
    assert!(
        !dst_dir.join("main.db.applying").exists(),
        "a completed apply must leave no staged image behind"
    );

    drop(retried);
    for dir in [&src_dir, &snap_dir, &delta_dir, &dst_dir] {
        std::fs::remove_dir_all(dir).ok();
    }
}

// ---------------------------------------------------------------------------
// Readers and the incremental image swap.
// ---------------------------------------------------------------------------

/// A reader pinned across a completed apply keeps reading its own generation.
///
/// The apply renames a different file over `main.db` and drops every cached
/// main page, so a pinned `ReadTxn` resolves its base page ids out of the
/// target image. That is safe by construction rather than by luck: a delta is
/// defined as target-reachable minus base-reader-visible and is refused if it
/// names a base-reader-visible page, and the image it is written into is a copy
/// of the base — so every page the pinned reader can reach still holds its base
/// bytes after the swap. This is the property that makes "a follower may apply
/// while it serves reads" coherent, so it is asserted on values rather than
/// left implied by the delta-planning code.
#[tokio::test(flavor = "current_thread")]
async fn a_reader_pinned_across_an_apply_keeps_reading_its_own_generation() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let db = make_db(&src_dir).await;
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0u32..256 {
            txn.put(format!("k{index:05}").as_bytes(), b"base-generation")
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let base_commit = db.latest_commit();
    db.snapshot_to(&snap_dir).await.unwrap();
    // Supersede every key the pinned reader will touch, so the target's own
    // pages carry visibly different bytes for the same keys.
    {
        let mut txn = db.begin_write().await.unwrap();
        for index in 0u32..256 {
            txn.put(format!("k{index:05}").as_bytes(), b"target-generation")
                .await
                .unwrap();
        }
        txn.commit().await.unwrap();
    }
    let target_commit = db.latest_commit();
    db.snapshot_incremental_to(base_commit, &delta_dir)
        .await
        .unwrap();
    drop(db);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();

    let pinned = follower.begin_read().await.unwrap();
    assert_eq!(pinned.commit_id(), base_commit);
    // Read one key before the swap and the rest after, so the pin is exercised
    // both warm (cached) and cold (re-read from whatever file is live).
    assert_eq!(
        pinned.get(b"k00000").await.unwrap().as_deref(),
        Some(b"base-generation".as_slice())
    );

    follower.apply_incremental(&delta_dir).await.unwrap();
    assert_eq!(follower.latest_commit(), target_commit);

    for index in 0u32..256 {
        let key = format!("k{index:05}");
        assert_eq!(
            pinned.get(key.as_bytes()).await.unwrap().as_deref(),
            Some(b"base-generation".as_slice()),
            "{key}: a pinned reader must never resolve its own page ids to target bytes"
        );
    }
    assert_eq!(
        pinned.commit_id(),
        base_commit,
        "the pin must not have moved"
    );
    drop(pinned);

    // And a reader admitted after the apply sees the target, so the two
    // generations are genuinely different bytes rather than an unchanged store.
    {
        let fresh = follower.begin_read().await.unwrap();
        assert_eq!(fresh.commit_id(), target_commit);
        assert_eq!(
            fresh.get(b"k00000").await.unwrap().as_deref(),
            Some(b"target-generation".as_slice())
        );
    }

    let report = run_deep_walk(&follower).await.unwrap();
    assert!(
        report.is_clean(),
        "follower after a pinned apply: {report:?}"
    );

    drop(follower);
    for dir in [&src_dir, &snap_dir, &delta_dir, &dst_dir] {
        std::fs::remove_dir_all(dir).ok();
    }
}

/// No reader may be admitted inside the apply's publication window.
///
/// Between the image swap and `publish_snapshot`, the live `main.db` is the
/// target image while the published snapshot still names base roots, and the
/// tombstone pin scan that decides whether a removed segment's file survives
/// has already run against `tracked_readers`. A reader admitted in that stretch
/// registers too late for the scan to see it and holds a base catalog that
/// names a segment file the apply has just renamed away — a snapshot that
/// describes a store that does not exist.
///
/// The apply is held inside that window and an admission is attempted there.
/// With reader admission closed for the whole stretch the attempt cannot
/// complete; the probe is bounded so a regression reports the inconsistency it
/// found rather than hanging.
#[tokio::test(flavor = "current_thread")]
async fn no_reader_is_admitted_inside_the_apply_publication_window() {
    let src_dir = tempdir();
    let snap_dir = tempdir();
    let delta_dir = tempdir();
    let dst_dir = tempdir();

    let source = make_db(&src_dir).await;
    let meta = {
        let mut writer = source
            .create_segment(REALM, SegmentKind::Unspecified)
            .await
            .unwrap();
        writer
            .append_page(SegmentPageKind::Data, b"window-segment")
            .await
            .unwrap();
        writer.seal().await.unwrap()
    };
    {
        let mut write = source.begin_write().await.unwrap();
        write.put(b"base", b"base-value").await.unwrap();
        write.link_segment("removed", &meta).await.unwrap();
        write.commit().await.unwrap();
    }
    let base_commit = source.latest_commit();
    source.snapshot_to(&snap_dir).await.unwrap();
    {
        let mut write = source.begin_write().await.unwrap();
        write.unlink_segment("removed").await.unwrap();
        write.commit().await.unwrap();
    }
    source
        .snapshot_incremental_to(base_commit, &delta_dir)
        .await
        .unwrap();
    drop(source);

    let restored = Db::<TokioVfs>::restore_from(&snap_dir, &dst_dir, OpenOptions::default(), KEK)
        .await
        .unwrap();
    let follower = restored.promote_to_follower().await.unwrap();
    let hook = Arc::new(VisibilityTestHook::default());
    follower.install_visibility_test_hook(hook.clone());

    let (applied, probe) = tokio::join!(follower.apply_incremental(&delta_dir), async {
        // Bounded so a build where the window is never reached fails on the
        // assertions below instead of hanging the suite.
        if tokio::time::timeout(
            std::time::Duration::from_secs(10),
            hook.apply_window_entered.notified(),
        )
        .await
        .is_err()
        {
            return None;
        }
        // `begin_read` also rendezvouses with this hook, after it has taken
        // admission and selected a snapshot. Leave the permit waiting so the
        // only thing that can hold the attempt up is admission itself.
        hook.allow_reader_registration.notify_one();
        let admitted =
            tokio::time::timeout(std::time::Duration::from_millis(250), follower.begin_read())
                .await;
        let observed = match admitted {
            // Admission stayed closed for the whole window: nothing to observe,
            // which is the outcome the gate exists to produce.
            Err(_elapsed) => None,
            Ok(reader) => {
                let reader = reader.expect("admission must not fail for any other reason");
                let names_removed = !reader.list_segments("removed").await.unwrap().is_empty();
                let opens_removed = reader.open_segment("removed").await.is_ok();
                let base_value = reader.get(b"base").await.unwrap();
                Some((names_removed, opens_removed, base_value))
            }
        };
        // Always release, so a failure surfaces as an assertion.
        hook.apply_window_release.notify_one();
        observed
    });

    // Every remaining read in this test is an ordinary one.
    follower.clear_visibility_test_hook();

    let stats = applied.expect("the apply itself must still complete");
    assert_eq!(
        stats.segments_tombstoned, 1,
        "this delta must remove a segment, or the publication window is never entered"
    );

    if let Some((names_removed, opens_removed, base_value)) = probe {
        assert_eq!(
            names_removed, opens_removed,
            "a reader admitted inside the publication window holds a catalog naming a \
             segment whose file the apply had already removed"
        );
        assert_eq!(
            base_value.as_deref(),
            Some(b"base-value".as_slice()),
            "an admitted reader must resolve its own generation's values"
        );
    }

    // The apply completed normally: the target is published and self-consistent.
    {
        let reader = follower.begin_read().await.unwrap();
        assert!(reader.list_segments("removed").await.unwrap().is_empty());
        assert!(reader.open_segment("removed").await.is_err());
        assert_eq!(
            reader.get(b"base").await.unwrap().as_deref(),
            Some(b"base-value".as_slice())
        );
    }
    let report = run_deep_walk(&follower).await.unwrap();
    assert!(
        report.is_clean(),
        "follower after a gated apply: {report:?}"
    );

    drop(follower);
    for dir in [&src_dir, &snap_dir, &delta_dir, &dst_dir] {
        std::fs::remove_dir_all(dir).ok();
    }
}