coordinode-lsm-tree 5.8.1

Embedded LSM-tree storage engine in pure Rust, no C/C++ dependency. MVCC snapshots, BuRR filters, zstd dictionary compression, columnar PAX blocks, AES-256-GCM at rest, self-healing per-block ECC, compaction on a near-full disk, no_std support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
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
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
use super::{BlobDropReason, DropReason, salvage_blob_file, salvage_sst};
// The options-bearing entry is exercised on every feature set: the
// prefix-extractor round-trip below is ungated (extractors are core
// configuration), so the import must not hide behind the encrypted /
// dictionary / delete-resurrection gates its other consumers carry.
use super::{SalvageOptions, salvage_sst_with_options};
use crate::comparator::default_comparator;
use crate::fs::{Fs, StdFs};
use crate::table::{Table, Writer};
use crate::{InternalValue, ValueType};
use alloc::sync::Arc;
use tempfile::tempdir;
use test_log::test;

/// Runs the whole reconcile family and returns the error, asserting it came
/// from the gate under test.
///
/// The gates share one decode of each block, so they are driven together; this
/// keeps each test pinning BOTH its own failure message and the fact that the
/// combined pass still routes that forgery to the right check.
#[cfg(feature = "std")]
fn reconcile_error(
    table: &Table,
    expected: crate::table::ReconcileGate,
    prefix_extractor: Option<&Arc<dyn crate::prefix::PrefixExtractor>>,
) -> crate::Error {
    match table.verify_reconcile_gates(prefix_extractor, false) {
        Ok(()) => panic!("the forgery must be rejected, the reconcile pass accepted it"),
        Err((gate, e)) => {
            assert_eq!(gate, expected, "the wrong gate rejected the table: {e}");
            e
        }
    }
}

/// Asserts the whole reconcile family accepts an honest table.
#[cfg(feature = "std")]
fn reconcile_clean(
    table: &Table,
    prefix_extractor: Option<&Arc<dyn crate::prefix::PrefixExtractor>>,
) {
    if let Err((gate, e)) = table.verify_reconcile_gates(prefix_extractor, false) {
        panic!("an honest table must pass every gate, {gate:?} refused it: {e}");
    }
}

/// Rot in a frame's length field is caught by the header CRC, after which the
/// consumed lengths cannot locate the next frame: the salvage walk resyncs at
/// the next magic instead of stopping. But the resync magic may be an original
/// boundary OR a `BLO4` frame nested in the rotted frame's user bytes, and every
/// frame CHAINED past it inherits that unproven anchor: a fabricated chain can
/// plant one valid frame after another. There is no independent anchor
/// mid-stream, so the taint is STICKY: the whole tail after the first resync is
/// dropped (fail closed), not just the frame reached immediately by the scan.
#[test]
fn salvage_blob_file_drops_the_whole_tail_after_a_resync() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_rot");
    let dest = dir.path().join("blob_rot_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    build_blob(
        &source,
        &fs,
        &[
            (b"aaaa", b"AAAAAAAA"),
            (b"bbbb", b"BBBBBBBB"),
            (b"cccc", b"CCCCCCCC"),
            (b"dddd", b"DDDDDDDD"),
        ],
    )?;

    // Rot the SECOND frame's key_len (4 -> 6). Frame layout: magic 4 |
    // checksum 16 | seqno 8 | key_len 2 | real_val_len 4 | on_disk_val_len 4
    // | header_crc 4 | key | value = 42 + 4 + 8 bytes; the data section
    // starts at file offset 0.
    let frame_len = 42 + 4 + 8;
    let kl_off = frame_len + 4 + 16 + 8;
    let mut bytes = std::fs::read(&source)?;
    let Some(slot) = bytes.get_mut(kl_off..kl_off + 2) else {
        panic!("second frame's key_len within the file");
    };
    slot.copy_from_slice(&6u16.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest,
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    // aaaa recovered; bbbb drops (header CRC) and arms the resync taint; cccc is
    // the first frame reached by the byte scan (unproven boundary). The taint is
    // sticky, so the walk STOPS there and reports the whole surrendered tail
    // (cccc and everything chained past it) as ONE drop. Only the frame BEFORE the
    // rot survives.
    assert_eq!(
        report.records_salvaged, 1,
        "only the frame before the rot is provable; the whole tail after the resync drops: {report:?}",
    );
    assert!(
        report
            .dropped
            .iter()
            .any(|d| matches!(&d.reason, BlobDropReason::Corrupt(msg) if msg.contains("HeaderCrcMismatch"))),
        "the rotted frame drops as a header CRC mismatch: {report:?}",
    );
    assert_eq!(
        report
            .dropped
            .iter()
            .filter(
                |d| matches!(&d.reason, BlobDropReason::Corrupt(msg) if msg.contains("surrendered"))
            )
            .count(),
        1,
        "the surrendered tail is recorded ONCE, not per tainted frame: {report:?}",
    );

    // The recovered copy carries only the single provable record.
    let Some(salvaged) = report.salvaged_path else {
        panic!("one record was salvaged");
    };
    let keys: Vec<Vec<u8>> = BlobScanner::new(&salvaged, &*fs, 0)?
        .map(|r| r.map(|e| e.key.to_vec()))
        .collect::<crate::Result<_>>()?;
    assert_eq!(keys, vec![b"aaaa".to_vec()]);
    Ok(())
}

/// A forged `tli_tail` that DROPS a handle passes every byte-level check
/// (fresh checksum, valid framing, Index role): a walk following the tail
/// would silently skip the hidden block and "recover" a copy missing its
/// keys — no drop, no error, just vanished rows. Pins that the salvage open
/// walks the HEAD `tli` copy, so a forged tail cannot steer which blocks
/// are recovered.
#[test]
fn salvage_recovers_all_blocks_under_a_forged_tli_tail() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Tiny block budget so the SST spills several data blocks (several TLI
    // handles — the forge needs at least two).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    crate::test_forge::forge_tli_tail_truncated(&source, 0, None)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.dropped.is_empty(),
        "every block is intact, nothing may drop: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 64,
        "the block the forged tail hides must still be recovered: {report:?}",
    );
    Ok(())
}

/// BOTH TLI mirrors forged to the SAME truncated handle list pass every
/// byte-level check AND the mirror comparison (two forged copies prove
/// nothing), so the salvage open's block index simply omits the hidden
/// block. A walk trusting that index neither recovers the block nor
/// reports it dropped — repair then installs an apparently complete copy
/// with the block's keys silently missing. The physical data-section
/// tiling is the only ground truth: salvage must frame and recover the
/// bytes the index does not cover.
#[test]
fn salvage_recovers_a_block_hidden_by_forged_tli_mirrors() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Tiny block budget so the SST spills several data blocks (several TLI
    // handles — the forge needs at least two).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    crate::test_forge::forge_tli_mirrors_truncated(&source, 0, None)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.dropped.is_empty(),
        "every block is intact, nothing may drop: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 64,
        "the block both forged mirrors hide must still be recovered: {report:?}",
    );
    Ok(())
}

/// BOTH TLI mirrors re-encoded with the first two handles SWAPPED keep
/// every block present and the section fully covered — but the stored
/// order is no longer the offset order the physical tiling assumes. A
/// tiling pass trusting that order frames the out-of-place block through
/// the gap probe AND pushes its handle again: the duplicate emit is
/// rejected by the writer's ordering validation, so an intact block is
/// reported dropped and the block totals are inflated. The tiling must
/// re-sort by offset and skip spans it already covered.
#[test]
fn salvage_recovers_all_blocks_under_a_reordered_tli() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    crate::test_forge::forge_tli_mirrors_swap_first_two(&source, 0, None)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.dropped.is_empty(),
        "every block is intact and covered once, nothing may drop: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 64,
        "a reordered index must not double-walk or lose blocks: {report:?}",
    );
    Ok(())
}

/// A partitioned index whose MIDDLE leaf partition is corrupt yields only the
/// earlier partitions' handles before erroring, setting `index_broken`. The
/// physical data section is still intact, writer-ordered, and self-framing, so
/// salvage must walk it independently and recover EVERY data block instead of
/// re-emitting only the enumerated prefix and silently dropping the failed and
/// later partitions' blocks.
#[test]
fn salvage_recovers_physical_blocks_past_a_broken_index_partition() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Tiny data blocks + a partitioned index spread the 256 blocks across
    // several leaf partitions (no range tombstone, so salvage re-emits rather
    // than failing closed).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(128)
        .use_partitioned_index();
    for i in 0u64..256 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the middle of the `index` section (a leaf partition), desyncing
    // the handle enumeration partway while leaving the data section intact.
    let (index_pos, index_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = crate::sfa::Reader::from_reader(&mut f)?;
        let Some((pos, len)) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"index")
            .map(|e| (e.pos(), e.len()))
        else {
            panic!("a partitioned-index SST must carry an index section");
        };
        (pos, len)
    };
    let Ok(flip) = usize::try_from(index_pos + index_len / 2) else {
        panic!("the index-section offset fits usize");
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert_eq!(
        report.entries_salvaged, 256,
        "every data block must be recovered via the physical walk when the \
         index enumeration breaks: {report:?}",
    );
    // The index enumeration broke, but the physical walk recovered every data
    // block: that structural index damage is NOT data loss, so the report must
    // grade complete rather than counting the index error as a dropped block.
    assert!(
        report.is_complete(),
        "a broken index the physical walk fully recovers around is not data loss: {report:?}",
    );
    Ok(())
}

/// A range tombstone hidden by RENAMING its section to a recognized name whose
/// block decodes cleanly (here an empty `filter`, since filtering is disabled)
/// must fail salvage closed. The rename keeps the catalogue uniquely named and
/// tiled and the block loads without degrading, so neither the TOC-concealment
/// check nor the rebuildable-section degradation flag fires — but the persisted
/// `range_tombstone_count` still records the tombstone, so salvage cross-checks
/// it and refuses rather than re-emitting the covered keys as live.
#[test]
fn salvage_refuses_a_range_tombstone_hidden_as_a_recognized_section() -> crate::Result<()> {
    use crate::UserKey;
    use crate::config::BloomConstructionPolicy;
    use crate::range_tombstone::RangeTombstone;
    use crate::table::block::BlockType;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Filtering disabled, so renaming range_tombstones to `filter` yields a
    // UNIQUE recognized name (no existing filter to duplicate).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_bloom_policy(BloomConstructionPolicy::BitsPerKey(0.0));
    for i in 0u64..8 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key-002".as_slice()),
        UserKey::from(b"key-005".as_slice()),
        9,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Rename range_tombstones -> filter and re-role its block to Filter: the
    // block loads as a (garbage) filter WITHOUT degrading, so the
    // rebuildable-section flag stays clear and the parsed table reports no range
    // tombstones — but the persisted count still records them.
    crate::test_forge::forge_duplicate_section_name(
        &source,
        b"range_tombstones",
        b"filter",
        BlockType::Filter,
    )?;

    let Err(err) = salvage_sst(&source, dest, &fs) else {
        panic!("a hidden range tombstone must fail salvage");
    };
    let crate::Error::FeatureUnsupported(reason) = &err else {
        panic!("the refusal must be FeatureUnsupported, got {err:?}");
    };
    assert!(
        reason.contains("range tombstones"),
        "the refusal must name range tombstones specifically, got {reason:?}",
    );
    Ok(())
}

/// When the index is UNTRUSTED (its mirror comparison, binary-index
/// authentication, or section tiling fails), an indexed offset is no more
/// provable than a byte-scanned one: a checksum-restamped TLI could point a
/// handle at a frame nested inside a corrupt block's value bytes. So once the
/// physical chain breaks, later indexed handles must be dropped too — the walk
/// recovers only the anchored prefix. (With a TRUSTED index the same corruption
/// stays block-granular; that path is covered by the recovery tests.)
#[test]
fn salvage_drops_indexed_blocks_after_a_break_when_the_index_is_untrusted() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(128)
        .use_partitioned_index();
    for i in 0u64..256 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Resolve a middle block offset BEFORE forging (data blocks precede the TLI,
    // so the TLI forge below leaves this offset valid).
    let smash_offset = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|h| *h.as_ref().offset())
            .collect();
        let Some(&off) = offsets.get(offsets.len() / 2) else {
            panic!("need several data blocks, got {}", offsets.len());
        };
        off
    };

    // Corrupt the tli_tail mirror so it disagrees with the head: the index
    // structure no longer authenticates (the mirrors diverge — exactly a
    // checksum-restamped-TLI signal), though head enumeration still yields
    // every handle.
    crate::test_forge::forge_flip_section_last_payload_byte(&source, b"tli_tail", None)?;

    // Smash the header of the middle data block: the physical chain breaks there.
    {
        let mut bytes = std::fs::read(&source)?;
        let Ok(at) = usize::try_from(smash_offset) else {
            panic!("data block offset {smash_offset} fits usize");
        };
        let Some(b) = bytes.get_mut(at) else {
            panic!("the block header at {at} lies within the file");
        };
        *b ^= 0xFF;
        std::fs::write(&source, &bytes)?;
    }

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    // The anchored prefix before the smash recovers.
    assert!(
        reopen_get(dest.clone(), &fs, b"key-000")?.is_some(),
        "the contiguous prefix before the broken chain must recover: {report:?}",
    );
    // A key in a block AFTER the smash is reachable only through its UNTRUSTED
    // index entry, past a broken boundary — it must NOT be re-emitted.
    assert!(
        reopen_get(dest, &fs, b"key-250")?.is_none(),
        "an indexed block after a broken chain, under an untrusted index, must \
         be dropped, not emitted: {report:?}",
    );
    assert!(
        report.dropped.iter().any(|d| matches!(
            &d.reason,
            DropReason::HeaderCorrupted(msg) if msg.contains("broken")
        )),
        "the surrendered tail must be reported as a broken-chain drop: {report:?}",
    );
    Ok(())
}

/// A PERSISTENT read failure on one block (a bad-sector `Other` / EIO, or a
/// truncated final block) must drop just that block, not abort the whole salvage
/// — otherwise one unreadable block sinks every intact sibling. Only a TRANSIENT
/// read aborts for a retry. The victim block's positioned read faults once with a
/// persistent kind; the rest of the file is intact.
#[test]
fn salvage_drops_a_persistently_unreadable_block_and_keeps_the_rest() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let clean: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer =
        Writer::new(source.clone(), 0, 0, Arc::clone(&clean))?.use_data_block_size(128);
    for i in 0u64..256 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Resolve a MIDDLE data block's offset.
    let victim_offset = {
        let table = open(source.clone(), &clean)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|h| *h.as_ref().offset())
            .collect();
        let Some(&off) = offsets.get(offsets.len() / 2) else {
            panic!("need several data blocks, got {}", offsets.len());
        };
        off
    };

    // Salvage through a fs whose positioned read of that ONE block ALWAYS fails
    // (a persistent bad sector); every read at a different offset succeeds.
    let fault = FaultFs::new(StdFs);
    fault.injector().arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other)).at_offset(victim_offset),
    );
    let faulting: Arc<dyn Fs> = Arc::new(fault);

    // Before the fix this aborted (`Err`); now it recovers, dropping just the
    // unreadable block. (The trusted index resolves the probe failure to a
    // broken-boundary drop rather than a ReadError, but the point is that ONE
    // unreadable block no longer sinks the salvage.)
    let report = salvage_sst(&source, dest.clone(), &faulting)?;
    assert!(
        !report.dropped.is_empty(),
        "a persistently unreadable block must be dropped, not abort the salvage: {report:?}",
    );
    assert!(
        report.blocks_salvaged >= report.blocks_total - report.dropped.len(),
        "every block except the dropped one is salvaged: {report:?}",
    );
    assert!(
        reopen_get(dest, &clean, b"key-000")?.is_some(),
        "an intact block must still be recovered past the dropped one: {report:?}",
    );
    Ok(())
}

/// When the broken-index physical walk hits an UNFRAMEABLE block header, the
/// bytes after it are reachable only by byte-scan resync, so their block
/// boundaries are unprovable: an uncompressed block can carry a complete
/// checksum-valid SST block inside a user value, and a resync would frame that
/// NESTED forge and re-emit its interior entries as genuine data. The walk must
/// fail closed like the blob resync path — drop the whole gap tail after the
/// broken boundary rather than emit unanchored candidates. Only the contiguous,
/// fully-framed prefix (anchored to the trusted section start) is recovered.
#[test]
fn salvage_drops_the_gap_tail_after_an_unframeable_block() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(128)
        .use_partitioned_index();
    for i in 0u64..256 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Smash the header of a block in the FIRST THIRD of the data section (its
    // first byte, so `probe_block_handle_at` cannot frame it). The blocks after
    // it are reachable only by resync, so they must be dropped, not emitted.
    let smash_offset = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|h| *h.as_ref().offset())
            .collect();
        let Some(&off) = offsets.get(offsets.len() / 3) else {
            panic!("need several data blocks, got {}", offsets.len());
        };
        off
    };
    {
        let mut bytes = std::fs::read(&source)?;
        let Ok(at) = usize::try_from(smash_offset) else {
            panic!("data block offset {smash_offset} fits usize");
        };
        let Some(b) = bytes.get_mut(at) else {
            panic!("the block header at {at} lies within the file");
        };
        *b ^= 0xFF;
        std::fs::write(&source, &bytes)?;
    }

    // Corrupt the `index` section so enumeration breaks and the physical walk
    // tiles the whole data section from the start.
    let (index_pos, index_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = crate::sfa::Reader::from_reader(&mut f)?;
        let Some((pos, len)) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"index")
            .map(|e| (e.pos(), e.len()))
        else {
            panic!("a partitioned-index SST must carry an index section");
        };
        (pos, len)
    };
    let Ok(flip) = usize::try_from(index_pos + index_len / 2) else {
        panic!("the index-section offset fits usize");
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    // The anchored prefix (contiguous from the trusted section start) recovers.
    assert!(
        reopen_get(dest.clone(), &fs, b"key-000")?.is_some(),
        "the contiguous prefix before the broken boundary must recover: {report:?}",
    );
    // A late key past the smashed block is reachable only by resync, so it must
    // NOT be re-emitted — its boundary cannot be proven original.
    assert!(
        reopen_get(dest, &fs, b"key-250")?.is_none(),
        "a block reached only by resync must be dropped, not emitted: {report:?}",
    );
    // The dropped tail is reported once with the unanchored reason.
    assert!(
        report.dropped.iter().any(|d| matches!(
            &d.reason,
            DropReason::HeaderCorrupted(msg) if msg.contains("unanchored")
        )),
        "the resync tail must be reported as an unanchored drop: {report:?}",
    );
    Ok(())
}

/// A header-checksum-valid FAKE header can declare an oversized `data_length`
/// that spans the real blocks after it. The walk LOADS each candidate so it
/// never advances by the unvalidated framed size, but the load failure it hits
/// at the fake header breaks the contiguous chain: the swallowed span is then
/// reachable only by byte-scan resync, whose boundaries are unprovable (a
/// nested checksum-valid frame in a user value is indistinguishable from a real
/// block). The walk must fail closed — drop the tail past the fake header
/// rather than resync into it. The anchored prefix before the forge recovers.
#[test]
fn salvage_drops_the_tail_past_a_fake_oversized_block_header() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(128)
        .use_partitioned_index();
    for i in 0u64..256 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Re-stamp a block a quarter of the way in so its header FRAMES (valid
    // header checksum) but claims a size reaching the three-quarter mark — a
    // fake oversized header whose enlarged payload cannot load. The blocks it
    // swallows hold real, mid-table keys.
    let (forge_off, forged_end) = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|h| *h.as_ref().offset())
            .collect();
        let n = offsets.len();
        assert!(n >= 8, "need several data blocks, got {n}");
        let (Some(&off), Some(&end)) = (offsets.get(n / 4), offsets.get(3 * n / 4)) else {
            panic!("the quarter and three-quarter block boundaries exist");
        };
        (off, end)
    };
    crate::test_forge::forge_data_block_oversized_header(&source, forge_off, forged_end)?;

    // Corrupt the `index` section so enumeration breaks and the physical walk
    // tiles the whole data section, reaching the fake header.
    let (index_pos, index_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = crate::sfa::Reader::from_reader(&mut f)?;
        let Some((pos, len)) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"index")
            .map(|e| (e.pos(), e.len()))
        else {
            panic!("a partitioned-index SST must carry an index section");
        };
        (pos, len)
    };
    let Ok(flip) = usize::try_from(index_pos + index_len / 2) else {
        panic!("the index-section offset fits usize");
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    // The anchored prefix before the forge (a quarter of the way in) recovers.
    assert!(
        reopen_get(dest.clone(), &fs, b"key-010")?.is_some(),
        "the contiguous prefix before the fake header must recover: {report:?}",
    );
    // A key inside the swallowed span is reachable only by resync past the fake
    // header, so it must NOT be re-emitted.
    assert!(
        reopen_get(dest, &fs, b"key-128")?.is_none(),
        "a block reached only by resync past the fake header must drop: {report:?}",
    );
    // Only the anchored prefix survives, so the count reflects the first
    // quarter, not the near-full 256 an unbounded resync would emit.
    assert!(
        report.entries_salvaged < 200,
        "the resync tail must not be recovered, got {} of 256: {report:?}",
        report.entries_salvaged,
    );
    assert!(
        report.dropped.iter().any(|d| matches!(
            &d.reason,
            DropReason::HeaderCorrupted(msg) if msg.contains("unanchored")
        )),
        "the swallowed tail must be reported as an unanchored drop: {report:?}",
    );
    Ok(())
}

/// An INTERIOR handle omitted from both forged mirrors leaves the hidden
/// block between two indexed neighbours, exercising the mid-list gap
/// probe (the truncated-mirror sibling only covers the section-tail
/// probe). The block must be framed from the physical tiling and
/// recovered like any indexed block.
#[test]
fn salvage_recovers_an_interior_block_hidden_by_forged_tli_mirrors() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    crate::test_forge::forge_tli_mirrors_drop_interior(&source, 0, None)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.dropped.is_empty(),
        "every block is intact, nothing may drop: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 64,
        "the interior block both forged mirrors hide must still be recovered: {report:?}",
    );
    Ok(())
}

/// BOTH TLI mirrors re-encoded as a SINGLE handle spanning the whole data
/// section pass the cumulative tiling (one span covers the section), the
/// mirror comparison, and the separator cross-check (only the FIRST
/// payload decodes; the tail reads as an unrecognized trailer on a
/// non-ECC block) — yet every later physical block is unreachable through
/// the index, so reads silently miss its keys after the table is
/// accepted. Each handle must frame EXACTLY one physical block.
#[test]
fn verify_tli_mirrors_rejects_a_section_spanning_handle() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the intact table passes the mirror gate.
    open(source.clone(), &fs)?.verify_tli_mirrors()?;

    crate::test_forge::forge_tli_mirrors_span_single_handle(&source, 0)?;

    let table = open(source, &fs)?;
    // Match the frame-check reason specifically: the gate returns several
    // distinct InvalidHeader reasons, and an unrelated one would keep this
    // green without proving the per-handle physical-frame check ran.
    let Err(err) = table.verify_tli_mirrors() else {
        panic!("a handle spanning several physical blocks must fail the mirror gate");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "an index handle's size disagrees with its block's physical frame"
            )
        ),
        "the spanning handle must be rejected by the physical-frame check, got {err:?}",
    );
    Ok(())
}

/// BOTH TLI mirrors re-encoded as a SINGLE handle spanning the whole data
/// section must not blind the SALVAGE walk: advancing the physical cursor
/// by the untrusted indexed size skips every later block, and the oversized
/// non-ECC handle still decodes its first payload — one block "salvaged",
/// zero drops, and repair installs a copy with the rest silently lost. The
/// tiler must trust each handle's span only after the block's own header
/// confirms it, falling back to the physically framed span otherwise.
#[test]
fn salvage_recovers_all_blocks_under_a_section_spanning_handle() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    crate::test_forge::forge_tli_mirrors_span_single_handle(&source, 0)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.dropped.is_empty(),
        "every block is intact, nothing may drop: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 64,
        "the blocks a spanning handle hides must still be recovered: {report:?}",
    );
    Ok(())
}

/// An index handle whose offset sits BEYOND the data section (a checksum-
/// repatched / forged entry) must not set the gap-probe's upper bound: probing
/// the range from the cursor up to that out-of-section offset would scan past
/// the section, potentially to an attacker-controlled `u64` (an unbounded hang,
/// and later SST sections read as candidate data frames). The tiler must skip
/// the out-of-section handle and bound the walk by the section end.
#[test]
fn salvage_ignores_an_index_handle_beyond_the_data_section() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    let n = 64u32;
    for i in 0..u64::from(n) {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Append an index handle at u64::MAX/2 (far past the data section). The real
    // handles stay intact, so a walk that bounds the gap probe to the section
    // recovers every block and finishes; the pre-fix walk scans up to the bogus
    // offset instead. The nextest slow-timeout terminates a hang, so completing
    // at all — with the full key range recovered — is the proof.
    crate::test_forge::forge_tli_mirrors_offset_beyond_section(&source, 0)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every real block is recovered once the out-of-section handle is skipped: {report:?}",
    );
    assert!(
        reopen_get(dest, &fs, b"key-060")?.is_some(),
        "a late key must survive the bounded walk: {report:?}",
    );
    Ok(())
}

/// A cleanly enumerated index handle whose block header does NOT frame and
/// whose stored span is oversized (a spanning forge with a smashed header)
/// must not advance the physical cursor by that UNVERIFIED size: trusting it
/// covers the whole remaining data section, hiding later blocks from the gap
/// walk. The tiler leaves the cursor where it is and lets the physical walk
/// tile the gap, but the smashed header breaks the contiguous chain at the
/// section start, so the tail is reachable only by unprovable byte-scan resync.
/// The walk must fail closed and drop that tail rather than emit it.
#[test]
fn salvage_drops_the_tail_after_an_unframeable_oversized_handle() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Resolve the FIRST data block's offset (the block the spanning handle
    // keeps) BEFORE the forge — the data section is first, so the tli rewrite
    // that follows only shifts later sections and leaves this offset valid.
    let first_off = {
        let table = open(source.clone(), &fs)?;
        let Some(off) = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|h| *h.as_ref().offset())
            .next()
        else {
            panic!("the source carries data blocks");
        };
        off
    };

    // Collapse both TLI mirrors into ONE handle spanning the whole data section
    // (size = sum of every block size), then smash that block's header first
    // byte so it cannot frame: the handle enumerates cleanly through the
    // mirror gate, but its oversized span is now UNVERIFIABLE.
    crate::test_forge::forge_tli_mirrors_span_single_handle(&source, 0)?;
    {
        let mut bytes = std::fs::read(&source)?;
        let Ok(at) = usize::try_from(first_off) else {
            panic!("data block offset {first_off} fits usize");
        };
        let Some(b) = bytes.get_mut(at) else {
            panic!("the block header lies within the file");
        };
        *b ^= 0xFF;
        std::fs::write(&source, &bytes)?;
    }

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    // The smashed header is the FIRST data block, so the contiguous chain never
    // starts: the whole section is reachable only by unprovable resync and must
    // drop. Nothing is recovered, so no salvaged table is written.
    assert_eq!(
        report.entries_salvaged, 0,
        "nothing is anchored, so no entry is recovered: {report:?}",
    );
    assert!(
        !dest.exists(),
        "an all-dropped section produces no salvaged table: {report:?}",
    );
    assert!(
        report.dropped.iter().any(|d| matches!(
            &d.reason,
            DropReason::HeaderCorrupted(msg) if msg.contains("broken")
        )),
        "the dropped section must be reported as a broken-chain drop: {report:?}",
    );
    Ok(())
}

/// A forged `data` SFA-section length whose `pos + len` OVERFLOWS `u64` breaks
/// the TOC tiling: the catalogue can no longer prove that no deletion section is
/// concealed, so standalone salvage fails CLOSED, the same decision repair
/// reaches by dropping such a table. It must reject PROMPTLY (the coverage
/// check reads the TOC, never scans to the overflowed bound), so the hang the
/// naive byte-at-a-time resync would suffer is avoided by refusing before the
/// walk rather than by tiling to a rejected bound.
#[test]
fn salvage_refuses_an_overflowing_data_section() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    let n = 64u32;
    for i in 0..u64::from(n) {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Forge the `data` section's advertised length to `u64::MAX` so its end
    // overflows: the tiling can no longer be proven, so a deletion section could
    // be hidden behind the oversized span.
    crate::test_forge::forge_section_len(&source, b"data", u64::MAX)?;

    // The nextest slow-timeout terminates a hang; a prompt error (before any
    // scan to the overflowed bound) is the proof the coverage check rejected
    // the catalogue instead of tiling to it.
    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("an overflowing data section must fail salvage closed");
    };
    assert!(
        matches!(err, crate::Error::FeatureUnsupported(msg) if msg.contains("TOC may hide a deletion section")),
        "the refusal must name the TOC-coverage gate, not any other refusal, got {err:?}",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "no salvaged copy is produced when the catalogue may hide a deletion",
    );
    Ok(())
}

/// A source whose `seqno_bounds` section is PRESENT but does not decode must
/// fail SALVAGE closed on a table that exposes NO deletion metadata: a
/// re-stamped TOC can rename a `range_tombstones` / `delete_bitmap` section to
/// `seqno_bounds` and re-role its block, leaving a uniquely named, tiled
/// catalogue whose parsed table reports no deletion. Salvage re-derives the
/// seqno bounds from the recovered entries, so it would discard that section
/// and re-emit the suppressed rows as live. A genuinely rotted seqno-bounds
/// section is indistinguishable from the relabel, so both fail closed; those
/// rows come back from a replica, a checkpoint plus journal replay, or a backup.
#[test]
fn salvage_refuses_a_corrupt_seqno_bounds_that_may_hide_a_deletion() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_seqno_in_index(true);
    for i in 0u64..50 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Rot one payload byte of the seqno_bounds block WITHOUT re-stamping its
    // checksum: the recover-time load fails and degrades the map to empty.
    {
        let pos = {
            let mut f = std::fs::File::open(&source)?;
            let reader = match crate::sfa::Reader::from_reader(&mut f) {
                Ok(r) => r,
                Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
            };
            let Some(entry) = reader.toc().iter().find(|e| e.name() == b"seqno_bounds") else {
                panic!("the source carries a seqno_bounds section");
            };
            let Ok(pos) = usize::try_from(entry.pos()) else {
                panic!("pos fits usize");
            };
            pos
        };
        let mut bytes = std::fs::read(&source)?;
        // Past the block header, inside the payload.
        let at = pos + 40;
        let Some(slot) = bytes.get_mut(at) else {
            panic!("payload byte within the file");
        };
        *slot ^= 0xFF;
        std::fs::write(&source, bytes)?;
    }

    // Salvage fails closed: the seqno-bounds section did not decode and the
    // table exposes no deletion, so it may be a relabeled deletion salvage
    // would discard — refuse instead of resurrecting rows.
    let Err(err) = salvage_sst(&source, dest, &fs) else {
        panic!("a corrupt seqno-bounds section with no visible deletion must fail salvage");
    };
    assert!(
        matches!(err, crate::Error::FeatureUnsupported(_)),
        "the refusal names the unsupported salvage, got {err:?}",
    );
    Ok(())
}

/// When BOTH meta mirrors decode under the expected id but DIVERGE (a forged,
/// internally-consistent tail: `compression#data` re-stamped None -> Lz4,
/// `meta_mid` untouched), the tail-first open decodes every data block under
/// the wrong codec, drops them all, and repair would discard a table whose
/// intact MID mirror recovers everything. Salvage must arbitrate the mirrors
/// and keep the attempt that recovers more.
#[cfg(feature = "lz4")]
#[test]
fn salvage_arbitrates_divergent_meta_mirrors() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Forge the TAIL meta's data-block compression from the written None
    // (tag 0) to Lz4 (tag 1) — fresh block checksum, `meta_mid` untouched.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(report.blocks_total > 0, "the walk saw the data blocks");
    assert_eq!(
        report.blocks_salvaged, report.blocks_total,
        "every block is recoverable through the intact MID mirror: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 100,
        "all rows recovered: {report:?}"
    );
    assert!(
        report.dropped.is_empty(),
        "nothing should drop under the intact mirror: {report:?}",
    );
    assert!(report.salvaged_path.is_some(), "a copy was written");

    // The MID attempt's sibling temp path must not survive the arbitration:
    // the winner is renamed over dest, the loser is discarded.
    for entry in std::fs::read_dir(dir.path())? {
        let name = entry?.file_name().to_string_lossy().into_owned();
        assert!(
            !name.contains(".healtmp-"),
            "the arbitration temp file must be renamed or removed, found {name:?}",
        );
    }
    Ok(())
}

/// A MID-arbitration publish whose post-rename directory sync FAILS must not
/// leave the owned destination behind: the rename already populated `dest`,
/// so returning the durability error without cleanup would leave a partial
/// SST a standalone retry's `create_new` open trips over (and the repair
/// caller's rebuilt manifest omits, leaving an orphan). Every other salvage
/// failure path removes its owned destination; this one must too.
///
/// `lz4`-gated: the divergent-mirror arbitration is driven by a
/// `compression#data` forge to Lz4, so the tail attempt only mis-decodes
/// (and the MID attempt wins, taking the publish path) when lz4 is built.
#[cfg(feature = "lz4")]
#[test]
fn salvage_removes_the_mid_copy_when_the_publish_dir_sync_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors so the MID attempt wins and publishes via rename.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // Fail the publish's post-rename directory sync. The tail attempt
    // mis-decodes under the forged codec and drops its only block, so it
    // never finishes (no sync); the MID writer's finish syncs the parent
    // once, and the publish after the MID rename syncs it again. Skip the
    // MID writer's sync and fire on the publish.
    injector.arm(FaultRule::new(FaultOp::SyncDirectory, Fault::Error(ErrorKind::Other)).skip(1));

    // The error must be the INJECTED directory-sync fault: only the publish
    // path both consumes the fault and propagates it. If a future change
    // adds an earlier directory sync, `skip(1)` fires on the MID writer's
    // finish instead — `mid` fails, the arbitration returns the tail
    // attempt's (different) mis-decode error, and this assertion flags that
    // the test no longer covers the publish-sync cleanup path.
    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a failed publish directory sync must fail the salvage");
    };
    assert!(
        err.to_string().contains("injected fault on SyncDirectory"),
        "the salvage error must be the injected publish-sync fault, got {err:?}",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "the owned MID copy must be removed when the publish sync fails",
    );
    for entry in std::fs::read_dir(dir.path())? {
        let name = entry?.file_name().to_string_lossy().into_owned();
        assert!(
            !name.contains(".healtmp-"),
            "the MID temp copy must not survive either, found {name:?}",
        );
    }
    Ok(())
}

/// The MID publish must fall back to a best-effort rename when the backend
/// leaves `Fs::hard_link` unsupported. Such a backend can still create and
/// rename ordinary files, so a divergent-meta salvage must still publish the
/// recovered copy rather than drop a recoverable table.
#[cfg(feature = "lz4")]
#[test]
fn salvage_publishes_the_mid_copy_when_hard_link_is_unsupported() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors so the MID attempt wins and reaches the publish path.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // The backend cannot hard-link: the publish must fall back to a rename.
    injector.arm(FaultRule::new(
        FaultOp::HardLink,
        Fault::Error(ErrorKind::Unsupported),
    ));

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.salvaged_path.as_deref(),
        Some(dest.as_path()),
        "the MID copy must be published via the rename fallback: {report:?}",
    );
    assert!(
        report.entries_salvaged > 0,
        "the recovered table must carry entries: {report:?}",
    );
    assert!(
        std::path::Path::new(&dest).exists(),
        "the recovered table must land at the destination",
    );
    Ok(())
}

/// The MID publish must claim `dest` with an atomic no-replace operation, never
/// a blind rename that clobbers an unowned file. When `dest` is already
/// occupied, the tail attempt's `create_new` open fails against it (so the MID
/// attempt wins and reaches the publish path), and the publish must surface an
/// error while leaving the occupant's bytes untouched and leaking no temp copy.
///
/// The narrower check-then-rename TOCTOU — `dest` appearing only AFTER an
/// existence probe reports it free — is not deterministically reachable through
/// the current fault surface (it cannot force `Fs::exists` to report a present
/// file absent); the no-replace `hard_link` publish closes that window
/// structurally rather than by a racy probe.
///
/// `lz4`-gated: the MID attempt only runs when the meta mirrors DIVERGE, driven
/// by a `compression#data` forge to Lz4 (as in the sibling MID-arbitration
/// tests). Without divergence `salvage_with_context` returns the tail attempt
/// and never reaches the publish path this test targets.
#[cfg(feature = "lz4")]
#[test]
fn salvage_does_not_clobber_an_occupied_destination_when_the_mid_attempt_wins() -> crate::Result<()>
{
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Diverge the meta mirrors so the MID attempt actually runs (the tail
    // attempt mis-decodes under the forged Lz4 codec and drops its block).
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // A racing worker already owns `dest`. The tail attempt's `create_new` open
    // fails against it, so the tail errors and the MID attempt (writing to a
    // temp) wins arbitration and must PUBLISH into the occupied path.
    std::fs::write(&dest, b"racing worker's file")?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "publishing over an occupied destination must fail, got {result:?}",
    );
    assert_eq!(
        std::fs::read(&dest)?,
        b"racing worker's file",
        "the occupant's bytes must survive the failed publish",
    );
    for entry in std::fs::read_dir(dir.path())? {
        let name = entry?.file_name().to_string_lossy().into_owned();
        assert!(
            !name.contains(".healtmp-"),
            "the MID temp copy must not leak, found {name:?}",
        );
    }
    Ok(())
}

/// A STALE arbitration temp file left by a crashed predecessor must not
/// block the MID attempt: the temp-name sequence is process-local, so a
/// fresh process would otherwise pick the same `.healtmp-0` name, fail its
/// `create_new` open, and return the tail attempt's inferior (or failing)
/// result without ever trying the recoverable MID mirror — and tree
/// recovery only sweeps this namespace inside table folders, so a
/// standalone salvage destination stays blocked indefinitely. The
/// arbitration must probe forward to a free name; the foreign artifact is
/// never reclaimed (it may belong to a concurrently running salvage).
///
/// `lz4`-gated: the divergent-mirror arbitration is driven by a
/// `compression#data` forge to Lz4 (see the sibling MID-cleanup test).
#[cfg(feature = "lz4")]
#[test]
fn salvage_arbitration_skips_a_stale_crash_artifact() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors so the MID attempt wins and publishes via rename.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // A crashed predecessor's artifact occupies the FIRST temp name this
    // process would pick (the sequence is a process-local counter and
    // nextest runs each test in its own process, so it starts at zero).
    let stale = dest.with_extension("healtmp-0");
    std::fs::write(&stale, b"crashed predecessor artifact")?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert_eq!(
        report.entries_salvaged, 100,
        "the MID attempt must pick a fresh temp name past the stale artifact: {report:?}",
    );
    assert!(
        std::path::Path::new(&stale).exists(),
        "a foreign artifact is never reclaimed",
    );
    assert_eq!(
        std::fs::read(&stale)?,
        b"crashed predecessor artifact".to_vec(),
        "the stale artifact's bytes stay untouched",
    );
    Ok(())
}

/// When two processes salvage the SAME divergent-mirror SST concurrently, the
/// process-local temp counter can hand both the same `.healtmp-0` name if one's
/// existence probe RACES the other's creation. The loser's `create_new` then
/// fails `AlreadyExists`, and it must NOT discard that path: the file there is
/// the winner's in-progress output. A stale existence probe (a Metadata fault
/// that reports the occupied name absent) plus a pre-existing foreign temp
/// reproduces the race: the tail attempt loses, mid wins, and the foreign
/// `.healtmp-0` must survive the arbitration cleanup.
///
/// `lz4`-gated: the divergent-mirror arbitration is driven by a
/// `compression#data` forge to Lz4.
#[cfg(feature = "lz4")]
#[test]
fn salvage_arbitration_keeps_a_foreign_temp_it_did_not_create() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors so the arbitration runs both attempts.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // A concurrent process's in-progress temp already occupies the FIRST name
    // this process would pick.
    let foreign = dest.with_extension("healtmp-0");
    let sentinel = b"concurrent salvage in-progress output".to_vec();
    std::fs::write(&foreign, &sentinel)?;

    // The tail attempt's existence probe RACES: a Metadata fault makes it see
    // `.healtmp-0` as absent, so it returns that name and the tail's create_new
    // then fails AlreadyExists against the foreign file. The mid attempt picks
    // `.healtmp-1` and wins.
    injector.arm(
        FaultRule::new(FaultOp::Metadata, Fault::Error(ErrorKind::Other))
            .on_path("healtmp-0")
            .once(),
    );

    let report = salvage_sst(&source, dest, &fs)?;
    assert_eq!(
        report.entries_salvaged, 100,
        "the mid attempt recovers every entry: {report:?}",
    );
    assert!(
        std::path::Path::new(&foreign).exists(),
        "the foreign concurrent temp must not be discarded by this salvage",
    );
    assert_eq!(
        std::fs::read(&foreign)?,
        sentinel,
        "the foreign temp's bytes stay untouched",
    );
    Ok(())
}

/// A TRANSIENT failure to open the source for the mirror-divergence probe must
/// not be laundered into `Ok(false)`: that would skip the dual-mirror
/// arbitration and salvage from the tail view alone, so a divergent source (a
/// forged tail layout) could omit healthy blocks the intact MID mirror keeps.
/// The source is being salvaged, so it EXISTS — an open failure here is
/// retryable I/O and must propagate, aborting the salvage so repair retries.
///
/// A single `Open` fault on the source hits exactly the probe's open (the first
/// source open in the flow); the later `salvage_attempt` opens then succeed, so
/// WITHOUT the fix salvage completes on the tail alone (`Ok`). WITH the fix it
/// returns the propagated I/O error.
///
/// `lz4`-gated: the divergent mirror is forged via `compression#data` → Lz4.
#[cfg(feature = "lz4")]
#[test]
fn salvage_propagates_a_transient_open_failure_from_the_mirror_probe() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors: without the fault, the probe would return `Ok(true)`
    // and run the arbitration. The transient open fault must abort instead.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    injector.arm(
        FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Other))
            .on_path("source")
            .once(),
    );

    let result = salvage_sst(&source, dest, &fs);
    assert!(
        matches!(result, Err(crate::Error::Io(_))),
        "a transient open failure in the mirror-divergence probe must propagate, not \
         skip arbitration and salvage tail-only: {result:?}",
    );
    Ok(())
}

/// The ENVIRONMENTAL counterpart: a `PermissionDenied` (or any access failure
/// that does not implicate the bytes) while reading ONE metadata mirror must
/// propagate too, not fall through to "mirrors agree". Falling through skips
/// arbitration and salvages from the remaining mirror alone — and if that one
/// only supports a partial recovery, the repair publishes the lossy result
/// even though a fixed environment would have recovered more from the other.
///
/// `lz4`-gated: the divergent mirror is forged via `compression#data` → Lz4.
#[cfg(feature = "lz4")]
#[test]
fn salvage_propagates_an_environmental_failure_from_the_mirror_probe() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // Fault the positioned reads the probe makes on the mirrors themselves —
    // one mirror unreadable, the other fine — sweeping the skip count so the
    // fault lands inside the probe wherever its reads fall.
    let mut reached = false;
    for skip in 0..24u64 {
        injector.clear();
        injector.arm(
            FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::PermissionDenied))
                .on_path("source")
                .skip(skip)
                .times(1),
        );
        let options = SalvageOptions {
            encryption: None,
            #[cfg(zstd_any)]
            zstd_dictionary: None,
            table_id: 0,
            expected_stored_id: None,
            output_id: None,
            allow_delete_resurrection: false,
            sync_mode: crate::fs::SyncMode::Normal,
            prefix_extractor: None,
            blob_rewrite: None,
            progress: None,
        };
        match super::meta_mirrors_diverge(&source, &fs, &options) {
            Ok(_) => {}
            Err(crate::Error::Io(io)) if io.kind() == ErrorKind::PermissionDenied => {
                reached = true;
            }
            Err(e) => panic!("unexpected probe failure at skip {skip}: {e:?}"),
        }
    }
    assert!(
        reached,
        "no skip count made the probe read a mirror; the sweep proves nothing",
    );
    let _ = dest;
    Ok(())
}

/// A PRE-EXISTING destination must survive a divergent-mirror salvage: the
/// tail attempt correctly fails its `create_new` open, but the MID attempt
/// writes to a sibling temp path and wins the arbitration — publishing it
/// by renaming over `dest` would silently destroy an unrelated file that an
/// API call refusing "destination occupied" is supposed to leave untouched.
///
/// `lz4`-gated: the divergent-mirror arbitration is driven by a
/// `compression#data` forge to Lz4 (see the sibling MID-cleanup test).
#[cfg(feature = "lz4")]
#[test]
fn salvage_refuses_to_overwrite_a_preexisting_destination() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Divergent mirrors, so the arbitration runs a MID attempt after the
    // tail attempt fails on the occupied destination.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    // An unrelated file already occupies the destination.
    let sentinel = b"unrelated pre-existing file".to_vec();
    std::fs::write(&dest, &sentinel)?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "an occupied destination must fail the salvage: {result:?}",
    );
    assert_eq!(
        std::fs::read(&dest)?,
        sentinel,
        "the pre-existing destination must survive byte-for-byte",
    );
    // The losing / refused MID copy must not leak its temp file either.
    for entry in std::fs::read_dir(dir.path())? {
        let name = entry?.file_name().to_string_lossy().into_owned();
        assert!(
            !name.contains(".healtmp-"),
            "the refused MID attempt must clean up its temp copy, found {name:?}",
        );
    }
    Ok(())
}

/// DIVERGENT meta mirrors disable the verbatim copy-through: a divergence
/// confined to a DECODE-TRANSPARENT layout field (`restart_interval#data` —
/// full block decoding is trailer-driven, so every block still reads clean
/// and nothing drops) lets the tail-first attempt finish perfectly, yet a
/// byte-copied block keeps the ORIGINAL encoding while the copy's meta is
/// stamped with the forged interval. The partial-decode read path
/// reconstructs prefix-compressed entries FROM that metadata interval, so
/// the inconsistent pair silently truncates synthesized blocks. Since
/// neither mirror is provably genuine, every block must be RE-ENCODED under
/// the chosen meta — self-consistent whichever mirror wins.
#[test]
fn salvage_reencodes_all_blocks_when_meta_mirrors_diverge() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Forge the TAIL meta's data restart interval from the written 16 to 4 —
    // fresh block checksum, `meta_mid` untouched. Blocks keep decoding
    // (trailer-driven), so the tail attempt sees zero drops.
    crate::test_forge::forge_tail_meta_value(&source, b"restart_interval#data", &[4])?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert_eq!(
        report.entries_salvaged, 100,
        "all rows recovered: {report:?}"
    );
    assert!(report.salvaged_path.is_some(), "a copy was written");
    assert_eq!(
        report.blocks_copied_verbatim, 0,
        "divergent mirrors must force the re-encode path: a byte-copied \
         block would keep the original encoding under the chosen meta's \
         forged layout: {report:?}",
    );
    Ok(())
}

/// When the meta mirrors diverge ONLY in `created_at`, both salvage attempts
/// recover identical blocks and entries, so the completeness tie-break picks the
/// tail. That is SAFE because the recovered copy re-stamps `created_at` fresh at
/// finish and re-derives every other authoritative field (key range, seqnos,
/// counts) from the actual re-emitted entries; the layout is mirrored but
/// re-encoded, so a backdated tail cannot be laundered into the copy. This
/// regression guards that property: if a future change ever carried the source
/// `created_at` forward, the forged backdated value would surface here.
#[test]
fn salvage_does_not_carry_a_forged_created_at_into_the_copy() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..100 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let backdated: u128 = 1;
    crate::test_forge::forge_tail_meta_value(&source, b"created_at", &backdated.to_le_bytes())?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.entries_salvaged, 100, "{report:?}");
    let recovered = open(dest, &fs)?;
    assert_ne!(
        *recovered.metadata.created_at, backdated,
        "the recovered copy must not carry the forged backdated created_at",
    );
    Ok(())
}

/// The point-read reachability walk must reject a cross-block internal-key
/// order inversion. A checksum-restamped later block that raises the seqno of a
/// key ending the previous block leaves both blocks decoding and probing
/// cleanly on their own, yet the global (user key ASC, seqno DESC) order is
/// broken across the boundary: after reopen the index seeks the first block and
/// a later compaction could persist the stale (lower-seqno) version.
#[test]
fn verify_point_read_reachability_rejects_a_cross_block_seqno_inversion() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Two versions of the SAME key, one per block (a 1-byte block budget forces
    // each entry into its own block), so the key's versions span the boundary:
    // block 0 = kkk@2, block 1 = kkk@1 (equal key, descending seqno: valid).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::from_components(
        b"kkk",
        b"v2",
        2,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"kkk",
        b"v1",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Raise the SECOND block's first entry seqno from 1 to 3: block 0 now ends
    // kkk@2 and block 1 starts kkk@3 (equal key, seqno RAISED across the
    // boundary: the invalid inversion).
    let block1_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&second) = offsets.get(1) else {
            panic!("the key's versions must span two blocks, got {offsets:?}");
        };
        let Ok(off) = usize::try_from(second) else {
            panic!("the block offset fits usize");
        };
        off
    };
    crate::test_forge::forge_raise_data_block_first_seqno(&source, block1_off, 3)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(
        &table,
        crate::table::ReconcileGate::PointReadReachability,
        None,
    );
    assert!(
        matches!(&err, crate::Error::InvalidHeader(msg) if msg.contains("out of order")),
        "a cross-block seqno inversion must be rejected, got {err:?}",
    );
    Ok(())
}

/// A checksum-clean row block that ITERATES to fewer entries than its
/// trailer declares must be dropped, not marked recovered: the entry decoder
/// turns a mid-stream parse failure into an ordinary end of iteration, so a
/// block with a valid prefix and a malformed tail would otherwise be
/// counted salvaged while silently losing the remaining keys (or byte-copied
/// verbatim, still malformed).
#[test]
fn salvage_drops_a_row_block_that_decodes_fewer_entries_than_declared() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..3 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Inflate the trailer's item count by one behind a re-stamped block
    // checksum: iteration now yields fewer entries than the block declares.
    crate::test_forge::forge_inflated_item_count(&source)?;

    let report = salvage_sst(&source, dest, &fs)?;
    assert_eq!(
        report.entries_salvaged, 0,
        "an under-decoding block must not contribute recovered entries: {report:?}",
    );
    assert!(
        report
            .dropped
            .iter()
            .any(|d| matches!(d.reason, DropReason::DecodeError(_))),
        "the count mismatch is a dropped DecodeError, not a clean recovery: {report:?}",
    );
    Ok(())
}

/// Regression: a data block can hold several MVCC versions of one user key
/// (same key, descending seqno). The verbatim copy-through path must accept
/// equal user keys — only columnar *ingest* requires strictly-unique keys — so
/// salvaging such a block recovers every version instead of erroring.
#[test]
fn salvage_recovers_a_block_with_multiple_versions_of_one_key() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // One block holding the same user key at several seqnos, surrounded by unique
    // keys. Valid SST order: user key ascending, seqno descending within a key.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    writer.write(InternalValue::from_components(
        b"a".to_vec(),
        b"a".to_vec(),
        1,
        ValueType::Value,
    ))?;
    for seqno in [3u64, 2, 1] {
        writer.write(InternalValue::from_components(
            b"dup".to_vec(),
            format!("v{seqno}").into_bytes(),
            seqno,
            ValueType::Value,
        ))?;
    }
    writer.write(InternalValue::from_components(
        b"z".to_vec(),
        b"z".to_vec(),
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "a healthy SST with MVCC duplicates salvages cleanly: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged, 5,
        "every version is recovered, including all 3 of `dup`: {report:?}",
    );

    let recovered = open(dest, &fs)?;
    assert_eq!(
        recovered.metadata.item_count, 5,
        "all 5 entries (3 versions of `dup`) are recovered",
    );
    Ok(())
}

/// A block where a weak tombstone is immediately followed by a value for the
/// same key (a reclaimable pair) salvages verbatim and recovers both entries —
/// exercising the reclaimable-weak-tombstone accounting on the copy-through path.
#[test]
fn salvage_recovers_a_reclaimable_weak_tombstone_pair() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // SST order is user key ascending, seqno descending: the weak tombstone
    // (higher seqno) precedes the value it reclaims (lower seqno) for `dup`.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    writer.write(InternalValue::from_components(
        b"a".to_vec(),
        b"a".to_vec(),
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"dup".to_vec(),
        b"".to_vec(),
        3,
        ValueType::WeakTombstone,
    ))?;
    writer.write(InternalValue::from_components(
        b"dup".to_vec(),
        b"v1".to_vec(),
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let report = salvage_sst(&source, dest, &fs)?;
    assert!(
        report.is_complete(),
        "healthy SST salvages cleanly: {report:?}"
    );
    assert_eq!(
        report.entries_salvaged, 3,
        "the weak tombstone and both values are recovered: {report:?}",
    );
    assert!(
        report.blocks_copied_verbatim >= 1,
        "the clean block is copied verbatim: {report:?}",
    );
    Ok(())
}

/// `verify_locator` must validate the SLOT hint, not only the block id: a
/// `Restart`-precision locator can keep the correct block id yet redirect
/// a key's slot to a later restart interval holding an older version, so
/// `point_read_at_slot` returns the stale value without falling back to
/// the sorted index. The `Writer` is driven directly (two versions of one
/// key in one block, `restart_interval = 1`, locator enabled) and the
/// locator section is rebuilt with that key's slot pushed from the newest
/// head (0) to the older head (1).
#[test]
fn verify_locator_rejects_a_slot_hint_pointing_at_an_older_version() -> crate::Result<()> {
    use crate::config::{LocatorPolicyEntry, LocatorPrecision};
    use crate::runtime_config::{ChecksumAlgorithm, KvChecksumPolicy};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_restart_interval(1)
        .use_kv_checksums(KvChecksumPolicy::AllLevels, ChecksumAlgorithm::Xxh3_64)
        .use_locator(LocatorPolicyEntry::Enabled {
            precision: LocatorPrecision::Restart,
            block_id_bits: None,
            slot_bits: None,
        });
    // Restart heads (restart_interval = 1) in one block: key-a@2 (head 0),
    // key-a@1 (head 1), key-b (head 2), key-c (head 3).
    writer.write(InternalValue::from_components(
        b"key-a".to_vec(),
        b"new".to_vec(),
        2,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"key-a".to_vec(),
        b"old".to_vec(),
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"key-b".to_vec(),
        b"vb".to_vec(),
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"key-c".to_vec(),
        b"vc".to_vec(),
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the honest locator passes the gates.
    reconcile_clean(&open(source.clone(), &fs)?, None);

    // Rebuild the locator with key-a's slot pushed to head 1 (the older
    // version); key-b / key-c keep their honest heads (2 / 3). block_id 0
    // for the single block.
    let h = |k: &[u8]| crate::hash::hash64(k);
    crate::test_forge::forge_locator_slots(
        &source,
        0,
        &[
            (h(b"key-a"), 0, 1),
            (h(b"key-b"), 0, 2),
            (h(b"key-c"), 0, 3),
        ],
    )?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::Locator, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "locator slot hint does not resolve a key's newest version"
            )
        ),
        "the redirect must be rejected by the slot-hint check, got {err:?}",
    );
    Ok(())
}

/// `verify_locator` must reject a present locator that gives NO answer for a
/// decoded key. The writer omits the section when it cannot build one and
/// otherwise encodes every unique key, so a no-answer locator is a forgery (a
/// `delete_bitmap` relabeled to a locator that resolves nothing). The read path
/// falls back to the sorted index on a miss, but the verifier must treat the
/// unanswered key as corrupt so the relabel cannot pass as deletion-free.
#[test]
fn verify_locator_rejects_a_no_answer_locator() -> crate::Result<()> {
    use crate::config::{LocatorPolicyEntry, LocatorPrecision};
    use crate::runtime_config::{ChecksumAlgorithm, KvChecksumPolicy};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_restart_interval(1)
        .use_kv_checksums(KvChecksumPolicy::AllLevels, ChecksumAlgorithm::Xxh3_64)
        .use_locator(LocatorPolicyEntry::Enabled {
            precision: LocatorPrecision::Restart,
            block_id_bits: None,
            slot_bits: None,
        });
    for k in [b"key-a".as_slice(), b"key-b", b"key-c"] {
        writer.write(InternalValue::from_components(
            k.to_vec(),
            b"v".to_vec(),
            1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the honest locator passes the gates.
    reconcile_clean(&open(source.clone(), &fs)?, None);

    // Rebuild the locator so key-c resolves to an OUT-OF-RANGE block id: the
    // handle lookup fails and `locate_block` yields no answer for that decoded
    // key (the read path would fall back to the sorted index; the verifier must
    // not). key-a / key-b keep their honest block 0.
    let h = |k: &[u8]| crate::hash::hash64(k);
    crate::test_forge::forge_locator_slots(
        &source,
        0,
        &[
            (h(b"key-a"), 0, 0),
            (h(b"key-b"), 0, 1),
            (h(b"key-c"), 99, 2),
        ],
    )?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::Locator, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "locator gives no answer for a decoded key it should resolve"
            )
        ),
        "the miss must be rejected by the no-answer check, got {err:?}",
    );
    Ok(())
}

/// `verify_filter` must probe the extractor's PREFIX hashes, not only
/// complete-key hashes: a full filter built WITHOUT the configured
/// extractor (a salvage that dropped it, or a forge) still answers every
/// complete-key probe, yet `maybe_contains_prefix` treats the table as
/// definitely absent and prefix scans silently omit its rows. No forge is
/// needed — a `Writer` run without the extractor produces exactly the
/// filter that lacks the prefix hashes.
#[test]
fn verify_filter_rejects_missing_prefix_hashes() -> crate::Result<()> {
    /// First four key bytes (keys are `keyNNNNN`, so the prefix is `key0`).
    struct FixedLengthPrefix;
    impl crate::prefix::PrefixExtractor for FixedLengthPrefix {
        fn prefixes<'a>(&self, key: &'a [u8]) -> Box<dyn Iterator<Item = &'a [u8]> + 'a> {
            key.get(..4).map_or_else(
                || Box::new(std::iter::empty()) as Box<dyn Iterator<Item = &'a [u8]>>,
                |p| Box::new(std::iter::once(p)),
            )
        }

        fn is_valid_scan_boundary(&self, prefix: &[u8]) -> bool {
            prefix.len() == 4
        }
    }

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let extractor: Arc<dyn crate::prefix::PrefixExtractor> = Arc::new(FixedLengthPrefix);

    // Written WITHOUT the extractor: the full filter holds only complete-key
    // hashes, exactly the state a salvage-without-extractor leaves behind.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u32..100 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let table = open(source, &fs)?;
    // Without an extractor the gate only probes complete keys and passes.
    reconcile_clean(&table, None);
    // WITH the extractor it probes each key's prefix hash, which the filter
    // never indexed — a false negative on an existing key's prefix.
    let err = reconcile_error(
        &table,
        crate::table::ReconcileGate::Filter,
        Some(&extractor),
    );
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "filter reports an existing key's prefix as definitely absent"
            )
        ),
        "the missing prefix hash must be the rejection reason, got {err:?}",
    );
    Ok(())
}

/// The point-read reachability gate must require the probe to return the
/// NEWEST version of a key, not merely SOME version. A key spanning two
/// restart intervals has a CONFLICT-marked hash bucket; redirecting that
/// bucket to the later interval (an OLDER version) still makes
/// `point_read(MAX_SEQNO)` return `Some`, so an `is_none` check would pass
/// — yet reads after reopen return the stale value. The `Writer` is driven
/// directly (two versions of one key in one block, `restart_interval = 1`,
/// hashed, footered) because a memtable flush deduplicates shadowed
/// versions and cannot produce this layout.
#[test]
fn verify_point_read_reachability_rejects_a_bucket_redirected_to_an_older_version()
-> crate::Result<()> {
    use crate::runtime_config::{ChecksumAlgorithm, KvChecksumPolicy};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_hash_ratio(2.0)
        .use_data_block_restart_interval(1)
        .use_kv_checksums(KvChecksumPolicy::AllLevels, ChecksumAlgorithm::Xxh3_64);
    // "key-a" twice: newest (seqno 2) then older (seqno 1), so both are
    // restart heads in the first block and the key's bucket conflicts.
    writer.write(InternalValue::from_components(
        b"key-a".to_vec(),
        b"new".to_vec(),
        2,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"key-a".to_vec(),
        b"old".to_vec(),
        1,
        ValueType::Value,
    ))?;
    for k in [b"key-b", b"key-c"] {
        writer.write(InternalValue::from_components(
            k.to_vec(),
            b"v".to_vec(),
            1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the intact table passes the reachability gate.
    reconcile_clean(&open(source.clone(), &fs)?, None);

    // Redirect the conflicting bucket to binary-index pos 1 — the second
    // restart head, holding the OLDER (seqno 1) version.
    crate::test_forge::forge_hash_index_bucket(&source, b"key-a", 1, None)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(
        &table,
        crate::table::ReconcileGate::PointReadReachability,
        None,
    );
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "a decoded key's point_read does not return its newest version \
                 (an in-block index disagrees with the entries)"
            )
        ),
        "the redirect must be rejected by the newest-version check, got {err:?}",
    );
    Ok(())
}

/// A `filter_tli` block that does not decode as a filter index must fail
/// SALVAGE closed on a table that exposes NO deletion metadata: a re-stamped
/// TOC can rename a `range_tombstones` / `delete_bitmap` section to
/// `filter_tli` and re-role its block, leaving a uniquely named, tiled
/// catalogue whose parsed table reports no deletion. Salvage re-derives the
/// filter from the recovered keys, so it would discard that section and
/// re-emit the suppressed rows as live. A genuinely rotted filter index is
/// indistinguishable from the relabel, so both fail closed; those rows come back
/// from a replica, a checkpoint plus journal replay, or a backup.
#[test]
fn salvage_refuses_a_corrupt_filter_index_that_may_hide_a_deletion() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_partitioned_filter()
        // A tiny partition budget so several filter partitions spill and
        // the writer emits the `filter_tli` top-level index over them.
        .use_meta_partition_size(3);
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Rot one payload byte of the filter_tli block WITHOUT re-stamping its
    // checksum, so loading it fails like any bit-rotted block.
    {
        let pos = {
            let mut f = std::fs::File::open(&source)?;
            let reader = match crate::sfa::Reader::from_reader(&mut f) {
                Ok(r) => r,
                Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
            };
            let Some(entry) = reader.toc().iter().find(|e| e.name() == b"filter_tli") else {
                panic!("the source carries a filter_tli section");
            };
            let Ok(pos) = usize::try_from(entry.pos()) else {
                panic!("pos fits usize");
            };
            pos
        };
        let mut bytes = std::fs::read(&source)?;
        // First payload byte, derived from the block header length (filter_tli
        // is an Index block) so a header-layout change cannot slide the flip
        // into the header and leave the payload untouched.
        let at =
            pos + crate::table::block::Header::header_len(crate::table::block::BlockType::Index);
        let Some(slot) = bytes.get_mut(at) else {
            panic!("payload byte within the file");
        };
        *slot ^= 0xFF;
        std::fs::write(&source, bytes)?;
    }

    // Provably corrupt: a LIVE open fails closed on the rotted filter index.
    assert!(
        open(source.clone(), &fs).is_err(),
        "the rotted filter index must fail a live open",
    );

    // Salvage fails closed: the filter index did not decode and the table
    // exposes no deletion, so it may be a relabeled deletion salvage would
    // discard — refuse instead of resurrecting rows.
    let Err(err) = salvage_sst(&source, dest, &fs) else {
        panic!("a corrupt filter index with no visible deletion must fail salvage");
    };
    assert!(
        matches!(err, crate::Error::FeatureUnsupported(_)),
        "the refusal names the unsupported salvage, got {err:?}",
    );
    Ok(())
}

/// The rebuilt filter must carry the source's PREFIX hashes: the extractor
/// is configuration (not persisted in the SST), so the salvage writer can
/// only index prefixes when the caller threads the tree's extractor
/// through [`SalvageOptions::prefix_extractor`]. Without it the salvaged
/// copy's filter holds complete-key hashes only, `maybe_contains_prefix`
/// reports every indexed prefix as definitely absent, and the copy's rows
/// silently vanish from prefix scans.
#[test]
fn salvage_preserves_prefix_filter_hashes() -> crate::Result<()> {
    /// First four key bytes, mirroring the tree-level extractor fixtures.
    struct FixedLengthPrefix;
    impl crate::prefix::PrefixExtractor for FixedLengthPrefix {
        fn prefixes<'a>(&self, key: &'a [u8]) -> Box<dyn Iterator<Item = &'a [u8]> + 'a> {
            key.get(..4).map_or_else(
                || Box::new(std::iter::empty()) as Box<dyn Iterator<Item = &'a [u8]>>,
                |p| Box::new(std::iter::once(p)),
            )
        }

        fn is_valid_scan_boundary(&self, prefix: &[u8]) -> bool {
            prefix.len() == 4
        }
    }

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let extractor: Arc<dyn crate::prefix::PrefixExtractor> = Arc::new(FixedLengthPrefix);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_prefix_extractor(Some(Arc::clone(&extractor)));
    for i in 0u32..100 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the SOURCE's filter answers the prefix probes (keys are
    // `key000NN`, so the indexed 4-byte prefixes are `key0`).
    let prefix_hash = crate::hash::hash64(b"key0");
    {
        let table = open(source.clone(), &fs)?;
        assert!(
            table.maybe_contains_prefix(prefix_hash)?,
            "the source filter indexes the prefix",
        );
    }

    let options = SalvageOptions {
        prefix_extractor: Some(Arc::clone(&extractor)),
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.entries_salvaged, 100,
        "all rows recovered: {report:?}"
    );

    // A missing prefix hash is a DEFINITE-absent answer from the rebuilt
    // filter — the salvaged copy would silently vanish from prefix scans.
    let table = open(dest, &fs)?;
    assert!(
        table.maybe_contains_prefix(prefix_hash)?,
        "the salvaged copy's filter must keep the source's prefix hashes",
    );
    Ok(())
}

/// Without a prefix extractor, salvage must NOT emit a filter at all. The
/// extractor is not persisted in the SST and cannot be inferred, so a filter
/// rebuilt from complete-key hashes only would answer `maybe_contains_prefix`
/// with a DEFINITE-absent for a source that came from a prefix-indexed tree,
/// silently dropping every recovered row from prefix scans once the copy is
/// reinstalled. Omitting the filter answers "maybe present" (a full block read),
/// which is always correct; the point-lookup speedup is sacrificed for
/// correctness because the source's indexing intent is unknowable here.
#[test]
fn salvage_omits_the_filter_without_a_prefix_extractor() -> crate::Result<()> {
    /// First four key bytes, mirroring the tree-level extractor fixtures.
    struct FixedLengthPrefix;
    impl crate::prefix::PrefixExtractor for FixedLengthPrefix {
        fn prefixes<'a>(&self, key: &'a [u8]) -> Box<dyn Iterator<Item = &'a [u8]> + 'a> {
            key.get(..4).map_or_else(
                || Box::new(std::iter::empty()) as Box<dyn Iterator<Item = &'a [u8]>>,
                |p| Box::new(std::iter::once(p)),
            )
        }

        fn is_valid_scan_boundary(&self, prefix: &[u8]) -> bool {
            prefix.len() == 4
        }
    }

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let extractor: Arc<dyn crate::prefix::PrefixExtractor> = Arc::new(FixedLengthPrefix);

    // Source built WITH a prefix extractor: its filter indexes the 4-byte
    // prefixes (`key0` for keys `key000NN`).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_prefix_extractor(Some(Arc::clone(&extractor)));
    for i in 0u32..100 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Salvage via the default path with NO extractor threaded (the CLI / API
    // default), so the source's prefix indexing intent is unknown here.
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.entries_salvaged, 100,
        "all rows recovered: {report:?}"
    );

    // The recovered copy must NOT answer a prefix probe definitely-absent: with
    // no extractor the safe rebuilt filter is none, so `maybe_contains_prefix`
    // falls back to "maybe present" instead of a false negative that would hide
    // every recovered row from a prefix scan.
    let prefix_hash = crate::hash::hash64(b"key0");
    let table = open(dest, &fs)?;
    assert!(
        table.maybe_contains_prefix(prefix_hash)?,
        "without the extractor the salvaged copy must not report a prefix as definitely absent",
    );
    Ok(())
}

fn iv(i: u32) -> InternalValue {
    InternalValue::from_components(
        format!("key{i:05}").into_bytes(),
        format!("val{i:05}").into_bytes(),
        1,
        ValueType::Value,
    )
}

/// File offset of the named SFA section, for a fault rule that targets one
/// section's positional read.
fn section_pos(path: &std::path::Path, name: &[u8]) -> u64 {
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) => panic!("opening the source failed: {e:?}"),
    };
    let reader = match crate::sfa::Reader::from_reader(&mut f) {
        Ok(r) => r,
        Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
    };
    let Some(entry) = reader.toc().iter().find(|e| e.name() == name) else {
        panic!(
            "source must carry a {} section",
            String::from_utf8_lossy(name)
        );
    };
    entry.pos()
}

/// Opens an SST as a `Table`, stamping the open with the file's current digest
/// (the source may be corrupt; per-block checksums catch the actual damage).
fn open(path: std::path::PathBuf, fs: &Arc<dyn Fs>) -> crate::Result<Table> {
    open_with_id(path, fs, 0)
}

/// As [`open`] but under an explicit expected table id (the recover
/// cross-checks it against the SST's stored `table_id`).
fn open_with_id(
    path: std::path::PathBuf,
    fs: &Arc<dyn Fs>,
    table_id: crate::TableId,
) -> crate::Result<Table> {
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&**fs, &path)?);
    let mut params = crate::table::RecoverParams::new(
        path,
        checksum,
        table_id,
        Arc::clone(fs),
        default_comparator(),
        Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
    );
    params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
    Table::recover(params)
}

/// As [`open`] but threads an encryption provider so a keyed SST recovers.
#[cfg(feature = "encryption")]
fn open_encrypted(
    path: std::path::PathBuf,
    fs: &Arc<dyn Fs>,
    encryption: Arc<dyn crate::encryption::EncryptionProvider>,
) -> crate::Result<Table> {
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&**fs, &path)?);
    let mut params = crate::table::RecoverParams::new(
        path,
        checksum,
        0,
        Arc::clone(fs),
        default_comparator(),
        Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
    );
    params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
    params.encryption = Some(encryption);
    Table::recover(params)
}

/// A reopen of a salvaged SST: recover it and return its live item count.
fn reopen_item_count(path: std::path::PathBuf, fs: &Arc<dyn Fs>) -> crate::Result<u64> {
    Ok(open(path, fs)?.metadata.item_count)
}

/// Point-reads `key` from the SST at `path` at the latest snapshot — the
/// LOGICAL visibility check behind the physical row counts (a delete either
/// masks the key or, under the resurrection opt-in, leaves it readable).
fn reopen_get(
    path: std::path::PathBuf,
    fs: &Arc<dyn Fs>,
    key: &[u8],
) -> crate::Result<Option<crate::InternalValue>> {
    open(path, fs)?.get(key, crate::MAX_SEQNO, crate::hash::hash64(key))
}

/// An SST from a KV-separated tree carries a `linked_blob_files` section
/// naming every blob file its `ValueHandle`s point into; blob GC / relocation
/// consults it (via `list_blob_file_references`) to decide whether a blob is
/// still referenced. The salvaged copy must carry the SOURCE's links —
/// omitting the section would let GC rewrite or delete a blob that only this
/// table still references, silently breaking its indirections.
#[test]
fn salvage_preserves_the_source_linked_blob_files() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A KV-separated tree: large values go to a blob file, the SST holds
    // indirections plus a linked_blob_files section.
    let crate::AnyTree::Blob(tree) = crate::Config::new(
        dir.path(),
        crate::SequenceNumberCounter::default(),
        crate::SequenceNumberCounter::default(),
    )
    .with_kv_separation(Some(crate::KvSeparationOptions::default()))
    .open()?
    else {
        unreachable!("kv separation configured");
    };
    let big = |i: u32| format!("{i:08}").repeat(512);
    for i in 0u32..10 {
        tree.insert(format!("key{i:05}"), big(i), u64::from(i) + 1);
    }
    tree.flush_active_memtable(10)?;
    let source = {
        let binding = tree.index.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };
    drop(tree);

    let dest = dir.path().join("salvaged");
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(report.is_complete(), "healthy SST: {report:?}");

    // The source's blob links survive into the recovered copy.
    let Some(source_links) = open(source, &fs)?.list_blob_file_references()? else {
        panic!("the source carries a linked_blob_files section");
    };
    assert!(!source_links.is_empty(), "the source references blob files");
    let Some(recovered_links) = open(dest, &fs)?.list_blob_file_references()? else {
        panic!("the salvaged copy carries a linked_blob_files section");
    };
    assert_eq!(
        recovered_links, source_links,
        "the salvaged copy references the same blob files as the source",
    );
    Ok(())
}

/// `verify_blob_links` must reject a table that still carries indirection
/// entries but advertises NO `linked_blob_files` section (dropped or renamed
/// away): returning `Ok` there lets a healed-digest refresh or salvage accept a
/// table with `ValueHandle`s but no blob references, after which blob GC — which
/// consults `list_blob_file_references()` for liveness — can rewrite or drop a
/// blob file this table still points into.
#[test]
fn verify_blob_links_rejects_a_missing_section_with_live_indirections() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let crate::AnyTree::Blob(tree) = crate::Config::new(
        dir.path(),
        crate::SequenceNumberCounter::default(),
        crate::SequenceNumberCounter::default(),
    )
    .with_kv_separation(Some(crate::KvSeparationOptions::default()))
    .open()?
    else {
        unreachable!("kv separation configured");
    };
    let big = |i: u32| format!("{i:08}").repeat(512);
    for i in 0u32..10 {
        tree.insert(format!("key{i:05}"), big(i), u64::from(i) + 1);
    }
    tree.flush_active_memtable(10)?;
    let source = {
        let binding = tree.index.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };
    drop(tree);

    // Drop the linked_blob_files section from the TOC: the table keeps its
    // indirection entries but now advertises no blob references.
    crate::test_forge::forge_section_omitted(&source, b"linked_blob_files")?;

    let table = open(source, &fs)?;
    assert!(
        table.list_blob_file_references()?.is_none(),
        "the forge must leave the table with no blob-link section",
    );
    let Err(err) = table.verify_blob_links() else {
        panic!("a table with live indirections but no blob-link section must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "table carries indirection entries but no linked_blob_files section"
            )
        ),
        "the rejection names the missing-blob-link-section reason, got {err:?}",
    );
    Ok(())
}

/// `verify_blob_links` must reject a PRESENT but empty (zero-count)
/// `linked_blob_files` section. The writer omits the section when there are no
/// blob references, so a present-but-blobless section is a forgery: a
/// `delete_bitmap` replaced by a four-byte zero-count `linked_blob_files` leaves
/// both the derived and recorded maps empty, so the equality check passes and
/// the table is kept after its deletion metadata vanished.
#[cfg(feature = "columnar")]
#[test]
fn verify_blob_links_rejects_a_present_empty_section() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A columnar delete-bearing SST with NO blob indirections (so no real
    // linked_blob_files section exists to duplicate).
    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Replace the delete_bitmap section with a four-byte zero-count
    // linked_blob_files (raw shape valid, records no blob references).
    crate::test_forge::forge_rename_and_replace_section(
        &source,
        b"delete_bitmap",
        b"linked_blob_files",
        &[0, 0, 0, 0],
    )?;

    let table = open(source, &fs)?;
    let Err(err) = table.verify_blob_links() else {
        panic!("a present zero-count linked_blob_files section must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "linked_blob_files section is present but records no blob references"
            )
        ),
        "the rejection names the present-empty blob-link reason, got {err:?}",
    );
    Ok(())
}

/// Standalone salvage must REFUSE a delete-bearing SST whose `delete_bitmap`
/// entry was OMITTED from a re-stamped TOC. The parsed table then reports no
/// deletion (the section's bytes linger unreferenced), no side section
/// degrades, and the mask is not unpositionable, so the relabel and
/// unpositionable guards both pass, and a naive walk would re-emit every
/// physically-present row as live, resurrecting the deleted ones. The repair
/// verifier catches the TOC tiling gap, but `salvage_sst` never runs it: the
/// coverage check must live inside salvage too.
#[cfg(feature = "columnar")]
#[test]
fn salvage_refuses_a_toc_that_omits_a_delete_bitmap() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // OMIT the delete_bitmap TOC entry (bytes remain, nothing references them),
    // re-stamping the trailer so the archive stays internally consistent.
    crate::test_forge::forge_section_omitted(&source, b"delete_bitmap")?;

    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a TOC that hides a deletion section must be refused, not resurrected");
    };
    assert!(
        matches!(err, crate::Error::FeatureUnsupported(msg) if msg.contains("TOC may hide a deletion section")),
        "the refusal must name the hidden-deletion gate, not any other refusal, got {err:?}",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "no salvaged copy is produced when the deletion section may be hidden",
    );
    Ok(())
}

/// A delete-bearing SST whose `delete_bitmap` section is HIDDEN (renamed away or
/// replaced by another valid optional section) must be rejected by the metadata
/// cross-check: the authenticated `descriptor#delete_bitmap_len` still records
/// the positions, so a `> 0` count with no readable bitmap section is a forgery
/// that would resurrect every positionally-deleted row. Uses omission (a
/// recognized-name rename or a valid filter replacement reaches the same state:
/// the count disagrees with the absent section).
#[cfg(feature = "columnar")]
#[test]
fn verify_metadata_bounds_rejects_a_hidden_delete_bitmap() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Hide the delete_bitmap section while the authenticated meta count still
    // records its 3 positions.
    crate::test_forge::forge_section_omitted(&source, b"delete_bitmap")?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("delete_bitmap count disagrees")),
        "the rejection must name the delete_bitmap count mismatch, got {err:?}",
    );
    Ok(())
}

/// An EQUAL-CARDINALITY `delete_bitmap` substitution (a different, checksum-valid
/// bitmap with the same number of positions) passes the count-only cross-check
/// but must be rejected by the content hash: during manifest repair, with no
/// original whole-file digest, it would otherwise resurrect the originally
/// deleted rows and drop different live ones.
#[cfg(feature = "columnar")]
#[test]
fn verify_metadata_bounds_rejects_an_equal_cardinality_delete_bitmap_substitution()
-> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Replace the bitmap with a DIFFERENT set of three positions (same chunk,
    // same cardinality and encoded length, so the count cross-check still
    // passes) — only the CONTENTS differ.
    crate::test_forge::forge_delete_bitmap_substitute(&source, 0, &[6, 21, 41])?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("delete_bitmap contents disagree")),
        "the rejection must name the delete_bitmap content-hash mismatch, got {err:?}",
    );
    Ok(())
}

/// The SALVAGE walk must authenticate the delete-bitmap CONTENTS, not just its
/// positions: an equal-cardinality substitution (a different, checksum-valid
/// bitmap) is structurally positionable, so without a content check salvage
/// applies it and masks the WRONG rows, resurrecting the authentically-deleted
/// rows and dropping different live ones. Salvage has no original whole-file
/// digest, so with the default (no resurrection opt-in) it must fail closed on an
/// unauthenticated bitmap (#90).
#[cfg(feature = "columnar")]
#[test]
fn salvage_authenticates_the_delete_bitmap_before_masking() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Substitute an equal-cardinality bitmap: same count, different positions,
    // checksum-valid, but the meta content hash still records the original.
    crate::test_forge::forge_delete_bitmap_substitute(&source, 0, &[6, 21, 41])?;

    // Default options do NOT opt into resurrection: salvage must refuse rather
    // than apply the unauthenticated (substituted) mask.
    let result = super::salvage_sst(&source, dest, &fs);
    assert!(
        matches!(&result, Err(crate::Error::InvalidHeader(msg)) if msg.contains("resurrect")),
        "an unauthenticated delete-bitmap substitution must fail closed, got {result:?}",
    );
    Ok(())
}

/// `attempt_owns_temp` must prove ownership from the OUTCOME (a written temp),
/// not infer it from the error kind: a salvage attempt that errors BEFORE
/// `Writer::new` (e.g. a range-tombstone refusal) never created the temp, so the
/// arbitration cleanup must NOT discard that path — on shared storage it could be
/// a concurrent creator's file.
#[test]
fn attempt_owns_temp_tracks_the_written_outcome_not_the_error_kind() {
    let report = |salvaged_path| super::SalvageReport {
        salvaged_path,
        blocks_total: 1,
        blocks_salvaged: 1,
        blocks_copied_verbatim: 0,
        entries_salvaged: 1,
        entries_dropped_by_rewrite: 0,
        dropped: alloc::vec::Vec::new(),
        delete_rows_resurrected: false,
    };

    // Wrote a temp → owned.
    assert!(super::attempt_owns_temp(&Ok(report(Some(
        std::path::PathBuf::from("/x")
    )))));
    // Recovered nothing (empty temp already discarded) → not owned.
    assert!(!super::attempt_owns_temp(&Ok(report(None))));
    // Errored BEFORE create (range tombstones) → temp never created → not owned.
    assert!(!super::attempt_owns_temp(&Err(
        crate::Error::FeatureUnsupported("range tombstones")
    )));
}

/// Divergent-mirror arbitration must not let a TRANSIENT failure on one attempt
/// lose to an INCOMPLETE success on the other: a retry of the transient mirror
/// could recover the blocks the incomplete winner dropped, so the arbitration
/// propagates the transient error. A COMPLETE success still wins (a retry cannot
/// improve on it), and a PERSISTENT failure always loses to any success.
#[test]
fn arbitrate_mirrors_propagates_a_transient_loss_to_an_incomplete_success() {
    use super::{DropReason, DroppedBlock, MirrorArbitration, SalvageReport, arbitrate_mirrors};

    let report = |dropped: usize| SalvageReport {
        salvaged_path: Some(std::path::PathBuf::from("/x")),
        blocks_total: 4,
        blocks_salvaged: 4 - dropped,
        blocks_copied_verbatim: 0,
        entries_salvaged: 4,
        entries_dropped_by_rewrite: 0,
        dropped: (0..dropped)
            .map(|i| DroppedBlock {
                offset: i as u64,
                section: b"data".to_vec(),
                reason: DropReason::ChecksumMismatch,
                key_range: None,
            })
            .collect(),
        delete_rows_resurrected: false,
    };
    let complete = || Ok(report(0));
    let incomplete = || Ok(report(1));
    let transient = || {
        Err(crate::Error::Io(crate::io::Error::from(
            crate::io::ErrorKind::Interrupted,
        )))
    };
    let persistent = || {
        Err(crate::Error::Io(crate::io::Error::from(
            crate::io::ErrorKind::Other,
        )))
    };

    // Transient loss vs an INCOMPLETE success → propagate (either side).
    assert_eq!(
        arbitrate_mirrors(&transient(), &incomplete()),
        MirrorArbitration::Propagate,
    );
    assert_eq!(
        arbitrate_mirrors(&incomplete(), &transient()),
        MirrorArbitration::Propagate,
    );
    // Transient loss vs a COMPLETE success → the complete success wins.
    assert_eq!(
        arbitrate_mirrors(&transient(), &complete()),
        MirrorArbitration::PublishMid,
    );
    assert_eq!(
        arbitrate_mirrors(&complete(), &transient()),
        MirrorArbitration::PublishTail,
    );
    // PERSISTENT failure vs an incomplete success → the success wins (a retry
    // cannot help the persistent failure).
    assert_eq!(
        arbitrate_mirrors(&persistent(), &incomplete()),
        MirrorArbitration::PublishMid,
    );
}

/// `publish_from_temp` must not delete `temp` when the winning attempt ERRORED:
/// a failure BEFORE `Writer::new` never created it, and a failure after already
/// discarded its own partial, so the caller owns nothing to remove. Ownership is
/// proven by the OUTCOME, never inferred from the error kind — otherwise, on
/// shared storage, an attempt whose `temp` path collides with a concurrent
/// process's file (e.g. across PID namespaces with the same numeric id) would
/// delete that process's file. Regression for the winner-publication arm, the
/// sibling of the arbitration loser-cleanup fix.
#[test]
fn publish_from_temp_keeps_a_foreign_temp_on_an_erroring_attempt() -> crate::Result<()> {
    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let temp = dir.path().join("dest.healtmp-0");
    let dest = dir.path().join("dest");

    // A concurrent process owns the temp path; THIS attempt never created it.
    std::fs::write(&temp, b"foreign process output")?;

    // The published attempt errored BEFORE `Writer::new` (a deletion-guard
    // refusal is a FeatureUnsupported, not an AlreadyExists race loss).
    let result = Err(crate::Error::FeatureUnsupported("deletion guard"));
    let Err(err) = super::publish_from_temp(&fs, result, &temp, &dest, &SalvageOptions::default())
    else {
        panic!("an erroring attempt must propagate its error");
    };
    assert!(
        matches!(err, crate::Error::FeatureUnsupported("deletion guard")),
        "the original error propagates unchanged, got {err:?}",
    );
    assert!(
        temp.exists(),
        "the foreign temp must survive: this attempt never created it",
    );
    Ok(())
}

/// A PRESENT `delete_bitmap` section that decodes to an EMPTY bitmap must fail
/// salvage closed. The writer only emits the section when the bitmap is
/// non-empty, so a checksum-consistent corruption to empty is a forge: it keeps
/// the section visible (exempting the concealment guards) yet carries no
/// positions, so the masked columnar path would re-emit every deleted row live
/// without the resurrection opt-in.
#[cfg(feature = "columnar")]
#[test]
fn salvage_refuses_a_present_but_empty_delete_bitmap() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Re-stamp the delete_bitmap section as a valid but EMPTY bitmap.
    crate::test_forge::forge_delete_bitmap_empty(&source, 0)?;

    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a present-but-empty delete bitmap must fail salvage closed");
    };
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("delete bitmap cannot be applied")),
        "the refusal must name the unpositionable delete mask, got {err:?}",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "no salvaged copy is produced when the delete bitmap is corrupt to empty",
    );
    Ok(())
}

/// A `delete_bitmap` section that is PRESENT and non-empty while the
/// authenticated `descriptor#delete_bitmap_len` records ZERO must be rejected.
/// The writer stamps the count as `0` precisely when no bitmap section is
/// written, so a `0` count paired with a live section is a forge: a
/// checksum-restamped TOC that grafts another table's bitmap (or relabels an
/// optional section to `delete_bitmap`) onto a no-delete table makes reads
/// apply that mask and silently drop live rows. The guard must compare the
/// count and the section state in BOTH directions, not only reject `count > 0`
/// with no section.
#[cfg(feature = "columnar")]
#[test]
fn verify_metadata_bounds_rejects_a_zero_count_with_a_live_bitmap() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Zero the authenticated count in both mirrors while the section keeps its
    // three live positions: the state a TOC forge reaches by grafting a bitmap
    // onto a genuinely no-delete table (recorded count 0).
    crate::test_forge::forge_meta_value_both_mirrors(
        &source,
        b"descriptor#delete_bitmap_len",
        &0u64.to_le_bytes(),
    )?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("delete_bitmap count disagrees")),
        "the rejection must name the delete_bitmap count mismatch, got {err:?}",
    );
    Ok(())
}

/// A forged TLI that REORDERS columnar block handles must fail salvage closed.
/// `delete_block_starts` is built by walking the index, so a reorder rebuilds
/// the starts in that same reordered sequence and `delete_positions_verified`
/// self-validates against them. But the bitmap positions were assigned in the
/// writer's PHYSICAL block order, so the salvage walk (which sorts blocks back
/// to physical order) would mask against the wrong starts, deleting live rows
/// and resurrecting deleted ones without the opt-in. Anchoring the verification
/// to monotonic physical offsets detects the reorder.
#[cfg(feature = "columnar")]
#[test]
fn salvage_refuses_a_reordered_columnar_index_with_deletes() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Small blocks so the SST spills several columnar data blocks; deletes land
    // across them.
    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 60, 120] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Swap the first two block handles in both TLI mirrors. The index and
    // delete_block_starts now agree with each other but not with the physical
    // bitmap positions.
    crate::test_forge::forge_tli_mirrors_swap_first_two(&source, 0, None)?;

    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a reordered columnar index with deletes must fail salvage closed");
    };
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("delete bitmap cannot be applied")),
        "the refusal must name the unpositionable delete mask, got {err:?}",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "no salvaged copy is produced when the delete bitmap cannot be positioned",
    );
    Ok(())
}

/// `verify_seqno_bounds` must reject a PRESENT `seqno_bounds` section that
/// decodes to an EMPTY map on a table that still holds data blocks: every real
/// writer emits one entry per block, so an empty map (a `delete_bitmap` renamed
/// to `seqno_bounds` and re-stamped empty) means the table's real bounds/deletes
/// metadata was laundered away. Accepting it lets a healed-digest refresh grade
/// the table clean and reopen it without its deletion metadata, resurrecting
/// positionally deleted rows.
#[test]
fn verify_seqno_bounds_rejects_a_present_empty_map_on_a_nonempty_table() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A PLAIN table with the per-block seqno_bounds section enabled.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_seqno_in_index(true)
        .use_data_block_size(128);
    for i in 0u64..64 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Re-stamp the seqno_bounds section as a valid but EMPTY map.
    crate::test_forge::forge_seqno_bounds_empty(&source, 0)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::SeqnoBounds, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader("seqno_bounds is missing a data block's entry")
        ),
        "the rejection names the missing-block-entry reason, got {err:?}",
    );
    Ok(())
}

/// `verify_block_layout` must reject a PRESENT `block_layout` section that
/// decodes to an EMPTY map on a table that carries multi-inner-block frames:
/// the writer only emits the section when it has boundaries to record, so an
/// empty map (a `delete_bitmap` renamed and re-roled to an empty `block_layout`)
/// means the deletion metadata was laundered away. The per-block loop cannot
/// catch it (a block absent from the map is skipped), so accepting it lets a
/// healed-digest refresh keep the table without its delete bitmap.
#[cfg(feature = "zstd")]
#[test]
fn verify_block_layout_rejects_a_present_empty_map_on_a_nonempty_table() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // 256 KiB blocks at zstd L19 split into many inner blocks, so the writer
    // records a real block_layout section.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256 * 1024)
        .use_data_block_compression(crate::CompressionType::Zstd(19));
    for i in 0u64..20_000 {
        writer.write(InternalValue::from_components(
            format!("key-{i:012}").into_bytes(),
            format!("value-{i:08}-payload").into_bytes(),
            1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Re-stamp the block_layout section as a valid but EMPTY map.
    crate::test_forge::forge_block_layout_empty(&source, 0, None)?;

    let table = open(source, &fs)?;
    let Err(err) = table.verify_block_layout() else {
        panic!("an empty block_layout on a table with data blocks must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "block_layout section is present but empty on a table with data blocks"
            )
        ),
        "the rejection names the present-empty block_layout reason, got {err:?}",
    );
    Ok(())
}

/// A recorded boundary that no longer marks where an inner zstd block ends
/// must be rejected BY NAME, and by the reconcile walk rather than a pass of
/// its own.
///
/// The forged section stays checksum-clean and structurally plausible: the ends
/// are still strictly increasing and still finish at the block's uncompressed
/// length, so every cheap check passes. Only decoding the frame reveals that an
/// interior boundary moved — and the partial range-read path bounds its
/// decompression by exactly that boundary, so believing it silently omits keys.
///
/// Driven through `verify_reconcile_gates` because that is where the check now
/// lives: it reuses the frame the walk already read, where the standalone pass
/// re-read every data block to get it.
#[cfg(feature = "zstd")]
#[test]
fn reconcile_gates_with_a_shifted_block_layout_boundary_reject_it() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // 256 KiB blocks at zstd L19: each data block splits into several inner
    // zstd blocks, which is the only shape that carries a block_layout.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256 * 1024)
        .use_data_block_compression(crate::CompressionType::Zstd(19));
    for i in 0u64..20_000 {
        writer.write(InternalValue::from_components(
            format!("key-{i:012}").into_bytes(),
            format!("value-{i:08}-payload").into_bytes(),
            1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Sanity: the untouched table reconciles clean, so the failure below is
    // the forgery and not the fixture.
    let table = open(source.clone(), &fs)?;
    assert!(
        table.verify_reconcile_gates(None, false).is_ok(),
        "the intact multi-inner-block table must reconcile clean",
    );
    drop(table);

    crate::test_forge::forge_block_layout_shifted_end(&source, 0)?;

    let table = open(source, &fs)?;
    let Err((gate, err)) = table.verify_reconcile_gates(None, false) else {
        panic!("a boundary that does not match the frame's inner blocks must be rejected");
    };
    assert!(
        matches!(gate, crate::table::ReconcileGate::BlockLayout),
        "the failure must be attributed to the block-layout gate, got {gate:?}",
    );
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader("block_layout disagrees with the frames' inner blocks")
        ),
        "the rejection names the frame disagreement, got {err:?}",
    );
    Ok(())
}

/// `verify_block_layout` must run the present-but-empty rejection on builds
/// WITHOUT zstd too. The function used to return `Ok(())` for the whole
/// non-zstd build before reading the section, so a columnar SST with positional
/// deletes whose `delete_bitmap` was relabeled to an empty `block_layout` graded
/// clean and reopened without its deletion metadata. The emptiness check now
/// runs independent of the zstd frame cross-check.
#[cfg(all(feature = "columnar", not(feature = "zstd")))]
#[test]
fn verify_block_layout_rejects_an_empty_map_without_zstd() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Relabel the delete_bitmap section to an empty block_layout (the writer
    // never emits a real one on a non-zstd build, so synthesise the forgery).
    crate::test_forge::forge_delete_bitmap_as_empty_block_layout(&source, 0)?;

    let table = open(source, &fs)?;
    let Err(err) = table.verify_block_layout() else {
        panic!("an empty block_layout on a non-zstd table with data blocks must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "block_layout section is present but empty on a table with data blocks"
            )
        ),
        "the rejection names the present-empty block_layout reason, got {err:?}",
    );
    Ok(())
}

/// `verify_filter` must reject a PRESENT full `filter` section that decodes to
/// the empty "no filter installed" sentinel on a table with data blocks: the
/// writer omits the section when filtering is disabled, so a present-empty
/// filter is a forgery (a `delete_bitmap` renamed and re-roled to an empty
/// filter). The read-path probe treats an empty payload permissively — `Ok(true)`
/// for every key — so without this rejection the relabel passes the whole check,
/// a healed digest keeps the table, and reopening resurrects the deleted rows.
#[test]
fn verify_filter_rejects_a_present_empty_full_filter() -> crate::Result<()> {
    use crate::config::BloomConstructionPolicy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_bloom_policy(BloomConstructionPolicy::BitsPerKey(10.0));
    for i in 0u32..200 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Re-stamp the full filter section as a valid but EMPTY payload.
    crate::test_forge::forge_filter_empty(&source, 0)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::Filter, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "filter section is present but empty on a table with data blocks"
            )
        ),
        "the rejection names the present-empty filter reason, got {err:?}",
    );
    Ok(())
}

/// `verify_filter` must reject an empty PARTITION too, not just an empty full
/// filter. The partitioned path seeks the partition for a key and probes it; on
/// the empty "no filter" sentinel `maybe_contains_hash` answers `Ok(true)` for
/// every key, so a partition the writer would never leave empty (a `delete_bitmap`
/// relabeled to an empty filter partition under a re-stamped `filter_tli`) would
/// pass the probe and keep the table as deletion-free.
#[test]
fn verify_filter_rejects_an_empty_partition_for_an_existing_key() -> crate::Result<()> {
    use crate::config::BloomConstructionPolicy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A partitioned filter with a tiny partition budget so several partitions
    // spill and the writer emits the filter_tli over them.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_partitioned_filter()
        .use_meta_partition_size(3)
        .use_bloom_policy(BloomConstructionPolicy::BitsPerKey(10.0));
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Empty the first partition in place (the one covering the lowest keys).
    crate::test_forge::forge_filter_first_partition_empty(&source)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::Filter, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "filter partition is present but empty for an existing key"
            )
        ),
        "the rejection names the present-empty partition reason, got {err:?}",
    );
    Ok(())
}

/// `verify_zone_map` must reject a PRESENT `zone_map` section that decodes to an
/// EMPTY map on a table with data blocks: the writer emits one entry per data
/// block whenever the section exists, so an empty map (a `delete_bitmap`
/// relabeled and re-roled to an empty `zone_map`) means the deletion metadata
/// was laundered away while every semantic gate still passes.
#[cfg(feature = "columnar")]
#[test]
fn verify_zone_map_rejects_a_present_empty_map_on_a_nonempty_table() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true);
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+zonemap SST is non-empty"
    );

    // Re-stamp the zone_map section as a valid but EMPTY map.
    crate::test_forge::forge_zone_map_empty(&source, 0)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::ZoneMap, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "zone_map section is present but empty on a table with data blocks"
            )
        ),
        "the rejection names the present-empty zone_map reason, got {err:?}",
    );
    Ok(())
}

/// On a ROW table `verify_zone_map` must authenticate the synthetic column's
/// IDENTITY, not only its min / max / row count. The writer stamps every
/// whole-block column with `column_id == 0` and zero type / codec / null
/// fields; a re-stamped map can change that id to a consumer value-column id
/// while leaving the key bounds untouched. The bounds check then passes, repair
/// keeps the table, and `ColumnRangePredicate::can_skip_block` reads those key
/// bounds as value-column statistics and can skip blocks holding matching rows.
#[test]
fn verify_zone_map_rejects_a_forged_synthetic_column_id() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_zone_map(true);
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source row+zonemap SST is non-empty"
    );

    // Repurpose the first block's whole-block key statistic as a value-column
    // statistic by changing its id, leaving min / max / row count intact.
    crate::test_forge::forge_zone_map_column_id(&source, 0)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::ZoneMap, None);
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("zone_map synthetic column")),
        "the rejection must name the synthetic column identity, got {err:?}",
    );
    Ok(())
}

/// On a COLUMNAR table `verify_zone_map` authenticates the FULL per-column map
/// by re-deriving it from each decoded block: a columnar block records one entry
/// per stored column, so a re-stamped id (here the user-key column's id flipped
/// to a consumer value-column id) no longer matches the re-derivation and is
/// rejected. This is the columnar counterpart of the row-block synthetic-column
/// identity check.
#[cfg(feature = "columnar")]
#[test]
fn verify_zone_map_rejects_a_forged_columnar_column_id() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true);
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+zonemap SST is non-empty"
    );

    // Flip the first block's first (user-key) column id, leaving every other
    // recorded field intact: the re-derived per-column map still expects the
    // user-key column at id 0, so the mismatch is caught.
    crate::test_forge::forge_zone_map_column_id(&source, 0)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::ZoneMap, None);
    assert!(
        matches!(err, crate::Error::InvalidHeader(msg) if msg.contains("per-column statistics")),
        "the rejection must name the columnar per-column mismatch, got {err:?}",
    );
    Ok(())
}

/// A salvaged COLUMNAR table must keep its per-column zone-map statistics. The
/// clean-block verbatim copy-through re-emits columnar blocks byte-for-byte via
/// `append_verbatim_data_block`; if that path recorded the row-block synthetic
/// column-0 statistic instead of the per-column stats, the salvaged table would
/// fail its own `verify_zone_map` forgery cross-check (the verifier re-derives
/// per-column stats from the decoded columnar block).
#[cfg(feature = "columnar")]
#[test]
fn salvaged_columnar_table_keeps_per_column_zone_statistics() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A clean columnar SST with a zone map and several small data blocks, so at
    // least one clean block is byte-copied verbatim during salvage.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(128);
    for i in 0u32..64 {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.salvaged_path.is_some(),
        "the clean SST salvages: {report:?}",
    );
    assert!(
        report.blocks_copied_verbatim > 0,
        "at least one clean columnar block is byte-copied verbatim: {report:?}",
    );

    let table = open(dest, &fs)?;
    assert!(table.has_zone_map(), "the salvaged copy carries a zone map");
    // The per-column stats the copy-through recorded must equal what the
    // verifier re-derives from each decoded columnar block.
    reconcile_clean(&table, None);
    Ok(())
}

/// `verify_block_layout` must apply the present-empty rejection to ENCRYPTED
/// tables too. The emptiness check used to sit AFTER the `self.encryption`
/// early return, so an encrypted table's empty `block_layout` (a `delete_bitmap`
/// relabeled to `block_layout`) slipped through. Decoding the section with the
/// provider both runs the check and, for a genuine relabel, fails the AEAD open
/// (the block-type AAD binds the real role).
#[cfg(all(feature = "encryption", feature = "zstd"))]
#[test]
fn verify_block_layout_rejects_an_empty_map_on_an_encrypted_table() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let enc: Arc<dyn crate::encryption::EncryptionProvider> =
        Arc::new(crate::encryption::Aes256GcmProvider::new(&[0x42; 32]));

    // 256 KiB blocks at zstd L19 split into many inner blocks, so the writer
    // records a real block_layout section even under encryption.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256 * 1024)
        .use_data_block_compression(crate::CompressionType::Zstd(19))
        .use_encryption(Some(Arc::clone(&enc)));
    for i in 0u64..20_000 {
        writer.write(InternalValue::from_components(
            format!("key-{i:012}").into_bytes(),
            format!("value-{i:08}-payload").into_bytes(),
            1,
            ValueType::Value,
        ))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source encrypted SST is non-empty",
    );

    // Re-stamp the block_layout section as a valid but EMPTY encrypted map.
    crate::test_forge::forge_block_layout_empty(&source, 0, Some(&*enc))?;

    let table = open_encrypted(source, &fs, Arc::clone(&enc))?;
    let Err(err) = table.verify_block_layout() else {
        panic!("an empty block_layout on an encrypted table with data blocks must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "block_layout section is present but empty on a table with data blocks"
            )
        ),
        "the rejection names the present-empty block_layout reason, got {err:?}",
    );
    Ok(())
}

/// `verify_metadata_bounds` must cross-check `seqno#min` against the decoded
/// entries even on a RANGE-TOMBSTONE-bearing table. The synthetic sentinel is
/// only written when the table has NO real KV items, so a table with both point
/// entries AND range tombstones has no sentinel and its decoded seqnos are all
/// real. Skipping the check for every RT-bearing table let both meta mirrors be
/// re-stamped with `seqno#min` raised above a real KV seqno, hiding live
/// versions from snapshots at/below the forged minimum after reopen.
#[test]
fn verify_metadata_bounds_rejects_a_raised_seqno_min_on_a_range_tombstone_table()
-> crate::Result<()> {
    use crate::UserKey;
    use crate::range_tombstone::RangeTombstone;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Point entries at seqnos 1..=8 PLUS a range tombstone: the table carries a
    // range_tombstones section but, having real KV items, writes no sentinel.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..8 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key-002".as_slice()),
        UserKey::from(b"key-005".as_slice()),
        9,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Raise seqno#min above the real minimum KV seqno (1) in BOTH meta mirrors.
    crate::test_forge::forge_meta_value_both_mirrors(&source, b"seqno#min", &5u64.to_le_bytes())?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader("meta seqno#min is above the decoded minimum seqno")
        ),
        "the rejection names the seqno#min branch specifically, got {err:?}",
    );
    Ok(())
}

/// The synthetic-sentinel exclusion must NOT fire on a table with REAL KV
/// entries. Only an RT-ONLY table carries a synthetic sentinel, whose RT-derived
/// seqno the writer keeps ABOVE `highest_kv_seqno`. On an RT+KV table a real weak
/// tombstone whose key and seqno happen to match the RT-minimal `(start, seqno)`
/// contributed to `highest_kv_seqno` (so its seqno is `<=` it) and must be counted
/// toward the seqno bounds — excluding it as if it were the sentinel drops the
/// true minimum, letting a `seqno#min` restamped above that entry pass and hide
/// the live version from snapshots at/below the forged minimum.
#[test]
fn verify_metadata_bounds_keeps_a_real_weak_tombstone_matching_the_rt_sentinel() -> crate::Result<()>
{
    use crate::UserKey;
    use crate::range_tombstone::RangeTombstone;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // key-002 is a REAL weak tombstone at seqno 3 — the TRUE minimum seqno — and
    // its (key, seqno) equals the (seqno, start)-minimal range tombstone's, so
    // the old code mistook it for the synthetic RT-only sentinel and excluded it.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    writer.write(InternalValue::from_components(
        b"key-000".to_vec(),
        b"val-000".to_vec(),
        4,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"key-001".to_vec(),
        b"val-001".to_vec(),
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::new_weak_tombstone(
        UserKey::from(b"key-002".as_slice()),
        3,
    ))?;
    for i in 3u64..8 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 3,
            ValueType::Value,
        ))?;
    }
    // The (seqno, start)-minimal range tombstone is (start = key-002, seqno = 3),
    // so the derived sentinel is exactly the real weak tombstone above. Its end
    // stays within the table key range (max key-007) so coverage passes.
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key-002".as_slice()),
        UserKey::from(b"key-005".as_slice()),
        3,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Raise seqno#min to 4 (above the real minimum 3, at the next-lowest seqno):
    // caught only if the seqno-3 weak tombstone is counted. With the sentinel
    // wrongly excluding it, the decoded minimum becomes 4 and 4 > 4 is false, so
    // the forge slips through.
    crate::test_forge::forge_meta_value_both_mirrors(&source, b"seqno#min", &4u64.to_le_bytes())?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader("meta seqno#min is above the decoded minimum seqno")
        ),
        "the rejection names the seqno#min branch specifically, got {err:?}",
    );
    Ok(())
}

/// `verify_metadata_bounds` must reject a `range_tombstones` section whose
/// decoded count disagrees with the recorded `range_tombstone_count`: a dropped
/// section (or a re-stamped block decoding to a subset) passes coverage for its
/// surviving entries, but the missing ranges no longer mask lower-level data —
/// reads resurrect the keys those tombstones deleted. The recorded count lives
/// in the (separately authenticated) meta block, so a mismatch is a forgery.
#[test]
fn verify_metadata_bounds_rejects_a_range_tombstone_count_mismatch() -> crate::Result<()> {
    use crate::UserKey;
    use crate::range_tombstone::RangeTombstone;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..8 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key-002".as_slice()),
        UserKey::from(b"key-005".as_slice()),
        9,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Drop the range_tombstones section: the meta block still records
    // range_tombstone_count = 1, so the decoded count (0) disagrees.
    crate::test_forge::forge_section_omitted(&source, b"range_tombstones")?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "range_tombstones count disagrees with the recorded range_tombstone_count"
            )
        ),
        "the rejection names the RT count-mismatch reason, got {err:?}",
    );
    Ok(())
}

/// `verify_tli_mirrors` must cross-check each PARTITIONED top-level separator
/// against its partition's last data-block separator. Lowering a top-level
/// separator (in both mirrors) keeps the mirrors equal, the handles tiling, and
/// every LEAF separator matching its block — yet `TwoLevelBlockIndex` seeks by
/// the top-level separator and would route reads to the wrong partition,
/// skipping the keys the real partition holds. Only comparing the top-level
/// separator with the partition's decoded last key catches it.
#[test]
fn verify_tli_mirrors_rejects_a_forged_partition_boundary() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A partitioned index with many small data blocks yields >= 2 top-level
    // partitions, so the forge lowers a real partition BOUNDARY (not a leaf).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_partitioned_index()
        .use_data_block_size(128)
        .use_meta_partition_size(2);
    for i in 0u64..512 {
        writer.write(InternalValue::from_components(
            format!("key-{i:05}").into_bytes(),
            format!("val-{i:05}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Lower the FIRST top-level separator in both TLI mirrors.
    crate::test_forge::forge_tli_mirrors_lower_first_separator(&source, 0, None)?;

    let table = open(source, &fs)?;
    let Err(err) = table.verify_tli_mirrors() else {
        panic!("a forged partition boundary must be rejected");
    };
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "tli separator disagrees with its partition's last separator"
            )
        ),
        "the rejection names the partition-boundary mismatch, got {err:?}",
    );
    Ok(())
}

/// A `linked_blob_files` section that PARSES but under-reports its contents
/// (count word forged to 0, record bytes left in place) must not be trusted
/// as the sole source of the recovered copy's links: the recovered entries
/// still hold `ValueHandle` indirections into the blob file, and blob GC /
/// relocation consults the links to decide liveness — an under-reported list
/// would let GC delete or rewrite a blob the copy still references. Salvage
/// derives the links from the recovered indirections and unions them with
/// the source list.
#[test]
fn salvage_rebuilds_blob_links_from_recovered_indirections() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let crate::AnyTree::Blob(tree) = crate::Config::new(
        dir.path(),
        crate::SequenceNumberCounter::default(),
        crate::SequenceNumberCounter::default(),
    )
    .with_kv_separation(Some(crate::KvSeparationOptions::default()))
    .open()?
    else {
        unreachable!("kv separation configured");
    };
    let big = |i: u32| format!("{i:08}").repeat(512);
    for i in 0u32..10 {
        tree.insert(format!("key{i:05}"), big(i), u64::from(i) + 1);
    }
    tree.flush_active_memtable(10)?;
    let source = {
        let binding = tree.index.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };
    drop(tree);

    // The TRUE links, before the forgery.
    let Some(true_links) = open(source.clone(), &fs)?.list_blob_file_references()? else {
        panic!("the source carries a linked_blob_files section");
    };
    assert!(!true_links.is_empty(), "the source references blob files");

    // Forge the count word to 0: the section still parses (the bound check
    // passes trivially) but reports NO links.
    let pos = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"linked_blob_files")
        else {
            panic!("the source must carry a linked_blob_files section");
        };
        usize::try_from(entry.pos()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(count) = bytes.get_mut(pos..pos + 4) else {
        panic!("linked_blob_files count header within the file");
    };
    count.copy_from_slice(&0u32.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    // Sanity: the forgery took — the source now under-reports.
    let Some(forged) = open(source.clone(), &fs)?.list_blob_file_references()? else {
        panic!("the forged section still parses");
    };
    assert!(forged.is_empty(), "the forged count hides every link");

    let dest = dir.path().join("salvaged");
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(report.is_complete(), "data blocks are healthy: {report:?}");

    // The copy's links are derived from its recovered indirections, not
    // parroted from the forged source list.
    let Some(recovered_links) = open(dest, &fs)?.list_blob_file_references()? else {
        panic!("the salvaged copy must carry links derived from its indirections");
    };
    for link in &true_links {
        assert!(
            recovered_links
                .iter()
                .any(|l| l.blob_file_id == link.blob_file_id),
            "blob file {} is referenced by recovered indirections but missing \
             from the copy's links: {recovered_links:?}",
            link.blob_file_id,
        );
    }
    Ok(())
}

/// A parseable `linked_blob_files` section that OVER-reports — carries a blob
/// id no recovered `ValueHandle` actually references — must not have that
/// source-only id copied into the salvaged table: the id may not exist under
/// `blobs/` at all (a forged record), and a manifest whose table links a blob
/// absent from the blob-file list is a corrupt reference downstream consumers
/// must never see. The copy's links are the recovered indirections, exactly.
#[test]
fn salvage_drops_source_only_blob_links() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let crate::AnyTree::Blob(tree) = crate::Config::new(
        dir.path(),
        crate::SequenceNumberCounter::default(),
        crate::SequenceNumberCounter::default(),
    )
    .with_kv_separation(Some(crate::KvSeparationOptions::default()))
    .open()?
    else {
        unreachable!("kv separation configured");
    };
    let big = |i: u32| format!("{i:08}").repeat(512);
    for i in 0u32..10 {
        tree.insert(format!("key{i:05}"), big(i), u64::from(i) + 1);
    }
    tree.flush_active_memtable(10)?;
    let source = {
        let binding = tree.index.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };
    drop(tree);

    // Forge the FIRST link record's blob id (the leading u64 of the 32-byte
    // record, right after the LE u32 count) to an id that exists nowhere.
    const FORGED_ID: u64 = 9_999_999;
    let pos = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"linked_blob_files")
        else {
            panic!("the source must carry a linked_blob_files section");
        };
        usize::try_from(entry.pos()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(id_slot) = bytes.get_mut(pos + 4..pos + 12) else {
        panic!("first link record within the file");
    };
    id_slot.copy_from_slice(&FORGED_ID.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    // Sanity: the forgery took — the source reports the forged id.
    let Some(forged) = open(source.clone(), &fs)?.list_blob_file_references()? else {
        panic!("the forged section still parses");
    };
    assert!(
        forged.iter().any(|l| l.blob_file_id == FORGED_ID),
        "the source's section carries the forged id",
    );

    let dest = dir.path().join("salvaged");
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(report.is_complete(), "data blocks are healthy: {report:?}");

    let Some(recovered_links) = open(dest, &fs)?.list_blob_file_references()? else {
        panic!("the salvaged copy carries links derived from its indirections");
    };
    assert!(
        !recovered_links.is_empty(),
        "the recovered indirections reference the real blob file",
    );
    assert!(
        !recovered_links.iter().any(|l| l.blob_file_id == FORGED_ID),
        "a source-only id no recovered indirection references must not be \
         copied into the salvaged table: {recovered_links:?}",
    );
    Ok(())
}

/// A KV-separated source whose `linked_blob_files` section is UNREADABLE (a
/// count header claiming more records than the section holds) must not abort
/// the salvage: the section is not authoritative — the walk derives the
/// copy's links from the recovered `ValueHandle` indirections — so the
/// readable data blocks are still recovered and the copy carries the derived
/// links. Failing here would leave the whole table unrecovered over a
/// non-authoritative side section.
#[test]
fn salvage_recovers_with_derived_links_when_the_blob_link_section_is_unreadable()
-> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let crate::AnyTree::Blob(tree) = crate::Config::new(
        dir.path(),
        crate::SequenceNumberCounter::default(),
        crate::SequenceNumberCounter::default(),
    )
    .with_kv_separation(Some(crate::KvSeparationOptions::default()))
    .open()?
    else {
        unreachable!("kv separation configured");
    };
    let big = |i: u32| format!("{i:08}").repeat(512);
    for i in 0u32..10 {
        tree.insert(format!("key{i:05}"), big(i), u64::from(i) + 1);
    }
    tree.flush_active_memtable(10)?;
    let source = {
        let binding = tree.index.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };
    drop(tree);

    // Overwrite the linked_blob_files count header (leading LE u32) with a
    // value far larger than the section can hold, so parsing the records
    // hits EOF and list_blob_file_references errors.
    let pos = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader
            .toc()
            .iter()
            .find(|e| e.name() == b"linked_blob_files")
        else {
            panic!("the source must carry a linked_blob_files section");
        };
        usize::try_from(entry.pos()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(count) = bytes.get_mut(pos..pos + 4) else {
        panic!("linked_blob_files count header within the file");
    };
    count.copy_from_slice(&u32::MAX.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    let dest = dir.path().join("salvaged");
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(report.is_complete(), "data blocks are healthy: {report:?}");

    // The copy's links are derived from its recovered indirections; the
    // unreadable source section contributes nothing.
    let Some(recovered_links) = open(dest, &fs)?.list_blob_file_references()? else {
        panic!("the salvaged copy must carry links derived from its indirections");
    };
    assert!(
        !recovered_links.is_empty(),
        "the recovered indirections reference at least one blob file",
    );
    Ok(())
}

/// Standalone salvage preserves the SOURCE's persisted table id: an
/// unencrypted SST written under a non-zero id salvages WITHOUT the caller
/// supplying that id (the salvage-mode open reads it from the metadata
/// instead of failing the id cross-check against the options default of 0),
/// and the recovered copy is stamped with the source's id — so it keeps its
/// identity when an operator swaps it in for the original.
#[test]
fn salvage_preserves_a_nonzero_source_table_id() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    const TID: crate::TableId = 7;
    let mut writer = Writer::new(source.clone(), TID, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Default options (table_id = 0): the salvage must still open the source
    // and carry its real id through.
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "a healthy non-zero-id SST salvages completely: {report:?}",
    );

    // The recovered copy reopens under the SOURCE's id (the recover
    // cross-checks the stored table_id against the expected one).
    let recovered = open_with_id(dest, &fs, TID)?;
    assert_eq!(
        recovered.metadata.id, TID,
        "the salvaged copy is stamped with the source's table id",
    );
    assert_eq!(recovered.metadata.item_count, u64::from(n));
    Ok(())
}

#[test]
fn salvage_of_a_healthy_sst_recovers_every_block() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Build a multi-block source SST: small data blocks force several blocks so
    // the per-block walk has more than one block to recover.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    assert!(
        report.is_complete(),
        "a healthy SST salvages with no dropped blocks: {report:?}",
    );
    assert!(
        report.blocks_total >= 2,
        "256-byte blocks over 200 entries should yield several data blocks, got {}",
        report.blocks_total,
    );
    assert_eq!(
        report.blocks_salvaged, report.blocks_total,
        "every block of a healthy SST is salvaged",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every entry is recovered",
    );
    assert_eq!(
        report.salvaged_path.as_deref(),
        Some(dest.as_path()),
        "a salvaged file is written when at least one block is recovered",
    );

    // Every block of a healthy SST reads back clean, so every salvaged block is
    // copied through verbatim — none re-encoded.
    assert_eq!(
        report.blocks_copied_verbatim, report.blocks_salvaged,
        "a healthy SST's blocks are all copied verbatim",
    );

    // The salvaged copy is a valid SST that reopens and holds every key.
    assert_eq!(
        reopen_item_count(dest, &fs)?,
        u64::from(n),
        "the salvaged SST reopens with the full item count",
    );
    Ok(())
}

/// A clean block is byte-copied verbatim, not decoded and re-encoded: its raw
/// on-disk bytes in the salvaged SST are identical to the source's, and the walk
/// reports it under `blocks_copied_verbatim`.
#[test]
fn salvage_copies_a_clean_block_verbatim() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "healthy SST salvages clean: {report:?}"
    );
    assert_eq!(
        report.blocks_copied_verbatim, report.blocks_total,
        "every clean block is copied verbatim, none re-encoded",
    );

    // The first data block's raw on-disk bytes must be byte-identical between the
    // source and the salvaged copy (each resolved through its own intact index).
    let first_block = |path: &std::path::Path| -> crate::Result<(usize, usize)> {
        let table = open(path.to_path_buf(), &fs)?;
        let Some(kh) = table.data_block_handles().find_map(Result::ok) else {
            panic!("a non-empty SST has at least one data block");
        };
        let off = usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX);
        Ok((off, kh.as_ref().size() as usize))
    };
    let (src_off, src_size) = first_block(&source)?;
    let (dst_off, dst_size) = first_block(&dest)?;
    assert_eq!(
        src_size, dst_size,
        "the verbatim copy preserves the block's on-disk size",
    );

    let src_bytes = std::fs::read(&source)?;
    let dst_bytes = std::fs::read(&dest)?;
    let src_block = src_bytes.get(src_off..src_off + src_size);
    let dst_block = dst_bytes.get(dst_off..dst_off + dst_size);
    assert!(
        src_block.is_some() && src_block == dst_block,
        "the clean block is copied byte-for-byte into the salvaged SST",
    );
    Ok(())
}

/// One deliberately corrupted data block: salvage drops exactly that block
/// (naming its key range) and recovers every other block, instead of failing
/// the whole file. This is the core block-granular contract.
#[test]
fn salvage_drops_a_corrupted_block_and_keeps_the_rest() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Resolve the second data block's on-disk offset from the (intact) index,
    // then flip a byte inside its PAYLOAD (past the fixed-size block header) so
    // the header still frames but the block's data checksum fails on load.
    // load_data_block reads the block by the index handle's size, so the
    // corruption surfaces as that one block failing at load — kept via the
    // index, dropped as a checksum mismatch — not as a physical-walk desync.
    let target = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&second) = offsets.get(1) else {
            panic!("source SST must have at least two data blocks, got {offsets:?}");
        };
        second
    };
    // Land well past the fixed data-block header (magic + type + checksums +
    // lengths) so the frame stays intact and only the payload rots.
    let header_len = crate::table::block::Header::header_len(crate::table::block::BlockType::Data);
    let Ok(target_usize) = usize::try_from(target) else {
        panic!("data block offset {target} does not fit usize on this target");
    };
    let flip = target_usize + header_len + 8;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    assert!(
        !report.is_complete(),
        "a corrupted block must be reported as dropped: {report:?}",
    );
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the one corrupted block is dropped: {report:?}",
    );
    assert_eq!(
        report.blocks_salvaged,
        report.blocks_total - 1,
        "every block but the corrupted one is recovered",
    );
    assert!(
        report.entries_salvaged > 0 && report.entries_salvaged < u64::from(n),
        "a partial key range is recovered, got {} of {n}",
        report.entries_salvaged,
    );
    assert!(
        report.dropped.first().is_some_and(|d| {
            matches!(d.reason, DropReason::ChecksumMismatch) && d.key_range.is_some()
        }),
        "the dropped block reports a checksum mismatch and names the key range it lost: {report:?}",
    );
    assert_eq!(report.salvaged_path.as_deref(), Some(dest.as_path()));

    // The salvaged copy reopens and holds exactly the recovered entries.
    assert_eq!(
        reopen_item_count(dest, &fs)?,
        report.entries_salvaged,
        "the salvaged SST holds exactly the entries the report counted",
    );
    Ok(())
}

/// A data block whose HEADER no longer frames is dropped by the physical gap
/// walk, not the load path: the index still points at it, but `probe_gap`
/// records the region rather than placing it in `items`. It must still count
/// toward `blocks_total` (the walk INSPECTED it and found it unframeable), so
/// the `blocks_total == recovered + dropped` contract holds. Previously a
/// header-corrupt block dropped without being counted, so `blocks_total`
/// equalled `blocks_salvaged` while a block had been lost: recovery ratios
/// reported full coverage despite the loss.
#[test]
fn salvage_counts_a_header_corrupt_block_in_blocks_total() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Flip a byte INSIDE the second data block's header (its magic), so the
    // physical frame no longer parses: the tiling walk cannot trust the index
    // span and resyncs PAST the block, dropping it through the gap probe rather
    // than the load path: a `dropped` entry that never enters `items`.
    let target = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&second) = offsets.get(1) else {
            panic!("source SST must have at least two data blocks, got {offsets:?}");
        };
        second
    };
    let Ok(target_usize) = usize::try_from(target) else {
        panic!("data block offset {target} does not fit usize on this target");
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(target_usize) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest, &fs)?;

    assert!(
        !report.dropped.is_empty(),
        "the header-corrupt block must be reported dropped: {report:?}",
    );
    assert_eq!(
        report.blocks_total,
        report.blocks_salvaged + report.dropped.len(),
        "every inspected block is either recovered or dropped, a header-corrupt \
         block must count toward the total, not vanish from it: {report:?}",
    );
    Ok(())
}

/// A data block that needs ECC recovery to read is NOT copied verbatim — its
/// on-disk bytes are faulty, so propagating them would carry the corruption into
/// the recovered copy. Salvage re-encodes the healed payload instead (clean bytes
/// in the copy), while the surrounding clean blocks are still copied verbatim.
#[cfg(feature = "page_ecc")]
#[test]
fn salvage_reencodes_an_ecc_recovered_block_rather_than_copying_it() -> crate::Result<()> {
    use crate::table::block::{EccParams, Header};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Data blocks carry RS(4,2) parity, so a small corruption is healed on read
    // rather than failing the block.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_ecc(Some(EccParams::RS_4_2));
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Flip one payload byte of the FIRST data block so reading it must repair via
    // RS parity (an ECC-recovered read, not a clean one).
    let first_off = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().find_map(Result::ok) else {
            panic!("a non-empty SST has at least one data block");
        };
        *kh.as_ref().offset()
    };
    let pos = usize::try_from(first_off).unwrap_or(usize::MAX) + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(pos) {
        *b ^= 0x80;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    // The healed block is recovered, not dropped — nothing is lost.
    assert!(
        report.is_complete(),
        "an ECC-recoverable block is healed, not dropped: {report:?}",
    );
    assert_eq!(
        report.blocks_salvaged, report.blocks_total,
        "every block is recovered",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every entry is recovered",
    );
    // Exactly the healed block was re-encoded; the rest were copied verbatim.
    assert_eq!(
        report.blocks_copied_verbatim,
        report.blocks_salvaged - 1,
        "the ECC-recovered block is re-encoded, not copied verbatim",
    );

    // The salvaged copy reopens with every key; its bytes are freshly encoded, so
    // they no longer need ECC repair.
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n));
    Ok(())
}

/// Bit rot confined to a block's PARITY trailer reads as clean (the payload
/// checksum passes and parity is only consulted on a mismatch), so a verbatim
/// copy would carry the rotted parity into the salvaged SST as latent ECC
/// corruption. Salvage must verify the trailer before copying and re-encode
/// (regenerating fresh parity) when it disagrees: every data block of the
/// recovered copy must carry parity that matches its payload.
#[cfg(feature = "page_ecc")]
#[test]
fn salvage_regenerates_a_rotted_parity_trailer_rather_than_copying_it() -> crate::Result<()> {
    use crate::coding::Decode;
    use crate::table::block::{EccParams, Header, expected_parity_len};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_ecc(Some(EccParams::RS_4_2));
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Flip one byte INSIDE the first data block's parity trailer (right after
    // its `data_length` payload). The payload checksum still verifies, so the
    // block reads back clean with no ECC recovery.
    let first_off = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().find_map(Result::ok) else {
            panic!("a non-empty SST has at least one data block");
        };
        usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(mut cursor) = bytes.get(first_off..) else {
        panic!("first data block within the file");
    };
    let header = Header::decode_from(&mut cursor)?;
    let trailer_pos =
        first_off + Header::header_len(header.block_type) + header.data_length as usize;
    let Some(slot) = bytes.get_mut(trailer_pos) else {
        panic!("parity trailer within the file");
    };
    *slot ^= 0xFF;
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "the payload is intact, every block is recovered: {report:?}",
    );
    assert_eq!(reopen_item_count(dest.clone(), &fs)?, u64::from(n));

    // Every data block of the salvaged copy carries parity that matches its
    // payload — the rotted trailer was regenerated, not byte-copied.
    let dest_bytes = std::fs::read(&dest)?;
    let dest_table = open(dest, &fs)?;
    let (ds, ps) = EccParams::RS_4_2.as_shards();
    for kh in dest_table.data_block_handles() {
        let kh = kh?;
        let off = usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX);
        let Some(mut cursor) = dest_bytes.get(off..) else {
            panic!("block at offset {off} within the file");
        };
        let hdr = Header::decode_from(&mut cursor)?;
        let hlen = Header::header_len(hdr.block_type);
        let dl = hdr.data_length as usize;
        let Some(payload) = dest_bytes.get(off + hlen..off + hlen + dl) else {
            panic!("payload of block at offset {off} within the file");
        };
        let plen = expected_parity_len(hdr.data_length, EccParams::RS_4_2) as usize;
        let Some(trailer) = dest_bytes.get(off + hlen + dl..off + hlen + dl + plen) else {
            panic!("parity trailer of block at offset {off} within the file");
        };
        let fresh = crate::ecc::encode_parity(payload, ds, ps)?;
        assert_eq!(
            trailer,
            fresh.as_slice(),
            "block at offset {off}: the salvaged copy's parity matches its payload",
        );
    }
    Ok(())
}

/// A columnar source with one corrupted PAX data block: the columnar loader
/// fails to reconstruct that block (a torn sub-column frame), so salvage drops
/// it and recovers every other block, writing the survivors as a plain row SST.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_a_corrupted_columnar_block_and_keeps_the_rest() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A columnar SST (PAX blocks + zone map), no deletes so there is no
    // delete-bitmap section to worry about here.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    // Corrupt the second columnar data block's PAYLOAD (offset from the intact
    // index, past the fixed block header) so the frame stays intact but its
    // reconstruction fails on load — kept via the index, dropped at load.
    let target = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&second) = offsets.get(1) else {
            panic!("source columnar SST must have at least two data blocks, got {offsets:?}");
        };
        second
    };
    // Land well past the fixed data-block header so only the payload rots and
    // the header still frames (otherwise the physical walk resyncs past it).
    let header_len = crate::table::block::Header::header_len(crate::table::block::BlockType::Data);
    let Ok(target_usize) = usize::try_from(target) else {
        panic!("data block offset {target} does not fit usize on this target");
    };
    let flip = target_usize + header_len + 8;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;

    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the one corrupted columnar block is dropped: {report:?}",
    );
    assert_eq!(
        report.blocks_salvaged,
        report.blocks_total - 1,
        "every columnar block but the corrupted one is recovered",
    );
    assert!(
        report.entries_salvaged > 0 && report.entries_salvaged < u64::from(n),
        "a partial key range is recovered, got {} of {n}",
        report.entries_salvaged,
    );
    assert_eq!(report.salvaged_path.as_deref(), Some(dest.as_path()));

    // The salvaged copy stays COLUMNAR (mirrored from the source) and holds the
    // recovered rows — no longer degraded to a row-major copy.
    let recovered = open(dest, &fs)?;
    assert_eq!(recovered.metadata.item_count, report.entries_salvaged);
    assert!(
        recovered.metadata.columnar,
        "a columnar source salvages into a columnar copy, not a row-major one",
    );
    Ok(())
}

/// A columnar block whose outer `ColumnBatch` frame decodes but whose row
/// materialization fails (an invalid value-type byte in an otherwise
/// checksum-consistent block) is dropped like any other block-local decode
/// failure — one malformed block must not abort the whole salvage and discard
/// the destination while later blocks are still recoverable.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_a_columnar_block_with_an_invalid_value_type() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::table::block::Header;
    use crate::table::columnar::{CodecId, ColumnBatch};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    // Poison the SECOND data block: decode its ColumnBatch, stamp an invalid
    // value-type tag into the first row, re-encode under the writer's Plain
    // codec (byte-identical framing => same length), and re-stamp the header
    // checksum. The block stays checksum-consistent, so the failure surfaces
    // in row materialization — not as an ordinary checksum drop.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let Some(payload) = block.get(header_len..header_len + header.data_length as usize) else {
        panic!("payload range within the block");
    };
    let mut batch = ColumnBatch::decode(payload)?;
    let poisoned_rows = u64::from(batch.row_count);
    // Columns are ordered (key, seqno, value-type, values...); 0xFF is not a
    // defined ValueType tag.
    let Some(vt_byte) = batch.columns.get_mut(2).and_then(|col| col.data.get_mut(0)) else {
        panic!("value-type column present and non-empty");
    };
    *vt_byte = 0xFF;
    let new_payload = batch.encode(CodecId::Plain)?;
    assert_eq!(
        new_payload.len(),
        payload.len(),
        "a one-byte in-place mutation re-encodes to the same length",
    );
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    assert_eq!(
        new_block.len(),
        header_len,
        "header re-encodes to its length"
    );
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    // Salvage drops exactly the poisoned block and recovers every other one.
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the poisoned block is dropped: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(DropReason::DecodeError(_))
        ),
        "the invalid value-type tag classifies as a decode error: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n) - poisoned_rows,
        "every row outside the poisoned block is recovered",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n) - poisoned_rows);
    Ok(())
}

/// A checksum-consistent columnar block whose entries are OUT OF internal-key
/// order (two adjacent keys swapped) must be dropped, not emitted: verbatim
/// paths skip the ingest ordering checks, so an unvalidated malformed block
/// would register a wrong last-key in the recovered SST's index and corrupt
/// binary search / scan order. The rest of the SST still salvages.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_a_columnar_block_with_out_of_order_keys() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::table::block::Header;
    use crate::table::columnar::{CodecId, ColumnBatch};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    // Poison the SECOND data block: swap the first two rows' user keys inside
    // the key column (equal-length keys keep the Bytes framing intact),
    // re-encode, and re-stamp the header checksum. The block stays
    // checksum-consistent and its rows materialize fine — only the ordering
    // invariant is broken.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let Some(payload) = block.get(header_len..header_len + header.data_length as usize) else {
        panic!("payload range within the block");
    };
    let mut batch = ColumnBatch::decode(payload)?;
    let poisoned_rows = u64::from(batch.row_count);
    assert!(batch.row_count >= 2, "block holds at least two rows");
    {
        // Key column framing: (row_count + 1) LE u32 offsets, then payload.
        let Some(key_col) = batch.columns.first_mut() else {
            panic!("key column present");
        };
        let table_len = (batch.row_count as usize + 1) * 4;
        let off = |data: &[u8], idx: usize| -> usize {
            let Some(b) = data.get(idx * 4..idx * 4 + 4) else {
                panic!("offset {idx} within the frame table");
            };
            u32::from_le_bytes(b.try_into().unwrap_or([0; 4])) as usize
        };
        let (o0, o1, o2) = (
            off(&key_col.data, 0),
            off(&key_col.data, 1),
            off(&key_col.data, 2),
        );
        assert_eq!(o1 - o0, o2 - o1, "adjacent keys are equal-length");
        let len = o1 - o0;
        let Some(first) = key_col.data.get(table_len + o0..table_len + o0 + len) else {
            panic!("first key within the column");
        };
        let first = first.to_vec();
        let Some(second) = key_col.data.get(table_len + o1..table_len + o1 + len) else {
            panic!("second key within the column");
        };
        let second = second.to_vec();
        let Some(dst0) = key_col.data.get_mut(table_len + o0..table_len + o0 + len) else {
            panic!("first key range within the column");
        };
        dst0.copy_from_slice(&second);
        let Some(dst1) = key_col.data.get_mut(table_len + o1..table_len + o1 + len) else {
            panic!("second key range within the column");
        };
        dst1.copy_from_slice(&first);
    }
    let new_payload = batch.encode(CodecId::Plain)?;
    assert_eq!(
        new_payload.len(),
        payload.len(),
        "an in-place key swap re-encodes to the same length",
    );
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    // Salvage drops exactly the out-of-order block and recovers every other one.
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the out-of-order block is dropped: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(DropReason::DecodeError(_))
        ),
        "the ordering violation classifies as a decode error: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n) - poisoned_rows,
        "every row outside the poisoned block is recovered",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n) - poisoned_rows);
    Ok(())
}

/// `verify_point_read_reachability` must enforce the GLOBAL internal-key order
/// for a COLUMNAR table too: it has no in-block key index to probe, but
/// `column_batch_match_entries` binary-searches the key column assuming it is
/// sorted. A checksum-consistent columnar block with two swapped keys — which the
/// other columnar gates (count / zone bounds) tolerate — would otherwise pass
/// salvage-mode repair and be KEPT, then miss the key or return a stale version.
#[cfg(feature = "columnar")]
#[test]
fn verify_point_read_reachability_rejects_a_reordered_columnar_block() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::table::block::Header;
    use crate::table::columnar::{CodecId, ColumnBatch};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    // Swap the first two rows' user keys inside the second block's key column
    // (equal-length keys keep the framing), re-encode, and re-stamp the header
    // checksum: the block stays checksum-consistent and its rows materialize,
    // only the ordering invariant is broken.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let Some(payload) = block.get(header_len..header_len + header.data_length as usize) else {
        panic!("payload range within the block");
    };
    let mut batch = ColumnBatch::decode(payload)?;
    assert!(batch.row_count >= 2, "block holds at least two rows");
    {
        let Some(key_col) = batch.columns.first_mut() else {
            panic!("key column present");
        };
        let table_len = (batch.row_count as usize + 1) * 4;
        let off = |data: &[u8], idx: usize| -> usize {
            let Some(b) = data.get(idx * 4..idx * 4 + 4) else {
                panic!("offset {idx} within the frame table");
            };
            u32::from_le_bytes(b.try_into().unwrap_or([0; 4])) as usize
        };
        let (o0, o1, o2) = (
            off(&key_col.data, 0),
            off(&key_col.data, 1),
            off(&key_col.data, 2),
        );
        assert_eq!(o1 - o0, o2 - o1, "adjacent keys are equal-length");
        let len = o1 - o0;
        let Some(first) = key_col.data.get(table_len + o0..table_len + o0 + len) else {
            panic!("first key within the column");
        };
        let first = first.to_vec();
        let Some(second) = key_col.data.get(table_len + o1..table_len + o1 + len) else {
            panic!("second key within the column");
        };
        let second = second.to_vec();
        let Some(dst0) = key_col.data.get_mut(table_len + o0..table_len + o0 + len) else {
            panic!("first key range within the column");
        };
        dst0.copy_from_slice(&second);
        let Some(dst1) = key_col.data.get_mut(table_len + o1..table_len + o1 + len) else {
            panic!("second key range within the column");
        };
        dst1.copy_from_slice(&first);
    }
    let new_payload = batch.encode(CodecId::Plain)?;
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    let table = open(source, &fs)?;
    let err = reconcile_error(
        &table,
        crate::table::ReconcileGate::PointReadReachability,
        None,
    );
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader(
                "columnar entries are out of order (a user key decreased, or an equal key's \
                 seqno did not strictly decrease) across the walk"
            )
        ),
        "the rejection names the columnar order violation, got {err:?}",
    );
    Ok(())
}

/// A checksum-clean columnar block that decodes as a ZERO-ROW `ColumnBatch`
/// is malformed input (a real writer never emits an empty block): the writer
/// primitive emits nothing for it, so counting it as salvaged would let an
/// SST whose only block is empty report `salvaged_path = Some(dest)` while
/// the empty-table `finish` REMOVES `dest` — and a mixed SST would
/// under-report its dropped key ranges. Such a block must be dropped as a
/// decode error.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_a_zero_row_columnar_block() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::table::block::Header;
    use crate::table::columnar::{
        COL_SEQNO, COL_USER_KEY, COL_VALUE, COL_VALUE_TYPE, CodecId, Column, ColumnBatch, TypeTag,
    };

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A single-block columnar SST (few rows, default block size). An ODD row
    // count lets the retry below flip the payload-length parity by growing
    // every value one byte.
    let n = 9u32;
    let build = |value_pad: usize| -> crate::Result<()> {
        let _ = std::fs::remove_file(&source);
        let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_columnar(true);
        for i in 0..n {
            writer.write(InternalValue::from_components(
                format!("key{i:05}").into_bytes(),
                format!("val{i:05}{}", "x".repeat(value_pad)).into_bytes(),
                1,
                ValueType::Value,
            ))?;
        }
        assert!(writer.finish()?.is_some(), "source SST is non-empty");
        Ok(())
    };
    build(0)?;

    // The zero-row replacement encodes to 8 (row/column counts) + 44 bytes of
    // intrinsic + value column headers, padded to the ORIGINAL payload length
    // with extra empty value sub-columns (Fixed = 10 bytes, Bytes = 14 — every
    // reachable length is even, so an odd source payload is rebuilt one byte
    // per value larger to flip its parity).
    let payload_len = |src: &std::path::Path| -> crate::Result<usize> {
        let bytes = std::fs::read(src)?;
        let mut cursor = bytes.as_slice();
        let header = Header::decode_from(&mut cursor)?;
        Ok(header.data_length as usize)
    };
    let mut target_len = payload_len(&source)?;
    if target_len % 2 != 0 {
        build(1)?;
        target_len = payload_len(&source)?;
    }
    assert_eq!(target_len % 2, 0, "an even payload length is reachable");

    let empty_fixed = |id: u16, width: u8| Column {
        column_id: id,
        type_tag: TypeTag::Fixed(width),
        validity: None,
        data: Vec::new(),
    };
    let mut columns = vec![
        Column {
            column_id: COL_USER_KEY,
            type_tag: TypeTag::Bytes,
            validity: None,
            // A zero-row Bytes column is exactly its (row_count + 1) * 4 = 4
            // byte offset table.
            data: vec![0u8; 4],
        },
        empty_fixed(COL_SEQNO, 8),
        empty_fixed(COL_VALUE_TYPE, 1),
        empty_fixed(COL_VALUE, 1),
    ];
    let Some(mut rem) = target_len.checked_sub(8 + 14 + 10 + 10 + 10) else {
        panic!("source payload larger than the zero-row skeleton");
    };
    let mut next_id = COL_VALUE + 1;
    // Greedy fill: Bytes columns (+14) until the remainder is divisible by
    // 10, then Fixed columns (+10).
    while rem % 10 != 0 {
        columns.push(Column {
            column_id: next_id,
            type_tag: TypeTag::Bytes,
            validity: None,
            data: vec![0u8; 4],
        });
        next_id += 1;
        let Some(next_rem) = rem.checked_sub(14) else {
            panic!("remainder covers a Bytes column");
        };
        rem = next_rem;
    }
    while rem > 0 {
        columns.push(empty_fixed(next_id, 1));
        next_id += 1;
        rem -= 10;
    }
    let batch = ColumnBatch {
        row_count: 0,
        columns,
    };
    let new_payload = batch.encode(CodecId::Plain)?;
    assert_eq!(
        new_payload.len(),
        target_len,
        "the zero-row batch pads to the original payload length",
    );

    // Splice it under a re-stamped checksum (frame length unchanged).
    let mut bytes = std::fs::read(&source)?;
    let mut cursor = bytes.as_slice();
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block: Vec<u8> = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(..new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    // The zero-row block is DROPPED, so nothing is recoverable: no destination
    // is left behind and no salvaged path is reported (the pre-fix behavior
    // counted it as salvaged, reporting Some(dest) for a file the empty-table
    // finish had just removed).
    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "the zero-row block is dropped as malformed: {report:?}",
    );
    assert_eq!(report.blocks_salvaged, 0, "{report:?}");
    assert_eq!(
        report.salvaged_path, None,
        "an SST whose only block is empty reports nothing salvaged",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind",
    );
    Ok(())
}

/// The ROW-source twin of the columnar out-of-order drop: a checksum-clean
/// row block with two adjacent keys swapped passes frame decode and row
/// materialization, so the ordering guard before the emit is the only thing
/// standing between it and a recovered SST with a corrupt index order. The
/// rejection is block-local: the block drops, the rest still salvages.
#[test]
fn salvage_drops_a_row_block_with_out_of_order_keys() -> crate::Result<()> {
    use crate::coding::Encode;
    use crate::comparator::default_comparator;
    use crate::table::block::Header;
    use crate::table::block::decoder::ParsedItem as _;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    // Restart interval 1 + no hash index: every entry stores its full key, so
    // swapping two equal-length keys re-encodes to a byte-identical length.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_data_block_restart_interval(1)
        .use_data_block_hash_ratio(0.0);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Poison the SECOND data block: decode its entries, swap the first two
    // (equal-length keys), re-encode under the same block parameters, and
    // re-stamp the header checksum.
    let (block_off, poisoned_rows, new_block) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        let block_off = usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX);
        let sb = table.salvage_load_block(kh.as_ref(), crate::table::block::BlockType::Data)?;
        let header = sb.block.header;
        let db = crate::table::DataBlock::from_loaded(sb.block, false)?;
        let iter = db.try_iter(default_comparator())?;
        let mut entries: alloc::vec::Vec<crate::InternalValue> =
            iter.map(|p| p.materialize(db.as_slice())).collect();
        assert!(entries.len() >= 2, "block holds at least two rows");
        entries.swap(0, 1);
        let mut new_payload: alloc::vec::Vec<u8> = alloc::vec::Vec::new();
        crate::table::DataBlock::encode_into(&mut new_payload, &entries, 1, 0.0)?;
        assert_eq!(
            new_payload.len(),
            header.data_length as usize,
            "an adjacent equal-length key swap re-encodes to the same length",
        );
        let header_len = Header::header_len(header.block_type);
        let new_header = Header {
            checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
            ..header
        };
        let mut new_block: alloc::vec::Vec<u8> =
            alloc::vec::Vec::with_capacity(header_len + new_payload.len());
        new_header.encode_into(&mut new_block)?;
        new_block.extend_from_slice(&new_payload);
        (block_off, entries.len() as u64, new_block)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the out-of-order block is dropped: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(DropReason::DecodeError(_))
        ),
        "the ordering violation classifies as a decode error: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n) - poisoned_rows,
        "every row outside the poisoned block is recovered",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n) - poisoned_rows);
    Ok(())
}

/// A delete-bearing columnar SST whose TLI mirrors AND zone map both omit
/// the same TRAILING block: the positioning chain over the remaining
/// indexed blocks stays self-consistent, so `delete_positions_verified`
/// passes and the walk takes the masked re-emit — but the hidden block is
/// recovered by the PHYSICAL gap walk with no verified start position,
/// and masking it as "all rows live" would permanently resurrect the rows
/// the delete bitmap marked there, without the explicit resurrection
/// opt-in. The masked path must DROP an index-omitted block instead.
#[cfg(feature = "columnar")]
#[test]
fn salvage_does_not_resurrect_deletes_in_an_index_omitted_block() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    // Deletes land in the LAST block (the one both forges will hide).
    let deleted = [n - 1, n - 2, n - 3];
    for pos in deleted {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Row count of the block both forges hide, for the loss accounting.
    let hidden_rows = {
        let table = open(source.clone(), &fs)?;
        let Some(last) = table.data_block_handles().filter_map(Result::ok).last() else {
            panic!("source must have data blocks");
        };
        let Some(batch) = table.load_columnar_block_masked(last.as_ref())? else {
            panic!("the last block holds live rows");
        };
        // The masked load on the INTACT source applies the bitmap, so add
        // the deletes back for the block's physical row count.
        u64::from(batch.row_count) + deleted.len() as u64
    };

    // Consistent forge: the zone map loses its last entry FIRST (the TLI
    // still addresses the block for the entry lookup), then both TLI
    // mirrors hide the same trailing block.
    crate::test_forge::forge_zone_map_drop_last_entry(&source, 0)?;
    crate::test_forge::forge_tli_mirrors_truncated(&source, 0, None)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "the index-omitted block has no verified delete position and must \
         drop, never re-emit live: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n) - deleted.len() as u64 - (hidden_rows - deleted.len() as u64),
        "every indexed block's surviving rows are recovered: {report:?}",
    );
    for pos in deleted {
        let key = format!("key{pos:05}");
        assert!(
            reopen_get(dest.clone(), &fs, key.as_bytes())?.is_none(),
            "a positionally deleted row must not resurrect via the gap walk",
        );
    }
    Ok(())
}

/// The DELETE-BEARING twin of the columnar out-of-order drop: the swapped
/// keys keep every block's row count intact, so the delete positions still
/// verify and the walk takes the masked re-emit — whose writer then rejects
/// the broken ordering. The rejection stays block-local: only the poisoned
/// block drops, deletes still apply to every other block.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_an_out_of_order_columnar_block_in_a_delete_bearing_sst() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::config::DeleteStrategy;
    use crate::table::block::Header;
    use crate::table::columnar::{CodecId, ColumnBatch};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    let deletes = [5u32, 50, 150];
    for pos in deletes {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Poison the SECOND data block exactly like the delete-free variant: swap
    // the first two rows' user keys inside the key column and re-stamp the
    // checksum. Row counts stay intact, so the delete positions still verify.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let Some(payload) = block.get(header_len..header_len + header.data_length as usize) else {
        panic!("payload range within the block");
    };
    let mut batch = ColumnBatch::decode(payload)?;
    let poisoned_rows = u64::from(batch.row_count);
    assert!(batch.row_count >= 2, "block holds at least two rows");
    {
        let Some(key_col) = batch.columns.first_mut() else {
            panic!("key column present");
        };
        let table_len = (batch.row_count as usize + 1) * 4;
        let off = |data: &[u8], idx: usize| -> usize {
            let Some(b) = data.get(idx * 4..idx * 4 + 4) else {
                panic!("offset {idx} within the frame table");
            };
            u32::from_le_bytes(b.try_into().unwrap_or([0; 4])) as usize
        };
        let (o0, o1, o2) = (
            off(&key_col.data, 0),
            off(&key_col.data, 1),
            off(&key_col.data, 2),
        );
        assert_eq!(o1 - o0, o2 - o1, "adjacent keys are equal-length");
        let len = o1 - o0;
        let Some(first) = key_col.data.get(table_len + o0..table_len + o0 + len) else {
            panic!("first key within the column");
        };
        let first = first.to_vec();
        let Some(second) = key_col.data.get(table_len + o1..table_len + o1 + len) else {
            panic!("second key within the column");
        };
        let second = second.to_vec();
        let Some(dst0) = key_col.data.get_mut(table_len + o0..table_len + o0 + len) else {
            panic!("first key range within the column");
        };
        dst0.copy_from_slice(&second);
        let Some(dst1) = key_col.data.get_mut(table_len + o1..table_len + o1 + len) else {
            panic!("second key range within the column");
        };
        dst1.copy_from_slice(&first);
    }
    let new_payload = batch.encode(CodecId::Plain)?;
    assert_eq!(
        new_payload.len(),
        payload.len(),
        "an in-place key swap re-encodes to the same length",
    );
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the out-of-order block is dropped: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(DropReason::DecodeError(_))
        ),
        "the ordering violation classifies as a decode error: {report:?}",
    );
    // Every row outside the poisoned block is recovered, minus the deletes
    // that fall outside it (none of 5 / 50 / 150 land in the second block,
    // which spans rows ~17..34 at 256-byte blocks).
    assert_eq!(
        report.entries_salvaged,
        u64::from(n) - poisoned_rows - deletes.len() as u64,
        "rows outside the poisoned block are recovered with deletes applied",
    );
    // LOGICAL visibility: the deletes were applied faithfully, so the deleted
    // keys stay masked while a neighbouring live key reads back.
    for pos in deletes {
        assert!(
            reopen_get(dest.clone(), &fs, format!("key{pos:05}").as_bytes())?.is_none(),
            "the deleted key at position {pos} stays masked in the recovered copy",
        );
    }
    assert!(
        reopen_get(dest, &fs, b"key00051")?.is_some(),
        "a neighbouring live key reads back from the recovered copy",
    );
    Ok(())
}

/// A DESTINATION write failure mid-walk is a hard error, not a dropped block:
/// the salvage propagates it and removes the partial destination so a retry
/// or repair caller never sees half-written output.
#[test]
fn salvage_sst_errors_and_discards_the_dest_on_a_write_failure() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    // Values big enough that the destination's buffered writer flushes
    // mid-walk (so the failure surfaces through a block emit, not finish).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..200u32 {
        writer.write(InternalValue::from_components(
            format!("key{i:05}").into_bytes(),
            vec![0xAB; 1_024],
            1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other))
            .on_path("salvaged")
            .once(),
    );
    let result = salvage_sst(&source, dest.clone(), &fs);
    injector.clear();

    assert!(
        result.is_err(),
        "a destination write failure errors the whole salvage: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "the partial destination is removed on a write failure",
    );
    Ok(())
}

/// A delete-bearing columnar SST whose `delete_bitmap` section is renamed and
/// re-roled to a full `filter` launders the deletion metadata: the TOC still
/// tiles with unique recognized names (nothing catches the rename), no delete
/// bitmap remains visible, and (unlike range tombstones) there is no persisted
/// count to cross-check. The relabeled block's payload is not a real `BuRR`
/// filter, so salvage must PROBE the full filter even though it never pins it —
/// the unparsable payload trips the rebuildable-section degradation and the
/// guard fails closed instead of re-emitting the deleted rows live.
#[cfg(feature = "columnar")]
#[test]
fn salvage_refuses_a_delete_bitmap_relabeled_to_a_full_filter() -> crate::Result<()> {
    use crate::config::{BloomConstructionPolicy, DeleteStrategy};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Filtering disabled, so renaming delete_bitmap to `filter` yields a UNIQUE
    // recognized name (no existing filter to duplicate).
    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .use_bloom_policy(BloomConstructionPolicy::BitsPerKey(0.0))
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Rename delete_bitmap -> filter and re-role its block to Filter.
    crate::test_forge::forge_duplicate_section_name(
        &source,
        b"delete_bitmap",
        b"filter",
        crate::table::block::BlockType::Filter,
    )?;

    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a delete_bitmap relabeled to a filter must fail salvage");
    };
    let crate::Error::FeatureUnsupported(reason) = &err else {
        panic!("the refusal must be FeatureUnsupported, got {err:?}");
    };
    assert!(
        reason.contains("rebuildable"),
        "the refusal must name the degraded rebuildable section, got {reason:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );
    Ok(())
}

/// A `delete_bitmap` RENAMED to `filter` in the TOC WITHOUT re-roling its block
/// header still launders the deletion: the block loads (its own checksum is
/// valid) but its role is `DeleteBitmap`, so the filter load returns an
/// `InvalidTag` role mismatch. Salvage must treat that STRUCTURAL failure as a
/// degraded rebuildable section (a byte-flip would break the checksum first, so
/// reaching `InvalidTag` means a valid block of the wrong name), not swallow it as
/// genuine bit-rot, so the guard fails closed rather than re-emitting the rows.
#[cfg(feature = "columnar")]
#[test]
fn salvage_refuses_a_delete_bitmap_renamed_to_a_filter_without_reroling() -> crate::Result<()> {
    use crate::config::{BloomConstructionPolicy, DeleteStrategy};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .use_bloom_policy(BloomConstructionPolicy::BitsPerKey(0.0))
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Rename delete_bitmap -> filter in the TOC but KEEP its DeleteBitmap block
    // role (to_role == the original role re-stamps the same header).
    crate::test_forge::forge_duplicate_section_name(
        &source,
        b"delete_bitmap",
        b"filter",
        crate::table::block::BlockType::DeleteBitmap,
    )?;

    let Err(err) = salvage_sst(&source, dest.clone(), &fs) else {
        panic!("a delete_bitmap renamed to a filter without re-roling must fail salvage");
    };
    let crate::Error::FeatureUnsupported(reason) = &err else {
        panic!("the refusal must be FeatureUnsupported, got {err:?}");
    };
    assert!(
        reason.contains("rebuildable"),
        "the refusal must name the degraded rebuildable section, got {reason:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );
    Ok(())
}

/// By default salvage FAILS CLOSED on a delete-bearing SST whose delete
/// bitmap is unreadable: recovering "all rows live" would resurrect
/// positionally-deleted rows, so that degradation requires the caller's
/// explicit [`SalvageOptions::allow_delete_resurrection`] opt-in. No
/// destination file is left behind.
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_a_corrupt_delete_bitmap_by_default() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Corrupt the `delete_bitmap` SFA section (data blocks stay intact).
    let (db_pos, db_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"delete_bitmap") else {
            panic!("source must carry a delete_bitmap section");
        };
        (entry.pos(), entry.len())
    };
    let flip = usize::try_from(db_pos + db_len / 2).unwrap_or(0);
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "default salvage refuses to resurrect deleted rows: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );
    Ok(())
}

/// Same fail-closed default for the other degradation: a READABLE delete
/// bitmap whose positioning zone map is corrupt cannot be applied, so the
/// default salvage refuses rather than recovering all rows live.
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_an_unpositionable_delete_bitmap_by_default() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Corrupt the `zone_map` section (the bitmap stays readable but can no
    // longer be positioned).
    let (zm_pos, zm_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"zone_map") else {
            panic!("source must carry a zone_map section");
        };
        (entry.pos(), entry.len())
    };
    let flip = usize::try_from(zm_pos + zm_len / 2).unwrap_or(0);
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "default salvage refuses to resurrect deleted rows: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );
    Ok(())
}

/// A columnar source carrying deletes whose `delete_bitmap` section is
/// corrupted (data blocks intact): normal recovery refuses to open it (opening
/// would resurrect deleted rows) and default salvage fails closed, but a
/// caller who explicitly opts into [`SalvageOptions::allow_delete_resurrection`]
/// degrades to "all rows live" and recovers every block.
#[cfg(feature = "columnar")]
#[test]
fn salvage_tolerates_a_corrupt_delete_bitmap_as_all_live() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    // Mark a few positions deleted so a delete-bitmap section is co-written.
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Corrupt the middle of the `delete_bitmap` SFA section (the data blocks
    // stay intact, so only the sidecar is damaged).
    let (db_pos, db_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"delete_bitmap") else {
            panic!("source must carry a delete_bitmap section");
        };
        (entry.pos(), entry.len())
    };
    let flip = usize::try_from(db_pos + db_len / 2).unwrap_or(0);
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    // Normal recovery fails closed: a corrupt bitmap would resurrect deleted rows.
    assert!(
        open(source.clone(), &fs).is_err(),
        "normal recovery must fail closed on a corrupt delete-bitmap",
    );

    // With the explicit opt-in, salvage degrades to "all rows live": every
    // block recovers, nothing masked.
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert!(
        report.is_complete(),
        "the data blocks are intact; only the sidecar was corrupt: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every row is recovered live, the corrupt bitmap is ignored",
    );
    // The SST was written WITH deletes (it carries a delete-bitmap section), so
    // even though the degraded bitmap reads as empty, salvage must NOT take the
    // verbatim copy-through fast path: that would byte-copy the physical blocks
    // (including positionally-deleted rows) without the bitmap. It re-emits
    // instead, so nothing is copied verbatim here.
    assert_eq!(
        report.blocks_copied_verbatim, 0,
        "a delete-bearing SST is never copied verbatim, even with a degraded bitmap: {report:?}",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n));
    Ok(())
}

/// A PERSISTENT read failure of the delete-bitmap SECTION (a bad sector) must
/// honor the salvage opt-in, not abort recovery unconditionally. It fails closed
/// by default, but with the explicit
/// [`SalvageOptions::allow_delete_resurrection`] opt-in it degrades the mask to
/// "all rows live" and recovers every block — the same outcome as a
/// decode-level corruption, reached through the I/O path. Only a TRANSIENT read
/// still propagates for a retry.
#[cfg(feature = "columnar")]
#[test]
fn salvage_tolerates_a_persistently_unreadable_delete_bitmap_as_all_live() -> crate::Result<()> {
    use crate::config::DeleteStrategy;
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let clean: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&clean))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Resolve the delete-bitmap section's file offset.
    let db_pos = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"delete_bitmap") else {
            panic!("source must carry a delete_bitmap section");
        };
        entry.pos()
    };

    // Every positional read of the delete-bitmap section fails with a persistent
    // `Other`/EIO; the data blocks (at other offsets) stay readable.
    let fault = FaultFs::new(StdFs);
    fault
        .injector()
        .arm(FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other)).at_offset(db_pos));
    let fs: Arc<dyn Fs> = Arc::new(fault);

    // Default policy fails closed: an unreadable bitmap would resurrect deleted rows.
    assert!(
        salvage_sst(&source, dest.clone(), &fs).is_err(),
        "default salvage must fail closed on a persistently unreadable delete-bitmap",
    );

    // With the opt-in, salvage degrades to "all rows live" and recovers every block.
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every row is recovered live once the unreadable bitmap degrades: {report:?}",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n));
    Ok(())
}

/// A PERSISTENT read failure of the derived `zone_map` SECTION must not fail the
/// whole `Table::recover`: the zone map is a rebuildable block-skip
/// optimization, so a bad sector in it degrades to an empty map (block-skip
/// disabled) rather than making an otherwise-readable SST unopenable. Only a
/// transient read propagates for a retry.
#[test]
fn recover_degrades_a_persistently_unreadable_zone_map_section() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let clean: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&clean))?.use_zone_map(true);
    for i in 0..64u32 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");
    let zm_pos = section_pos(&source, b"zone_map");

    let fault = FaultFs::new(StdFs);
    fault
        .injector()
        .arm(FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other)).at_offset(zm_pos));
    let fs: Arc<dyn Fs> = Arc::new(fault);

    // Open must SUCCEED with block-skip disabled, not abort on the bad sector.
    let table = open(source, &fs)?;
    assert!(
        table.zone_map.is_empty(),
        "the persistently unreadable zone map degrades to an empty map",
    );
    Ok(())
}

/// As above for the derived `seqno_bounds` SECTION: a persistent read failure
/// disables the seqno block-skip rather than failing `Table::recover`.
#[test]
fn recover_degrades_a_persistently_unreadable_seqno_bounds_section() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let clean: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer =
        Writer::new(source.clone(), 0, 0, Arc::clone(&clean))?.use_seqno_in_index(true);
    for i in 0..64u32 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");
    let sb_pos = section_pos(&source, b"seqno_bounds");

    let fault = FaultFs::new(StdFs);
    fault
        .injector()
        .arm(FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other)).at_offset(sb_pos));
    let fs: Arc<dyn Fs> = Arc::new(fault);

    // Open must SUCCEED with the seqno block-skip disabled, not abort.
    let table = open(source, &fs)?;
    assert!(
        table.seqno_bounds.is_empty(),
        "the persistently unreadable seqno-bounds section degrades to an empty map",
    );
    Ok(())
}

/// An UNREADABLE data block inside a delete-bearing columnar SST makes every
/// later delete position unverifiable: the block's actual row count is
/// unknowable, and trusting the zone map's claim for it would let a
/// checksum-repatched count on exactly that block shift the masks of all
/// later readable blocks undetected. Default salvage must fail closed; the
/// explicit [`SalvageOptions::allow_delete_resurrection`] opt-in recovers the
/// readable rows live (never masking against unverified positions).
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_an_unreadable_block_in_a_delete_bearing_sst() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Corrupt the SECOND data block's bytes (a plain checksum break): the
    // block becomes unreadable, so its actual row count is unknowable.
    let target = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&second) = offsets.get(1) else {
            panic!("source must have at least two data blocks, got {offsets:?}");
        };
        second
    };
    let flip = usize::try_from(target).unwrap_or(0) + 16;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    // Default: fail closed — the delete positions past the unreadable block
    // cannot be proven faithful.
    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "unverifiable delete positions fail the default salvage: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );

    // Explicit opt-in: the readable rows are recovered LIVE; only the corrupt
    // block's rows are lost.
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the corrupt block is dropped: {report:?}",
    );
    assert!(
        report.entries_salvaged < u64::from(n),
        "the dropped block's rows are lost: {report:?}",
    );
    assert_eq!(
        reopen_item_count(dest.clone(), &fs)?,
        report.entries_salvaged,
        "the recovered copy reopens with every salvaged row live",
    );
    // LOGICAL visibility of the resurrection: the deleted positions live
    // outside the corrupt block, so under the opt-in their keys read back.
    for pos in [5u32, 50, 150] {
        assert!(
            reopen_get(dest.clone(), &fs, format!("key{pos:05}").as_bytes())?.is_some(),
            "the opt-in resurrects the deleted key at position {pos}",
        );
    }
    Ok(())
}

/// A delete-bearing columnar SST where one block was REPLACED by a zero-row
/// batch and the zone map's claim for it patched to 0: the position verifier
/// would accept the block (decoded count 0 matches the claim) while the walk
/// drops it as malformed — leaving later blocks masked at starts that no
/// longer reflect the ORIGINAL row layout the bitmap was built against.
/// A zero-row batch is malformed input everywhere else in the salvage
/// pipeline, so the verifier must reject it too and fail the salvage closed.
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_a_zero_row_block_in_a_delete_bearing_sst() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::config::DeleteStrategy;
    use crate::table::block::Header;
    use crate::table::columnar::{
        COL_SEQNO, COL_USER_KEY, COL_VALUE, COL_VALUE_TYPE, CodecId, Column, ColumnBatch, TypeTag,
    };

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Replace the SECOND data block with a length-preserving ZERO-ROW batch
    // (skeleton + padding columns, checksum re-stamped) — the same forgery
    // the plain zero-row test uses.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let target_len = header.data_length as usize;
    assert_eq!(
        target_len % 2,
        0,
        "the padded skeleton needs an even length"
    );
    let empty_fixed = |id: u16, width: u8| Column {
        column_id: id,
        type_tag: TypeTag::Fixed(width),
        validity: None,
        data: Vec::new(),
    };
    let mut columns = vec![
        Column {
            column_id: COL_USER_KEY,
            type_tag: TypeTag::Bytes,
            validity: None,
            data: vec![0u8; 4],
        },
        empty_fixed(COL_SEQNO, 8),
        empty_fixed(COL_VALUE_TYPE, 1),
        empty_fixed(COL_VALUE, 1),
    ];
    let Some(mut rem) = target_len.checked_sub(8 + 14 + 10 + 10 + 10) else {
        panic!("source payload larger than the zero-row skeleton");
    };
    let mut next_id = COL_VALUE + 1;
    while rem % 10 != 0 {
        columns.push(Column {
            column_id: next_id,
            type_tag: TypeTag::Bytes,
            validity: None,
            data: vec![0u8; 4],
        });
        next_id += 1;
        let Some(next_rem) = rem.checked_sub(14) else {
            panic!("remainder covers a Bytes column");
        };
        rem = next_rem;
    }
    while rem > 0 {
        columns.push(empty_fixed(next_id, 1));
        next_id += 1;
        rem -= 10;
    }
    let new_payload = ColumnBatch {
        row_count: 0,
        columns,
    }
    .encode(CodecId::Plain)?;
    assert_eq!(new_payload.len(), target_len, "length-preserving forgery");
    let new_header = Header {
        checksum: crate::Checksum::from_raw(crate::hash::hash128(&new_payload)),
        ..header
    };
    let mut new_block: Vec<u8> = Vec::with_capacity(header_len + new_payload.len());
    new_header.encode_into(&mut new_block)?;
    new_block.extend_from_slice(&new_payload);
    let Some(target) = bytes.get_mut(block_off..block_off + new_block.len()) else {
        panic!("block range within the file");
    };
    target.copy_from_slice(&new_block);

    // Patch the zone map's row_count claim for the second block to 0 (the
    // first column's count drives the derived delete starts) and re-stamp
    // the zone-map block checksum, so the tampered chain is self-consistent.
    let zm_pos = {
        let mut f = std::io::Cursor::new(&bytes);
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"zone_map") else {
            panic!("source must carry a zone_map section");
        };
        usize::try_from(entry.pos()).unwrap_or(usize::MAX)
    };
    let Some(mut zm_cursor) = bytes.get(zm_pos..) else {
        panic!("zone_map section within the file");
    };
    let zm_header = Header::decode_from(&mut zm_cursor)?;
    let zm_header_len = Header::header_len(zm_header.block_type);
    let zm_payload_range =
        zm_pos + zm_header_len..zm_pos + zm_header_len + zm_header.data_length as usize;
    {
        let Some(payload) = bytes.get_mut(zm_payload_range.clone()) else {
            panic!("zone_map payload within the file");
        };
        // Walk the wire layout (count u32; per block: block_offset u64 +
        // n_columns u16; per column: id u32 + type u8 + codec u8 +
        // null_count u32 + row_count u32 + min_len u32 + min + max_len u32
        // + max) to the SECOND block's FIRST column row_count — the field
        // the derived delete starts are built from.
        let read_u32 = |data: &[u8], at: usize| -> u32 {
            let Some(b) = data.get(at..at + 4) else {
                panic!("u32 at {at} within the zone map payload");
            };
            u32::from_le_bytes(b.try_into().unwrap_or([0; 4]))
        };
        let read_u16 = |data: &[u8], at: usize| -> u16 {
            let Some(b) = data.get(at..at + 2) else {
                panic!("u16 at {at} within the zone map payload");
            };
            u16::from_le_bytes(b.try_into().unwrap_or([0; 2]))
        };
        let mut at = 4; // past the block count
        // Skip block 1 entirely: offset u64 + n_columns u16, then each
        // column's fixed 14 bytes + variable min/max.
        at += 8;
        let block1_cols = read_u16(payload, at);
        at += 2;
        for _ in 0..block1_cols {
            at += 10; // id + type + codec + null_count
            at += 4; // row_count
            let min_len = read_u32(payload, at) as usize;
            at += 4 + min_len;
            let max_len = read_u32(payload, at) as usize;
            at += 4 + max_len;
        }
        // Block 2: seek to its first column's row_count and zero it.
        at += 8; // block_offset
        at += 2; // n_columns
        at += 10; // first column's id + type + codec + null_count
        let claimed = read_u32(payload, at);
        assert!(claimed > 0, "the second block originally holds rows");
        let Some(rc) = payload.get_mut(at..at + 4) else {
            panic!("second block's first row_count within the zone map payload");
        };
        rc.copy_from_slice(&0u32.to_le_bytes());
    }
    let new_zm_checksum = crate::Checksum::from_raw(crate::hash::hash128(
        bytes.get(zm_payload_range).unwrap_or(&[]),
    ));
    let new_zm_header = Header {
        checksum: new_zm_checksum,
        ..zm_header
    };
    let mut zm_hdr_bytes: Vec<u8> = Vec::with_capacity(zm_header_len);
    new_zm_header.encode_into(&mut zm_hdr_bytes)?;
    let Some(zm_dst) = bytes.get_mut(zm_pos..zm_pos + zm_header_len) else {
        panic!("zone_map header within the file");
    };
    zm_dst.copy_from_slice(&zm_hdr_bytes);
    std::fs::write(&source, &bytes)?;

    // Default: fail closed — the zero-row block is unpositionable input (the
    // walk drops it while later blocks would be masked at starts the bitmap
    // was never built against).
    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "a zero-row block in a delete-bearing SST fails the default salvage: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );
    Ok(())
}

/// A footer-bearing row SST (per-KV checksums) whose block checksum was
/// re-stamped over a tampered entry: the BLOCK checksum verifies, but the
/// entry no longer matches its per-KV digest. Salvage must verify the footer
/// before emitting (verbatim or re-encoded) — otherwise it recovers a block
/// the live per-KV scrub would reject, laundering the corruption into a
/// "fully valid" copy.
#[test]
fn salvage_drops_a_row_block_with_a_stale_kv_digest() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::runtime_config::{ChecksumAlgorithm, KvChecksumPolicy};
    use crate::table::block::Header;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_kv_checksums(KvChecksumPolicy::AllLevels, ChecksumAlgorithm::Xxh3_64);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Tamper one entry byte inside the SECOND block's inner payload and
    // re-stamp the BLOCK checksum: the frame verifies clean, but the entry's
    // stored per-KV digest no longer matches its bytes.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let payload_range =
        block_off + header_len..block_off + header_len + header.data_length as usize;
    {
        let Some(payload) = bytes.get_mut(payload_range.clone()) else {
            panic!("payload range within the block");
        };
        // A byte inside the first entry's value bytes (past the entry header),
        // well before the per-KV footer at the payload tail.
        let Some(b) = payload.get_mut(12) else {
            panic!("entry byte within the payload");
        };
        *b ^= 0xFF;
    }
    let new_checksum = crate::Checksum::from_raw(crate::hash::hash128(
        bytes.get(payload_range).unwrap_or(&[]),
    ));
    let new_header = Header {
        checksum: new_checksum,
        ..header
    };
    let mut hdr_bytes: Vec<u8> = Vec::with_capacity(header_len);
    new_header.encode_into(&mut hdr_bytes)?;
    let Some(hdr_dst) = bytes.get_mut(block_off..block_off + header_len) else {
        panic!("block header within the file");
    };
    hdr_dst.copy_from_slice(&hdr_bytes);
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "the block with a stale per-KV digest is dropped: {report:?}",
    );
    assert!(
        report.entries_salvaged < u64::from(n),
        "the tampered block's rows are not laundered into the copy: {report:?}",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, report.entries_salvaged);
    Ok(())
}

/// A delete-bearing columnar SST with a checksum-clean block whose
/// `ColumnBatch` does NOT decode (a repatched tamper that keeps the leading
/// row-count u32 intact but breaks the column framing): the block's ACTUAL row
/// count is unknowable, so every later block's delete positions are
/// unverifiable — the position verifier must fully decode each block rather
/// than trust the leading four bytes, and the default salvage must fail
/// closed instead of dropping the block and masking later rows at positions
/// it could not prove.
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_an_undecodable_checksum_clean_block_with_deletes() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::config::DeleteStrategy;
    use crate::table::block::Header;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Poison the SECOND data block: stamp an invalid type tag into the first
    // column's header (payload layout: row_count u32, column_count u32, then
    // per column id u16 + type u8 + ... — so the first type byte sits at
    // payload offset 10) and re-stamp the block checksum. The leading
    // row-count u32 stays intact, the frame stays checksum-consistent, but
    // `ColumnBatch::decode` fails on the unknown tag.
    let (block_off, block_size) = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().filter_map(Result::ok).nth(1) else {
            panic!("source must have at least two data blocks");
        };
        (
            usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX),
            kh.as_ref().size() as usize,
        )
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(block) = bytes.get(block_off..block_off + block_size) else {
        panic!("block range within the file");
    };
    let mut cursor = block;
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let payload_range =
        block_off + header_len..block_off + header_len + header.data_length as usize;
    {
        let Some(payload) = bytes.get_mut(payload_range.clone()) else {
            panic!("payload range within the block");
        };
        let Some(tag) = payload.get_mut(10) else {
            panic!("first column's type byte within the payload");
        };
        *tag = 0xEE;
    }
    let new_checksum = crate::Checksum::from_raw(crate::hash::hash128(
        bytes.get(payload_range).unwrap_or(&[]),
    ));
    let new_header = Header {
        checksum: new_checksum,
        ..header
    };
    let mut hdr_bytes = Vec::with_capacity(header_len);
    new_header.encode_into(&mut hdr_bytes)?;
    let Some(hdr_dst) = bytes.get_mut(block_off..block_off + header_len) else {
        panic!("block header within the file");
    };
    hdr_dst.copy_from_slice(&hdr_bytes);
    std::fs::write(&source, &bytes)?;

    // Default: fail closed — the block reads back checksum-clean but cannot
    // be decoded, so its actual row count (and every later block's delete
    // positions) cannot be proven faithful.
    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "unverifiable delete positions fail the default salvage: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );

    // Explicit opt-in: the poisoned block is dropped, every other row is
    // recovered LIVE (never masked against unproven positions).
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the poisoned block is dropped: {report:?}",
    );
    assert!(
        report.entries_salvaged < u64::from(n),
        "the poisoned block's rows are lost: {report:?}",
    );
    assert_eq!(
        reopen_item_count(dest.clone(), &fs)?,
        report.entries_salvaged,
        "the recovered copy reopens with every salvaged row live",
    );
    // LOGICAL visibility of the resurrection: the deleted positions live
    // outside the poisoned block, so under the opt-in their keys read back.
    for pos in [5u32, 50, 150] {
        assert!(
            reopen_get(dest.clone(), &fs, format!("key{pos:05}").as_bytes())?.is_some(),
            "the opt-in resurrects the deleted key at position {pos}",
        );
    }
    Ok(())
}

/// A zone map that DECODES but carries wrong per-block row counts (a
/// checksum-repatched tamper) would misposition the delete bitmap: the masked
/// re-emit derives each block's start row from the zone map, so deletes land
/// on the wrong rows — deleted rows resurrect AND live rows vanish, silently.
/// Salvage must cross-check the claimed positions against the actual decoded
/// row counts and fail closed on a mismatch; with the explicit
/// [`SalvageOptions::allow_delete_resurrection`] opt-in it recovers all rows
/// live instead of masking against the wrong positions.
#[cfg(feature = "columnar")]
#[test]
fn salvage_fails_closed_on_a_zone_map_with_wrong_row_counts() -> crate::Result<()> {
    use crate::coding::{Decode, Encode};
    use crate::config::DeleteStrategy;
    use crate::table::block::Header;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Tamper the FIRST block's row count inside the zone map (wire layout:
    // count u32, then block_offset u64 + n_columns u16, then per column
    // id u32 + type_tag u8 + codec_id u8 + null_count u32 + row_count u32 —
    // so the first row_count sits at payload bytes 24..28) and re-stamp the
    // section block's checksum. The zone map still DECODES — only its claimed
    // positions are shifted for every block after the first.
    let zm_pos = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"zone_map") else {
            panic!("source must carry a zone_map section");
        };
        usize::try_from(entry.pos()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    let Some(mut cursor) = bytes.get(zm_pos..) else {
        panic!("zone_map section within the file");
    };
    let header = Header::decode_from(&mut cursor)?;
    let header_len = Header::header_len(header.block_type);
    let payload_range = zm_pos + header_len..zm_pos + header_len + header.data_length as usize;
    {
        let Some(payload) = bytes.get_mut(payload_range.clone()) else {
            panic!("zone_map payload within the file");
        };
        let Some(rc) = payload.get_mut(24..28) else {
            panic!("first row_count within the zone map payload");
        };
        let claimed = u32::from_le_bytes(rc.try_into().unwrap_or([0; 4]));
        assert!(claimed >= 2, "the first block holds at least two rows");
        rc.copy_from_slice(&(claimed - 1).to_le_bytes());
    }
    let new_checksum = crate::Checksum::from_raw(crate::hash::hash128(
        bytes.get(payload_range).unwrap_or(&[]),
    ));
    let new_header = Header {
        checksum: new_checksum,
        ..header
    };
    let mut hdr_bytes = Vec::with_capacity(header_len);
    new_header.encode_into(&mut hdr_bytes)?;
    let Some(hdr_dst) = bytes.get_mut(zm_pos..zm_pos + header_len) else {
        panic!("zone_map header within the file");
    };
    hdr_dst.copy_from_slice(&hdr_bytes);
    std::fs::write(&source, &bytes)?;

    // Default: fail closed — masking against the shifted positions would
    // silently corrupt visibility in the recovered SST.
    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.is_err(),
        "a mispositioning zone map fails the default salvage: {result:?}",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "no destination file is left behind by the refused salvage",
    );

    // Explicit opt-in: recover all rows LIVE (never mask against the wrong
    // positions).
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert!(
        report.is_complete(),
        "the data blocks are intact; only the zone map lies: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every row is recovered live under the opt-in",
    );
    assert_eq!(reopen_item_count(dest.clone(), &fs)?, u64::from(n));
    // LOGICAL visibility of the resurrection: "all rows live" means the keys
    // at the deleted positions read back.
    for pos in [5u32, 50, 150] {
        assert!(
            reopen_get(dest.clone(), &fs, format!("key{pos:05}").as_bytes())?.is_some(),
            "the opt-in resurrects the deleted key at position {pos}",
        );
    }
    Ok(())
}

/// A columnar SST with deletes whose ZONE MAP is corrupt (the bitmap stays
/// readable): the bitmap cannot be positioned without the zone map, so normal
/// recovery and default salvage fail closed, but a caller who explicitly opts
/// into [`SalvageOptions::allow_delete_resurrection`] ignores the bitmap
/// ("all rows live") and recovers every row.
#[cfg(feature = "columnar")]
#[test]
fn salvage_ignores_a_delete_bitmap_without_a_readable_zone_map() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 50, 150] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Corrupt the zone_map section (the bitmap stays intact). The zone map
    // degrades to empty, leaving a readable bitmap that cannot be positioned.
    let (zm_pos, zm_len) = {
        let mut f = std::fs::File::open(&source)?;
        let reader = match crate::sfa::Reader::from_reader(&mut f) {
            Ok(r) => r,
            Err(e) => panic!("reading the SFA trailer failed: {e:?}"),
        };
        let Some(entry) = reader.toc().iter().find(|e| e.name() == b"zone_map") else {
            panic!("source must carry a zone_map section");
        };
        (entry.pos(), entry.len())
    };
    let flip = usize::try_from(zm_pos + zm_len / 2).unwrap_or(0);
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    // Normal recovery fails closed: a bitmap with no positioning zone map.
    assert!(
        open(source.clone(), &fs).is_err(),
        "normal recovery must reject a bitmap with no readable zone map",
    );

    // With the explicit opt-in, salvage ignores the unpositionable bitmap and
    // recovers every row live.
    let options = SalvageOptions {
        allow_delete_resurrection: true,
        ..SalvageOptions::default()
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert!(
        report.is_complete(),
        "the data blocks are intact; only the zone map was corrupt: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every row is recovered live once the unpositionable bitmap is ignored",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n));
    Ok(())
}

/// When the source cannot be opened at all (a corrupt SFA trailer makes even
/// salvage-mode recovery fail), `salvage_sst` returns an error rather than
/// writing a partial file.
#[test]
fn salvage_sst_errors_when_the_source_cannot_be_opened() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..50 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Truncate away the tail (SFA trailer + section mirrors) so the container is
    // unparseable and even salvage-mode recovery cannot open it.
    let mut bytes = std::fs::read(&source)?;
    bytes.truncate(bytes.len() / 2);
    std::fs::write(&source, &bytes)?;

    assert!(
        salvage_sst(&source, dest.clone(), &fs).is_err(),
        "an unparseable container must fail salvage, not write a partial file",
    );
    assert!(
        !dest.exists(),
        "no destination is written on an open failure"
    );
    Ok(())
}

/// A single-block SST whose only data block is corrupt salvages nothing: no
/// destination file is written and the report records the dropped block.
#[test]
fn salvage_sst_recovers_nothing_when_the_only_block_is_corrupt() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A handful of small keys fit in one default-sized data block.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..8 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the sole data block (offset from the intact index).
    let target = {
        let table = open(source.clone(), &fs)?;
        let offsets: alloc::vec::Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        let Some(&only) = offsets.first() else {
            panic!("expected a single data block, got {offsets:?}");
        };
        assert_eq!(
            offsets.len(),
            1,
            "expected a single data block, got {offsets:?}"
        );
        only
    };
    let flip = usize::try_from(target).unwrap_or(0) + 16;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.blocks_salvaged, 0, "the only block was corrupt");
    assert_eq!(report.entries_salvaged, 0, "no entries recovered");
    assert_eq!(report.dropped.len(), 1, "the dropped block is reported");
    assert!(
        report.salvaged_path.is_none(),
        "nothing recoverable means no file is written",
    );
    assert!(!dest.exists(), "no destination file on an empty salvage");
    Ok(())
}

/// A columnar source whose delete-bitmap wholly covers its leading data
/// block(s): those blocks carry no live rows, so salvage skips them (nothing
/// salvaged, nothing dropped) and recovers the live rows of the rest.
#[cfg(feature = "columnar")]
#[test]
fn salvage_skips_a_wholly_deleted_block() -> crate::Result<()> {
    use crate::config::DeleteStrategy;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let n = 200u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_data_block_size(256)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    // Delete the first 60 row positions: with 256-byte blocks this wholly covers
    // the leading data block(s), which then load as "no live rows".
    let deleted = 60u32;
    for pos in 0..deleted {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "wholly-deleted blocks are skipped, not dropped: {report:?}",
    );
    assert!(
        report.blocks_salvaged < report.blocks_total,
        "at least one leading block was wholly deleted and skipped: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n - deleted),
        "every live row is recovered, the deleted prefix is skipped",
    );
    assert_eq!(reopen_item_count(dest, &fs)?, u64::from(n - deleted));
    Ok(())
}

/// An SST carrying range tombstones cannot be salvaged: the positional KV walk
/// re-emits only point entries, so the tombstones would be silently dropped and
/// lower-level keys they cover could reappear after repair. Until the writer
/// path re-emits them, salvage fails closed.
#[test]
fn salvage_rejects_an_sst_with_range_tombstones() -> crate::Result<()> {
    use crate::UserKey;
    use crate::range_tombstone::RangeTombstone;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..20 {
        writer.write(iv(i))?;
    }
    // A range tombstone over part of the key space: the salvaged copy must not
    // silently drop it.
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key00005".as_slice()),
        UserKey::from(b"key00010".as_slice()),
        2,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        matches!(result, Err(crate::Error::FeatureUnsupported(_))),
        "an SST with range tombstones must fail closed, got {result:?}",
    );
    assert!(
        !dest.exists(),
        "no salvaged file is written when salvage fails closed",
    );
    Ok(())
}

/// Salvage drives every read and write through the injected `Fs`: an SST that
/// lives only in an in-memory backend (never on the real filesystem) salvages
/// and reopens purely through that backend. A source-digest path that bypassed
/// `fs` and read through `std::fs` would fail to find the file at all.
#[test]
fn salvage_sst_reads_and_writes_through_the_injected_fs() -> crate::Result<()> {
    use crate::fs::MemFs;

    let fs: Arc<dyn Fs> = Arc::new(MemFs::new());
    // `Writer::new` rewrites its path through `std::path::absolute`, which on
    // Windows resolves a `/`-rooted path against the current drive (`/memfs` ->
    // `D:\memfs`). Create the parent under that same absolutized form so the
    // writer's parent-directory check finds it on every platform (on Unix
    // `absolute` is a no-op, so this is just `/memfs`).
    let dir = std::path::absolute("/memfs")?;
    fs.create_dir_all(&dir)?;
    let source = dir.join("source");
    let dest = dir.join("salvaged");

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(256);
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "in-memory source SST is non-empty"
    );

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "a healthy in-memory SST salvages with no dropped blocks: {report:?}",
    );
    assert_eq!(
        report.entries_salvaged,
        u64::from(n),
        "every entry is recovered through the in-memory backend",
    );
    assert_eq!(report.salvaged_path.as_deref(), Some(dest.as_path()));
    assert_eq!(
        reopen_item_count(dest, &fs)?,
        u64::from(n),
        "the salvaged SST reopens through the same in-memory backend",
    );
    Ok(())
}

// --- Forwarded recovery context: encrypted + dictionary-compressed sources ---

/// Reads the second data block's on-disk offset from a context-aware reopen of
/// `source`, then flips a byte just past that block's header so its checksum /
/// AEAD tag fails on load while every other block stays intact.
#[cfg(any(feature = "encryption", zstd_any))]
fn corrupt_second_data_block(
    source: &std::path::Path,
    fs: &Arc<dyn Fs>,
    table_id: crate::table::TableId,
    encryption: Option<Arc<dyn crate::encryption::EncryptionProvider>>,
    #[cfg(zstd_any)] zstd_dictionary: Option<Arc<crate::compression::ZstdDictionary>>,
) -> crate::Result<()> {
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&**fs, source)?);
    let table = {
        // Open under the source's table id so an encrypted index (AAD binds the
        // id) decrypts when reading the block offsets.
        let mut params = crate::table::RecoverParams::new(
            source.to_path_buf(),
            checksum,
            table_id,
            Arc::clone(fs),
            default_comparator(),
            Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
        );
        params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
        params.encryption = encryption;
        #[cfg(zstd_any)]
        {
            params.zstd_dictionary = zstd_dictionary;
        }
        Table::recover(params)?
    };
    let offsets: alloc::vec::Vec<u64> = table
        .data_block_handles()
        .filter_map(Result::ok)
        .map(|kh| *kh.as_ref().offset())
        .collect();
    let Some(&second) = offsets.get(1) else {
        panic!("source SST must have at least two data blocks, got {offsets:?}");
    };
    let flip = usize::try_from(second).unwrap_or(0) + 16;
    let mut bytes = std::fs::read(source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(source, &bytes)?;
    Ok(())
}

/// An encrypted source: salvage cannot open it without the provider (the gap this
/// closes), but with the provider in `SalvageOptions` it block-salvages like a
/// plain SST and the recovered copy reopens under the same encryption.
#[cfg(feature = "encryption")]
#[test]
fn salvage_recovers_an_encrypted_sst_with_the_provider() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let enc: Arc<dyn crate::encryption::EncryptionProvider> =
        Arc::new(crate::encryption::Aes256GcmProvider::new(&[0x42; 32]));

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_encryption(Some(Arc::clone(&enc)));
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source encrypted SST is non-empty"
    );

    corrupt_second_data_block(
        &source,
        &fs,
        0,
        Some(Arc::clone(&enc)),
        #[cfg(zstd_any)]
        None,
    )?;

    // Without the provider, the encrypted source cannot even be opened.
    assert!(
        salvage_sst(&source, dest.clone(), &fs).is_err(),
        "an encrypted SST must not salvage without the provider",
    );

    // With the provider, it block-salvages: the corrupt block is dropped, the
    // rest recovered, and the copy is written encrypted.
    let options = SalvageOptions {
        encryption: Some(Arc::clone(&enc)),
        #[cfg(zstd_any)]
        zstd_dictionary: None,
        table_id: 0,
        expected_stored_id: None,
        output_id: None,
        allow_delete_resurrection: false,
        sync_mode: crate::fs::SyncMode::Normal,
        prefix_extractor: None,
        blob_rewrite: None,
        progress: None,
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the corrupt block drops: {report:?}"
    );
    assert!(
        report.entries_salvaged > 0 && report.entries_salvaged < u64::from(n),
        "a partial key range is recovered, got {} of {n}",
        report.entries_salvaged,
    );

    // The salvaged copy reopens UNDER ENCRYPTION (a plaintext copy would fail the
    // encrypted reopen) and holds exactly the recovered entries.
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&*fs, &dest)?);
    let reopened = {
        let mut params = crate::table::RecoverParams::new(
            dest,
            checksum,
            0,
            Arc::clone(&fs),
            default_comparator(),
            Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
        );
        params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
        params.encryption = Some(Arc::clone(&enc));
        Table::recover(params)?
    };
    assert_eq!(
        reopened.metadata.item_count, report.entries_salvaged,
        "the encrypted salvaged copy reopens with exactly the recovered entries",
    );
    Ok(())
}

/// A zstd-dictionary-compressed source: salvage cannot decompress it without the
/// dictionary, but with the dictionary in `SalvageOptions` it block-salvages and
/// the recovered copy reopens under the same dictionary.
#[cfg(zstd_any)]
#[test]
fn salvage_recovers_a_dictionary_sst_with_the_dictionary() -> crate::Result<()> {
    use crate::CompressionType;
    use crate::compression::ZstdDictionary;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A small training corpus so the dictionary has content to match against.
    let samples: alloc::vec::Vec<u8> = (0..4000u32).map(|i| (i % 251) as u8).collect();
    let dict = Arc::new(ZstdDictionary::new(&samples));
    let compression = CompressionType::ZstdDict {
        level: 3,
        dict_id: dict.id(),
    };

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_data_block_compression(compression)
        .use_zstd_dictionary(Some(Arc::clone(&dict)));
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source dictionary SST is non-empty"
    );

    corrupt_second_data_block(&source, &fs, 0, None, Some(Arc::clone(&dict)))?;

    // Without the dictionary, the source cannot even be opened: `recover_inner`
    // fail-fasts on the ZstdDict-id mismatch at open time (before any block
    // walk), so salvage returns `Err`, not a zero-recovered report.
    assert!(
        salvage_sst(&source, dest.clone(), &fs).is_err(),
        "a dictionary SST must not salvage without the dictionary",
    );

    let options = SalvageOptions {
        encryption: None,
        zstd_dictionary: Some(Arc::clone(&dict)),
        table_id: 0,
        expected_stored_id: None,
        output_id: None,
        allow_delete_resurrection: false,
        sync_mode: crate::fs::SyncMode::Normal,
        prefix_extractor: None,
        blob_rewrite: None,
        progress: None,
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the corrupt block drops: {report:?}"
    );
    assert!(
        report.entries_salvaged > 0 && report.entries_salvaged < u64::from(n),
        "a partial key range is recovered, got {} of {n}",
        report.entries_salvaged,
    );

    // The salvaged copy reopens UNDER THE DICTIONARY with the recovered entries.
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&*fs, &dest)?);
    let reopened = {
        let mut params = crate::table::RecoverParams::new(
            dest,
            checksum,
            0,
            Arc::clone(&fs),
            default_comparator(),
            Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
        );
        params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
        params.zstd_dictionary = Some(Arc::clone(&dict));
        Table::recover(params)?
    };
    assert_eq!(
        reopened.metadata.item_count, report.entries_salvaged,
        "the dictionary salvaged copy reopens with exactly the recovered entries",
    );
    Ok(())
}

/// A dictionary-compressed BLOB file salvaged under the WRONG dictionary must
/// fail closed BEFORE the record walk. Without the up-front id check, every
/// frame's decompress fails with a per-record dictionary mismatch that the
/// walk's catch-all records as a `Corrupt` drop — the run "succeeds" with
/// zero records salvaged, and a repair that trusts the report throws away a
/// fully intact file whose only problem was a mis-supplied dictionary.
#[cfg(zstd_any)]
#[test]
fn a_blob_salvage_under_the_wrong_dictionary_fails_closed() -> crate::Result<()> {
    use crate::CompressionType;
    use crate::compression::ZstdDictionary;

    let dir = tempdir()?;
    let source = dir.path().join("dict_blob");
    let dest = dir.path().join("dict_blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let samples_a: alloc::vec::Vec<u8> = (0..4000u32).map(|i| (i % 251) as u8).collect();
    let dict_a = Arc::new(ZstdDictionary::new(&samples_a));
    let compression = CompressionType::ZstdDict {
        level: 3,
        dict_id: dict_a.id(),
    };

    let mut writer = BlobWriter::new(&source, 0, 0, &*fs)?
        .use_compression(compression)
        .use_zstd_dictionary(Some(Arc::clone(&dict_a)));
    for i in 0..8u32 {
        let key = format!("key{i:04}");
        let value: alloc::vec::Vec<u8> = (0..512u32).map(|j| ((i + j) % 251) as u8).collect();
        writer.write(key.as_bytes(), 0, &value)?;
    }
    writer.finish()?;

    // A DIFFERENT training corpus yields a different dictionary id.
    let samples_b: alloc::vec::Vec<u8> = (0..4000u32).map(|i| (i % 13) as u8).collect();
    let dict_b = Arc::new(ZstdDictionary::new(&samples_b));
    assert_ne!(dict_a.id(), dict_b.id(), "the fixture needs distinct ids");

    let Err(err) = salvage_blob_file(
        &source,
        dest,
        &fs,
        0,
        &default_comparator(),
        0,
        Some(&dict_b),
    ) else {
        panic!("a mismatched dictionary must fail the salvage, not empty it");
    };
    assert!(
        matches!(
            &err,
            crate::Error::ZstdDictMismatch { expected, got }
                if *expected == dict_a.id() && *got == Some(dict_b.id())
        ),
        "the failure names both ids: {err:?}",
    );
    Ok(())
}

/// An encrypted source sealed under a NON-ZERO table id: the encrypted-block AAD
/// binds the table id, so salvage must be given that id. With the wrong id the
/// AAD-bound blocks cannot be decrypted (the gap repair hit when it passed a
/// hardcoded `0`); with the right id it block-salvages and the copy reopens.
#[cfg(feature = "encryption")]
#[test]
fn salvage_recovers_an_encrypted_sst_with_a_nonzero_table_id() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let enc: Arc<dyn crate::encryption::EncryptionProvider> =
        Arc::new(crate::encryption::Aes256GcmProvider::new(&[0x37; 32]));
    const TID: crate::table::TableId = 7;

    let mut writer = Writer::new(source.clone(), TID, 0, Arc::clone(&fs))?
        .use_data_block_size(256)
        .use_encryption(Some(Arc::clone(&enc)));
    let n = 200u32;
    for i in 0..n {
        writer.write(iv(i))?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source encrypted SST is non-empty"
    );

    corrupt_second_data_block(
        &source,
        &fs,
        TID,
        Some(Arc::clone(&enc)),
        #[cfg(zstd_any)]
        None,
    )?;

    // Wrong table id (the legacy hardcoded 0): the AAD-bound blocks cannot be
    // decrypted, so nothing is recovered (salvage either fails to open or drops
    // every block).
    let wrong = SalvageOptions {
        encryption: Some(Arc::clone(&enc)),
        #[cfg(zstd_any)]
        zstd_dictionary: None,
        table_id: 0,
        expected_stored_id: None,
        output_id: None,
        allow_delete_resurrection: false,
        sync_mode: crate::fs::SyncMode::Normal,
        prefix_extractor: None,
        blob_rewrite: None,
        progress: None,
    };
    let recovered_wrong = salvage_sst_with_options(&source, dest.clone(), &fs, &wrong)
        .map_or(0, |r| r.entries_salvaged);
    assert_eq!(
        recovered_wrong, 0,
        "the wrong table id cannot decrypt the AAD-bound encrypted source",
    );

    // Right table id: block-salvages, dropping only the corrupt block.
    let options = SalvageOptions {
        encryption: Some(Arc::clone(&enc)),
        #[cfg(zstd_any)]
        zstd_dictionary: None,
        table_id: TID,
        expected_stored_id: None,
        output_id: None,
        allow_delete_resurrection: false,
        sync_mode: crate::fs::SyncMode::Normal,
        prefix_extractor: None,
        blob_rewrite: None,
        progress: None,
    };
    let report = salvage_sst_with_options(&source, dest.clone(), &fs, &options)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "exactly the corrupt block drops: {report:?}"
    );
    assert!(
        report.entries_salvaged > 0 && report.entries_salvaged < u64::from(n),
        "a partial key range is recovered, got {} of {n}",
        report.entries_salvaged,
    );

    // The recovered copy reopens under the same table id + encryption.
    let checksum = crate::Checksum::from_raw(crate::repair::compute_table_checksum(&*fs, &dest)?);
    let reopened = {
        let mut params = crate::table::RecoverParams::new(
            dest,
            checksum,
            TID,
            Arc::clone(&fs),
            default_comparator(),
            Arc::new(crate::cache::Cache::with_capacity_bytes(1 << 20)),
        );
        params.descriptor_table = Some(Arc::new(crate::descriptor_table::DescriptorTable::new(8)));
        params.encryption = Some(Arc::clone(&enc));
        Table::recover(params)?
    };
    assert_eq!(
        reopened.metadata.item_count, report.entries_salvaged,
        "the recovered copy reopens under the same table id with the recovered entries",
    );
    Ok(())
}

// --- Blob (vlog) file record-granular salvage ---

use crate::vlog::blob_file::scanner::Scanner as BlobScanner;
use crate::vlog::blob_file::writer::Writer as BlobWriter;

/// Builds a blob file at `path` from `(key, value)` records (seqno 0, no
/// compression).
fn build_blob(
    path: &std::path::Path,
    fs: &Arc<dyn Fs>,
    records: &[(&[u8], &[u8])],
) -> crate::Result<()> {
    let mut writer = BlobWriter::new(path, 0, 0, &**fs)?;
    for (k, v) in records {
        writer.write(k, 0, v)?;
    }
    writer.finish()?;
    Ok(())
}

/// Mirrors that disagree in a NON-DERIVABLE field must not be arbitrated at
/// all. The salvage walk re-derives the entry-backed metadata from the records
/// it re-emits, so a "complete" attempt settles those — but `bulk_ingested`,
/// `recency` and the compaction lineage are copied from whichever mirror is
/// selected, and nothing in the file authenticates them. A forged tail that
/// clears `bulk_ingested` would otherwise win on block completeness alone and
/// republish an ingested SST at global seqno 0, visible to snapshots that
/// never saw it.
#[test]
fn divergent_non_derivable_metadata_is_never_arbitrated() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A bulk-ingested SST: every entry at local seqno 0, provenance recorded.
    let mut writer =
        Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_bulk_ingested(Some(true));
    for i in 0..32u32 {
        writer.write(crate::InternalValue::from_components(
            format!("k{i:05}").into_bytes(),
            b"v".to_vec(),
            0,
            crate::ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "the source SST is non-empty");

    // Forge ONLY the tail mirror's provenance: the blocks stay intact, so the
    // tail attempt recovers everything and would win on completeness.
    crate::test_forge::forge_tail_meta_value(&source, b"descriptor#bulk_ingested", &[0])?;

    let result = salvage_sst(&source, dest, &fs);
    assert!(
        result.is_err(),
        "a disagreement in provenance the walk cannot re-derive must refuse \
         arbitration, not publish the mirror that happens to decode: {result:?}",
    );
    Ok(())
}

/// The PREPASS twin: the physical tiling walk that discovers blocks must
/// propagate an environmental read too. A break in that chain drops the
/// candidate — and, past an untrusted index, the whole unanchored tail — as
/// permanently lost, so repair publishes the partial replacement and removes
/// a source whose bytes were never proven corrupt. The sweep drives a
/// corrupt table (which forces the physical walk) with a one-shot
/// `PermissionDenied` at increasing skip counts.
#[test]
fn an_environmental_read_never_breaks_the_physical_tiling_silently() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let mut fault_reached_the_walk = false;
    for skip in 0..48u64 {
        let dir = tempdir()?;
        let source = dir.path().join("source");
        let dest = dir.path().join("salvaged");
        let plain: Arc<dyn Fs> = Arc::new(StdFs);
        {
            let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&plain))?
                .use_data_block_size(128)
                .use_partitioned_index();
            for i in 0..256u32 {
                writer.write(iv(i))?;
            }
            assert!(writer.finish()?.is_some(), "the source SST is non-empty");
        }
        // Break the INDEX section: enumeration stops partway and the salvage
        // falls back to the physical tiling walk, which is the path under test.
        {
            let (index_pos, index_len) = {
                let mut f = std::fs::File::open(&source)?;
                let reader = crate::sfa::Reader::from_reader(&mut f)?;
                let Some((pos, len)) = reader
                    .toc()
                    .iter()
                    .find(|e| e.name() == b"index")
                    .map(|e| (e.pos(), e.len()))
                else {
                    panic!("the SST carries an index section");
                };
                (pos, len)
            };
            let Ok(flip) = usize::try_from(index_pos + index_len / 2) else {
                panic!("the index-section offset fits usize");
            };
            let mut bytes = std::fs::read(&source)?;
            if let Some(b) = bytes.get_mut(flip) {
                *b ^= 0xFF;
            }
            std::fs::write(&source, &bytes)?;
        }

        let fault = FaultFs::new(StdFs);
        fault.injector().arm(
            FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::PermissionDenied))
                .skip(skip)
                .times(1),
        );
        let fs: Arc<dyn Fs> = Arc::new(fault);
        match salvage_sst(&source, dest, &fs) {
            Ok(report) => {
                assert!(
                    !report
                        .dropped
                        .iter()
                        .any(|d| format!("{:?}", d.reason).contains("PermissionDenied")),
                    "an environmental failure must never be recorded as a \
                     dropped block (skip {skip}): {report:?}",
                );
            }
            Err(e) => {
                assert!(
                    matches!(&e, crate::Error::Io(io) if io.kind() == ErrorKind::PermissionDenied),
                    "the only acceptable failure is the propagated \
                     environmental error (skip {skip}): {e:?}",
                );
                fault_reached_the_walk = true;
            }
        }
    }
    assert!(
        fault_reached_the_walk,
        "no skip count reached the salvage read path; the sweep proves nothing",
    );
    Ok(())
}

/// The SST twin: an ENVIRONMENTAL data-block read failure must PROPAGATE,
/// never be recorded as a dropped block. The metadata and index are readable,
/// so the walk reaches the block reads; a `PermissionDenied` there is an ACL
/// mistake or host pressure, not rotted bytes, and accepting it as a drop
/// finishes a partial replacement that repair installs before removing the
/// source — permanent loss a fixed environment would have avoided. The sweep
/// arms a one-shot fault at increasing skip counts; wherever it lands, the
/// walk either succeeds untouched or fails with the environmental error.
#[test]
fn an_environmental_read_failure_never_becomes_a_lossy_sst_salvage() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let mut fault_reached_the_walk = false;
    for skip in 0..64u64 {
        let dir = tempdir()?;
        let source = dir.path().join("source");
        let dest = dir.path().join("salvaged");
        let plain: Arc<dyn Fs> = Arc::new(StdFs);
        {
            let mut writer =
                Writer::new(source.clone(), 0, 0, Arc::clone(&plain))?.use_data_block_size(256);
            for i in 0..64u32 {
                writer.write(iv(i))?;
            }
            assert!(writer.finish()?.is_some(), "the source SST is non-empty");
        }

        let fault = FaultFs::new(StdFs);
        fault.injector().arm(
            FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::PermissionDenied))
                .skip(skip)
                .times(1),
        );
        let fs: Arc<dyn Fs> = Arc::new(fault);
        match salvage_sst(&source, dest, &fs) {
            Ok(report) => {
                assert!(
                    !report
                        .dropped
                        .iter()
                        .any(|d| format!("{:?}", d.reason).contains("PermissionDenied")),
                    "an environmental failure must never be recorded as a \
                     dropped block (skip {skip}): {report:?}",
                );
            }
            Err(e) => {
                assert!(
                    matches!(&e, crate::Error::Io(io) if io.kind() == ErrorKind::PermissionDenied),
                    "the only acceptable failure is the propagated \
                     environmental error (skip {skip}): {e:?}",
                );
                fault_reached_the_walk = true;
            }
        }
    }
    assert!(
        fault_reached_the_walk,
        "no skip count reached the salvage read path; the sweep proves nothing",
    );
    Ok(())
}

/// An ENVIRONMENTAL read failure mid-walk (`PermissionDenied`, `OutOfMemory`
/// — an ACL mistake or host pressure, not rotted bytes) must PROPAGATE like
/// a transient one, never be recorded as corruption: accepting it as a drop
/// finishes a lossy salvage whose committed loss a fixed environment would
/// have avoided entirely. The sweep arms a one-shot `PermissionDenied` read
/// fault at increasing skip counts; wherever it lands, the walk either
/// succeeds untouched or fails with the environmental error — no run may
/// report a `PermissionDenied` as a corrupt drop.
#[test]
fn an_environmental_read_failure_never_becomes_a_lossy_blob_salvage() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let mut fault_reached_the_walk = false;
    for skip in 0..64u64 {
        let dir = tempdir()?;
        let source = dir.path().join("blob_env");
        let dest = dir.path().join("blob_env_salvaged");
        let plain: Arc<dyn Fs> = Arc::new(StdFs);
        build_blob(
            &source,
            &plain,
            &[
                (b"aaaa", b"AAAAAAAA"),
                (b"bbbb", b"BBBBBBBB"),
                (b"cccc", b"CCCCCCCC"),
            ],
        )?;

        let fault = FaultFs::new(StdFs);
        fault.injector().arm(
            FaultRule::new(FaultOp::Read, Fault::Error(ErrorKind::PermissionDenied))
                .skip(skip)
                .times(1),
        );
        let fs: Arc<dyn Fs> = Arc::new(fault);
        let result = salvage_blob_file(
            &source,
            dest,
            &fs,
            0,
            &default_comparator(),
            0,
            #[cfg(zstd_any)]
            None,
        );
        match result {
            Ok(report) => {
                assert!(
                    !report
                        .dropped
                        .iter()
                        .any(|d| matches!(&d.reason, BlobDropReason::Corrupt(msg) if msg.contains("PermissionDenied"))),
                    "an environmental failure must never be recorded as a \
                     corrupt drop (skip {skip}): {report:?}",
                );
            }
            Err(e) => {
                assert!(
                    matches!(&e, crate::Error::Io(io) if io.kind() == ErrorKind::PermissionDenied),
                    "the only acceptable failure is the propagated \
                     environmental error (skip {skip}): {e:?}",
                );
                fault_reached_the_walk = true;
            }
        }
    }
    assert!(
        fault_reached_the_walk,
        "no skip count reached the salvage read path; the sweep proves nothing",
    );
    Ok(())
}

/// Scans a blob file into its `(key, value)` records (Ok records only).
fn scan_blob(path: &std::path::Path, fs: &Arc<dyn Fs>) -> crate::Result<Vec<(Vec<u8>, Vec<u8>)>> {
    Ok(BlobScanner::new(path, &**fs, 0)?
        .filter_map(Result::ok)
        .map(|e| (e.key.to_vec(), e.value.to_vec()))
        .collect())
}

#[test]
fn salvage_blob_file_recovers_every_record_of_a_healthy_file() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let records: Vec<(&[u8], &[u8])> = vec![
        (b"k0", b"v0"),
        (b"k1", b"v1"),
        (b"k2", b"v2"),
        (b"k3", b"v3"),
    ];
    build_blob(&source, &fs, &records)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert!(
        report.is_complete(),
        "a healthy blob file drops nothing: {report:?}"
    );
    assert_eq!(report.records_salvaged, 4);
    assert_eq!(report.salvaged_path.as_deref(), Some(dest.as_path()));

    let recovered = scan_blob(&dest, &fs)?;
    let expected: Vec<(Vec<u8>, Vec<u8>)> = records
        .iter()
        .map(|(k, v)| (k.to_vec(), v.to_vec()))
        .collect();
    assert_eq!(
        recovered, expected,
        "every record round-trips through salvage"
    );
    Ok(())
}

/// A published salvage whose TEMP-name removal fails persistently must
/// surface the error, not shrug: the repair caller commits a manifest that
/// never references the temp, so a stuck `.healtmp-` name makes the next
/// open's artifact sweep hit the same removal failure — reporting success
/// would describe a tree that cannot open. Arbitration forces the
/// temp-then-publish path; `lz4`-gated for the mirror-divergence forge.
#[cfg(feature = "lz4")]
#[test]
fn publish_fails_when_the_temp_name_cannot_be_dropped() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");

    // The fault filter has no separator, so it matches Windows paths too.
    let fault = FaultFs::new(StdFs);
    fault.injector().arm(
        FaultRule::new(
            FaultOp::RemoveFile,
            Fault::Error(ErrorKind::PermissionDenied),
        )
        .on_path("healtmp"),
    );
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..10 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.as_ref().is_err_and(
            |e| matches!(e, crate::Error::Io(e) if e.kind() == ErrorKind::PermissionDenied)
        ),
        "a stuck temp name must fail the salvage, not be shrugged off: {result:?}",
    );
    // The freshly linked destination must be unwound with the error: left
    // installed, a retry after the filesystem is fixed would bounce off
    // AlreadyExists forever despite this call reporting failure.
    assert!(
        !dest.exists(),
        "the unpublished destination must not survive the failure",
    );
    Ok(())
}

/// A backend WITHOUT `hard_link` (the trait's default `Unsupported` impl)
/// whose `exists` probe races a concurrent creator: the probe reports the
/// destination free, but a full file already sits there by publish time.
/// The publish must still refuse to replace it — `rename` REPLACES an
/// existing destination by contract, so a probe-then-rename fallback would
/// silently overwrite the concurrently published file. The claim must be
/// atomic (`create_new`), never a TOCTOU probe.
///
/// The wrapper models the race deterministically: `exists` always answers
/// `false` (the probe's view), every other operation is the real backend.
/// Divergent meta mirrors force the arbitration path, whose winner publishes
/// through the temp-then-claim helper; `lz4`-gated because the divergence is
/// forged via `compression#data` → Lz4.
#[cfg(feature = "lz4")]
#[test]
fn publish_refuses_to_replace_a_concurrently_created_destination_without_hard_links()
-> crate::Result<()> {
    use crate::fs::{Fs, FsDirEntry, FsFile, FsMetadata, FsOpenOptions};
    use crate::io;
    use std::path::Path;

    /// Delegates to [`StdFs`], but: `hard_link` stays the trait default
    /// (`Unsupported`), and `exists` always reports `false` — the state the
    /// probe saw before a concurrent creator published the destination.
    #[derive(Debug)]
    struct RacingProbeFs(StdFs);
    impl Fs for RacingProbeFs {
        fn open(&self, path: &Path, opts: &FsOpenOptions) -> io::Result<Box<dyn FsFile>> {
            self.0.open(path, opts)
        }
        fn create_dir_all(&self, path: &Path) -> io::Result<()> {
            self.0.create_dir_all(path)
        }
        fn read_dir(&self, path: &Path) -> io::Result<Vec<FsDirEntry>> {
            self.0.read_dir(path)
        }
        fn remove_file(&self, path: &Path) -> io::Result<()> {
            self.0.remove_file(path)
        }
        fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
            self.0.remove_dir_all(path)
        }
        fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
            self.0.rename(from, to)
        }
        fn metadata(&self, path: &Path) -> io::Result<FsMetadata> {
            self.0.metadata(path)
        }
        fn sync_directory(&self, path: &Path) -> io::Result<()> {
            self.0.sync_directory(path)
        }
        fn exists(&self, _path: &Path) -> io::Result<bool> {
            Ok(false)
        }
    }

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // The concurrently published destination the probe cannot see.
    let concurrent = b"concurrently published content".to_vec();
    std::fs::write(&dest, &concurrent)?;

    let fs: Arc<dyn Fs> = Arc::new(RacingProbeFs(StdFs));
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0u64..10 {
        writer.write(InternalValue::from_components(
            format!("key-{i:03}").into_bytes(),
            format!("val-{i:03}").into_bytes(),
            i + 1,
            ValueType::Value,
        ))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");
    // Diverge the meta mirrors so salvage takes the arbitration path, whose
    // winning attempt publishes from a private temp.
    crate::test_forge::forge_tail_meta_value(&source, b"compression#data", &[1])?;

    let result = salvage_sst(&source, dest.clone(), &fs);
    assert!(
        result.as_ref().is_err_and(
            |e| matches!(e, crate::Error::Io(e) if e.kind() == crate::io::ErrorKind::AlreadyExists)
        ),
        "the publish must refuse the taken destination, not replace it: {result:?}",
    );
    assert_eq!(
        std::fs::read(&dest)?,
        concurrent,
        "the concurrently published file must survive byte-for-byte",
    );
    Ok(())
}

/// A bare relative destination (`recovered`, no parent component) must
/// salvage cleanly on `MemFs` too: the backend accepts the empty parent as
/// its implicit root at creation, so the post-publication entry sync (which
/// names that root `.`) must not fail and drag the freshly written
/// destination down with it.
///
/// No SST twin exists for this shape: the SST writer absolutizes its path up
/// front (so open / remove / directory fsync all see one name), which means a
/// bare relative SST destination on `MemFs` fails cleanly at CREATION (the
/// absolutized parent is no `MemFs` directory) — the post-publication window
/// this test pins is unreachable on that path.
#[test]
fn salvage_blob_file_accepts_a_bare_relative_destination_on_memfs() -> crate::Result<()> {
    let fs: Arc<dyn Fs> = Arc::new(crate::fs::MemFs::new());
    let source = std::path::Path::new("blob_source");
    let dest = std::path::PathBuf::from("recovered");

    let records: Vec<(&[u8], &[u8])> = vec![(b"k0", b"v0"), (b"k1", b"v1")];
    build_blob(source, &fs, &records)?;

    let report = salvage_blob_file(
        source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert!(report.is_complete(), "nothing to drop: {report:?}");
    assert_eq!(report.records_salvaged, 2);
    assert!(
        fs.exists(&dest)?,
        "the salvaged destination survives its entry sync",
    );
    Ok(())
}

/// A checksum-consistent frame whose key regresses below the previous salvaged
/// record must be DROPPED, not re-emitted: `BlobWriter` requires records in
/// key order, and a salvaged file that violates it corrupts its own key range
/// and later breaks the merge scanner's per-reader sorted-input assumption. The
/// source here is written physically out of order (the writer does not enforce
/// its precondition), so every frame is individually valid but the sequence is
/// not sorted.
#[test]
fn salvage_blob_file_drops_a_frame_whose_key_regresses() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Physically out of order: k2 precedes k1. Each frame is checksum-valid.
    let records: Vec<(&[u8], &[u8])> = vec![(b"k0", b"v0"), (b"k2", b"v2"), (b"k1", b"v1")];
    build_blob(&source, &fs, &records)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(
        report.records_salvaged, 2,
        "the order-regressing frame is dropped, not re-emitted: {report:?}",
    );
    let [dropped] = report.dropped.as_slice() else {
        panic!(
            "exactly the regressing frame drops, got {:?}",
            report.dropped
        );
    };
    assert!(
        matches!(dropped.reason, BlobDropReason::Corrupt(_)),
        "the drop is recorded as corruption: {:?}",
        dropped.reason,
    );

    // The salvaged file is sorted, so it re-opens under the writer's contract.
    let recovered = scan_blob(&dest, &fs)?;
    assert_eq!(
        recovered,
        vec![
            (b"k0".to_vec(), b"v0".to_vec()),
            (b"k2".to_vec(), b"v2".to_vec())
        ],
        "only the in-order prefix survives, still sorted",
    );
    Ok(())
}

/// The blob-order guard must use the TREE comparator, not raw bytes: a blob file
/// written by a reverse-comparator tree is in descending key order, which is
/// perfectly valid there. Salvaging it under that comparator must keep every
/// record; bytewise ordering would wrongly judge each record as regressing and
/// drop healthy data.
#[test]
fn salvage_blob_file_keeps_reverse_ordered_records_under_a_reverse_comparator() -> crate::Result<()>
{
    struct ReverseComparator;
    impl crate::comparator::UserComparator for ReverseComparator {
        fn name(&self) -> &'static str {
            "reverse-lexicographic-test"
        }
        fn compare(&self, a: &[u8], b: &[u8]) -> core::cmp::Ordering {
            b.cmp(a)
        }
    }

    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // Descending key order: correct for a reverse-comparator tree.
    let records: Vec<(&[u8], &[u8])> = vec![(b"k2", b"v2"), (b"k1", b"v1"), (b"k0", b"v0")];
    build_blob(&source, &fs, &records)?;

    let comparator: crate::comparator::SharedComparator = Arc::new(ReverseComparator);
    let report = salvage_blob_file(
        &source,
        dest,
        &fs,
        0,
        &comparator,
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(
        report.records_salvaged, 3,
        "descending order is NOT regressing under a reverse comparator: {report:?}",
    );
    assert!(
        report.dropped.is_empty(),
        "no record is dropped as out-of-order: {report:?}",
    );
    Ok(())
}

/// `salvage_blob_file` must fsync the destination's PARENT DIRECTORY before
/// returning a salvaged path: the writer syncs the blob file's bytes, but
/// without the directory sync a power loss can discard the new directory entry
/// even though the report says recovery succeeded (the SST salvage writer
/// already syncs its parent directory). Fault-inject the directory fsync to
/// prove it happens — a build that never syncs the directory never triggers the
/// fault and wrongly reports the move durable.
#[test]
fn salvage_blob_file_syncs_the_destination_directory() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultInjector, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let out = dir.path().join("blobdest");
    std::fs::create_dir_all(&out)?;
    let dest = out.join("blob_salvaged");

    let injector = Arc::new(FaultInjector::new());
    let fs: Arc<dyn Fs> = Arc::new(FaultFs::with_injector(StdFs, Arc::clone(&injector)));

    let records: Vec<(&[u8], &[u8])> = vec![(b"k0", b"v0"), (b"k1", b"v1")];
    build_blob(&source, &fs, &records)?;

    // Arm AFTER building, so only the salvage's destination-directory sync trips.
    injector.arm(
        FaultRule::new(FaultOp::SyncDirectory, Fault::Error(ErrorKind::Other)).on_path("blobdest"),
    );

    let Err(err) = salvage_blob_file(
        &source,
        dest,
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    ) else {
        panic!("the destination-directory fsync fault must surface");
    };
    // Assert the surfaced error is the INJECTED directory-sync fault, not some
    // unrelated failure: a build that stopped syncing the directory would fail
    // elsewhere (or not at all), and a loose "any error" check would not notice.
    assert!(
        err.to_string().contains("injected fault on SyncDirectory"),
        "the salvage error must be the injected destination-directory sync fault, got {err:?}",
    );
    Ok(())
}

/// The TOCTOU variant of the pre-existing-destination guarantee: a file that
/// appears at `dest` AFTER any existence probe but BEFORE the writer's
/// `create_new` open (a concurrent worker winning the destination) must also
/// survive the failed salvage. Ownership is decided by `create_new` alone —
/// when it fails, this call created nothing and must remove nothing. The
/// injected `Metadata` fault materializes the race window deterministically:
/// the probe cannot see the file, yet `create_new` finds it.
#[test]
fn salvage_blob_file_keeps_a_racing_dest_created_after_the_existence_probe() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_dest");
    let plain: Arc<dyn Fs> = Arc::new(StdFs);
    build_blob(&source, &plain, &[(b"k0", b"v0")])?;

    // The "racing" worker's file is already at dest, but any metadata probe of
    // dest fails — exactly the window where the file lands between a stat and
    // the `create_new` open.
    std::fs::write(&dest, b"racing worker's blob")?;
    let fault = FaultFs::new(StdFs);
    fault.injector().arm(
        FaultRule::new(FaultOp::Metadata, Fault::Error(ErrorKind::NotFound)).on_path("blob_dest"),
    );
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let result = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    );
    assert!(
        result.is_err(),
        "the destination is taken, the salvage fails: {result:?}",
    );
    assert_eq!(
        std::fs::read(&dest)?,
        b"racing worker's blob",
        "the racing worker's file survives the failed salvage",
    );
    Ok(())
}

/// A transient I/O failure on the verbatim REREAD must not drop the block:
/// the first, recovery-aware read has already produced a verified decoded
/// block, so the loader falls back to the re-encode path (`verbatim = None`)
/// exactly like a checksum / parity mismatch on the re-read frame. Reserving
/// `Err` for the initial verified read keeps one flaky pread from discarding
/// a block that is provably recoverable.
#[test]
fn salvage_load_block_reencodes_when_the_verbatim_reread_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;
    use crate::table::block::BlockType;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..50u32 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Collect the first data block's handle BEFORE arming the fault (the
    // open + index walk issue their own reads).
    let table = open(source, &fs)?;
    let Some(kh) = table.data_block_handles().find_map(Result::ok) else {
        panic!("source has at least one data block");
    };
    let handle = *kh.as_ref();

    // Within `salvage_load_block` the FIRST positional read is the verified
    // recovery-aware load; the SECOND is the raw verbatim re-read. Fail
    // exactly that second read, once.
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("source")
            .skip(1)
            .once(),
    );
    let result = table.salvage_load_block(&handle, BlockType::Data);
    injector.clear();

    let sb = match result {
        Ok(sb) => sb,
        Err(e) => panic!("a failed verbatim re-read falls back to re-encode, got Err({e:?})"),
    };
    assert!(
        sb.verbatim.is_none(),
        "the re-read was never verified, so the block must not be byte-copied",
    );
    assert!(
        !sb.block.data.is_empty(),
        "the verified first read's decoded payload is preserved for re-encoding",
    );
    Ok(())
}

/// `tli_structure_authenticated` must PROPAGATE a TRANSIENT I/O fault from
/// opening / reading the index mirrors rather than fold it into `false` (an
/// untrusted index). The salvage walk consults this to decide whether an indexed
/// offset is a trusted block boundary; reading a flaky open as `false` degrades
/// to physical-chain-only provenance and surrenders every block past the first
/// header break — dropping healthy keys the intact TLI could anchor on retry. A
/// single transient-kind (`Interrupted`) `Open` fault reproduces the flaky
/// failure; the method must return the propagated I/O error.
#[test]
fn tli_structure_authenticated_propagates_a_transient_read_failure() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..50u32 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Open cleanly, THEN fault the dedicated open the authentication read issues
    // with a TRANSIENT (`Interrupted`) kind.
    let table = open(source, &fs)?;
    injector.arm(
        FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Interrupted))
            .on_path("source")
            .once(),
    );
    let result = table.tli_structure_authenticated();
    injector.clear();
    assert!(
        matches!(result, Err(crate::Error::Io(_))),
        "a transient failure authenticating the index structure must propagate, not be \
         read as an untrusted index: {result:?}",
    );
    Ok(())
}

/// `tli_structure_authenticated` must DEGRADE a PERSISTENT I/O fault to `false`
/// (an untrusted index) rather than propagate it. When one mirror is
/// persistently unreadable (a bad sector) but the other mirror and the data
/// section stay readable, propagating the error makes the `salvage_blocks`
/// caller's `?` abort before its physical-chain fallback, recovering NONE of the
/// intact data blocks. `false` lets the walk fall back to physical-chain
/// provenance and recover the readable blocks.
#[test]
fn tli_structure_authenticated_degrades_a_persistent_read_failure() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    for i in 0..50u32 {
        writer.write(iv(i))?;
    }
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Open cleanly, THEN fault the authentication read's open with a PERSISTENT
    // (`Other`/EIO) kind.
    let table = open(source, &fs)?;
    injector.arm(FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Other)).on_path("source"));
    let result = table.tli_structure_authenticated();
    injector.clear();
    assert!(
        matches!(result, Ok(false)),
        "a persistent authentication failure must degrade to an untrusted index so the \
         salvage walk can still recover the readable data: {result:?}",
    );
    Ok(())
}

/// `delete_positions_verified` must PROPAGATE a transient I/O fault rather than
/// fold it into `false` (an unpositionable mask). Under the default
/// `allow_delete_resurrection == false` a `false` verdict aborts salvage, so a
/// flaky block read during `repair_with_salvage` would drop the table from the
/// rebuilt manifest even though a retry could recover it faithfully. A single
/// `ReadAt` fault on the first positional read the walk issues reproduces the
/// transient read; the method must return the propagated I/O error, not
/// `Ok(false)`.
#[cfg(feature = "columnar")]
#[test]
fn delete_positions_verified_propagates_a_transient_block_read_failure() -> crate::Result<()> {
    use crate::config::DeleteStrategy;
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Open cleanly (footer + block-index reads happen here), THEN fault the
    // first positional read the verification walk issues with a TRANSIENT
    // (`Interrupted`) kind.
    let table = open(source, &fs)?;
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Interrupted))
            .on_path("source")
            .once(),
    );
    let result = table.delete_positions_verified();
    injector.clear();
    assert!(
        matches!(result, Err(crate::Error::Io(_))),
        "a transient read during delete-position validation must propagate, not be read \
         as a persistent unpositionable mask: {result:?}",
    );
    Ok(())
}

/// An ENVIRONMENTAL failure is not always transient: `PermissionDenied` (a
/// refused mount), `StorageFull`, a missing key, a missing dictionary. None of
/// them say anything about the DATA, and every one of them is fixed by
/// correcting the context and retrying. Folding one into `Ok(false)` makes the
/// mask unpositionable, which under the default resurrection policy aborts the
/// salvage — so `repair_with_salvage` rebuilds the manifest without a table
/// that was never damaged.
#[cfg(feature = "columnar")]
#[test]
fn delete_positions_verified_propagates_an_environmental_block_read_failure() -> crate::Result<()> {
    use crate::config::DeleteStrategy;
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Open cleanly, THEN refuse the first positional read the walk issues.
    // `PermissionDenied` is environmental but NOT transient — the class the
    // narrower gate let fall through to `Ok(false)`.
    let table = open(source, &fs)?;
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::PermissionDenied))
            .on_path("source")
            .once(),
    );
    let result = table.delete_positions_verified();
    injector.clear();
    assert!(
        matches!(result, Err(crate::Error::Io(ref e)) if e.kind() == ErrorKind::PermissionDenied),
        "a refused read during delete-position validation must propagate, not be read \
         as a persistent unpositionable mask: {result:?}",
    );
    Ok(())
}

/// `delete_positions_verified` must DEGRADE a PERSISTENT positional read failure
/// to `Ok(false)` (an unpositionable mask), not propagate it: with
/// `allow_delete_resurrection` a bad sector under one block still lets the caller
/// re-emit the remaining readable rows unmasked, instead of aborting the whole
/// salvage.
#[cfg(feature = "columnar")]
#[test]
fn delete_positions_verified_degrades_a_persistent_block_read_failure() -> crate::Result<()> {
    use crate::config::DeleteStrategy;
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let n = 64u32;
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .delete_strategy(DeleteStrategy::MergeOnRead);
    for i in 0..n {
        writer.write(iv(i))?;
    }
    for pos in [5u32, 20, 40] {
        writer.delete_bitmap_mut().insert(pos);
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar+deletes SST is non-empty",
    );

    // Open cleanly, THEN fault the first positional read the verification walk
    // issues with a PERSISTENT (`Other`/EIO) kind.
    let table = open(source, &fs)?;
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("source")
            .once(),
    );
    let result = table.delete_positions_verified();
    injector.clear();
    assert!(
        matches!(result, Ok(false)),
        "a persistent read during delete-position validation must degrade to an \
         unpositionable mask so the resurrection opt-in can take effect: {result:?}",
    );
    Ok(())
}

/// `salvage_blob_file` must not delete a pre-existing file at `dest` when the
/// destination cannot be created (the writer's `create_new` open fails because
/// the path already exists): the error-path cleanup is only for a partial file
/// THIS call created. Deleting a pre-existing destination would turn an
/// argument mistake (a stale path collision, or `source == dest`) into data
/// loss.
#[test]
fn salvage_blob_file_keeps_a_preexisting_dest_on_open_failure() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_dest");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    build_blob(&source, &fs, &[(b"k0", b"v0")])?;
    std::fs::write(&dest, b"pre-existing destination bytes")?;

    let result = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    );
    assert!(
        result.is_err(),
        "an already-existing destination fails the salvage: {result:?}",
    );
    assert_eq!(
        std::fs::read(&dest)?,
        b"pre-existing destination bytes",
        "a pre-existing destination file survives the failed salvage",
    );
    Ok(())
}

/// The salvaged blob file is COMPACTED: after a dropped record every later
/// record shifts to a new offset, and existing SST `ValueHandle::offset`
/// values point into the SOURCE. The report's `offset_remap` must map every
/// salvaged record's source frame offset to its offset in the recovered file
/// (and omit the dropped one), so a caller can re-target handles before
/// swapping the file in.
#[test]
fn salvage_blob_file_reports_an_offset_remap_for_every_salvaged_record() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let records: Vec<(&[u8], &[u8])> = vec![
        (b"k0", b"v0-payload"),
        (b"k1", b"v1-payload"),
        (b"k2", b"v2-payload"),
        (b"k3", b"v3-payload"),
    ];
    build_blob(&source, &fs, &records)?;

    // Source frame offsets, in order, from a clean pre-corruption scan.
    let source_offsets: Vec<u64> = BlobScanner::new(&source, &*fs, 0)?
        .filter_map(Result::ok)
        .map(|e| e.offset)
        .collect();
    assert_eq!(source_offsets.len(), 4, "four source records");

    // Corrupt the SECOND record's value bytes (a checksum break): the scanner
    // re-syncs at the next magic. k2, reached by that byte scan through k1's
    // damaged bytes, has an unprovable boundary; the taint is sticky, so the walk
    // STOPS there and reports the surrendered tail (k2, k3) as ONE drop. So only
    // record 0 (before the corruption) survives.
    {
        let Some(&second) = source_offsets.get(1) else {
            panic!("second record offset");
        };
        // Past the frame header, inside key/value bytes.
        let flip = usize::try_from(second).unwrap_or(0) + 45;
        let mut bytes = std::fs::read(&source)?;
        if let Some(b) = bytes.get_mut(flip) {
            *b ^= 0xFF;
        }
        std::fs::write(&source, &bytes)?;
    }

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(report.records_salvaged, 1, "{report:?}");
    assert_eq!(
        report.dropped.len(),
        2,
        "the corrupt record + the surrendered tail (recorded once) drop: {report:?}"
    );

    // The remap covers exactly the salvaged records, keyed by their SOURCE
    // offsets, and its targets are the actual frame offsets AND on-disk value
    // sizes in the recovered file (verified against a scan of the destination —
    // a live read cross-checks the handle's size against the frame header, so
    // the relocation must carry the re-emitted size, not the source's).
    let dest_records: Vec<(u64, u32)> = BlobScanner::new(&dest, &*fs, 0)?
        .filter_map(Result::ok)
        .map(|e| {
            let value_start = e.offset
                + u64::try_from(crate::vlog::blob_file::writer::BLOB_HEADER_LEN).unwrap_or(0)
                + u64::try_from(e.key.len()).unwrap_or(0);
            (
                e.offset,
                u32::try_from(e.frame_end - value_start).unwrap_or(0),
            )
        })
        .collect();
    let expected: Vec<(u64, super::BlobRecordRelocation)> = std::iter::once(&0usize)
        .zip(&dest_records)
        .map(|(&src_idx, &(offset, on_disk_size))| {
            (
                source_offsets.get(src_idx).copied().unwrap_or(u64::MAX),
                super::BlobRecordRelocation {
                    offset,
                    on_disk_size,
                },
            )
        })
        .collect();
    assert_eq!(
        report.offset_remap, expected,
        "the remap maps each surviving source frame to its compacted target",
    );
    // The dropped record's source offset is NOT in the map: its handle is lost.
    let Some(&dropped_src) = source_offsets.get(1) else {
        panic!("second record offset");
    };
    assert!(
        report
            .offset_remap
            .iter()
            .all(|(src, _)| *src != dropped_src),
        "a dropped record has no remap target: {report:?}",
    );
    Ok(())
}

/// When a record write to the destination fails mid-salvage, `salvage_blob_file`
/// must error AND remove the partial destination it created, so a retry / repair
/// caller never finds a half-written blob file.
#[test]
fn salvage_blob_file_removes_the_partial_dest_when_a_write_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fault = FaultFs::new(StdFs);
    let injector = fault.injector();
    let fs: Arc<dyn Fs> = Arc::new(fault);

    let records: Vec<(&[u8], &[u8])> = vec![(b"k0", b"v0"), (b"k1", b"v1")];
    build_blob(&source, &fs, &records)?;

    // Fail every write to the destination file: the first recovered record's
    // write-back errors.
    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other)).on_path("blob_salvaged"),
    );

    let result = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    );
    assert!(
        result.is_err(),
        "a failed destination write must error the salvage",
    );
    assert!(
        !std::path::Path::new(&dest).exists(),
        "the partial destination is removed on a write failure",
    );
    Ok(())
}

#[test]
fn salvage_blob_file_drops_a_corrupt_record_and_keeps_the_rest() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let records: Vec<(&[u8], &[u8])> = vec![
        (b"k0", b"value-zero"),
        (b"k1", b"value-one"),
        (b"k2", b"value-two"),
        (b"k3", b"value-three"),
    ];
    build_blob(&source, &fs, &records)?;

    // Flip the last byte of the second record's value: the checksum (over
    // key + value) fails, but the frame header (lengths, magic) stays intact, so
    // the scanner reports a checksum mismatch and re-syncs at the next record.
    let Some(second_frame_end) = BlobScanner::new(&source, &*fs, 0)?
        .filter_map(Result::ok)
        .nth(1)
        .map(|e| e.frame_end)
    else {
        panic!("source blob must have at least two records");
    };
    let flip = usize::try_from(second_frame_end - 1).unwrap_or(0);
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(flip) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    // The corrupt k1 drops on its checksum, and the scanner then RESYNCS to the
    // next magic. k2's frame is reached by that byte scan through k1's damaged
    // bytes, so its boundary is UNPROVEN. The taint is sticky, so the walk STOPS at
    // k2 and reports the whole surrendered tail (k2 and k3 chained past it) as ONE
    // drop, rather than re-emitting a possibly-fabricated chain. Only k0, before
    // the corruption, is provable.
    assert_eq!(
        report.dropped.len(),
        2,
        "the corrupt record + the surrendered tail (recorded once) drop: {report:?}"
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(BlobDropReason::ChecksumMismatch)
        ),
        "the corrupt record reports a checksum mismatch: {report:?}",
    );
    assert_eq!(
        report
            .dropped
            .iter()
            .filter(
                |d| matches!(&d.reason, BlobDropReason::Corrupt(m) if m.contains("surrendered"))
            )
            .count(),
        1,
        "the surrendered tail after the resync is recorded ONCE: {report:?}",
    );
    assert_eq!(
        report.records_salvaged, 1,
        "only k0 is recovered; k1 (corrupt) and the surrendered tail (k2, k3) are not"
    );

    // The salvaged file holds only k0: k1 (corrupt) and the whole tainted tail
    // (k2, k3) after the resync are absent.
    let recovered = scan_blob(&dest, &fs)?;
    let keys: Vec<Vec<u8>> = recovered.iter().map(|(k, _)| k.clone()).collect();
    assert_eq!(
        keys,
        vec![b"k0".to_vec()],
        "only the provable frame before the corruption survives",
    );
    Ok(())
}

/// A blob file where EVERY record is corrupt salvages nothing: the report
/// carries only drops, `salvaged_path` is `None`, and the empty destination
/// placeholder the writer created is removed (a repair caller would otherwise
/// re-reject a stray zero-record blob file in its place).
#[test]
fn salvage_blob_file_removes_the_empty_dest_when_nothing_is_recoverable() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let records: Vec<(&[u8], &[u8])> = vec![(b"k0", b"value-zero"), (b"k1", b"value-one")];
    build_blob(&source, &fs, &records)?;

    // Flip the last value byte of BOTH records: each frame header stays
    // intact, so the scanner reports one checksum mismatch per record and
    // re-syncs — leaving zero salvageable records.
    let frame_ends: Vec<u64> = BlobScanner::new(&source, &*fs, 0)?
        .filter_map(Result::ok)
        .map(|e| e.frame_end)
        .collect();
    assert_eq!(frame_ends.len(), 2, "source blob holds two records");
    let mut bytes = std::fs::read(&source)?;
    for end in frame_ends {
        let flip = usize::try_from(end - 1).unwrap_or(0);
        if let Some(b) = bytes.get_mut(flip) {
            *b ^= 0xFF;
        }
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(report.records_salvaged, 0, "{report:?}");
    assert_eq!(report.dropped.len(), 2, "both records drop: {report:?}");
    assert_eq!(
        report.salvaged_path, None,
        "nothing recoverable yields no salvaged path",
    );
    assert!(
        fs.metadata(&dest).is_err(),
        "the empty destination placeholder is removed",
    );
    Ok(())
}

/// A STRUCTURAL failure mid-walk (a record frame whose magic bytes are gone,
/// not a checksum miss) terminates the blob walk: the scanner cannot re-sync
/// past it, so the salvage records one `Corrupt` drop for the unreadable tail
/// and keeps everything scanned before it.
#[test]
fn salvage_blob_file_stops_at_a_smashed_frame_and_keeps_the_prefix() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let records: Vec<(&[u8], &[u8])> = vec![
        (b"k0", b"value-zero"),
        (b"k1", b"value-one"),
        (b"k2", b"value-two"),
    ];
    build_blob(&source, &fs, &records)?;

    // Smash the LAST record's frame magic (the file structure and trailer
    // stay intact): the scanner reports it as a structural InvalidHeader it
    // cannot re-sync from, unlike a checksum miss.
    let Some(last_start) = BlobScanner::new(&source, &*fs, 0)?
        .filter_map(Result::ok)
        .nth(1)
        .map(|e| e.frame_end)
    else {
        panic!("source blob must have at least two records");
    };
    let mut bytes = std::fs::read(&source)?;
    let at = usize::try_from(last_start).unwrap_or(0);
    let Some(magic) = bytes.get_mut(at..at + 4) else {
        panic!("last record's frame magic within the file");
    };
    magic.copy_from_slice(b"????");
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(
        report.records_salvaged, 2,
        "the records before the smashed frame are recovered: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(BlobDropReason::Corrupt(_))
        ),
        "the truncated tail is recorded as a structural drop: {report:?}",
    );
    let recovered = scan_blob(&dest, &fs)?;
    assert_eq!(recovered.len(), 2, "the salvaged copy holds the prefix");
    Ok(())
}

/// A blob frame whose header CRC and data checksum are internally consistent
/// but whose `key_len` is ZERO yields an Ok scanner entry with an empty key —
/// which the blob writer's ingest asserts against. Salvage must route such a
/// frame through the corrupt-record path (dropped, walk continues) instead of
/// panicking in the writer and leaving a partial destination behind.
#[test]
fn salvage_blob_file_drops_an_empty_key_frame() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    build_blob(&source, &fs, &[(b"k", b"vvvv"), (b"k2", b"second")])?;

    // Re-frame the FIRST record as `key_len = 0`: its key byte becomes the
    // first value byte (the hashed key||value byte span is unchanged), with
    // the header CRC and data checksum recomputed so the frame stays
    // internally consistent. V4 frame layout from offset 0:
    //   magic 4 | checksum 16 | seqno 8 | key_len 2 | real_val_len 4 |
    //   on_disk_val_len 4 | header_crc 4 | key | value.
    let mut bytes = std::fs::read(&source)?;
    let seqno = {
        let Some(b) = bytes.get(20..28) else {
            panic!("seqno within the first frame");
        };
        u64::from_le_bytes(b.try_into().unwrap_or([0; 8]))
    };
    // header_crc = truncated xxh3 over (seqno, key_len, real_val_len,
    // on_disk_val_len), matching the writer's framing.
    let new_hcrc = {
        let mut hasher = xxhash_rust::xxh3::Xxh3::default();
        hasher.update(&seqno.to_le_bytes());
        hasher.update(&0u16.to_le_bytes());
        hasher.update(&5u32.to_le_bytes());
        hasher.update(&5u32.to_le_bytes());
        #[expect(
            clippy::cast_possible_truncation,
            reason = "intentionally truncated to the 4-byte header CRC"
        )]
        {
            hasher.digest() as u32
        }
    };
    // data checksum = xxh3_128(key || value || header_crc_le); with the empty
    // key the hashed span is the same "kvvvv" bytes plus the NEW header CRC.
    let new_checksum = {
        let mut hasher = xxhash_rust::xxh3::Xxh3::default();
        hasher.update(b"kvvvv");
        hasher.update(&new_hcrc.to_le_bytes());
        hasher.digest128()
    };
    let patch = |bytes: &mut Vec<u8>, range: core::ops::Range<usize>, val: &[u8]| {
        let Some(slot) = bytes.get_mut(range) else {
            panic!("patch range within the first frame");
        };
        slot.copy_from_slice(val);
    };
    patch(&mut bytes, 4..20, &new_checksum.to_le_bytes());
    patch(&mut bytes, 28..30, &0u16.to_le_bytes());
    patch(&mut bytes, 30..34, &5u32.to_le_bytes());
    patch(&mut bytes, 34..38, &5u32.to_le_bytes());
    patch(&mut bytes, 38..42, &new_hcrc.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(
        report.dropped.len(),
        1,
        "the empty-key frame drops as corrupt: {report:?}",
    );
    assert!(
        matches!(
            report.dropped.first().map(|d| &d.reason),
            Some(BlobDropReason::Corrupt(_))
        ),
        "the drop reason names the malformed frame: {report:?}",
    );
    assert_eq!(
        report.records_salvaged, 1,
        "the record after the malformed frame is still recovered",
    );
    let recovered = scan_blob(&dest, &fs)?;
    assert_eq!(
        recovered,
        vec![(b"k2".to_vec(), b"second".to_vec())],
        "the salvaged copy holds exactly the healthy record",
    );
    Ok(())
}

/// A blob frame whose header CRC and data checksum are internally consistent
/// but whose `real_val_len` field disagrees with the bytes actually stored
/// (`on_disk_val_len`, an uncompressed source) is REJECTED by the live blob
/// reader — salvage must not launder it: re-emitting through the writer would
/// restamp the frame with a consistent length and count a record the live
/// read path treats as corrupt as salvaged. It must drop through the
/// corrupt-record path instead.
#[test]
fn salvage_blob_file_drops_a_frame_with_a_forged_value_length() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    build_blob(&source, &fs, &[(b"k", b"vvvv"), (b"k2", b"second")])?;

    // Re-stamp the FIRST record's `real_val_len` (4 → 5) while the stored
    // bytes stay 4 (`on_disk_val_len` unchanged), with the header CRC and
    // data checksum recomputed so the frame stays internally consistent —
    // exactly the shape the scanner accepts and `Reader::get` rejects.
    // V4 frame layout from offset 0:
    //   magic 4 | checksum 16 | seqno 8 | key_len 2 | real_val_len 4 |
    //   on_disk_val_len 4 | header_crc 4 | key | value.
    let mut bytes = std::fs::read(&source)?;
    let seqno = {
        let Some(b) = bytes.get(20..28) else {
            panic!("seqno within the first frame");
        };
        u64::from_le_bytes(b.try_into().unwrap_or([0; 8]))
    };
    let new_hcrc = {
        let mut hasher = xxhash_rust::xxh3::Xxh3::default();
        hasher.update(&seqno.to_le_bytes());
        hasher.update(&1u16.to_le_bytes());
        hasher.update(&5u32.to_le_bytes());
        hasher.update(&4u32.to_le_bytes());
        #[expect(
            clippy::cast_possible_truncation,
            reason = "intentionally truncated to the 4-byte header CRC"
        )]
        {
            hasher.digest() as u32
        }
    };
    let new_checksum = {
        let mut hasher = xxhash_rust::xxh3::Xxh3::default();
        hasher.update(b"kvvvv");
        hasher.update(&new_hcrc.to_le_bytes());
        hasher.digest128()
    };
    let patch = |bytes: &mut Vec<u8>, range: core::ops::Range<usize>, val: &[u8]| {
        let Some(slot) = bytes.get_mut(range) else {
            panic!("patch range within the first frame");
        };
        slot.copy_from_slice(val);
    };
    patch(&mut bytes, 4..20, &new_checksum.to_le_bytes());
    patch(&mut bytes, 30..34, &5u32.to_le_bytes());
    patch(&mut bytes, 38..42, &new_hcrc.to_le_bytes());
    std::fs::write(&source, &bytes)?;

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(
        report.dropped.len(),
        1,
        "the forged-length frame drops as corrupt: {report:?}",
    );
    assert_eq!(
        report.records_salvaged, 1,
        "the record after the malformed frame is still recovered",
    );
    let recovered = scan_blob(&dest, &fs)?;
    assert_eq!(
        recovered,
        vec![(b"k2".to_vec(), b"second".to_vec())],
        "the salvaged copy holds exactly the healthy record",
    );
    Ok(())
}

/// A compressed blob source is rejected (fail-closed): the scanner yields on-disk
/// compressed bytes that this path cannot faithfully re-emit yet.
#[cfg(feature = "lz4")]
#[test]
#[expect(clippy::expect_used, reason = "test code")]
fn salvage_blob_file_recovers_a_compressed_source() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let value = b"some compressible value aaaaaaaaaaaaaaaa";

    {
        let mut writer =
            BlobWriter::new(&source, 0, 0, &*fs)?.use_compression(crate::CompressionType::Lz4);
        writer.write(b"k0", 0, value)?;
        writer.finish()?;
    }

    // A compressed source is salvaged by DECOMPRESSING each record (proving it
    // round-trips) and re-emitting it under the same compression descriptor —
    // never copied through verbatim, which would store undecodable bytes.
    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        None,
    )?;
    assert_eq!(report.records_salvaged, 1, "the record is recovered");
    assert!(
        report.is_complete(),
        "nothing dropped: {:?}",
        report.dropped
    );
    assert_eq!(report.salvaged_path.as_ref(), Some(&dest));

    // The recovered copy reads back through the live blob reader.
    let handle = crate::vlog::recover_blob_file(
        &dest,
        0,
        crate::Checksum::from_raw(crate::repair::compute_table_checksum(&*fs, &dest)?),
        0,
        &fs,
    )?;
    assert_eq!(
        handle.compression(),
        crate::CompressionType::Lz4,
        "the copy keeps the source's compression descriptor",
    );
    // A live SST handle is rebuilt straight from the relocation: BOTH its
    // fields come from the salvaged file (the reader cross-checks the size
    // against the frame header, so the relocation's size must be the
    // re-emitted one).
    let (_, relocation) = *report.offset_remap.first().expect("one remap entry");
    let file = std::fs::File::open(&dest)?;
    let reader = crate::vlog::blob_file::reader::Reader::new(&handle, &file);
    let vhandle = crate::vlog::ValueHandle {
        blob_file_id: 0,
        offset: relocation.offset,
        on_disk_size: relocation.on_disk_size,
    };
    assert_eq!(
        reader.get(b"k0", &vhandle)?.as_ref(),
        value,
        "the salvaged record decompresses to its original value",
    );
    Ok(())
}

/// With the matching dictionary supplied (manifest repair passes the tree's
/// configured one), a dictionary-compressed source salvages like any other
/// compressed blob: intact records decompress, re-emit under the same
/// descriptor, and damaged records drop — instead of the whole file (and every
/// dependent SST) being set aside for want of dictionary context.
#[cfg(zstd_any)]
#[test]
#[expect(clippy::expect_used, reason = "test code")]
fn salvage_blob_file_recovers_a_dictionary_source_with_the_dictionary() -> crate::Result<()> {
    use std::io::{Seek, SeekFrom, Write};

    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let dict = Arc::new(crate::compression::ZstdDictionary::new(
        b"sample sample sample sample payload payload payload",
    ));
    let compression = crate::CompressionType::ZstdDict {
        level: 3,
        dict_id: dict.id(),
    };

    {
        let mut w = BlobWriter::new(&source, 0, 0, &*fs)?
            .use_compression(compression)
            .use_zstd_dictionary(Some(Arc::clone(&dict)));
        w.write(b"a", 1, b"sample payload sample payload sample payload")?;
        w.write(b"b", 2, b"sample payload sample payload sample sample")?;
        w.finish()?;
    }

    // Rot the SECOND record's payload (checksum fails, the record drops; the
    // first record is the intact survivor the dictionary must decode).
    let entries: Vec<_> =
        crate::vlog::BlobFileScanner::new(&source, &*fs, 0)?.collect::<crate::Result<Vec<_>>>()?;
    let second = entries.get(1).expect("two records");
    {
        let mut f = std::fs::OpenOptions::new().write(true).open(&source)?;
        f.seek(SeekFrom::Start(second.frame_end - 4))?;
        f.write_all(&[0xFF, 0xFF, 0xFF, 0xFF])?;
    }

    let report = salvage_blob_file(
        &source,
        dest.clone(),
        &fs,
        0,
        &default_comparator(),
        0,
        #[cfg(zstd_any)]
        Some(&dict),
    )?;
    assert_eq!(
        report.records_salvaged, 1,
        "the intact dictionary-compressed record is recovered: {report:?}",
    );
    assert_eq!(report.dropped.len(), 1, "the rotted record drops");

    // The re-emitted record round-trips under the SAME dictionary descriptor.
    let salvaged = crate::vlog::BlobFileScanner::new(&dest, &*fs, 0)?
        .next()
        .expect("one salvaged record")?;
    let value = super::decompress_blob_value(
        compression,
        &salvaged.value,
        salvaged.uncompressed_len as usize,
        #[cfg(zstd_any)]
        Some(&dict),
    )?;
    assert_eq!(
        value.as_ref(),
        b"sample payload sample payload sample payload",
        "the salvaged record decodes to its original value under the dictionary",
    );
    Ok(())
}

#[cfg(all(feature = "lz4", zstd_any))]
#[test]
fn salvage_blob_file_rejects_a_dictionary_compressed_source() -> crate::Result<()> {
    let dir = tempdir()?;
    let source = dir.path().join("blob_source");
    let dest = dir.path().join("blob_salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    // A dictionary descriptor with no dictionary context on this standalone
    // path: fail closed rather than re-emit undecodable values.
    {
        let mut writer =
            BlobWriter::new(&source, 0, 0, &*fs)?.use_compression(crate::CompressionType::Lz4);
        writer.metadata_compression_override = Some(crate::CompressionType::ZstdDict {
            level: 3,
            dict_id: 7,
        });
        writer.write(b"k0", 0, b"some compressible value aaaaaaaaaaaaaaaa")?;
        writer.finish()?;
    }

    assert!(
        matches!(
            salvage_blob_file(
                &source,
                dest,
                &fs,
                0,
                &default_comparator(),
                0,
                #[cfg(zstd_any)]
                None
            ),
            // The SAME error a wrong dictionary raises, with `got: None`:
            // both are a mis-supplied recovery context, and repair
            // propagates that class instead of grading the file damaged.
            Err(crate::Error::ZstdDictMismatch {
                expected: 7,
                got: None
            }),
        ),
        "a dictionary-compressed blob file must be rejected rather than mis-salvaged",
    );
    Ok(())
}

/// The blob-handle rewrite must install BOTH relocation fields into a remapped
/// indirection: the salvaged file is compacted (offset moves) AND its records
/// are re-compressed (the on-disk size may change — compressor output is not
/// stable across versions), while `Reader::get` cross-checks the handle's size
/// against the frame header and rejects a mismatch. Carrying only the offset
/// would leave otherwise-salvaged values unreadable.
#[test]
#[expect(clippy::expect_used, reason = "test code")]
fn blob_handle_rewrite_installs_the_relocated_size() -> crate::Result<()> {
    use crate::blob_tree::handle::BlobIndirection;
    use crate::coding::{Decode, Encode};
    use crate::vlog::ValueHandle;
    use crate::{InternalValue, ValueType};

    let ind = BlobIndirection {
        vhandle: ValueHandle {
            blob_file_id: 7,
            offset: 400,
            on_disk_size: 64,
        },
        size: 100,
    };
    let mut value = Vec::new();
    ind.encode_into(&mut value)?;
    let entries = vec![InternalValue::from_components(
        b"k".to_vec(),
        value,
        1,
        ValueType::Indirection,
    )];

    // The salvaged replacement re-emitted this record at a new offset AND a
    // new (re-compressed) on-disk size.
    let mut map = crate::HashMap::default();
    map.insert(
        400u64,
        super::BlobRecordRelocation {
            offset: 16,
            on_disk_size: 61,
        },
    );
    let mut rewrite = crate::HashMap::default();
    // The replacement is a FRESH blob file, so the handle must be retargeted
    // at its id as well as at the new offset.
    rewrite.insert(
        7u64,
        super::BlobFileRewrite::Remap {
            new_id: 9,
            offsets: map,
        },
    );

    let mut dropped = 0u64;
    let (out, carry) = super::rewrite_block_indirections(entries, &rewrite, &mut dropped)?;
    assert_eq!(dropped, 0, "the record survived, nothing drops");
    assert!(carry.is_none(), "nothing was beheaded, nothing to suppress");
    let entry = out.first().expect("one rewritten entry");
    let rewritten = BlobIndirection::decode_from(&mut &entry.value[..])?;
    assert_eq!(
        rewritten.vhandle.blob_file_id, 9,
        "the handle names the salvaged replacement, not the damaged original",
    );
    assert_eq!(rewritten.vhandle.offset, 16, "the offset is re-targeted");
    assert_eq!(
        rewritten.vhandle.on_disk_size, 61,
        "the on-disk size is the RE-EMITTED record's, not the source's: the \
         reader rejects a handle whose size disagrees with the frame header",
    );
    Ok(())
}

/// Losing a blob record removes the HEAD of a key's version chain, so the older
/// versions behind it must go too: keeping them republishes an overwritten value
/// as current, or undoes a newer write by exposing an older tombstone.
#[test]
fn blob_handle_rewrite_drops_older_versions_when_the_head_record_is_lost() -> crate::Result<()> {
    use crate::blob_tree::handle::BlobIndirection;
    use crate::coding::Encode;
    use crate::vlog::ValueHandle;
    use crate::{InternalValue, ValueType};

    let indirection = |offset: u64| -> crate::Result<Vec<u8>> {
        let mut value = Vec::new();
        BlobIndirection {
            vhandle: ValueHandle {
                blob_file_id: 7,
                offset,
                on_disk_size: 64,
            },
            size: 100,
        }
        .encode_into(&mut value)?;
        Ok(value)
    };

    // The salvaged replacement re-emitted NOTHING of the original: every
    // handle into file 7 has lost its record.
    let mut rewrite = crate::HashMap::default();
    rewrite.insert(
        7u64,
        super::BlobFileRewrite::Remap {
            new_id: 9,
            offsets: crate::HashMap::default(),
        },
    );

    // `k`'s newest version is the lost indirection; its older INLINE value sits
    // right behind it, and `z` ends the run.
    let entries = vec![
        InternalValue::from_components(
            b"k".to_vec(),
            indirection(400)?,
            10,
            ValueType::Indirection,
        ),
        InternalValue::from_components(b"k".to_vec(), b"old".to_vec(), 5, ValueType::Value),
        InternalValue::from_components(b"z".to_vec(), b"v".to_vec(), 1, ValueType::Value),
    ];
    let mut dropped = 0u64;
    let (out, carry) = super::rewrite_block_indirections(entries, &rewrite, &mut dropped)?;
    let keys: Vec<_> = out.iter().map(|e| e.key.user_key.to_vec()).collect();
    assert_eq!(
        keys,
        vec![b"z".to_vec()],
        "the beheaded key goes entirely; the next key is untouched",
    );
    assert_eq!(dropped, 2, "both the lost head and the version behind it");
    assert!(
        carry.is_none(),
        "a surviving entry with a different key ended the run",
    );

    // The same chain, but the block ENDS inside it: the suppression has to
    // continue into the next block.
    let entries = vec![
        InternalValue::from_components(
            b"k".to_vec(),
            indirection(400)?,
            10,
            ValueType::Indirection,
        ),
        InternalValue::from_components(b"k".to_vec(), b"old".to_vec(), 5, ValueType::Value),
    ];
    let mut dropped = 0u64;
    let (out, carry) = super::rewrite_block_indirections(entries, &rewrite, &mut dropped)?;
    assert!(out.is_empty(), "the whole block was one beheaded key");
    assert_eq!(
        carry.as_deref(),
        Some(b"k".as_slice()),
        "nothing proved the run ended, so the key keeps suppressing",
    );
    Ok(())
}

/// A columnar source carrying a per-field value sub-column salvages into a copy
/// that KEEPS the sub-column (verbatim `ColumnBatch` re-emit), instead of
/// collapsing it into a single value column via a row round-trip.
#[cfg(feature = "columnar")]
#[test]
fn salvage_preserves_columnar_value_subcolumns() -> crate::Result<()> {
    use crate::table::columnar::{Column, TypeTag, entries_to_column_batch};

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let cmp = default_comparator();

    // Two columnar blocks whose value is a single fixed-4 sub-column (id 3),
    // written verbatim through the ingest batch path (per-row seqno 0).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true);
    for block in 0..2u32 {
        let entries: Vec<InternalValue> = (0..4u32)
            .map(|i| {
                let k = format!("k{:04}", block * 4 + i);
                InternalValue::from_components(k.into_bytes(), b"x".to_vec(), 0, ValueType::Value)
            })
            .collect();
        let mut batch = entries_to_column_batch(&entries)?;
        batch.columns.pop();
        let mut data = Vec::new();
        for i in 0..4u32 {
            data.extend_from_slice(&(block * 4 + i).to_le_bytes());
        }
        batch.columns.push(Column {
            column_id: 3,
            type_tag: TypeTag::Fixed(4),
            validity: None,
            data,
        });
        writer.write_columnar_batch(&batch, &cmp)?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "a healthy columnar SST drops nothing: {report:?}"
    );
    // No deletes + clean blocks: each columnar block is copied through verbatim,
    // which is exactly why the per-field sub-columns survive byte-for-byte.
    assert_eq!(
        report.blocks_copied_verbatim, report.blocks_salvaged,
        "clean columnar blocks are copied verbatim",
    );

    // Reopen and project sub-column 3 via the per-SST scan: it survives as a
    // sub-column. A row round-trip would have collapsed it into the value column.
    let recovered = open(dest, &fs)?;
    assert!(
        recovered.metadata.columnar,
        "the recovered copy stays columnar"
    );
    let batches = recovered.columnar_scan(&[3], None)?;
    let rows: u32 = batches.iter().map(|b| b.row_count).sum();
    assert_eq!(rows, 8, "every row's sub-column is recovered");
    assert!(
        batches
            .iter()
            .all(|b| b.columns.iter().all(|c| c.column_id == 3)),
        "the value sub-column (id 3) is preserved verbatim, not collapsed",
    );
    Ok(())
}

/// A columnar Page-ECC SST with a single-byte RS-recoverable fault in a data
/// block (no deletes): salvage recovers the block from parity and **re-encodes**
/// the healed batch rather than copying the faulty on-disk bytes verbatim, so the
/// recovered copy carries clean bytes. The clean block around it is still copied
/// verbatim.
#[cfg(all(feature = "columnar", feature = "page_ecc"))]
#[test]
fn salvage_reencodes_an_ecc_recovered_columnar_block() -> crate::Result<()> {
    use crate::table::block::{EccParams, Header};
    use crate::table::columnar::entries_to_column_batch;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let dest = dir.path().join("salvaged");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let cmp = default_comparator();

    // Two columnar blocks under RS(4,2) parity, no deletes (so the no-deletes
    // copy-through / recover path is taken, not the delete-masked one).
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_zone_map(true)
        .use_ecc(Some(EccParams::RS_4_2));
    for block in 0..2u32 {
        let entries: Vec<InternalValue> = (0..4u32)
            .map(|i| {
                let k = format!("k{:04}", block * 4 + i);
                InternalValue::from_components(k.into_bytes(), b"x".to_vec(), 0, ValueType::Value)
            })
            .collect();
        let batch = entries_to_column_batch(&entries)?;
        writer.write_columnar_batch(&batch, &cmp)?;
    }
    assert!(
        writer.finish()?.is_some(),
        "source columnar SST is non-empty"
    );

    // Flip one byte of the first columnar data block (RS(4,2) recovers a single
    // byte error).
    let first_off = {
        let table = open(source.clone(), &fs)?;
        let Some(kh) = table.data_block_handles().find_map(Result::ok) else {
            panic!("a non-empty SST has at least one data block");
        };
        usize::try_from(*kh.as_ref().offset()).unwrap_or(usize::MAX)
    };
    let pos = first_off + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(pos) {
        *b ^= 0x80;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert!(
        report.is_complete(),
        "an RS-recoverable columnar block is healed, not dropped: {report:?}",
    );
    assert_eq!(
        report.blocks_salvaged, report.blocks_total,
        "every block is recovered",
    );
    // The recovered block was re-encoded (verbatim:None), so fewer verbatim copies
    // than salvaged blocks; the other (clean) block is copied verbatim.
    assert!(
        report.blocks_copied_verbatim < report.blocks_salvaged,
        "the ECC-recovered columnar block is re-encoded, not copied verbatim: {report:?}",
    );

    let recovered = open(dest, &fs)?;
    assert!(
        recovered.metadata.columnar,
        "the recovered copy stays columnar"
    );
    assert_eq!(recovered.metadata.item_count, 8, "every row is recovered");
    Ok(())
}

/// Salvage decides key identity the way the rest of the engine does, so a
/// version whose bytes differ is a DIFFERENT key and survives the loss of its
/// neighbour. That is not a shortcut for ordering: a comparator that called two
/// different spellings equal would break point lookups outright — filters and
/// the locator hash the raw bytes — which is why the trait's contract forbids
/// it, and why every path can share one relation.
#[test]
fn salvage_suppresses_only_the_shadowed_key_itself() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One entry per block: a deletion for `K` in block 1, then a DIFFERENT key
    // `k` in block 2 (a byte-distinct key, hence a distinct key), then `z`.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::new_tombstone(b"K".as_slice(), 10))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"z",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the FIRST block: the deletion of `K` is lost.
    let first_off = {
        let table = open_with_id(source.clone(), &fs, 0)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 3,
            "one block per entry, got {}",
            offsets.len()
        );
        usize::try_from(offsets.first().copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(first_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.dropped.len(), 1, "one block is lost: {report:?}");

    let recovered = open_with_id(dest, &fs, 0)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_some(),
        "`k` is a different key from the lost `K`: its own newest version is \
         intact and must survive",
    );
    Ok(())
}

/// The blob-handle rewrite suppresses a beheaded chain the same way, and asks
/// the same question: losing a key's newest record takes every OLDER version of
/// THAT key with it, and leaves a different key alone.
#[test]
fn the_blob_rewrite_suppresses_only_the_beheaded_key() -> crate::Result<()> {
    use crate::coding::Encode;
    use crate::{InternalValue, ValueType};

    let indirection = |offset: u64| -> crate::Result<Vec<u8>> {
        let ind = crate::blob_tree::handle::BlobIndirection {
            vhandle: crate::vlog::ValueHandle {
                blob_file_id: 7,
                offset,
                on_disk_size: 16,
            },
            size: 16,
        };
        let mut buf = Vec::new();
        ind.encode_into(&mut buf)?;
        Ok(buf)
    };

    // `a` (newest) points at a record the salvage LOST, and its own older
    // version follows; `z` is a different key whose record survived.
    let entries = vec![
        InternalValue::from_components(b"a", indirection(100)?, 10, ValueType::Indirection),
        InternalValue::from_components(b"a", indirection(200)?, 5, ValueType::Indirection),
        InternalValue::from_components(b"z", indirection(200)?, 1, ValueType::Indirection),
    ];

    // The remap holds only offset 200: the record behind `a`'s newest is gone.
    let mut offsets = crate::HashMap::default();
    offsets.insert(
        200u64,
        super::BlobRecordRelocation {
            offset: 300,
            on_disk_size: 16,
        },
    );
    let mut rewrite = crate::HashMap::default();
    rewrite.insert(7u64, super::BlobFileRewrite::Remap { new_id: 9, offsets });

    let mut dropped = 0u64;
    let (kept, carry) = super::rewrite_block_indirections(entries, &rewrite, &mut dropped)?;

    let keys: Vec<_> = kept.iter().map(|e| e.key.user_key.to_vec()).collect();
    assert_eq!(
        keys,
        vec![b"z".to_vec()],
        "the beheaded key's older version goes with it; a different key stays",
    );
    assert_eq!(
        dropped, 2,
        "both the lost head and its orphaned older version"
    );
    assert!(
        carry.is_none(),
        "a surviving different key ended the run inside this block",
    );
    Ok(())
}

#[test]
fn salvage_keeps_tied_seqno_merge_operands() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One write batch adds several merge operands for a key, so they share the
    // batch's seqno and a flush stores every one of them. The pair below sits in
    // ONE block; `z` gets its own so a corruption elsewhere can trigger salvage.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(100);
    writer.write(InternalValue::new_merge_operand(
        b"k".as_slice(),
        [b'A'; 64],
        10,
    ))?;
    writer.write(InternalValue::new_merge_operand(
        b"k".as_slice(),
        [b'B'; 64],
        10,
    ))?;
    writer.write(InternalValue::from_components(
        b"z",
        [b'z'; 128],
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the LAST block so salvage runs while the operand block is clean.
    let last_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 2,
            "the fixture needs the operands and `z` in separate blocks, got {}",
            offsets.len(),
        );
        usize::try_from(offsets.last().copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(last_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "only `z`'s block is lost: {report:?}"
    );

    let recovered = open(dest, &fs)?;
    let operands: Vec<_> = recovered
        .scan()?
        .filter_map(Result::ok)
        .filter(|e| e.key.user_key.as_ref() == b"k")
        .map(|e| e.value.to_vec())
        .collect();
    assert_eq!(
        operands.len(),
        2,
        "both operands are valid input to the merge, so a clean block holding \
         them must not be rejected as out of order: {operands:?}",
    );
    Ok(())
}

/// The same run can straddle a block boundary — the batch's operands do not have
/// to land in one block — so the cross-edge check has to accept the tie too.
#[test]
fn salvage_keeps_tied_seqno_merge_operands_across_a_block_boundary() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One entry per block, so the two operands sit on either side of an edge.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::new_merge_operand(b"k".as_slice(), b"A", 10))?;
    writer.write(InternalValue::new_merge_operand(b"k".as_slice(), b"B", 10))?;
    writer.write(InternalValue::from_components(
        b"z",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let last_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert_eq!(offsets.len(), 3, "one block per entry");
        usize::try_from(offsets.last().copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(last_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(
        report.dropped.len(),
        1,
        "only `z`'s block is lost: {report:?}"
    );

    let recovered = open(dest, &fs)?;
    let operands = recovered
        .scan()?
        .filter_map(Result::ok)
        .filter(|e| e.key.user_key.as_ref() == b"k")
        .count();
    assert_eq!(
        operands, 2,
        "the tie spanning the block edge is a valid run, not a violation",
    );
    Ok(())
}

/// A key's MVCC versions are contiguous, so they can straddle a block
/// boundary: the newest can be the last entry of one block and an older one the
/// first entry of the next. When the block holding the newest version is
/// dropped, emitting the next block as-is republishes the older version as
/// current — a delete resurrects, or an overwritten value comes back. The
/// boundary key's entries must be dropped with it unless resurrection is on.
#[test]
fn salvage_drops_the_boundary_key_when_its_newest_version_is_lost() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One entry per block, so `k`'s newest version (a deletion) is the whole of
    // block 1 and its older value the whole of block 2.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::from_components(
        b"a",
        b"v",
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::new_tombstone(b"k".as_slice(), 10))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"z",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the block whose last key is `k` and whose seqno is the newest:
    // the second data block in offset order.
    let second_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 3,
            "the fixture needs one block per entry, got {}",
            offsets.len(),
        );
        usize::try_from(offsets.get(1).copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(second_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.dropped.len(), 1, "one block is lost: {report:?}");

    let recovered = open(dest, &fs)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_none(),
        "the older version of the boundary key must not be republished as \
         current when the newest version was lost",
    );
    assert!(
        recovered
            .get(b"a", crate::SeqNo::MAX, crate::hash::hash64(b"a"))?
            .is_some(),
        "unaffected keys are still recovered",
    );
    Ok(())
}

/// A version chain can span MORE than one surviving block. Clearing the
/// suppression on the first block after the drop lets the second one publish an
/// even older version of the same key, so the boundary has to hold until a
/// surviving entry with a different key proves the run ended.
#[test]
fn salvage_keeps_suppressing_a_boundary_key_across_a_whole_shadowed_block() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One entry per block: `k`'s newest version (a deletion) is block 1, and its
    // two older values are blocks 2 and 3 — a chain of whole shadowed blocks.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::new_tombstone(b"k".as_slice(), 10))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"mid",
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"z",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Corrupt the FIRST data block: the one holding `k`'s newest version.
    let first_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 4,
            "the fixture needs one block per entry, got {}",
            offsets.len(),
        );
        usize::try_from(offsets.first().copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(first_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.dropped.len(), 1, "one block is lost: {report:?}");

    let recovered = open(dest, &fs)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_none(),
        "the chain continues past the first surviving block, so every older \
         version of the boundary key has to stay suppressed",
    );
    assert!(
        recovered
            .get(b"z", crate::SeqNo::MAX, crate::hash::hash64(b"z"))?
            .is_some(),
        "the key that ends the run is recovered",
    );
    Ok(())
}

/// A lost block whose KEY RANGE is unknown (no index separator survived) must
/// arm the suppression as unknown, not with the last key seen. Naming the
/// previous surviving block's key instead suppresses a key nothing shadowed
/// while the key the lost block really covered is republished from its older
/// version.
#[test]
fn salvage_arms_an_unknown_boundary_when_the_lost_block_has_no_range() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // Block 1: `a`. Block 2: `k`'s newest version, lost with its index entry.
    // Block 3: `k`'s older value — the version that must NOT come back.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(1);
    writer.write(InternalValue::from_components(
        b"a",
        b"v",
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::new_tombstone(b"k".as_slice(), 10))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        5,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // Smash the second block's header MAGIC so the physical walk cannot frame
    // it. The index stays intact, so the walk still trusts the following
    // handle's boundary and emits it — the block itself is recorded as a lost
    // REGION by the gap probe, carrying no key range at all.
    let second_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 3,
            "the fixture needs one block per entry, got {}",
            offsets.len(),
        );
        usize::try_from(offsets.get(1).copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(second_off) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    let recovered = open(dest, &fs)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_none(),
        "the lost region'\u{2019}s range is unknown, so the FOLLOWING block'\u{2019}s \
         first key is the one it may have shadowed: {report:?}",
    );
    Ok(())
}

/// Suppression rewrites what the block CONTAINS, so the block can no longer be
/// byte-copied: a verbatim append would carry the shadowed key's bytes into the
/// recovered copy while the filtered entry list quietly claims it is gone.
#[test]
fn salvage_does_not_byte_copy_a_block_it_suppressed_a_key_from() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // Block 1: `k`'s newest version, big enough to fill a block on its own and
    // lost below. Block 2: `k`'s older value TOGETHER WITH `m`, so suppression
    // leaves the block non-empty and the emit path still has something to write.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?.use_data_block_size(100);
    writer.write(InternalValue::from_components(
        b"k",
        [b'n'; 200],
        10,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"m",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let first_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert_eq!(
            offsets.len(),
            2,
            "the fixture needs the lost version alone in block 1 and the \
             shadowed one sharing block 2",
        );
        usize::try_from(offsets.first().copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(first_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.dropped.len(), 1, "one block is lost: {report:?}");

    let recovered = open(dest, &fs)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_none(),
        "a verbatim copy would carry the suppressed key'\u{2019}s bytes through \
         untouched, republishing the version its newer one had replaced",
    );
    assert!(
        recovered
            .get(b"m", crate::SeqNo::MAX, crate::hash::hash64(b"m"))?
            .is_some(),
        "the block'\u{2019}s other key is still recovered",
    );
    Ok(())
}

/// A columnar source publishes its recovered blocks through its own branch, so
/// it carries the same no-resurrection obligation: losing the block that held a
/// key's newest version must not let the columnar path re-emit an older one.
#[cfg(feature = "columnar")]
#[test]
fn salvage_drops_a_columnar_boundary_key_when_its_newest_version_is_lost() -> crate::Result<()> {
    use crate::table::Writer;
    use crate::{InternalValue, ValueType};

    let dir = tempfile::tempdir()?;
    let fs: Arc<dyn Fs> = Arc::new(StdFs);
    let source = dir.path().join("source");
    let dest = dir.path().join("dest");

    // One entry per block, so `k`'s newest version (a deletion) is the whole of
    // block 2 and its older value the whole of block 3.
    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?
        .use_columnar(true)
        .use_data_block_size(1);
    writer.write(InternalValue::from_components(
        b"a",
        b"v",
        1,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::new_tombstone(b"k".as_slice(), 10))?;
    writer.write(InternalValue::from_components(
        b"k",
        b"old",
        5,
        ValueType::Value,
    ))?;
    writer.write(InternalValue::from_components(
        b"z",
        b"v",
        1,
        ValueType::Value,
    ))?;
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    let second_off = {
        let table = open(source.clone(), &fs)?;
        let offsets: Vec<u64> = table
            .data_block_handles()
            .filter_map(Result::ok)
            .map(|kh| *kh.as_ref().offset())
            .collect();
        assert!(
            offsets.len() >= 3,
            "the fixture needs one block per entry, got {}",
            offsets.len(),
        );
        usize::try_from(offsets.get(1).copied().unwrap_or_default()).unwrap_or(usize::MAX)
    };
    let mut bytes = std::fs::read(&source)?;
    if let Some(b) = bytes.get_mut(second_off + crate::table::block::Header::MIN_LEN + 1) {
        *b ^= 0xFF;
    }
    std::fs::write(&source, &bytes)?;

    let report = salvage_sst(&source, dest.clone(), &fs)?;
    assert_eq!(report.dropped.len(), 1, "one block is lost: {report:?}");

    let recovered = open(dest, &fs)?;
    assert!(
        recovered
            .get(b"k", crate::SeqNo::MAX, crate::hash::hash64(b"k"))?
            .is_none(),
        "the columnar branch must suppress the boundary key too, or salvage \
         republishes a value the deletion had removed",
    );
    assert!(
        recovered
            .get(b"a", crate::SeqNo::MAX, crate::hash::hash64(b"a"))?
            .is_some(),
        "unaffected keys are still recovered",
    );
    Ok(())
}

/// The narrow shape the multi-entry sibling test does not reach: a table whose
/// ONLY point entry is a real weak tombstone that coincides with the
/// `(seqno, start)`-minimal range tombstone. `item_count == 1` then holds, so
/// the sentinel gate fires and the real entry is excluded, leaving NO decoded
/// seqno to cross-check. A re-stamped `seqno#min` therefore passes unchallenged
/// and `point_read` skips the table at snapshots below the forged minimum,
/// exposing an older value from a lower level.
///
/// One write batch produces this shape: entries in a batch share one seqno, so
/// `remove_weak(k)` beside `remove_range(k..)` lands both at the same seqno with
/// the same start key.
#[test]
fn verify_metadata_bounds_keeps_a_lone_weak_tombstone_matching_the_rt_sentinel() -> crate::Result<()>
{
    use crate::UserKey;
    use crate::range_tombstone::RangeTombstone;

    let dir = tempdir()?;
    let source = dir.path().join("source");
    let fs: Arc<dyn Fs> = Arc::new(StdFs);

    let mut writer = Writer::new(source.clone(), 0, 0, Arc::clone(&fs))?;
    writer.write(InternalValue::new_weak_tombstone(
        UserKey::from(b"key-002".as_slice()),
        3,
    ))?;
    writer.write_range_tombstone(RangeTombstone::new(
        UserKey::from(b"key-002".as_slice()),
        UserKey::from(b"key-005".as_slice()),
        3,
    ));
    assert!(writer.finish()?.is_some(), "source SST is non-empty");

    // An honest one-key table cannot hold this RT: coverage pins the RT inside
    // the key range, and an empty RT is rejected at decode. But `key#max` lives
    // in the SAME meta block as `seqno#min`, so the adversary these checks
    // exist to stop re-stamps both, and the shape becomes reachable.
    crate::test_forge::forge_meta_value_both_mirrors(&source, b"key#max", b"key-005")?;

    // Raise seqno#min above the real entry's seqno: caught only if that entry
    // still counts toward the decoded minimum.
    crate::test_forge::forge_meta_value_both_mirrors(&source, b"seqno#min", &9u64.to_le_bytes())?;

    let table = open(source, &fs)?;
    let err = reconcile_error(&table, crate::table::ReconcileGate::MetadataBounds, None);
    assert!(
        matches!(
            err,
            crate::Error::InvalidHeader("meta seqno#min is above the decoded minimum seqno")
        ),
        "the rejection names the seqno#min branch specifically, got {err:?}",
    );
    Ok(())
}