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
#![expect(
    clippy::expect_used,
    reason = "tests assert on known-present values; a panic is the failure signal"
)]
// Target-conditional: `u64 as usize` on a block offset only narrows on
// 32-bit pointer widths, so clippy does NOT fire on the 64-bit CI host.
// This must stay `allow`, NOT `expect`: an `#[expect]` that never fires (as on
// the 64-bit host) is itself a warning (`unfulfilled_lint_expectations`), so the
// usual `#[expect]`-over-`#[allow]` preference does not apply to a lint that only
// triggers on some targets.
#![allow(
    clippy::cast_possible_truncation,
    reason = "in-file block offsets fit usize; only narrow on 32-bit targets"
)]

use super::*;
use crate::{
    AbstractTree,
    MAX_SEQNO,
    SequenceNumberCounter,
    runtime_config::EccScheme,
    // `BlockIndex` is imported only for its `.iter()` method on
    // `table.block_index` (a trait method); `as _` keeps it in scope for
    // method resolution without binding the unused type name.
    table::{block::Header, block_index::BlockIndex as _},
};

/// Opens an RS(8,2) Page-ECC tree at `dir`.
fn open_ecc_tree(dir: &std::path::Path) -> crate::Tree {
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir,
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .open()
    .expect("open ecc tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    tree
}

/// Writes one ECC SST under `dir` and returns `(sst_path, first_data_block)`.
fn write_ecc_sst(dir: &std::path::Path) -> (std::path::PathBuf, crate::table::BlockHandle) {
    let tree = open_ecc_tree(dir);
    for i in 0u64..2_000 {
        tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
    }
    tree.flush_active_memtable(2_000).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let keyed = table
        .block_index
        .iter()
        .next()
        .expect("table has at least one data block")
        .expect("block index entry decodes");
    let handle = crate::table::BlockHandle::new(keyed.offset(), keyed.size());
    ((*table.path).clone(), handle)
}

/// A SINGLE-data-block ECC SST, so the heal's positioned-read sequence is
/// predictable for fault-injection tests: the up-front correction-prediction
/// pass reads the block twice (scrub + re-read) and the write-back pass reads it
/// twice more, in that order.
fn write_single_block_ecc_sst(
    dir: &std::path::Path,
) -> (std::path::PathBuf, crate::table::BlockHandle) {
    let tree = open_ecc_tree(dir);
    for i in 0u64..4 {
        tree.insert(format!("key-{i:03}"), format!("v{i:03}"), i);
    }
    tree.flush_active_memtable(4).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let keyed = table
        .block_index
        .iter()
        .next()
        .expect("table has at least one data block")
        .expect("block index entry decodes");
    let handle = crate::table::BlockHandle::new(keyed.offset(), keyed.size());
    ((*table.path).clone(), handle)
}

/// As [`write_ecc_sst`], but with per-KV checksum footers
/// (`KvChecksumPolicy::AllLevels`). Footered tables keep the stale-digest
/// reconcile available on a later clean pass (their value bytes re-derive
/// authentication through the per-KV gate), so reconcile tests use this
/// fixture.
fn write_ecc_sst_footered(
    dir: &std::path::Path,
) -> (std::path::PathBuf, crate::table::BlockHandle) {
    let tree = open_ecc_tree(dir);
    tree.update_runtime_config(|c| {
        c.kv_checksums = crate::runtime_config::KvChecksumPolicy::AllLevels;
    })
    .expect("enable kv checksums");
    for i in 0u64..2_000 {
        tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
    }
    tree.flush_active_memtable(2_000).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let keyed = table
        .block_index
        .iter()
        .next()
        .expect("table has at least one data block")
        .expect("block index entry decodes");
    let handle = crate::table::BlockHandle::new(keyed.offset(), keyed.size());
    ((*table.path).clone(), handle)
}

/// As [`write_ecc_sst`], plus a range tombstone so the SST carries the
/// `range_tombstones` section — the deletion metadata the digest
/// reconciliation cannot semantically authenticate.
fn write_ecc_sst_with_range_tombstone(
    dir: &std::path::Path,
) -> (std::path::PathBuf, crate::table::BlockHandle) {
    let tree = open_ecc_tree(dir);
    for i in 0u64..2_000 {
        tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
    }
    tree.remove_range("key-000100", "key-000200", 2_000);
    tree.flush_active_memtable(2_100).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let keyed = table
        .block_index
        .iter()
        .next()
        .expect("table has at least one data block")
        .expect("block index entry decodes");
    let handle = crate::table::BlockHandle::new(keyed.offset(), keyed.size());
    ((*table.path).clone(), handle)
}

#[test]
fn patrol_scrub_corrects_seeded_single_bit_fault_and_schedules_heal() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Flip one payload byte of the first data block (RS-correctable: a single
    // byte error is within the RS(8,2) budget).
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes
        .get_mut(corrupt_pos)
        .expect("corrupt_pos in range for the SST bytes");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // Reopen (fresh caches + fds) and opt into rewrite scheduling.
    let tree = open_ecc_tree(dir.path());
    tree.update_runtime_config(|c| c.auto_heal = true)?;
    assert!(tree.heal_hints().is_empty(), "fresh tree has no hints");

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default());

    assert!(
        report.corrections_applied >= 1,
        "scrub must correct the seeded fault: {report:?}",
    );
    assert_eq!(
        report.ssts_scheduled_for_rewrite, 1,
        "the corrected SST is queued for healing exactly once: {report:?}",
    );
    assert_eq!(report.uncorrectable_blocks, 0, "{report:?}");
    assert!(
        report.is_ok(),
        "a fully-correctable scrub is ok: {report:?}"
    );
    assert!(
        !tree.heal_hints().is_empty(),
        "the SST is recorded in the heal queue",
    );
    #[cfg(feature = "metrics")]
    assert_eq!(
        tree.metrics().ecc_auto_heal_scheduled_count(),
        1,
        "the scheduled SST is counted once in metrics",
    );
    Ok(())
}

#[test]
fn patrol_scrub_corrects_without_scheduling_when_auto_heal_off() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes.get_mut(corrupt_pos).expect("corrupt_pos in range");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // Reopen WITHOUT enabling auto_heal (default off).
    let tree = open_ecc_tree(dir.path());
    assert!(!tree.heal_hints().is_enabled(), "auto_heal defaults off");

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default());

    assert!(
        report.corrections_applied >= 1,
        "correction-on-read still happens with auto_heal off: {report:?}",
    );
    assert_eq!(
        report.ssts_scheduled_for_rewrite, 0,
        "auto_heal off suppresses rewrite scheduling: {report:?}",
    );
    assert!(
        tree.heal_hints().is_empty(),
        "no SST queued when scheduling is off",
    );
    assert!(report.is_ok());
    Ok(())
}

/// The scrub's byte counters measure PHYSICAL file sizes: the metadata's
/// `file_size` is recorded at the end of data-block emission, before the
/// index / filter / meta / footer sections are appended, so totals derived
/// from it systematically underreport the bytes the scrub actually reads.
#[test]
fn patrol_scrub_progress_measures_physical_sizes() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _block) = write_ecc_sst(dir.path());
    let physical = std::fs::metadata(&sst_path)?.len();

    let tree = open_ecc_tree(dir.path());
    let progress = std::sync::Arc::new(crate::RecoveryProgress::default());
    let report = patrol_scrub(
        &tree,
        &PatrolScrubOptions {
            progress: Some(std::sync::Arc::clone(&progress)),
            ..PatrolScrubOptions::default()
        },
    );
    assert!(report.is_ok(), "{report:?}");

    let snap = progress.snapshot();
    assert_eq!(
        snap.bytes_total, physical,
        "the total is the SST's physical size, not the pre-section \
         metadata figure: {snap:?}",
    );
    assert_eq!(
        snap.bytes_processed, snap.bytes_total,
        "a finished scrub reaches 100%: {snap:?}",
    );
    Ok(())
}

/// A scrub-corrected block published to [`crate::RecoveryProgress`] must keep
/// the snapshot invariant `blocks_healed <= blocks_recovered`
/// ([`crate::RecoveryProgressSnapshot::blocks_healed`] documents healed as a
/// subset of recovered): a correction that bumps only the healed counter
/// makes monitoring consumers compute >100% heal ratios.
#[test]
fn patrol_scrub_progress_keeps_healed_within_recovered() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes.get_mut(corrupt_pos).expect("corrupt_pos in range");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    let tree = open_ecc_tree(dir.path());
    let progress = std::sync::Arc::new(crate::RecoveryProgress::default());
    let report = patrol_scrub(
        &tree,
        &PatrolScrubOptions {
            progress: Some(std::sync::Arc::clone(&progress)),
            ..PatrolScrubOptions::default()
        },
    );
    assert!(report.corrections_applied >= 1, "{report:?}");

    let snap = progress.snapshot();
    assert!(
        snap.blocks_healed >= 1,
        "the correction must be published: {snap:?}",
    );
    assert!(
        snap.blocks_healed <= snap.blocks_recovered,
        "healed blocks are a subset of recovered blocks: {snap:?}",
    );
    Ok(())
}

#[test]
fn patrol_scrub_reports_uncorrectable_block_not_silently_skipped() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Wreck the whole payload+parity of the first data block (header left
    // intact so it still parses): far beyond the RS(8,2) correction budget,
    // so the block is uncorrectable.
    let payload_start = block.offset().0 as usize + Header::MIN_LEN;
    let payload_end = block.offset().0 as usize + block.size() as usize;
    let mut bytes = std::fs::read(&sst_path)?;
    for slot in bytes
        .get_mut(payload_start..payload_end)
        .expect("block payload range in bounds")
    {
        *slot ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;

    let tree = open_ecc_tree(dir.path());
    tree.update_runtime_config(|c| c.auto_heal = true)?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default());

    assert!(
        report.uncorrectable_blocks >= 1,
        "an unrecoverable block must be reported, not skipped: {report:?}",
    );
    assert!(!report.is_ok(), "uncorrectable corruption fails the scrub");
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::UncorrectableBlock { .. })),
        "the finding is an UncorrectableBlock: {report:?}",
    );
    Ok(())
}

#[test]
fn patrol_scrub_clean_ecc_tree_reports_no_corrections() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let _ = write_ecc_sst(dir.path());

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default());

    assert_eq!(report.sst_files_scanned, 1);
    assert!(report.blocks_scanned >= 1);
    assert_eq!(report.corrections_applied, 0, "no fault → no correction");
    assert_eq!(report.uncorrectable_blocks, 0);
    assert!(report.is_ok());

    // Sanity: a clean read of a key still returns the right value.
    let got = tree.get(b"key-000000", MAX_SEQNO)?.expect("key present");
    assert_eq!(&*got, b"v000000");
    Ok(())
}

#[test]
fn patrol_scrub_heals_in_place_restoring_the_block_byte_for_byte() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Snapshot the healthy file, then flip one RS-correctable payload byte.
    let original = std::fs::read(&sst_path)?;
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = original.clone();
    let slot = bytes
        .get_mut(corrupt_pos)
        .expect("corrupt_pos in range for the SST bytes");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;
    assert_ne!(bytes, original, "the seeded fault changed the file");

    // Heal in place: persist the correction at the block's offset, no full rewrite.
    let tree = open_ecc_tree(dir.path());
    let opts = PatrolScrubOptions::default().heal_in_place(true);
    let report = patrol_scrub(&tree, &opts);

    assert_eq!(
        report.blocks_healed_in_place, 1,
        "exactly the corrupted block is healed in place: {report:?}",
    );
    assert_eq!(report.corrections_applied, 1, "{report:?}");
    assert_eq!(
        report.ssts_scheduled_for_rewrite, 0,
        "in-place heal schedules no full-file rewrite: {report:?}",
    );
    assert_eq!(report.uncorrectable_blocks, 0, "{report:?}");
    assert!(report.is_ok(), "{report:?}");

    // The heal reconstructs the ORIGINAL frame (RS-recovered data + recomputed
    // parity == as-written bytes), so the file is byte-identical to before the
    // fault: the correction was persisted, and no healthy block was touched.
    let healed = std::fs::read(&sst_path)?;
    assert_eq!(
        healed, original,
        "in-place heal restores the SST byte-for-byte (O(damage), nothing else moved)",
    );

    // A second pass finds nothing to heal — the on-disk bytes now read clean.
    // Drop the first tree first: the directory lock is exclusive, so a second
    // open of the same dir while it is alive would fail with `Locked`.
    drop(tree);
    let tree2 = open_ecc_tree(dir.path());
    let report2 = patrol_scrub(&tree2, &PatrolScrubOptions::default().heal_in_place(true));
    assert_eq!(
        report2.blocks_healed_in_place, 0,
        "nothing left to heal after a clean heal: {report2:?}",
    );
    assert_eq!(report2.corrections_applied, 0, "{report2:?}");
    Ok(())
}

#[test]
fn patrol_scrub_heal_in_place_leaves_an_uncorrectable_block_for_salvage() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Wreck the whole payload+parity (header intact): beyond the RS(8,2) budget.
    let payload_start = block.offset().0 as usize + Header::MIN_LEN;
    let payload_end = block.offset().0 as usize + block.size() as usize;
    let mut bytes = std::fs::read(&sst_path)?;
    for slot in bytes
        .get_mut(payload_start..payload_end)
        .expect("block payload range in bounds")
    {
        *slot ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;
    let corrupted = std::fs::read(&sst_path)?;

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "an uncorrectable block is not healed in place: {report:?}",
    );
    assert!(
        report.uncorrectable_blocks >= 1,
        "the uncorrectable block is reported, not silently skipped: {report:?}",
    );
    assert!(
        !report.is_ok(),
        "uncorrectable corruption fails the heal pass"
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::UncorrectableBlock { .. })),
        "the finding is an UncorrectableBlock: {report:?}",
    );
    // The heal must not have written anything for that block: it is left intact
    // for block salvage (the new-file copy-through path).
    let after = std::fs::read(&sst_path)?;
    assert_eq!(
        after, corrupted,
        "an uncorrectable block is left untouched in place for salvage",
    );
    Ok(())
}

/// A table WITHOUT Page-ECC still has its integrity checked under
/// `heal_in_place`: there is nothing to heal without parity, so it takes the
/// checksum-verifying scrub path, and a corrupt block is reported uncorrectable
/// rather than silently reported clean.
#[test]
fn patrol_scrub_heal_in_place_still_checks_a_non_ecc_table() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // Build a plain (no Page-ECC) SST, then drop the tree so the file can be
    // corrupted and reopened with fresh caches.
    let sst_path;
    let block_off;
    {
        let crate::AnyTree::Standard(tree) = crate::Config::new(
            dir.path(),
            SequenceNumberCounter::default(),
            SequenceNumberCounter::default(),
        )
        .open()
        .expect("open plain tree") else {
            unreachable!("standard tree configured (no kv separation)");
        };
        for i in 0u64..2_000 {
            tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
        }
        tree.flush_active_memtable(2_000).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        let keyed = table
            .block_index
            .iter()
            .next()
            .expect("table has a data block")
            .expect("index entry decodes");
        sst_path = (*table.path).clone();
        block_off = keyed.offset().0 as usize;
    }

    // Flip a payload byte of the first data block (no parity → uncorrectable).
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes
        .get_mut(block_off + Header::MIN_LEN + 3)
        .expect("corrupt position in range");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .open()
    .expect("reopen plain tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "a non-ECC table has nothing to heal in place: {report:?}",
    );
    assert!(
        report.uncorrectable_blocks >= 1,
        "a corrupt block in a non-ECC table is reported, not silently clean: {report:?}",
    );
    assert!(!report.is_ok(), "uncorrectable corruption fails the pass");
    Ok(())
}

/// Bit rot confined to a block's PARITY trailer reads as Clean (the payload
/// checksum passes and parity is only consulted on a payload mismatch), so
/// without an explicit trailer check the heal pass would leave dead ECC on
/// disk — a later payload fault could no longer be recovered. `heal_in_place`
/// must verify each clean block's trailer against freshly computed parity and
/// PERSIST a rebuilt trailer on a mismatch (the pass holds the read+write
/// handle; the payload is untouched, so the rewrite is size-preserving).
#[test]
fn heal_in_place_restores_a_rotted_parity_trailer() -> crate::Result<()> {
    use crate::coding::Decode;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // 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.
    let mut bytes = std::fs::read(&sst_path)?;
    let base = block.offset().0 as usize;
    let Some(mut cursor) = bytes.get(base..) else {
        panic!("first data block within the file");
    };
    let header = Header::decode_from(&mut cursor)?;
    let trailer_pos = base + 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");
    };
    let original = *slot;
    *slot = original ^ 0xFF;
    std::fs::write(&sst_path, &bytes)?;

    // Reopen (fresh caches + fds) and heal in place.
    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));

    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted parity trailer is rebuilt and persisted: {report:?}",
    );
    assert_eq!(report.uncorrectable_blocks, 0, "{report:?}");
    assert!(report.is_ok(), "a parity rebuild is a heal, not a finding");

    // The on-disk byte is restored to its EXACT original value (not merely
    // changed): the rebuilt parity is recomputed over the untouched payload,
    // so anything but the original would be wrong parity persisted.
    let healed = std::fs::read(&sst_path)?;
    let Some(&now) = healed.get(trailer_pos) else {
        panic!("parity trailer within the healed file");
    };
    assert_eq!(now, original, "the original parity byte was restored");
    Ok(())
}

/// Opens an RS(8,2) Page-ECC tree at `dir` through the given filesystem
/// (fault-injection variant of [`open_ecc_tree`]).
fn open_ecc_tree_on(dir: &std::path::Path, fs: std::sync::Arc<dyn crate::fs::Fs>) -> crate::Tree {
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir,
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .with_shared_fs(fs)
    .open()
    .expect("open ecc tree on injected fs") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    tree
}

/// Flips one parity-trailer byte of `block` in the SST at `path`. Payload
/// checksums stay clean, so only the heal pass (which verifies trailers)
/// notices; a heal then rebuilds the trailer in place.
fn corrupt_parity_trailer_byte(
    path: &std::path::Path,
    block: &crate::table::BlockHandle,
) -> crate::Result<()> {
    use crate::coding::Decode;

    let mut bytes = std::fs::read(path)?;
    let base = block.offset().0 as usize;
    let Some(mut cursor) = bytes.get(base..) else {
        panic!("data block within the file");
    };
    let header = Header::decode_from(&mut cursor)?;
    let trailer_pos = base + 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(path, &bytes)?;
    Ok(())
}

/// Rebuilds the manifest by hand, recording the digest of the CURRENT
/// (possibly rotted) bytes of the single table under `tables/`. This seeds the
/// state the reconcile tests need — a manifest digest that matches damaged
/// bytes exactly (as when the damage lands before the digest is first
/// recorded) — which `Config::repair()` deliberately refuses to produce: its
/// block verification drops a table whose data blocks do not verify
/// rather than blessing a laundered digest.
fn rebuild_manifest_over_current_bytes(dir: &std::path::Path) -> crate::Result<()> {
    use crate::version::{Level, Run, Version};
    use std::sync::Arc;

    let fs: Arc<dyn crate::fs::Fs> = Arc::new(crate::fs::StdFs);
    let sst_path = dir.join("tables").join("0");
    let checksum =
        crate::Checksum::from_raw(crate::repair::compute_table_checksum(&*fs, &sst_path)?);
    #[cfg(feature = "metrics")]
    let metrics = Arc::new(crate::Metrics::default());
    let table = {
        #[cfg_attr(not(feature = "metrics"), expect(unused_mut))]
        let mut params = crate::table::RecoverParams::new(
            sst_path,
            checksum,
            0,
            Arc::clone(&fs),
            crate::comparator::default_comparator(),
            Arc::new(crate::Cache::with_capacity_bytes(1_000_000)),
        );
        #[cfg(feature = "metrics")]
        {
            params.metrics = metrics;
        }
        crate::table::Table::recover(params)?
    };

    // Remove the prior snapshots so the hand-built one is the newest.
    let mut next_version_id = 0u64;
    for entry in fs.read_dir(dir)? {
        if let Some(rest) = entry.file_name.strip_prefix('v')
            && let Ok(n) = rest.parse::<u64>()
        {
            next_version_id = next_version_id.max(n + 1);
        }
    }

    let run = Run::new(alloc::vec![table]).expect("a non-empty run");
    let mut levels = alloc::vec![Level::from_runs(alloc::vec![Arc::new(run)])];
    for _ in 1..7 {
        levels.push(Level::empty());
    }
    let version = Version::from_levels(
        next_version_id,
        crate::config::TreeType::Standard,
        levels,
        crate::version::BlobFileList::new(crate::HashMap::default()),
        crate::blob_tree::FragmentationMap::default(),
    );
    crate::version::persist_version(
        dir,
        &version,
        crate::comparator::default_comparator().name(),
        &*fs,
        Arc::new(crate::runtime_config::types::RuntimeConfig::default()),
        None,
        crate::fs::SyncMode::Full,
    )?;
    Ok(())
}

/// Opens a FaultFs-backed ECC tree at `dir` with a ONE-SHOT `Open` fault
/// armed on the manifest edit log ("edits"), so the first digest refresh
/// fails while the heal itself (which only touches the SST under tables/)
/// proceeds. Returns the tree and the injector for the caller to `clear()`.
fn open_ecc_tree_with_failing_edit_log(
    dir: &std::path::Path,
) -> (crate::Tree, std::sync::Arc<crate::fs::FaultInjector>) {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir, std::sync::Arc::new(fault));
    injector.arm(
        FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Other))
            .on_path("edits")
            .once(),
    );
    (tree, injector)
}

/// A failed raw re-read during the clean-block parity-trailer check is a
/// finding, not a silent skip: the block's trailer could not be verified, so
/// the heal pass reports it as uncorrectable and moves on (the remaining
/// blocks still get their trailers checked).
#[test]
fn heal_in_place_reports_a_failed_parity_reread_as_uncorrectable() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (_sst_path, _block) = write_single_block_ecc_sst(dir.path());

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The single block is read twice in the up-front correction-prediction pass
    // (scrub, then the raw frame re-read for the parity-trailer comparison) and
    // twice again in the write-back pass. Skip the two prediction reads and the
    // write-back scrub, then fail exactly the write-back parity re-read.
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(3)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.uncorrectable_blocks, 1,
        "the unverifiable trailer is a finding: {report:?}",
    );
    assert!(
        format!("{report:?}").contains("parity re-read failed"),
        "the finding names the failed re-read: {report:?}",
    );
    assert_eq!(
        report.blocks_healed_in_place, 0,
        "nothing was persisted for the failed block: {report:?}",
    );
    Ok(())
}

/// A parity-trailer rebuild whose WRITE fails is a finding: the rot stays on
/// disk, so the heal must report the block as uncorrectable instead of
/// counting a heal that never landed.
#[test]
fn heal_in_place_reports_a_failed_trailer_writeback_as_uncorrectable() -> crate::Result<()> {
    use crate::coding::Decode;
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte of the first data block (payload checksum
    // still verifies, so the block scrubs Clean and the trailer check fires).
    let mut bytes = std::fs::read(&sst_path)?;
    let base = block.offset().0 as usize;
    let Some(mut cursor) = bytes.get(base..) else {
        panic!("first data block within the file");
    };
    let header = Header::decode_from(&mut cursor)?;
    let trailer_pos = base + 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");
    };
    let rotted = *slot ^ 0xFF;
    *slot = rotted;
    std::fs::write(&sst_path, &bytes)?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The rot leaves the file differing from the (un-rebuilt) manifest, so this is
    // the restorative heal path: the FIRST write to `tables/` is the crash-recovery
    // marker sidecar, the SECOND is the trailer rebuild. Let the marker land, then
    // fail the trailer write-back.
    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(1)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "a write-back that failed is not counted as a heal: {report:?}",
    );
    assert_eq!(report.uncorrectable_blocks, 1, "{report:?}");
    assert!(
        format!("{report:?}").contains("in-place parity rebuild"),
        "the finding names the failed rebuild: {report:?}",
    );

    // The rot is still on disk (nothing was silently half-written).
    let after = std::fs::read(&sst_path)?;
    assert_eq!(
        after.get(trailer_pos).copied(),
        Some(rotted),
        "the rotted trailer byte is untouched after the failed write-back",
    );
    Ok(())
}

/// A write-back that FAILS must KEEP the in-progress marker, even though zero
/// blocks were counted as healed. `write_all` reports no byte count on error, so
/// a failure may have PARTIALLY written the block (or a full write's later sync
/// failed while the bytes still reach storage): the file may already differ from
/// the manifest digest, and dropping the marker would strand it with no
/// attribution for a later refresh. Removal is reserved for the no-mutation case
/// (a block that was never written — see the sibling uncorrectable test).
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_keeps_the_marker_when_a_write_back_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    // Rot a parity trailer (payload checksum still verifies, so the block scrubs
    // Clean and the trailer-rebuild heal fires) and rebuild the manifest over
    // the rotted bytes, so the pre-heal digest matches and the marker is written.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The FIRST write to `tables/` is the marker sidecar; the SECOND is the
    // trailer rebuild. Skip the marker write so the marker lands, then fail the
    // trailer write so zero blocks heal but a write WAS attempted.
    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(1)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "a failed write-back heals no block: {report:?}",
    );
    assert!(
        report.uncorrectable_blocks >= 1
            && format!("{report:?}").contains("in-place parity rebuild"),
        "the failed trailer write-back must be recorded, proving the write was \
         attempted: {report:?}",
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the marker must be KEPT after a failed write-back — the file may already be \
         partially modified, so a later patrol still needs the attribution",
    );
    Ok(())
}

/// The RESTORATIVE heal path (the current bytes already differ from the manifest
/// digest, but healing restores exactly what the manifest describes) must ALSO
/// persist its `.heal-attest` marker BEFORE the first write-back. Otherwise a
/// crash after syncing some of several corrections leaves the file matching
/// neither the manifest nor the healed digest, and with no marker a checkpoint
/// hard-links those intermediate bytes under the stale manifest digest, producing
/// a permanently inconsistent checkpoint. Rot a parity trailer but leave the
/// manifest holding the ORIGINAL digest (so the heal is restorative, not
/// attributable), fault the write-back after the marker lands, and assert the
/// marker persists (#78).
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_keeps_the_marker_when_a_restorative_write_back_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    // Rot a parity trailer but DO NOT rebuild the manifest: the current bytes now
    // differ from the manifest digest (pre-heal does NOT match), yet rebuilding the
    // trailer restores exactly the original bytes the manifest still describes
    // (predicted == manifest): the restorative path.
    corrupt_parity_trailer_byte(&sst_path, &block)?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The FIRST write to `tables/` is the marker sidecar; the SECOND is the trailer
    // rebuild. Let the marker land, then fail the write-back so the file may be
    // partially modified with the marker still present.
    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(1)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "a failed write-back heals no block: {report:?}",
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the restorative heal must persist its marker BEFORE the first write-back, so a \
         crash cannot expose unattested intermediate bytes to a checkpoint hard-link",
    );
    Ok(())
}

/// The marker IS removed when no write was ever attempted: every candidate block
/// is uncorrectable, so the file is untouched and the marker attests to a heal
/// that never happened. Removing it prevents its unexpiring `pre == manifest`
/// binding from later authorizing an unrelated digest mismatch.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_removes_the_marker_when_no_write_is_attempted() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    // Wreck the ENTIRE first data block (payload + parity trailer) BEYOND RS
    // recovery so it scrubs uncorrectable and the heal reaches no write-back at
    // all, then rebuild the manifest so the pre-heal digest matches and the
    // marker is written up front.
    let start = block.offset().0 as usize + Header::MIN_LEN;
    let end = block.offset().0 as usize + block.size() as usize;
    let mut bytes = std::fs::read(&sst_path)?;
    for off in start..end {
        if let Some(b) = bytes.get_mut(off) {
            *b ^= 0xFF;
        }
    }
    std::fs::write(&sst_path, &bytes)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "an uncorrectable block heals nothing: {report:?}",
    );
    assert!(
        report.uncorrectable_blocks >= 1,
        "the uncorrectable block is recorded: {report:?}",
    );
    assert!(
        !heal_attest_path(&sst_path).exists(),
        "the marker must be removed when no write was attempted, so it cannot authorize a \
         later unrelated mismatch",
    );
    Ok(())
}

/// A heal that lands its block but then hits a TRANSIENT read error during the
/// out-of-band reconcile walk must KEEP the heal attestation. The block was
/// genuinely healed and the marker is its only durable attribution; deleting it
/// on an inconclusive (retryable) failure would strand the healed SST under the
/// stale manifest digest, and every later clean patrol would then reject the
/// reconcile forever. The marker is dropped only on PROVEN corruption.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_keeps_the_marker_when_the_reconcile_walk_read_fails_transiently()
-> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;

    // A SINGLE-data-block ECC SST: the heal scan then does exactly two SST reads
    // (the block scrub, then the persist-side re-read), so the NEXT read is the
    // reconcile walk — the read this test faults.
    let (sst_path, block) = {
        let tree = open_ecc_tree(dir.path());
        for i in 0u64..4 {
            tree.insert(format!("key-{i:03}"), format!("v{i:03}"), i);
        }
        tree.flush_active_memtable(4).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        let keyed = table
            .block_index
            .iter()
            .next()
            .expect("table has at least one data block")
            .expect("block index entry decodes");
        (
            (*table.path).clone(),
            crate::table::BlockHandle::new(keyed.offset(), keyed.size()),
        )
    };

    // Rot the parity trailer (the payload stays checksum-clean, so the block
    // scrubs Clean and the trailer-rebuild heal fires) and rebuild the manifest
    // over the rotted bytes so the pre-heal digest matches and the marker lands.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The heal reads the block twice in the up-front correction-prediction pass
    // (scrub + parity re-read) and twice more in the write-back pass, so the
    // block's trailer rebuild lands after 4 positioned reads; every read after
    // that belongs to the reconcile walk / semantic checks (the digest passes
    // stream sequentially, not via ReadAt). Fail them all so the reconcile hits
    // a transient read error, which must NOT delete the just-written
    // attestation.
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(4),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 1,
        "the trailer rebuild must land before the walk fault: {report:?}",
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "the transient walk read must refuse the digest refresh: {report:?}",
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "a transient walk failure must KEEP the marker for retry, not strand the \
         healed SST under the stale manifest digest",
    );
    Ok(())
}

/// A TRANSIENT read during the up-front correction-PREDICTION pass must
/// PROPAGATE, not be folded into "no correction". Swallowing it would drop the
/// block from the predicted offset set, so the write pass — gated on that set —
/// would skip a correction it re-discovers on the healable block and report a
/// clean pass with the fault still on disk. Fault ONLY the first positioned read
/// (the prediction pass's initial block scrub); the write-pass reads then
/// succeed, so the pre-fix `Err(_) => Ok(None)` silently skips the heal while the
/// fixed code surfaces the transient read.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_propagates_a_transient_read_during_correction_prediction() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;

    // A single-data-block ECC SST whose parity trailer is rotted (payload stays
    // checksum-clean, so the block would heal via a trailer rebuild).
    let (sst_path, block) = {
        let tree = open_ecc_tree(dir.path());
        for i in 0u64..4 {
            tree.insert(format!("key-{i:03}"), format!("v{i:03}"), i);
        }
        tree.flush_active_memtable(4).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        let keyed = table
            .block_index
            .iter()
            .next()
            .expect("table has at least one data block")
            .expect("block index entry decodes");
        (
            (*table.path).clone(),
            crate::table::BlockHandle::new(keyed.offset(), keyed.size()),
        )
    };
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // Fault the FIRST positioned read — the prediction pass's initial block
    // scrub — and let every later read succeed, so the write pass would find the
    // block healable but never see its offset in the predicted set.
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    // The transient prediction read must SURFACE (an error / inconclusive pass),
    // not vanish into a clean report that leaves the fault on disk.
    assert!(
        !report.is_ok(),
        "a transient prediction read must surface as an error, not report a clean pass \
         over the un-healed fault: {report:?}",
    );
    Ok(())
}

/// The reconcile must ABORT if it cannot persist the crash-recovery attestation:
/// installing the refreshed digest while that marker's write failed would leave
/// the healed bytes with no on-disk marker for a crash mid-install, and a later
/// patrol would then refuse to attribute the mismatch. Fault the reconcile's
/// attestation write (the SECOND sidecar write; the up-front one during the heal
/// succeeds) and assert the refresh is refused with the marker kept for retry.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_refuses_the_refresh_when_the_reconcile_attestation_write_fails()
-> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;

    let (sst_path, block) = {
        let tree = open_ecc_tree(dir.path());
        for i in 0u64..4 {
            tree.insert(format!("key-{i:03}"), format!("v{i:03}"), i);
        }
        tree.flush_active_memtable(4).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        let keyed = table
            .block_index
            .iter()
            .next()
            .expect("table has at least one data block")
            .expect("block index entry decodes");
        (
            (*table.path).clone(),
            crate::table::BlockHandle::new(keyed.offset(), keyed.size()),
        )
    };

    // Attributable trailer-rebuild heal (payload stays checksum-clean).
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The heal writes the completed marker UP FRONT (first sidecar write); the
    // reconcile re-writes it before installing (second sidecar write). Skip the
    // first and fail the second so only the reconcile's attestation write fails.
    injector.arm(
        FaultRule::new(FaultOp::Write, Fault::Error(ErrorKind::Other))
            .on_path(".heal-attest")
            .skip(1)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 1,
        "the trailer rebuild lands before the reconcile: {report:?}",
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a failed reconcile attestation write must refuse the digest refresh, not \
         install it without a durable marker: {report:?}",
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the marker is kept for the next patrol to retry the reconcile",
    );
    Ok(())
}

/// A tight-space RESTRICTED table's heal walk must SKIP the punched-out prefix:
/// a block whose last key is below the restriction bound was reclaimed by a
/// superseding output table, so reading its frame reports a spurious
/// uncorrectable error that would suppress the digest refresh for a real
/// correction in the live suffix. The walk must start at the bound.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_skips_blocks_below_the_restriction_bound() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, first_block) = write_ecc_sst(dir.path());

    // Wreck the FIRST data block's payload beyond RS recovery (uncorrectable):
    // it holds the lowest keys, so a bound above them puts it in the prefix.
    let start = first_block.offset().0 as usize + Header::MIN_LEN;
    let mut bytes = std::fs::read(&sst_path)?;
    for off in start..start + 256 {
        if let Some(b) = bytes.get_mut(off) {
            *b ^= 0xFF;
        }
    }
    std::fs::write(&sst_path, &bytes)?;

    // Re-open the table restricted to a bound well above the first block's keys,
    // so the wrecked block sits in the (punched) prefix the walk must skip.
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));
    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let restricted = table.reopen_restricted(crate::UserKey::from(b"key-001000".as_slice()))?;

    let (report, _healed) =
        restricted.heal_data_blocks_in_place(crate::fs::SyncMode::Full, restricted.checksum());
    assert!(
        report.errors.is_empty()
            && report.uncorrectable_blocks == 0
            && report.blocks_healed_in_place == 0,
        "the wrecked block below the restriction bound must be skipped entirely, \
         neither healed nor reported: {report:?}",
    );
    Ok(())
}

/// EVERY table the tree makes reachable must carry the heal-hint sink,
/// whichever path published it. A table that skips it looks perfectly healthy
/// and fails silently much later: a confirmed-persistent ECC correction can
/// never queue it for a healing rewrite, so the bitrot stays on disk and every
/// read pays the correction again.
///
/// Publication happens from several places — flush, compaction, and bulk
/// ingest, which builds and installs its tables itself — and each one binding
/// the sinks by hand is what let two of them drift. This walks the live
/// version after exercising all three, so a future path that forgets is
/// caught here rather than in a support ticket.
#[cfg(feature = "page_ecc")]
#[test]
fn every_published_table_carries_the_heal_hint_sink() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempfile::tempdir()?;
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));

    // Flush, then compaction over two flushed tables.
    for round in 0..2u64 {
        for i in 0..32u64 {
            tree.insert(
                format!("key-{i:06}").as_bytes(),
                format!("v{round}").as_bytes(),
                round * 100 + i,
            );
        }
        tree.flush_active_memtable(0)?;
    }
    tree.major_compact(u64::MAX, 1_000)?;

    // Bulk ingest, which publishes its tables without going through the
    // flush path's registration.
    let mut ingestion = crate::tree::ingest::Ingestion::new(&tree)?;
    for i in 0..16u64 {
        ingestion.write(
            format!("ingested-{i:06}").as_bytes().into(),
            format!("i{i}").as_bytes().into(),
        )?;
    }
    ingestion.finish()?;

    let live: Vec<_> = {
        let binding = tree.version_history.read().latest_version();
        binding.version.iter_tables().cloned().collect()
    };
    assert!(
        live.len() >= 2,
        "flush, compaction and ingest all published"
    );
    for table in &live {
        assert!(
            table
                .heal_hints_for_test()
                .is_some_and(|sink| std::sync::Arc::ptr_eq(&sink, &tree.heal_hints)),
            "live table {} carries no heal-hint sink: a correctable fault in \
             it could never schedule a durable heal",
            table.id(),
        );
    }
    Ok(())
}

/// Compaction installs its outputs directly instead of going through
/// `register_tables`, so it must install the same tree-wide sinks a flush
/// gets — the heal-hint sink included. Without it a confirmed-persistent ECC
/// correction while reading a compaction output corrects the block in memory
/// but can never queue that SST for a healing rewrite, so the bitrot stays on
/// disk indefinitely (and every later read pays the correction again).
#[cfg(feature = "page_ecc")]
#[test]
fn a_compaction_output_carries_the_heal_hint_sink() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempfile::tempdir()?;
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));

    // Two flushes, then a compaction that merges them into a fresh output.
    for round in 0..2u64 {
        for i in 0..64u64 {
            tree.insert(
                format!("key-{i:06}").as_bytes(),
                format!("v{round}").as_bytes(),
                round * 100 + i,
            );
        }
        tree.flush_active_memtable(0)?;
    }
    tree.major_compact(u64::MAX, 1_000)?;

    let outputs: Vec<_> = {
        let binding = tree.version_history.read().latest_version();
        binding.version.iter_tables().cloned().collect()
    };
    assert!(!outputs.is_empty(), "the compaction produced an output");
    for table in &outputs {
        assert!(
            table
                .heal_hints_for_test()
                .is_some_and(|sink| { std::sync::Arc::ptr_eq(&sink, &tree.heal_hints) }),
            "compaction output {} must carry the tree's heal-hint sink, or a \
             correctable read from it can never schedule a durable heal",
            table.id(),
        );
    }
    Ok(())
}

/// A tight-space restricted reopen produces a DISTINCT `Inner`, so every
/// tree-installed shared gate must be carried forward — including the ECC
/// heal-hint sink. Without it, a correctable read from the restricted view
/// can no longer queue the table for a healing recompaction: persistent
/// bitrot keeps being corrected in memory on every read but is never
/// scheduled for a durable rewrite.
#[cfg(feature = "page_ecc")]
#[test]
fn restricted_reopen_carries_the_heal_hint_sink_forward() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (_sst_path, _block) = write_ecc_sst(dir.path());

    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));
    let table = {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table")
            .clone()
    };
    // The sink the owning tree installed (install one if the config left the
    // slot empty — the transfer contract is the same either way).
    table.install_heal_hints(crate::heal_hints::HealHints::new_shared(true));
    let installed = table.heal_hints_for_test().expect("the sink is installed");

    let restricted = table.reopen_restricted(crate::UserKey::from(b"key-001000".as_slice()))?;
    let carried = restricted.heal_hints_for_test();
    assert!(
        carried.is_some_and(|c| std::sync::Arc::ptr_eq(&c, &installed)),
        "the restricted reopen must carry the SAME heal-hint sink forward, or \
         correctable reads from the restricted view stop queueing the table \
         for a durable healing recompaction",
    );
    Ok(())
}

/// A heal whose manifest-digest refresh loses the compaction-state `try_lock`
/// (a concurrent compaction is mid-install; blocking would invert the
/// heal-lock / compaction-state order and deadlock) must NOT report a clean
/// pass: the healed bytes are durable but the manifest digest stays stale and
/// the attestation stays pending, so a later integrity check flags the mismatch
/// and a checkpoint can abort despite the "clean" scrub. The contention must
/// surface as a `ChecksumRefreshFailed` finding; the marker is kept for the
/// next patrol to reconcile.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_reports_a_contended_checksum_refresh_as_a_finding() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_single_block_ecc_sst(dir.path());

    // Attributable trailer-rebuild heal (payload stays checksum-clean): the
    // manifest digest covers the CURRENT (rotted) bytes, so the heal changes
    // them and the reconcile must install a refreshed digest.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));
    // Hold the compaction state across the scrub, as a long-running concurrent
    // compaction would: the reconcile's `try_lock` then loses.
    let _compaction_guard = tree.compaction_state.lock();

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert_eq!(
        report.blocks_healed_in_place, 1,
        "the heal itself lands; only the digest install is contended: {report:?}",
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "install-lock contention must surface as a finding, not a clean pass: {report:?}",
    );
    assert!(!report.is_ok(), "{report:?}");
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the marker is kept for the next patrol to reconcile",
    );
    Ok(())
}

/// A patrol whose CAPTURED table view went stale — tight-space compaction
/// installed a RESTRICTED same-id view (whose manifest digest covers only the
/// live suffix) after the capture — must scan the CURRENT view, not the captured
/// one. Scanning the captured whole-file view against the current suffix
/// checksum makes the pre-heal digest probe fail unconditionally, so the
/// divergent-heal guard returns a default CLEAN report before the block walk:
/// the patrol claims `is_ok()` with zero blocks healed while the known
/// correctable fault stays on disk.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_scans_the_current_view_when_the_captured_one_went_stale() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _first_block) = write_ecc_sst(dir.path());

    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(crate::fs::StdFs));
    // Capture the UNRESTRICTED view, as a patrol does before its scan.
    let captured = {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table")
            .clone()
    };

    // A tight-space slice installs a RESTRICTED same-id view after the capture;
    // `with_tight_slice` is the worker's install transform. The restricted
    // view's manifest digest covers only the live suffix.
    let restricted = captured.reopen_restricted(crate::UserKey::from(b"key-001000".as_slice()))?;
    tree.version_history.write().upgrade_version(
        &tree.config.path,
        |current| {
            let mut copy = current.clone();
            let ctx = crate::version::TransformContext::new(tree.config.comparator.as_ref());
            copy.version = copy.version.with_tight_slice(
                &[(captured.id(), restricted.clone())],
                &[],
                &[],
                vec![],
                None,
                0,
                &ctx,
            );
            Ok(copy)
        },
        &tree.config.seqno,
        &tree.config.visible_seqno,
        &*tree.config.fs,
        tree.runtime_config.load_full(),
        tree.config.encryption.clone(),
    )?;

    // Rot one payload byte (RS-correctable) in the LAST data block — well above
    // the restriction bound, squarely inside the live suffix the current view
    // serves. The rot lands AFTER the restricted digest was captured, so the
    // heal is plainly restorative for the current view.
    let last_block = {
        let mut last = None;
        for handle in restricted.block_index.iter() {
            let handle = handle?;
            last = Some(crate::table::BlockHandle::new(
                handle.offset(),
                handle.size(),
            ));
        }
        last.expect("table has data blocks")
    };
    let corrupt_pos = last_block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let Some(slot) = bytes.get_mut(corrupt_pos) else {
        panic!("corrupt_pos in range for the SST bytes");
    };
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // Scan through the STALE captured view. The restriction mismatch must make
    // the scan target the CURRENT view; a scan of the captured one would trip
    // the divergent-heal guard and report clean with the fault untouched.
    let report = super::scan_and_reconcile(
        &tree,
        &captured,
        &PatrolScrubOptions::default().heal_in_place(true),
    );
    assert!(
        report.blocks_healed_in_place >= 1,
        "the known correctable fault must be healed through the current view, \
         not silently skipped by the divergent-heal guard: {report:?}",
    );
    assert!(report.is_ok(), "{report:?}");
    Ok(())
}

/// A corrected block whose heal RE-READ fails (transient I/O on the second,
/// persist-side read) is a finding: the correction cannot be written back, so
/// the block is reported uncorrectable rather than silently skipped.
#[test]
fn heal_in_place_reports_a_failed_heal_reread_as_uncorrectable() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_single_block_ecc_sst(dir.path());

    // Flip one payload byte of the block (RS-correctable).
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let Some(slot) = bytes.get_mut(corrupt_pos) else {
        panic!("corrupt_pos in range for the SST bytes");
    };
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // The corrupted first block is read twice in the up-front correction-
    // prediction pass (scrub + `heal_frame` re-read) and twice in the write-back
    // pass. Skip the two prediction reads and the write-back scrub, then fail the
    // write-back `heal_frame` re-read.
    injector.arm(
        FaultRule::new(FaultOp::ReadAt, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .skip(3)
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "nothing was persisted for the failed block: {report:?}",
    );
    assert_eq!(report.uncorrectable_blocks, 1, "{report:?}");
    assert!(
        format!("{report:?}").contains("heal re-read failed"),
        "the finding names the failed heal re-read: {report:?}",
    );
    Ok(())
}

/// An in-place heal must not mutate an inode a checkpoint hard-links: the
/// checkpoint's manifest recorded the digest of the bytes AT SNAPSHOT TIME,
/// and rewriting the shared inode underneath it permanently desynchronizes
/// the snapshot from its own manifest (only the LIVE tree's digest is
/// reconciled). The heal must instead break the link (heal a private copy of
/// the live file), leaving the checkpoint's inode byte-identical to what its
/// manifest describes.
#[test]
fn heal_in_place_does_not_mutate_a_hard_linked_checkpoint_inode() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one payload byte (RS-correctable) BEFORE the snapshot: the
    // checkpoint captures the rotted bytes, exactly what its manifest
    // would describe.
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes.get_mut(corrupt_pos).expect("corrupt_pos in range");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // Checkpoint-style hard link to the (rotted) SST. A separate directory
    // outside the tree keeps recovery from treating it as an orphan.
    let cp_dir = tempfile::tempdir_in(dir.path().parent().expect("tempdir has a parent"))?;
    let link_path = cp_dir.path().join("checkpoint.sst");
    std::fs::hard_link(&sst_path, &link_path)?;
    let snapshot = std::fs::read(&link_path)?;

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the live file's fault is healed: {report:?}",
    );
    assert!(report.is_ok(), "{report:?}");

    // The LIVE path carries the healed bytes...
    let live = std::fs::read(&sst_path)?;
    assert_ne!(
        live, snapshot,
        "the live path must expose the healed bytes after the scrub",
    );
    // ...while the checkpoint's inode still holds exactly the snapshot the
    // checkpoint manifest describes.
    let checkpoint = std::fs::read(&link_path)?;
    assert_eq!(
        checkpoint, snapshot,
        "the checkpoint's hard-linked inode must keep its snapshot bytes: \
         healing through a shared inode desynchronizes the checkpoint from \
         its own manifest digest",
    );
    Ok(())
}

/// After an unshare detaches the live path onto a new inode, the table's
/// descriptor cache may still hold the OLD inode's fd: a later heal on the
/// same open tree would then SCRUB the stale inode (clean) while its
/// re-read and write-back use the live file — a recoverable fault on the
/// live copy reads as an unexplained checksum mismatch and is reported
/// uncorrectable without ever attempting ECC recovery. The unshare must
/// invalidate the cached descriptor.
#[test]
fn heal_in_place_rebinds_the_descriptor_cache_after_an_unshare() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte so the FIRST heal actually WRITES (the
    // unshare runs lazily, only before the first write-back), then
    // hard-link the SST so that write takes the unshare path.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    let cp_dir = tempfile::tempdir_in(dir.path().parent().expect("tempdir has a parent"))?;
    std::fs::hard_link(&sst_path, cp_dir.path().join("checkpoint.sst"))?;

    let tree = open_ecc_tree(dir.path());

    // Prime the descriptor cache with the ORIGINAL inode, then heal (the
    // unshare renames a private copy over the live path).
    assert!(tree.get("key-000000", crate::SeqNo::MAX)?.is_some());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(report.is_ok(), "the trailer rebuild succeeds: {report:?}");
    assert!(
        report.blocks_healed_in_place >= 1,
        "the first pass must write, so the unshare runs: {report:?}",
    );

    // A recoverable payload fault lands on the LIVE (post-rename) inode.
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes
        .get_mut(corrupt_pos)
        .expect("corrupt_pos in range for the SST bytes");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // SECOND heal on the SAME open tree: the scrub must see the live inode's
    // fault as ECC-recoverable, not scrub a stale cached fd clean and then
    // report the live mismatch as uncorrectable.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the live fault is ECC-recovered and healed in place: {report:?}",
    );
    assert!(report.is_ok(), "{report:?}");
    Ok(())
}

/// The descriptor invalidation must happen as soon as the publish RENAME
/// succeeds — even when the post-rename directory sync fails: the live path
/// already points at the new inode, so bailing out before the invalidation
/// leaves the cache pinned to the old checkpoint-linked inode, and a later
/// heal (which sees one link on the new inode and does not unshare again)
/// scrubs the stale inode while the live file rots.
#[test]
fn heal_in_place_rebinds_the_descriptor_cache_when_the_directory_sync_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte (the unshare only runs before the first
    // write-back), then hard-link the SST so the FIRST heal takes the
    // unshare path.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    let cp_dir = tempfile::tempdir_in(dir.path().parent().expect("tempdir has a parent"))?;
    std::fs::hard_link(&sst_path, cp_dir.path().join("checkpoint.sst"))?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));

    // Prime the descriptor cache with the ORIGINAL inode, then heal with the
    // post-rename directory sync failing: the unshare errors out AFTER the
    // rename has already replaced the live path.
    assert!(tree.get("key-000000", crate::SeqNo::MAX)?.is_some());
    injector.arm(
        FaultRule::new(FaultOp::SyncDirectory, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(
        !report.is_ok(),
        "the failed unshare is a finding: {report:?}"
    );

    // A recoverable payload fault lands on the LIVE (post-rename) inode.
    let corrupt_pos = block.offset().0 as usize + Header::MIN_LEN + 3;
    let mut bytes = std::fs::read(&sst_path)?;
    let slot = bytes
        .get_mut(corrupt_pos)
        .expect("corrupt_pos in range for the SST bytes");
    *slot ^= 0x80;
    std::fs::write(&sst_path, &bytes)?;

    // SECOND heal on the SAME open tree: the scrub must see the live
    // inode's fault as ECC-recoverable, not scrub the stale cached fd.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the live fault is ECC-recovered and healed in place: {report:?}",
    );
    assert!(report.is_ok(), "{report:?}");
    Ok(())
}

/// The digest reconciliation must not restamp over a RENAMED section: a
/// TOC whose `filter` entry was re-labelled to an unknown name (trailer
/// checksum re-stamped) hides the section from every reader while each
/// block inside still passes its byte-level checks — an unknown
/// block-format section must FAIL the walk closed, or the restamp would
/// legitimize an archive whose known sections silently vanished.
#[test]
fn heal_in_place_does_not_restamp_over_a_renamed_section() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    // Open FIRST (lazy filters, so the missing `filter` section is not
    // touched by the scan), then rename the section in the TOC.
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .filter_block_pinning_policy(crate::config::PinningPolicy::new([false]))
    .open()
    .expect("open ecc tree with lazy filters") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    crate::test_forge::forge_section_name(&sst_path, b"filter", b"filtex")?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "an unknown section name must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the renamed-section SST must keep failing verify_integrity: \
         restamping its digest would legitimize the vanished section",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over DIVERGED metadata
/// mirrors: a tail `meta` block whose payload was re-stamped to another
/// internally-consistent value (a changed `compression#data`, ECC descriptor
/// untouched) passes every byte-level check, and the in-memory table keeps
/// serving reads from its previously loaded metadata — so only a FULL
/// comparison of the decoded mirrors can catch it. Restamping would make
/// `verify_integrity` accept a file whose next recovery prefers the altered
/// tail and misreads every data block.
#[test]
fn heal_in_place_does_not_restamp_over_diverged_meta_mirrors() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    // Open FIRST: the live tree keeps serving reads from its previously
    // loaded metadata, so the forge below is invisible to the data/KV scan.
    let tree = open_ecc_tree(dir.path());

    // Re-stamp the TAIL meta's data-block compression from the written
    // None (tag 0, the default L0 policy) to Lz4 (tag 1) — same value
    // length, fresh block checksum and parity, `meta_mid` untouched. Only
    // the NEXT recovery would prefer the altered tail and misread every
    // data block.
    crate::test_forge::forge_tail_meta_value(&sst_path, b"compression#data", &[1])?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "diverged meta mirrors must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would mask a forge only the mirror comparison detects",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `zone_map`: a
/// payload re-stamped to another structurally valid map (a changed max
/// value, fresh block checksum + parity) passes every byte-level and framing
/// check, yet a predicate scan trusts its min/max to SKIP blocks — a shrunk
/// range silently omits matching rows. Only a cross-check against the blocks'
/// decoded key ranges can catch it before the refresh legitimizes the forge.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_zone_map() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;

    // An ECC tree WITH the zone_map section (off by default).
    let sst_path = {
        let tree = open_ecc_tree(dir.path());
        tree.update_runtime_config(|c| c.zone_map = true)?;
        for i in 0u64..2_000 {
            tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
        }
        tree.flush_active_memtable(2_000).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        (*table.path).clone()
    };

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_flip_section_last_payload_byte(&sst_path, b"zone_map", Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged zone_map must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let predicate scans silently skip matching blocks",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over ALTERED deletion
/// metadata: a `range_tombstones` payload changed to another value (fresh
/// block checksum + parity) passes every byte-level, framing, and role
/// check, and NO semantic gate can authenticate which ranges were genuinely
/// deleted — the tombstones ARE the source of truth, there is nothing
/// in-file to cross-check them against. Refreshing the digest would
/// permanently legitimize the alteration: later reads either resurrect
/// deleted data or hide previously live data. The refresh must fail closed
/// unless the mismatch is provably attributable to this pass's own heal
/// writes.
#[test]
fn heal_in_place_does_not_restamp_over_altered_range_tombstones() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_with_range_tombstone(dir.path());

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_flip_section_last_payload_byte(
        &sst_path,
        b"range_tombstones",
        Some((8, 2)),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "altered range tombstones must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the alteration stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the altered SST must keep failing verify_integrity: restamping its \
         digest would let reads resurrect deleted data or hide live data",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED VALUE in a
/// footer-less (default) table: a value byte changed behind a re-stamped
/// block checksum + parity decodes cleanly with the same keys, seqnos, and
/// counts, so every derived-metadata cross-check passes — the manifest
/// digest is the ONLY record of the original value bytes, and refreshing it
/// without attribution to this pass's own heal writes would erase that
/// record permanently.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_footerless_value() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_value_byte_in_first_data_block(&sst_path, Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged footer-less value must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would erase the only record of the original value bytes",
    );
    Ok(())
}

/// As [`write_ecc_sst_footered`], but with 256 KiB zstd data blocks over
/// ~600 KiB of KV so at least one data block splits into >= 2 inner zstd
/// blocks and the SST carries a `block_layout` section.
fn write_ecc_zstd_multiblock_sst(dir: &std::path::Path) -> std::path::PathBuf {
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir,
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .data_block_size_policy(crate::config::BlockSizePolicy::all(256 * 1024))
    .data_block_compression_policy(crate::config::CompressionPolicy::all(
        crate::CompressionType::Zstd(19),
    ))
    .open()
    .expect("open ecc zstd tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    tree.update_runtime_config(|c| {
        c.kv_checksums = crate::runtime_config::KvChecksumPolicy::AllLevels;
    })
    .expect("enable kv checksums");
    for i in 0u64..20_000 {
        tree.insert(format!("key-{i:012}"), format!("value-{i:08}-payload"), i);
    }
    tree.flush_active_memtable(20_000).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    assert!(
        table.regions.block_layout.is_some(),
        "the multi-inner-block fixture must carry a block_layout section",
    );
    (*table.path).clone()
}

/// Salvage must NOT byte-copy a MULTI-INNER block verbatim: its recorded
/// `block_layout` is the very (checksum-consistent, unauthenticated) section a
/// forge can corrupt to route an otherwise-readable zstd SST through salvage, so
/// copying the block verbatim would re-emit the same untrusted inner boundaries
/// and keep partial range reads omitting keys even though salvage reports
/// success. The block re-encodes from the verified payload instead
/// (`verbatim = None`); single-inner blocks (empty layout) still copy verbatim.
#[test]
fn salvage_load_block_re_encodes_a_multi_inner_block() -> crate::Result<()> {
    use crate::table::BlockHandle;
    use crate::table::block::BlockType;

    let dir = tempfile::tempdir()?;
    // Build a multi-inner-block zstd SST and keep the tree alive so its table
    // handle stays valid for the salvage-load probe below.
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .data_block_size_policy(crate::config::BlockSizePolicy::all(256 * 1024))
    .data_block_compression_policy(crate::config::CompressionPolicy::all(
        crate::CompressionType::Zstd(19),
    ))
    .open()
    .expect("open ecc zstd tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    tree.update_runtime_config(|c| {
        c.kv_checksums = crate::runtime_config::KvChecksumPolicy::AllLevels;
    })
    .expect("enable kv checksums");
    for i in 0u64..20_000 {
        tree.insert(format!("key-{i:012}"), format!("value-{i:08}-payload"), i);
    }
    tree.flush_active_memtable(20_000).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    let multi_inner_offsets = table.block_layout.offsets();
    assert!(
        !multi_inner_offsets.is_empty(),
        "the fixture must carry at least one multi-inner-block frame",
    );

    // The data block recorded in the block_layout is multi-inner: salvage must
    // re-encode it, not verbatim-copy its untrusted boundaries.
    let multi = table
        .block_index
        .iter()
        .filter_map(Result::ok)
        .find(|kh| multi_inner_offsets.contains(&kh.offset().0))
        .map(|kh| BlockHandle::new(kh.offset(), kh.size()))
        .expect("a block index handle for the multi-inner offset");
    let sb = table.salvage_load_block(&multi, BlockType::Data)?;
    assert!(
        sb.verbatim.is_none(),
        "a multi-inner block must re-encode from the verified payload, not byte-copy its \
         unauthenticated recorded layout",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `block_layout`:
/// a middle cumulative end shifted to another structurally valid value
/// (fresh block checksum + parity) passes every byte-level and framing
/// check — no gate compares the recorded boundaries with the zstd frames'
/// real inner-block layout — yet the partial range-read path trusts it to
/// bound decompression, silently omitting keys from the mis-mapped span.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_block_layout() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let sst_path = write_ecc_zstd_multiblock_sst(dir.path());

    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .data_block_size_policy(crate::config::BlockSizePolicy::all(256 * 1024))
    .data_block_compression_policy(crate::config::CompressionPolicy::all(
        crate::CompressionType::Zstd(19),
    ))
    .open()
    .expect("reopen ecc zstd tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    crate::test_forge::forge_block_layout_shift_middle_end(&sst_path, Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged block_layout must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let partial range reads silently omit keys",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over TLI mirrors forged
/// CONSISTENTLY: both copies re-encoded to the same truncated handle list
/// (fresh checksums, parity, Index role) pass every byte-level check AND
/// the decoded mirror comparison — the equality of two forged copies proves
/// nothing. Only a structural check of the decoded handles against the
/// physical data section (the writer emits data blocks back-to-back, so the
/// handles must exactly TILE it) can catch the dropped handle before the
/// next recovery loads the forged list and range scans silently lose the
/// unreachable block. Footered fixture, so the forge is not pre-empted by
/// the footer-less attribution rule.
#[test]
fn heal_in_place_does_not_restamp_over_consistently_forged_tli_mirrors() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Open FIRST (the live table already loaded its index), then forge.
    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_tli_mirrors_truncated(
        &sst_path,
        0,
        Some(crate::table::block::EccParams::try_new(8, 2)?),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "consistently forged TLI mirrors must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let the next recovery hide the dropped block",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over FORGED metadata KEY
/// BOUNDS: both meta mirrors re-stamped CONSISTENTLY to a narrower
/// `key#max` (fresh checksums and parity) pass every byte-level check and
/// the full mirror comparison — only a cross-check of the recorded range
/// against the decoded data keys can catch it. Restamping would make run
/// selection trust the forged range and silently skip this table for real
/// keys outside it. The fixture is footered, so the forge is not
/// pre-empted by the footer-less attribution rule.
#[test]
fn heal_in_place_does_not_restamp_over_forged_meta_key_bounds() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    let tree = open_ecc_tree(dir.path());
    // Real keys run up to "key-001999"; narrow the recorded max below half
    // the key space (same value length keeps the frame geometry).
    crate::test_forge::forge_meta_value_both_mirrors(&sst_path, b"key#max", b"key-000999")?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "forged meta key bounds must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let run selection silently skip real keys",
    );
    Ok(())
}

/// Opens an RS(8,2) Page-ECC tree at `dir` whose data blocks are
/// uncompressed and carry an embedded hash index — the layout
/// `forge_hash_index_all_free` requires.
fn open_ecc_hashed_tree(dir: &std::path::Path) -> crate::Tree {
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir,
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .data_block_compression_policy(crate::config::CompressionPolicy::all(
        crate::CompressionType::None,
    ))
    .data_block_hash_ratio_policy(crate::config::HashRatioPolicy::all(2.0))
    .open()
    .expect("open ecc hashed tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    tree
}

/// A footered, uncompressed ECC SST whose data blocks carry an embedded
/// HASH INDEX (non-zero `data_block_hash_ratio`), for the hash-index forge.
fn write_ecc_sst_footered_hashed(dir: &std::path::Path) -> std::path::PathBuf {
    let tree = open_ecc_hashed_tree(dir);
    tree.update_runtime_config(|c| {
        c.kv_checksums = crate::runtime_config::KvChecksumPolicy::AllLevels;
    })
    .expect("enable kv checksums");
    for i in 0u64..2_000 {
        tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
    }
    tree.flush_active_memtable(2_000).expect("flush");

    let binding = tree.version_history.read().latest_version();
    let table = binding
        .version
        .iter_tables()
        .next()
        .expect("flush produced one table");
    (*table.path).clone()
}

/// The digest reconciliation must not restamp over a FORGED embedded HASH
/// INDEX: filling the first block's hash index with `MARKER_FREE` leaves
/// every logical entry, per-KV footer, and the outer block checksum intact,
/// so a sequential decode and the count / key / seqno gates all pass — yet
/// after reopen `point_read` trusts the hash index and returns `None` for
/// every existing key in that block. The indexes must be probed against the
/// decoded keys before the digest is trusted.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_hash_index() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let sst_path = write_ecc_sst_footered_hashed(dir.path());

    let tree = open_ecc_hashed_tree(dir.path());
    crate::test_forge::forge_hash_index_all_free(&sst_path, Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged hash index must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let point reads miss existing keys",
    );
    Ok(())
}

/// The reconcile gates must judge the bytes ON DISK, not the block cache:
/// a block read before the forge leaves its pristine copy cached, and a
/// gate that loads through the cache validates that stale original instead
/// of the file being reconciled. Same forge as
/// [`heal_in_place_does_not_restamp_over_a_forged_hash_index`], but with a
/// point read FIRST so the pristine first data block is cached when the
/// heal scan runs — the refresh must still be refused.
#[test]
fn heal_in_place_does_not_trust_cached_blocks_over_the_disk_bytes() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let sst_path = write_ecc_sst_footered_hashed(dir.path());

    let tree = open_ecc_hashed_tree(dir.path());
    // Warm the block cache with the PRISTINE first data block (the key lives
    // in it), then forge the on-disk hash index; the cached copy stays good.
    assert!(
        tree.get("key-000000", MAX_SEQNO)?.is_some(),
        "pre-forge read warms the cache",
    );
    crate::test_forge::forge_hash_index_all_free(&sst_path, Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged hash index must refuse the digest refresh even when the \
         pristine block is cached: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let point reads miss existing keys after the cache cools",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over FORGED metadata SEQUENCE
/// bounds: on a footer-bearing table WITHOUT deletion metadata (no sentinel
/// to complicate the bounds), both meta mirrors re-stamped with `seqno#min`
/// raised while every data entry stays intact pass the mirror walk and all
/// per-KV / key / count gates — yet after reopen a snapshot read whose
/// threshold is at or below the forged minimum returns early at
/// `Table::get`, silently missing older visible versions. The recorded
/// bounds must be cross-checked against the decoded entries' real seqnos.
#[test]
fn heal_in_place_does_not_restamp_over_forged_meta_seqno_bounds() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Read the SST's real recorded max so the forged min stays <= max (a
    // min > max would fail the meta load for a different reason).
    let tree = open_ecc_tree(dir.path());
    let recorded_max = {
        let binding = tree.version_history.read().latest_version();
        let table = binding.version.iter_tables().next().expect("one table");
        table.get_highest_seqno()
    };
    // Raise seqno#min to the recorded max — every entry below it is now
    // hidden from snapshots at or under the forged minimum.
    crate::test_forge::forge_meta_value_both_mirrors(
        &sst_path,
        b"seqno#min",
        &recorded_max.to_le_bytes(),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "forged metadata seqno bounds must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let snapshot reads silently skip older visible versions",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `created_at`:
/// both meta mirrors re-stamped with an OLDER timestamp (same 16-byte
/// length, fresh checksums and parity) pass every byte-level check, the
/// mirror comparison, and every content-derived gate — no cross-check can
/// re-derive a wall-clock timestamp from the entries. Yet after reopen
/// FIFO compaction trusts the recorded `created_at` for its TTL decision
/// and can classify the live SST as expired, permanently dropping it. The
/// disk-fresh meta must equal the recovery-time copy field for field
/// before the digest is trusted.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_created_at() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Open FIRST so the live table keeps its recovery-time timestamp, then
    // back-date the on-disk copy in both mirrors (u128 LE nanoseconds; the
    // equal value length keeps the frame geometry).
    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_meta_value_both_mirrors(
        &sst_path,
        b"created_at",
        &1u128.to_le_bytes(),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged created_at must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let FIFO compaction drop the live SST as TTL-expired",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a `created_at` back-dated
/// while the tree was CLOSED. The post-open forge above is caught by the
/// field-for-field bounds check because the live table keeps the honest
/// recovery-time copy; an OFFLINE restamp defeats that check by poisoning the
/// recovery-time copy itself — recovery loads the forged `created_at`, so the
/// disk-fresh copy equals it. The manifest's whole-file digest is then the
/// only surviving record of the honest bytes, and the mismatch it produces is
/// UNATTRIBUTABLE to any heal. Because no cross-check can re-derive a
/// wall-clock timestamp, an unattributed mismatch must fail closed even on a
/// footer-bearing table; otherwise the patrol would persist the forged digest
/// and FIFO compaction would drop the live SST as TTL-expired.
#[test]
fn heal_in_place_rejects_a_created_at_restamped_before_open() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Back-date `created_at` in BOTH mirrors BEFORE the tree opens: recovery
    // then loads the forgery into the live table's metadata.
    crate::test_forge::forge_meta_value_both_mirrors(
        &sst_path,
        b"created_at",
        &1u128.to_le_bytes(),
    )?;

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    // Pin the fail-closed reason, not just the error variant: another gate
    // could raise ChecksumRefreshFailed for a different cause and keep this
    // test green while the attribution gate goes uncovered.
    assert!(
        report.errors.iter().any(|e| matches!(
            e,
            ScrubError::ChecksumRefreshFailed { reason, .. }
                if reason.contains("not attributable to this pass's heal")
        )),
        "an unattributed mismatch on a footer-bearing table must not reconcile a \
         pre-open created_at restamp: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its digest \
         would let FIFO compaction drop the live SST as TTL-expired",
    );
    Ok(())
}

/// A stale IN-PROGRESS heal marker must NOT authorize a reconcile. The
/// in-progress marker binds only `pre == manifest`, not the healed bytes, so a
/// crash after the marker was written but before any block was healed leaves it
/// attesting a heal that never happened. If a checksum-restamped alteration to a
/// non-authenticatable surface (here a pre-open `created_at` back-date, which
/// poisons the recovery-time copy so no gate can catch it) then lands, the
/// marker would legitimize it: the patrol refreshes the manifest over the forged
/// bytes. Attribution must come only from this pass's heal or a COMPLETED marker
/// (which binds `post == current`); a bare pre-only marker is ignored, so the
/// mismatch stays unattributable and fails closed.
#[cfg(feature = "page_ecc")]
#[test]
fn heal_in_place_ignores_a_stale_in_progress_marker() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Back-date `created_at` in BOTH mirrors before open, poisoning the
    // recovery-time copy so the field-for-field gate cannot catch it — the
    // mismatch is unattributable unless a marker authorizes it.
    crate::test_forge::forge_meta_value_both_mirrors(
        &sst_path,
        b"created_at",
        &1u128.to_le_bytes(),
    )?;

    let tree = open_ecc_tree(dir.path());
    // Manufacture a stale in-progress marker whose `pre` equals the manifest
    // digest (the clean, pre-forge checksum the manifest still records), as a
    // crash between the marker write and the first heal would leave.
    let manifest_checksum = {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table")
            .checksum()
    };
    crate::scrub::heal_attest::write_in_progress(
        &crate::fs::StdFs,
        &sst_path,
        None,
        0,
        manifest_checksum,
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.errors.iter().any(|e| matches!(
            e,
            ScrubError::ChecksumRefreshFailed { reason, .. }
                if reason.contains("not attributable to this pass's heal")
        )),
        "a stale in-progress marker must not make an unattributed mismatch \
         attributable: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: a stale in-progress \
         marker must not authorize restamping its digest",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED KV-footer
/// DESCRIPTOR: both meta mirrors re-stamped with `descriptor#kv_checksum`
/// set to off while the footer-bearing data blocks are left intact. The
/// mirror walk accepts the matching copies, and the in-memory descriptor is
/// still the recovery-time `Some(algo)` so `verify_kv_checksums` passes —
/// yet after reopen the on-disk `None` descriptor stops footer stripping,
/// so point reads misread footer bytes as the data-block trailer. The
/// disk-fresh descriptor must be cross-checked against the recovery-time
/// one before trusting the metadata.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_kv_checksum_descriptor() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    // Open FIRST so the live table keeps its recovery-time Some(algo), then
    // forge the on-disk descriptor to off (byte 0) in both mirrors.
    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_meta_value_both_mirrors(&sst_path, b"descriptor#kv_checksum", &[0])?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged kv-checksum descriptor must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let point reads misread footer bytes as the trailer",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED metadata BLOCK
/// COUNT: both mirrors re-stamped consistently to a smaller
/// `block_count#data` (fresh checksums and parity) pass every byte-level
/// check and the mirror comparison, and the bounds gate's key/item checks
/// stay clean (the blocks themselves are untouched) — yet `Table::scan`
/// hands the recorded count to the compaction scanner, which stops after
/// that many blocks: a rewrite silently drops every key in the omitted
/// tail. Footered fixture, so the forge is not pre-empted by the
/// footer-less attribution rule.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_data_block_count() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    let tree = open_ecc_tree(dir.path());
    // The fixture writes 9 data blocks; record 1 (little-endian u64, same
    // value length keeps the frame geometry).
    crate::test_forge::forge_meta_value_both_mirrors(
        &sst_path,
        b"block_count#data",
        &1u64.to_le_bytes(),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged data-block count must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let compaction scans silently drop the omitted blocks",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED TLI SEPARATOR
/// key: both mirrors re-encoded with the first block's separator lowered to
/// a truncated prefix stay equal, sorted, and section-tiling — yet after
/// reopen the index binary search routes keys in `(forged_separator,
/// real_last_key]` to the wrong block, so `point_read` misses existing keys.
///
/// What refuses it here is the ATTRIBUTION rule, not a cross-check: the forge
/// landed before this pass, so the pre-heal digest already disagreed with the
/// manifest and the mismatch is not attributable to any correction this pass
/// made. The gate chain (separators included) is only reached on the
/// attributable branch, which a pre-existing forge can never satisfy — so this
/// pins the attribution guard, and the separator cross-check itself is pinned
/// against the reconcile pass directly in the table tests.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_tli_separator() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_tli_mirrors_lower_first_separator(
        &sst_path,
        0,
        Some(crate::table::block::EccParams::try_new(8, 2)?),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged TLI separator must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let point reads miss keys routed to the wrong block",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED TLI BINARY
/// INDEX: both mirrors re-stamped with the last binary-index pointer
/// redirected to the first restart head leave the sequential entry stream
/// untouched, so mirror equality, section tiling, and every separator
/// cross-check pass — yet after reopen the index binary search trusts the
/// forged pointer and can start at the wrong restart head, silently
/// missing keys on seeks. Each disk-fresh pointer must be validated
/// against the sequentially derived restart heads.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_tli_binary_index() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst_footered(dir.path());

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_tli_binary_index_pointer(
        &sst_path,
        0,
        Some(crate::table::block::EccParams::try_new(8, 2)?),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged TLI binary index must refuse the digest refresh: {report:?}",
    );

    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let index seeks start at the wrong restart head",
    );
    Ok(())
}

/// A LEGITIMATE heal on a tombstone-bearing table must still reconcile the
/// manifest digest: attribution (the pre-write digest matched the manifest,
/// so the file now differs by exactly this pass's verified corrections)
/// proves the deletion metadata itself is untouched — the fail-closed rule
/// for unattributable mismatches must not permanently flag every healed
/// table that happens to carry range tombstones.
#[test]
fn heal_in_place_reconciles_a_tombstone_bearing_table_after_a_legit_heal() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_with_range_tombstone(dir.path());

    // Rot one parity-trailer byte, then let a manifest rebuild record the
    // digest of the ROTTED bytes: the heal restores the original trailer,
    // so the reconciliation has a real mismatch to persist.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted trailer is rebuilt in place: {report:?}",
    );
    assert!(
        report.is_ok(),
        "an attributable heal reconciles the digest despite the deletion \
         metadata: {report:?}",
    );
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        integrity.is_ok(),
        "the healed table verifies clean against the refreshed digest, got {:?}",
        integrity.errors,
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `filter`: a
/// payload altered to another parseable `BuRR` filter (fresh block checksum +
/// parity) passes every byte-level, framing, and role check — the walk never
/// probes the filter against the table's keys — yet `check_bloom` trusts it
/// to SKIP point reads, so a key made into a false negative silently
/// disappears from every read. Only a probe of each decoded key against the
/// filter can catch it before the refresh legitimizes the forge.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_filter() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    let tree = open_ecc_tree(dir.path());
    // The forge targets the section's FIRST filter block, which covers the
    // table's lowest keys — make its first key the false negative.
    crate::test_forge::forge_filter_false_negative(
        &sst_path,
        crate::hash::hash64(b"key-000000"),
        Some((8, 2)),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged filter must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let point reads silently miss existing keys",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `seqno_bounds`
/// map: a payload re-stamped to another structurally valid map (fresh block
/// checksum + parity, `min <= max`, ascending offsets) passes every
/// byte-level and framing check, yet `scan_since_seqno` trusts it to SKIP
/// blocks — zeroed bounds silently omit a block's live entries from every
/// CDC / incremental scan. Only a cross-check against the blocks' decoded
/// entries can catch it before the refresh legitimizes the forge.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_seqno_bounds() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;

    // An ECC tree WITH the seqno_bounds section (off by default).
    let sst_path = {
        let tree = open_ecc_tree(dir.path());
        tree.update_runtime_config(|c| c.seqno_in_index = true)?;
        for i in 0u64..2_000 {
            tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
        }
        tree.flush_active_memtable(2_000).expect("flush");
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        (*table.path).clone()
    };

    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_seqno_bounds_zeroed_entry(&sst_path, Some((8, 2)))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a forged seqno_bounds map must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would let scans silently skip live blocks",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a FORGED `tli_tail`: a
/// tail mirror re-encoded to a truncated handle list is independently
/// checksum-, parity-, and role-consistent, so the out-of-band walk reads it
/// clean — yet `read_tli` prefers it on the next recovery, and the hidden
/// block's keys silently vanish. Only a comparison of the two DECODED TLI
/// mirrors can catch it before the digest refresh legitimizes the forge.
#[test]
fn heal_in_place_does_not_restamp_over_a_forged_tli_tail() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    // Open FIRST (the live table already loaded its index), then forge.
    let tree = open_ecc_tree(dir.path());
    crate::test_forge::forge_tli_tail_truncated(
        &sst_path,
        0,
        Some(crate::table::block::EccParams::try_new(8, 2)?),
    )?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "diverged TLI mirrors must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the forged SST must keep failing verify_integrity: restamping its \
         digest would hide a mirror only the decoded comparison detects",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over a RELABELED section
/// block: a checksum-clean block whose `block_type` was forged (a filter
/// block re-stamped as Data) passes payload and parity verification, so
/// only a section-vs-role cross-check in the out-of-band walk can catch
/// it. Restamping would make `verify_integrity` accept an SST whose lazy
/// filter load rejects the role at read time.
#[test]
fn heal_in_place_does_not_restamp_over_a_relabeled_section_block() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    // Relabel the FIRST filter block as Data and re-stamp its header: the
    // payload and its checksum are untouched, so every byte-level check
    // stays clean while the role no longer matches the section.
    crate::test_forge::forge_section_block_role(
        &sst_path,
        b"filter",
        crate::table::block::BlockType::Data,
    )?;

    // Reopen with LAZY filters (no pinning): the default policy pins the L0
    // filter at open, which loads it and rejects the role before the scrub
    // even runs — the dangerous variant is the lazy one, where nothing
    // touches the filter until a point read long after the restamp.
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .filter_block_pinning_policy(crate::config::PinningPolicy::new([false]))
    .open()
    .expect("open ecc tree with lazy filters") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "the relabeled block must refuse the digest refresh: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the forge stays visible.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the relabeled SST must keep failing verify_integrity: restamping \
         its digest would mask a forge only the role cross-check detects",
    );
    Ok(())
}

/// A heal scan over a HEALTHY hard-linked SST must not detach it: the
/// unshare exists to protect a checkpoint from in-place writes, and a scan
/// that finds nothing to write has no reason to stream the whole file into
/// a private copy. Detaching eagerly turns a heal patrol over a
/// checkpointed database into O(database) writes and permanently doubles
/// the disk usage of every linked SST, breaking the option's O(damage)
/// contract.
// Unix-gated for the `nlink` assertion (`std` exposes the NTFS count only
// behind an unstable feature); the lazy-detach behaviour itself is
// platform-independent.
#[cfg(unix)]
#[test]
fn heal_in_place_keeps_a_healthy_sst_hard_linked() -> crate::Result<()> {
    use std::os::unix::fs::MetadataExt as _;

    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    let cp_dir = tempfile::tempdir_in(dir.path().parent().expect("tempdir has a parent"))?;
    std::fs::hard_link(&sst_path, cp_dir.path().join("checkpoint.sst"))?;

    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(report.is_ok(), "{report:?}");
    assert_eq!(report.blocks_healed_in_place, 0, "nothing to heal");

    assert_eq!(
        std::fs::metadata(&sst_path)?.nlink(),
        2,
        "a clean scan must leave the checkpoint link in place: detaching \
         without a write to protect it from costs a full-file copy and \
         doubles the SST's disk usage",
    );
    Ok(())
}

/// A failed link-count probe must FAIL CLOSED: the heal cannot prove the
/// inode is exclusive, so it must take the unshare (copy) path as if the file
/// were shared — and still heal the detached copy, not skip the table or
/// write through the possibly-shared inode.
#[test]
fn heal_in_place_treats_an_unknown_link_count_as_shared() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;

    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));
    injector.arm(
        FaultRule::new(FaultOp::HardLinkCount, Fault::Error(ErrorKind::Other))
            .on_path("tables")
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    // The heal proceeded through the copy path: the trailer rot is healed and
    // nothing surfaced as a finding.
    assert!(
        report.blocks_healed_in_place >= 1,
        "fail-closed still heals (through the detached copy): {report:?}",
    );
    assert!(report.is_ok(), "{report:?}");
    Ok(())
}

/// A failed unshare must not leave its `*.healtmp` artifact behind: recovery
/// parses every non-special file under `tables/` as a numeric table id, so a
/// leftover temp copy makes the NEXT open of the whole tree fail
/// `Unrecoverable` — a heal that could not proceed must degrade to a
/// read-only scan, not brick the reopen path.
#[test]
fn heal_in_place_cleans_up_the_temp_copy_when_the_unshare_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte (so the heal has something to WRITE — the
    // unshare only runs before the first write-back), then hard-link the
    // rotted SST so the heal takes the unshare path.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    let cp_dir = tempfile::tempdir_in(dir.path().parent().expect("tempdir has a parent"))?;
    std::fs::hard_link(&sst_path, cp_dir.path().join("checkpoint.sst"))?;

    // Fail the pre-publish sync of the heal copy: the copy was already
    // created and fully written by then.
    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));
    injector.arm(
        FaultRule::new(FaultOp::SyncAll, Fault::Error(ErrorKind::Other))
            .on_path("healtmp")
            .once(),
    );
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(
        !report.is_ok(),
        "the failed unshare is a finding: {report:?}"
    );

    // No temp artifact may survive the failure...
    let leftovers: Vec<_> = std::fs::read_dir(sst_path.parent().expect("sst in tables dir"))?
        .filter_map(Result::ok)
        .filter(|e| e.file_name().to_string_lossy().contains("healtmp"))
        .collect();
    assert!(
        leftovers.is_empty(),
        "a failed unshare must remove its temp copy: {leftovers:?}",
    );

    // ...and the tree must reopen: a heal failure must never brick recovery.
    // The trailer rot is still on disk (the write was refused), so the
    // integrity scan keeps flagging it.
    drop(tree);
    let tree = open_ecc_tree(dir.path());
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the refused heal leaves the rot in place and visible",
    );
    Ok(())
}

/// The digest reconciliation must not restamp over corruption the heal scan
/// never looked at: the scan covers DATA blocks only, so rot in a side
/// section (filter, zone map, range tombstones) leaves the scan clean while
/// the file digest disagrees with the manifest; blindly installing the fresh
/// digest would make `verify_integrity` accept the corrupted file, masking
/// the rot until the side section is lazily loaded.
#[test]
fn heal_in_place_does_not_restamp_over_side_section_rot() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _) = write_ecc_sst(dir.path());

    // Rot a 64-byte run inside the FILTER section's payload (well past the
    // RS(8,2) correction budget): the data blocks stay clean, but the
    // out-of-band section walk (and any later filter load) flags it.
    let (pos, len) = {
        let mut f = std::fs::File::open(&sst_path)?;
        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") else {
            panic!("the SST must carry a filter section");
        };
        (entry.pos(), entry.len())
    };
    assert!(len > 128, "filter section large enough to rot: {len}");
    let start = usize::try_from(pos).expect("filter offset fits usize") + 40;
    let mut bytes = std::fs::read(&sst_path)?;
    let Some(run) = bytes.get_mut(start..start + 64) else {
        panic!("filter payload within the file");
    };
    for b in run {
        *b ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;

    // Heal scan: every DATA block reads clean, yet the file digest now
    // disagrees with the manifest (the filter byte changed).
    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        !report.is_ok(),
        "a digest mismatch the scan cannot attribute to a heal must be a \
         finding, not silently restamped: {report:?}",
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "the finding must be the refused digest refresh: {report:?}",
    );
    assert_eq!(
        report.uncorrectable_blocks, 0,
        "the data blocks themselves stay clean: {report:?}",
    );

    // The manifest keeps the ORIGINAL digest, so the corruption stays
    // visible to integrity scans instead of being laundered into a fresh
    // manifest entry.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the corrupted file must keep failing verify_integrity: restamping \
         its digest over unverified side sections would mask the rot",
    );
    Ok(())
}

/// Byte path of the heal attestation sidecar next to an SST.
fn heal_attest_path(sst_path: &std::path::Path) -> std::path::PathBuf {
    let mut name = sst_path.as_os_str().to_os_string();
    name.push(".heal-attest");
    std::path::PathBuf::from(name)
}

/// A manifest-digest refresh that FAILED (or a crash after the heal's
/// `sync_data` but before the manifest update) leaves a stale digest. Because
/// the heal writes a sidecar ATTESTATION before the reconciliation, a later
/// clean heal-in-place scrub — which sees only clean blocks and cannot
/// attribute the mismatch to any write of its own — reconciles the digest via
/// that attestation instead of flagging the healed table as corrupt forever.
/// (For an unencrypted table the attestation is plaintext; forging it needs the
/// same directory write access that could re-stamp the SST directly, which is
/// outside the on-disk-tamper model the digest gate defends.)
#[test]
fn heal_in_place_reconciles_a_crashed_refresh_via_the_attestation() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // FIRST heal pass: the trailer is rebuilt in place and an attestation is
    // written, but the manifest refresh fails (injected fault on the edit-log
    // open), leaving the stale digest AND the attestation on disk.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(report.blocks_healed_in_place >= 1, "{report:?}");
    assert!(
        !report.is_ok(),
        "the failed refresh is a finding: {report:?}"
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the heal must leave an attestation for the crashed refresh",
    );

    // SECOND heal pass, fault gone: every block reads clean (nothing to heal),
    // and the manifest still carries the rotted digest. The attestation proves
    // the file is the healed version, so the mismatch is reconciled.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.is_ok(),
        "a crashed refresh must reconcile via the attestation on the next scrub: {report:?}",
    );
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        integrity.is_ok(),
        "the reconciled digest matches the healed file, got {:?}",
        integrity.errors,
    );
    assert!(
        !heal_attest_path(&sst_path).exists(),
        "the attestation is consumed once its reconciliation lands",
    );
    Ok(())
}

/// A heal writes the completed attestation UP FRONT — before any block is
/// healed — binding the deterministic post-heal digest, so a crash anywhere in
/// the heal leaves that marker on disk. The next clean scrub reconciles via it:
/// the marker binds `post == current`, so once the file reaches the healed
/// state the mismatch is attributable and the structural gates re-verify before
/// the digest is trusted. Without it the clean re-scan cannot attribute the
/// mismatch and the stale digest is rejected forever.
#[test]
fn heal_in_place_reconciles_via_a_completed_marker() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // First heal pass with a failing edit-log: the blocks are healed and the
    // completed attestation is written, but the manifest refresh fails.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(report.blocks_healed_in_place >= 1, "{report:?}");

    // Model the crash window explicitly: the file is healed, and the completed
    // marker binds the manifest's (stale) `pre` to the healed file's `post`.
    let (table_id, manifest_digest) = {
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("the healed table is still in the manifest");
        (table.id(), table.checksum())
    };
    let healed_digest = crate::Checksum::from_raw(crate::repair::compute_table_checksum(
        &crate::fs::StdFs,
        &sst_path,
    )?);
    std::fs::remove_file(heal_attest_path(&sst_path))?;
    crate::scrub::heal_attest::write(
        &crate::fs::StdFs,
        &sst_path,
        None,
        table_id,
        manifest_digest,
        healed_digest,
    )?;

    // Second pass, fault gone: every block reads clean (nothing to heal), so the
    // mismatch is attributable only via the completed marker.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert_eq!(
        report.blocks_healed_in_place, 0,
        "the second pass must find every block clean, so ONLY the marker attributes the \
         mismatch (a re-heal would make attribution direct and skip the marker path): {report:?}",
    );
    assert!(
        report.is_ok(),
        "a crash before the manifest refresh must reconcile via the completed \
         marker on the next scrub: {report:?}",
    );
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        integrity.is_ok(),
        "the reconciled digest matches the healed file, got {:?}",
        integrity.errors,
    );
    assert!(
        !heal_attest_path(&sst_path).exists(),
        "the marker is consumed once its reconciliation lands",
    );
    Ok(())
}

/// `attests_post` is the discriminator the heal path uses to decide a not-matched
/// heal is NOT diverging: it matches only a COMPLETED marker recording exactly
/// `post` for this table, regardless of the marker's `pre`. A wrong post or a
/// wrong table id does not match, so a genuinely diverging heal is not mistaken
/// for a safe restore-to-an-attested-digest.
#[test]
fn attests_post_matches_only_the_recorded_completed_post() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let path = dir.path().join("t.sst");
    std::fs::write(&path, b"x")?;

    let pre = crate::Checksum::from_raw(0x1111);
    let post = crate::Checksum::from_raw(0x2222);
    crate::scrub::heal_attest::write(&crate::fs::StdFs, &path, None, 7, pre, post)?;

    use crate::scrub::heal_attest::AttestResult;
    // The recorded post matches for the right table, whatever the `pre` was.
    assert!(matches!(
        crate::scrub::heal_attest::attests_post(&crate::fs::StdFs, &path, None, 7, post),
        AttestResult::Attests,
    ));
    // A different post does not match.
    assert!(matches!(
        crate::scrub::heal_attest::attests_post(
            &crate::fs::StdFs,
            &path,
            None,
            7,
            crate::Checksum::from_raw(0x3333),
        ),
        AttestResult::Absent,
    ));
    // A different table id does not match.
    assert!(matches!(
        crate::scrub::heal_attest::attests_post(&crate::fs::StdFs, &path, None, 8, post),
        AttestResult::Absent,
    ));
    Ok(())
}

/// A TRANSIENT read of the attestation sidecar must resolve to `Inconclusive`,
/// never `Absent`. Collapsing it to "does not attest" (the old `bool` return)
/// would make the diverging-heal check skip the heal, then let the reconcile
/// reread the now-readable marker, find it no longer matches the current bytes,
/// and delete a VALID marker — permanently stranding the healed table.
#[test]
fn attests_post_is_inconclusive_on_a_transient_sidecar_read() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;
    use crate::scrub::heal_attest::AttestResult;

    let dir = tempfile::tempdir()?;
    let path = dir.path().join("t.sst");
    std::fs::write(&path, b"x")?;
    let post = crate::Checksum::from_raw(0x2222);
    crate::scrub::heal_attest::write(
        &crate::fs::StdFs,
        &path,
        None,
        7,
        crate::Checksum::from_raw(0x1111),
        post,
    )?;

    // Fault the sidecar OPEN with a transient (non-NotFound) error: `read_sidecar`
    // maps that to `Inconclusive`, and `attests_post` must propagate it.
    let fault = FaultFs::new(crate::fs::StdFs);
    fault.injector().arm(
        FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Interrupted)).on_path("heal-attest"),
    );

    assert!(
        matches!(
            crate::scrub::heal_attest::attests_post(&fault, &path, None, 7, post),
            AttestResult::Inconclusive,
        ),
        "a transient sidecar read must be Inconclusive, not Absent",
    );
    Ok(())
}

/// Without a valid attestation, an unattributable stale digest STILL fails
/// closed: the attestation is the only thing that lets a clean re-scan
/// reconcile, so deleting it (modelling a crash before the attestation was
/// written, or an offline restamp with no attestation at all) must restore the
/// fail-closed behavior — nothing else distinguishes the mismatch from an
/// offline restamp of the non-derivable meta scalars.
#[test]
fn heal_in_place_fails_closed_without_a_heal_attestation() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // First pass heals + attests, but the refresh fails.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(report.blocks_healed_in_place >= 1, "{report:?}");

    // Remove the attestation before the retry: the mismatch is now
    // unattributable with no evidence of a legitimate heal.
    std::fs::remove_file(heal_attest_path(&sst_path))?;

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.errors.iter().any(|e| matches!(
            e,
            ScrubError::ChecksumRefreshFailed { reason, .. }
                if reason.contains("not attributable to this pass's heal")
        )),
        "without an attestation the stale digest must fail closed: {report:?}",
    );
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "the unattested stale digest keeps flagging, got {:?}",
        integrity.errors,
    );
    Ok(())
}

/// A transiently-unreadable sidecar must NOT be treated as an absent marker on
/// the unattributable re-scan path: deleting it on a retryable read error would
/// strand the healed table under the stale digest forever. The read is
/// INCONCLUSIVE, so the reconcile fails closed (no digest refresh) but KEEPS the
/// marker for the next pass to retry.
#[test]
fn reconcile_keeps_the_marker_when_the_sidecar_read_is_inconclusive() -> crate::Result<()> {
    use crate::fs::{Fault, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // First pass heals + writes the attestation, but the manifest refresh fails,
    // leaving the marker on disk for a later pass to reconcile.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(report.blocks_healed_in_place >= 1, "{report:?}");
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the heal left a marker"
    );

    // Second pass: the block is clean, so the mismatch is attributable only via
    // the marker, but its read fails transiently (an open error, not not-found).
    // That is inconclusive, not absent, so the marker must survive.
    injector
        .arm(FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Other)).on_path(".heal-attest"));
    let _ = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert!(
        heal_attest_path(&sst_path).exists(),
        "an inconclusive sidecar read must keep the marker, not delete it",
    );
    Ok(())
}

/// A `.heal-attest` sidecar whose SST is absent from the recovered manifest is
/// an orphan: its table was retired (compacted away, its numeric file unlinked)
/// while the attestation lingered. Recovery must SWEEP the orphan rather than
/// skip it forever — an attestation can only ever reconcile a table that still
/// exists, so a leaked sidecar is dead weight that every future recovery scan
/// re-processes. A LIVE table's pending attestation must still be preserved.
#[test]
fn recovery_sweeps_an_orphaned_heal_attestation_but_keeps_a_live_one() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, _block) = write_ecc_sst(dir.path());
    let tables_dir = sst_path.parent().expect("the SST lives in a tables folder");

    // An orphan sidecar for a table id that is NOT in the manifest.
    let orphan = tables_dir.join("99999.heal-attest");
    std::fs::write(&orphan, b"orphaned attestation")?;
    // A pending attestation for the LIVE SST (its id IS in the manifest).
    let live = heal_attest_path(&sst_path);
    std::fs::write(&live, b"live attestation")?;

    // Reopen: recovery scans the tables folder and reconciles sidecars.
    let _tree = open_ecc_tree(dir.path());

    assert!(
        !orphan.exists(),
        "recovery must sweep a sidecar whose table id is absent from the manifest",
    );
    assert!(
        live.exists(),
        "recovery must preserve a live table's pending attestation",
    );
    Ok(())
}

/// A prior reconciliation may have installed the refreshed checksum but crashed
/// (or its best-effort sidecar unlink transiently failed) before removing the
/// `.heal-attest` marker. The next reconciliation then finds the on-disk digest
/// already matches the manifest and must RECLAIM the now-obsolete marker:
/// leaving it makes every future checkpoint classify the table as pending and
/// run a full heal scan before snapshotting.
#[test]
fn reconcile_reclaims_an_obsolete_marker_when_the_digest_already_matches() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // A clean ECC table: its on-disk digest already matches the manifest.
    let (sst_path, _block) = write_ecc_sst(dir.path());

    // Plant a leftover sidecar, modelling a prior reconcile that installed the
    // digest but did not manage to remove its marker.
    let marker = heal_attest_path(&sst_path);
    std::fs::write(&marker, b"obsolete marker")?;
    assert!(marker.exists());

    // A heal-in-place patrol scrub: the table is clean, so the reconcile takes
    // the `fresh == current` branch, which must reclaim the obsolete marker.
    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.is_ok(),
        "a clean ECC table scrubs cleanly: {report:?}"
    );

    assert!(
        !marker.exists(),
        "an obsolete marker must be reclaimed once the digest already matches the manifest",
    );
    Ok(())
}

/// The checkpoint-time guard `abort_checkpoint_if_pending_heals` must not wedge
/// on an OBSOLETE marker: a prior reconcile installed the refreshed digest but
/// crashed before removing the sidecar, so the file ALREADY matches the
/// manifest. A build WITHOUT `page_ecc` never runs reconciliation to clear it,
/// so an unconditional abort would fail EVERY checkpoint forever. When the
/// live-region digest already agrees with the manifest the guard reclaims the
/// stale marker and proceeds; a genuine pending heal (a digest that does NOT
/// match) still aborts.
#[test]
fn abort_checkpoint_ignores_an_obsolete_marker_but_aborts_on_a_stale_digest() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // A clean ECC table: its on-disk digest already matches the manifest.
    let (sst_path, _block) = write_ecc_sst(dir.path());
    let marker = heal_attest_path(&sst_path);

    // Case 1: an obsolete leftover marker (a crash between the digest refresh
    // and the marker unlink). The guard must proceed and reclaim it.
    std::fs::write(&marker, b"obsolete marker")?;
    let tree = open_ecc_tree(dir.path());
    crate::scrub::abort_checkpoint_if_pending_heals(&tree, "obsolete-marker case")?;
    assert!(
        !marker.exists(),
        "an obsolete marker matching the manifest must be reclaimed, not wedge the checkpoint",
    );

    // Case 2: a genuine pending heal — the on-disk digest no longer matches the
    // manifest. Flip an interior data byte (length and trailer intact) so the
    // streamed digest diverges while the in-memory manifest entry is unchanged.
    std::fs::write(&marker, b"pending marker")?;
    let mut bytes = std::fs::read(&sst_path)?;
    if let Some(b) = bytes.get_mut(64) {
        *b ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;
    let err = crate::scrub::abort_checkpoint_if_pending_heals(&tree, "stale-digest case")
        .expect_err("a pending heal whose digest does not match the manifest must abort");
    assert!(
        matches!(err, crate::Error::Io(_)),
        "the abort is surfaced as an Io error, got {err:?}",
    );
    assert!(
        marker.exists(),
        "a genuine pending marker is kept for the next reconciliation",
    );
    Ok(())
}

/// A checkpoint must not hold the link window's write half while its flush
/// blocks on `compaction_state`: with Page ECC that closes a three-way cycle —
/// a tight-space compaction holds `compaction_state` while waiting for a
/// table's heal lock, and a heal patrol holds that heal lock while waiting for
/// the link window's read half. Orchestrates all three parties (the test
/// thread stands in for the compaction, holding `compaction_state` and then
/// wanting the heal lock) and asserts every one completes; pre-fix the trio
/// deadlocks and the test hangs into the harness timeout.
#[cfg(feature = "page_ecc")]
#[test]
fn checkpoint_flush_does_not_deadlock_with_patrol_and_compaction() -> crate::Result<()> {
    use crate::AbstractTree;
    use std::sync::Arc;
    use std::time::Duration;

    let dir = tempfile::tempdir()?;
    write_ecc_sst(dir.path());
    let tree = Arc::new(open_ecc_tree_on(dir.path(), Arc::new(crate::fs::StdFs)));

    // Data in the active memtable, so the checkpoint's flush genuinely
    // installs a version (an empty flush never reaches `compaction_state`).
    tree.insert("pending-row", "v", 5_000);

    let table = {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table")
            .clone()
    };

    // Party 1 (this thread, standing in for a mid-install compaction): hold
    // `compaction_state` for the whole orchestration.
    let state_guard = tree.compaction_state.lock();

    // Party 2: the checkpoint. Its flush blocks on `compaction_state` (held
    // above). Pre-fix it blocked there while HOLDING the link window's write
    // half; the fix flushes before taking the window.
    let checkpoint = {
        let tree = Arc::clone(&tree);
        let dst = dir.path().join("checkpoint");
        std::thread::spawn(move || tree.create_checkpoint(&dst))
    };
    std::thread::sleep(Duration::from_millis(300));

    // Party 3: a heal patrol. It takes the table's heal lock and then enters
    // the mutation window (the link window's read half) — pre-fix it blocked
    // there while holding the heal lock.
    let patrol = {
        let tree = Arc::clone(&tree);
        std::thread::spawn(move || {
            patrol_scrub(&*tree, &PatrolScrubOptions::default().heal_in_place(true))
        })
    };
    std::thread::sleep(Duration::from_millis(300));

    // Party 1 now wants the heal lock, exactly like the tight-space slice loop
    // does while holding `compaction_state`. Pre-fix: the patrol holds it and
    // waits for the link window the checkpoint holds while the checkpoint
    // waits for our `compaction_state` — the cycle hangs all three.
    drop(table.heal_lock_arc().lock());
    drop(state_guard);

    let report = patrol.join().expect("patrol thread must not panic");
    assert!(report.is_ok(), "{report:?}");
    checkpoint
        .join()
        .expect("checkpoint thread must not panic")?;
    Ok(())
}

/// A checkpoint taken while a table carries a PENDING heal attestation (healed
/// bytes on disk, the live version still recording the pre-heal digest, and the
/// `.heal-attest` sidecar which the checkpoint does NOT copy) must not capture
/// that stale digest: the immutable checkpoint would fail integrity
/// verification forever with no marker to reconcile. The checkpoint reconciles
/// pending heals BEFORE snapshotting, so the captured version is self-consistent
/// (healed bytes under a refreshed digest).
#[cfg(feature = "page_ecc")]
#[test]
fn checkpoint_reconciles_a_pending_heal_before_snapshotting() -> crate::Result<()> {
    use crate::AbstractTree;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // Heal with a failing edit-log: the blocks are healed and the attestation
    // is written, but the manifest refresh fails, leaving a PENDING heal.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();
    assert!(report.blocks_healed_in_place >= 1, "{report:?}");
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the failed refresh must leave a pending attestation",
    );

    // Snapshot while the heal is still pending.
    let dst = dir.path().join("checkpoint");
    tree.create_checkpoint(&dst)?;

    // The immutable checkpoint must verify clean: reconciling the pending heal
    // before the snapshot means the captured digest matches the linked (healed)
    // bytes (pre-fix it captured the stale pre-heal digest and failed forever).
    let checkpoint = open_ecc_tree(&dst);
    let integrity = crate::verify::verify_integrity(&checkpoint);
    assert!(
        integrity.is_ok(),
        "the checkpoint must not capture a table's stale pre-heal digest, got {:?}",
        integrity.errors,
    );
    Ok(())
}

/// A real-on-disk [`Fs`](crate::fs::Fs) (over `StdFs`) whose `exists` probe
/// FAILS for any `.heal-attest` sidecar, modelling a stat error on the
/// attestation probe. Every other operation delegates to `StdFs`.
mod exists_fail_fs {
    use crate::fs::{Fs, FsDirEntry, FsFile, FsMetadata, FsOpenOptions, StdFs};
    use crate::io;
    use std::path::Path;

    pub(super) struct ExistsFailFs;

    impl Fs for ExistsFailFs {
        fn open(&self, path: &Path, opts: &FsOpenOptions) -> io::Result<Box<dyn FsFile>> {
            StdFs.open(path, opts)
        }
        fn create_dir_all(&self, path: &Path) -> io::Result<()> {
            StdFs.create_dir_all(path)
        }
        fn read_dir(&self, path: &Path) -> io::Result<Vec<FsDirEntry>> {
            StdFs.read_dir(path)
        }
        fn remove_file(&self, path: &Path) -> io::Result<()> {
            StdFs.remove_file(path)
        }
        fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
            StdFs.remove_dir_all(path)
        }
        fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
            StdFs.rename(from, to)
        }
        fn metadata(&self, path: &Path) -> io::Result<FsMetadata> {
            StdFs.metadata(path)
        }
        fn sync_directory(&self, path: &Path) -> io::Result<()> {
            StdFs.sync_directory(path)
        }
        fn exists(&self, path: &Path) -> io::Result<bool> {
            if path.to_string_lossy().ends_with(".heal-attest") {
                return Err(io::Error::other("injected attestation probe failure"));
            }
            StdFs.exists(path)
        }
        fn backend_id(&self) -> Option<u64> {
            StdFs.backend_id()
        }
        fn volume_id(&self, path: &Path) -> Option<u64> {
            StdFs.volume_id(path)
        }
    }
}

/// The checkpoint's pending-heal reconciliation probes each ECC table for a
/// `.heal-attest` sidecar. If that probe FAILS (an I/O error, not a clean
/// absent), treating it as "no pending heal" would let the checkpoint snapshot
/// the table's bytes under a possibly-stale digest with no marker to reconcile.
/// The probe must fail CLOSED: a probe error aborts the reconciliation, which
/// the checkpoint propagates (aborting the snapshot). Drives
/// [`reconcile_pending_heals`] directly — the exact step the checkpoint runs
/// before its link window — so the fault needs only the probe, not the
/// checkpoint's full filesystem surface.
#[test]
fn reconcile_pending_heals_aborts_when_the_attestation_probe_fails() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // A plain ECC table (no corruption needed): the reconcile still probes it
    // for a pending sidecar, and that probe is what fails here.
    let _ = write_ecc_sst_footered(dir.path());

    let tree = open_ecc_tree_on(
        dir.path(),
        std::sync::Arc::new(exists_fail_fs::ExistsFailFs),
    );

    let result = crate::scrub::reconcile_pending_heals(&tree);
    assert!(
        result.is_err(),
        "a failed attestation probe must abort the reconciliation, not silently \
         skip the table (pre-fix the probe error was swallowed as 'no pending heal'): \
         {result:?}",
    );
    Ok(())
}

/// The attributable heal path (the manifest digest matches the CURRENT pre-heal
/// bytes) is about to change bytes the manifest still matches, so its
/// crash-recovery attestation MUST be durable BEFORE the first block is mutated.
/// If the attestation cannot be persisted, the heal must ABORT (not proceed and
/// only log), because a crash after a corrected block syncs but before the
/// manifest refresh would leave healed bytes under the stale digest with no
/// marker, which fail-closed reconciliation rejects forever, permanently
/// stranding a table that was reconcilable a moment earlier. Leaving the block
/// corrupt keeps the table reconcilable; the next patrol retries.
#[test]
fn heal_in_place_aborts_when_the_attestation_cannot_be_persisted() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    // Seed the ATTRIBUTABLE reconcile scenario: rot a parity byte, then rebuild
    // the manifest over the rotted bytes so the manifest digest == the current
    // (pre-heal) file. `pre_heal_digest_matches` is then true and the heal would
    // change bytes the manifest currently matches (the only path that writes a
    // crash-recovery marker).
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;
    let before = std::fs::read(&sst_path)?;

    // Fault every open of the attestation sidecar so it can never be persisted.
    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));
    injector
        .arm(FaultRule::new(FaultOp::Open, Fault::Error(ErrorKind::Other)).on_path(".heal-attest"));

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    // The heal aborted: no block was mutated, so the file is byte-for-byte what
    // it was before the pass (pre-fix the heal proceeds and rewrites the block).
    assert_eq!(
        report.blocks_healed_in_place, 0,
        "the heal must not mutate any block when its attestation cannot be persisted: {report:?}",
    );
    let after = std::fs::read(&sst_path)?;
    assert_eq!(
        after, before,
        "the corrupt block must stay untouched so the table stays reconcilable",
    );
    // The skipped heal is surfaced as a finding, not silently swallowed.
    assert!(
        !report.is_ok(),
        "aborting the heal must surface a finding: {report:?}",
    );
    // A failed attestation write must not leave a partial marker behind.
    assert!(
        !heal_attest_path(&sst_path).exists(),
        "no partial attestation marker after a failed write",
    );
    Ok(())
}

/// A heal whose block WRITE landed but whose `sync_data` FAILED keeps its
/// attestation on purpose (the on-disk bytes may already differ from the
/// manifest digest, so a later patrol must still be able to attribute them).
/// That later patrol reads the corrected bytes back from the page cache and
/// finds the table clean — but refreshing the manifest digest then would
/// record a post-heal digest over bytes that were never synced: a power loss
/// discards the healed block while the manifest keeps the new digest, and the
/// table is permanently unreconcilable. The reconciliation must therefore sync
/// the SST data itself before refreshing, and keep reporting the table as
/// unreconciled when that sync fails.
#[test]
fn heal_reconcile_refuses_to_refresh_when_the_sst_data_cannot_be_synced() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());

    // Attributable heal scenario: rot a parity byte, rebuild the manifest over
    // the rotted bytes so the digest matches the CURRENT file.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;
    let manifest_digest = |tree: &crate::Tree| {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .map(crate::table::Table::checksum)
            .expect("the table is in the manifest")
    };

    // Heal with the SST's data sync faulted: the block write lands (so the
    // attestation is deliberately kept) while the bytes are never durable.
    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));
    let digest_before = manifest_digest(&tree);
    injector
        .arm(FaultRule::new(FaultOp::SyncData, Fault::Error(ErrorKind::Other)).on_path("tables"));
    let _ = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        heal_attest_path(&sst_path).exists(),
        "a write-attempted heal keeps its attestation for a later patrol",
    );

    // The follow-up patrol sees clean (page-cached) bytes and would refresh the
    // manifest digest through the marker — but the SST data still cannot be
    // synced, so the refresh must be refused.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        manifest_digest(&tree),
        digest_before,
        "the manifest digest must not be refreshed over bytes that were never \
         synced: a power loss would discard the healed block: {report:?}",
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "the marker survives so a later, syncable patrol can still reconcile",
    );
    Ok(())
}

/// The checkpoint's pre-window reconciliation only scans ECC tables, so a
/// pending `.heal-attest` marker it cannot consume (here: one on a non-ECC
/// table) whose digest is STALE — healed bytes not yet reconciled — must still
/// be caught by the post-link-window fail-closed guard rather than snapshot the
/// table under that stale digest with no marker. Models the residual race where
/// a genuine pending heal survives the pre-window reconcile. (A marker whose
/// digest already matches the manifest is obsolete and does NOT abort; see
/// [`abort_checkpoint_ignores_an_obsolete_marker_but_aborts_on_a_stale_digest`].)
#[test]
fn checkpoint_aborts_when_a_pending_marker_survives_the_pre_window_reconcile() -> crate::Result<()>
{
    use crate::AbstractTree;

    let dir = tempfile::tempdir()?;
    // A plain (non-ECC) tree: the pre-window reconcile scans only ECC tables,
    // so a marker planted here survives to the post-link-window guard.
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .open()?
    else {
        unreachable!("standard tree configured");
    };
    for i in 0u64..4 {
        tree.insert(format!("key-{i:03}"), format!("v{i:03}"), i);
    }
    tree.flush_active_memtable(4)?;
    let sst_path = {
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        (*table.path).clone()
    };

    // Make the on-disk digest diverge from the manifest so the surviving marker
    // models a GENUINE pending heal (healed bytes the reconcile has not caught
    // up to), the case the post-window guard must abort on. Flip an interior
    // byte (length and trailer intact); the manifest still records the pre-flip
    // digest.
    let mut bytes = std::fs::read(&sst_path)?;
    if let Some(b) = bytes.get_mut(50) {
        *b ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;
    // Plant a pending marker the ECC-only pre-window reconcile will not consume.
    std::fs::write(heal_attest_path(&sst_path), b"pending marker")?;

    let dst = dir.path().join("checkpoint");
    let result = tree.create_checkpoint(&dst);
    assert!(
        result.is_err(),
        "a pending marker with a stale digest the pre-window reconcile cannot consume must \
         abort the checkpoint at the post-link-window guard: {result:?}",
    );
    Ok(())
}

/// The pre-heal digest probe (`live_region_checksum`, a SEQUENTIAL full-file
/// read) can fail transiently. Converting that I/O error into an ordinary
/// "digest does not match the manifest" would let the heal proceed writing
/// corrections with NO completed attestation: if the manifest legitimately
/// describes the degraded pre-heal bytes (a rebuild over a correctable fault),
/// the healed digest then differs from the manifest and reconciliation rejects
/// it forever with no marker. The probe failure must ABORT the heal before the
/// first write, exactly like a digest-prediction / attestation-persistence
/// failure. Faults only the sequential `Read` (the digest probe); block loads
/// use `read_at`, so the correctable fault is still discovered.
#[test]
fn heal_in_place_aborts_when_the_pre_heal_digest_probe_fails() -> crate::Result<()> {
    use crate::fs::{Fault, FaultFs, FaultOp, FaultRule};
    use crate::io::ErrorKind;

    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst_footered(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;
    let before = std::fs::read(&sst_path)?;

    // Fail the sequential digest read only (block loads use read_at).
    let fault = FaultFs::new(crate::fs::StdFs);
    let injector = fault.injector();
    let tree = open_ecc_tree_on(dir.path(), std::sync::Arc::new(fault));
    injector.arm(FaultRule::new(FaultOp::Read, Fault::Error(ErrorKind::Other)).on_path("tables"));

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert_eq!(
        report.blocks_healed_in_place, 0,
        "a failed pre-heal digest probe must abort before any block is mutated: {report:?}",
    );
    let after = std::fs::read(&sst_path)?;
    assert_eq!(
        after, before,
        "the corrupt block must stay untouched so the table stays reconcilable",
    );
    assert!(
        !report.is_ok(),
        "aborting the heal must surface a finding: {report:?}",
    );
    Ok(())
}

/// An in-place heal that changes the SST's bytes must REFRESH the manifest's
/// full-file checksum. The heal itself restores the block's original bytes
/// (whose digest usually matches the manifest), but a table admitted by a
/// MANIFEST REBUILD while its parity was already rotted carries the digest of
/// the ROTTED bytes — a later heal then restores the original parity and
/// `verify_integrity` flags the freshly healed table as corrupt against the
/// stale digest, durably, on every scan.
#[test]
fn heal_in_place_refreshes_the_manifest_checksum() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte, then let a manifest rebuild admit the
    // table with the digest of the ROTTED bytes (parity-only rot grades
    // degraded-but-readable, so the rebuild keeps the file as-is).
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // Heal the trailer in place: the file's bytes return to their ORIGINAL
    // state, which no longer matches the rotted digest the rebuilt manifest
    // recorded.
    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted trailer is rebuilt in place: {report:?}",
    );

    // Without a manifest-checksum refresh, every later integrity scan flags
    // the freshly healed (fully verifiable) table as corrupt.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        integrity.is_ok(),
        "a healed table must verify clean against a refreshed manifest \
         checksum, got {:?}",
        integrity.errors,
    );

    // The refreshed checksum survives a reopen (persisted, not just patched
    // in memory).
    drop(tree);
    let tree = open_ecc_tree(dir.path());
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        integrity.is_ok(),
        "the refreshed checksum is durable across reopen, got {:?}",
        integrity.errors,
    );
    Ok(())
}

/// A reconciliation whose captured Table VIEW predates another patrol's
/// successful digest refresh must treat the already-reconciled file as
/// clean: the view's checksum snapshot is stale, but the CURRENT manifest
/// entry and the file agree, so there is nothing left to reconcile. Two
/// concurrent heal patrols hit exactly this interleaving — both capture
/// the same version before the per-table heal lock serializes them — and
/// on a footer-less table the loser has no attributable correction, so
/// the stale comparison surfaced as a spurious `ChecksumRefreshFailed`
/// on a healthy, already-reconciled table.
#[test]
fn checksum_refresh_is_idempotent_against_a_stale_table_view() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // Footer-less on purpose: without heal attribution the fail-closed
    // authoritative-content rule turns the stale mismatch into a finding.
    let (sst_path, block) = write_ecc_sst(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let tree = open_ecc_tree(dir.path());
    // Capture the table view BEFORE the heal, like a concurrently started
    // second patrol would.
    let stale_view = {
        let binding = tree.version_history.read().latest_version();
        binding
            .version
            .iter_tables()
            .next()
            .expect("one table")
            .clone()
    };

    // First patrol: heals the trailer in place and installs the refreshed
    // digest into the manifest.
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted trailer is rebuilt in place: {report:?}",
    );
    assert!(report.is_ok(), "the first patrol reconciles: {report:?}");

    // Second patrol's reconcile step, still holding the pre-heal view: the
    // current manifest and the file already agree, so it must be a no-op.
    let finding = refresh_healed_checksum(&tree, &stale_view, false);
    assert!(
        finding.is_none(),
        "an already-reconciled file must not be reported: {finding:?}",
    );
    Ok(())
}

/// A PINNED file descriptor (a tree opened without an FD cache) cannot be
/// retargeted at the private copy the hard-link unshare produces: after
/// the copy + rename this Table would keep reading the DEAD inode forever
/// — reads, scrub probes, and digest checks all resolve through the
/// pinned handle while the manifest and live path refer to the healed
/// copy. The heal must REFUSE the detach instead: the blocked write-backs
/// surface as findings and every checkpoint link stays byte-identical to
/// what its manifest describes.
#[test]
fn heal_in_place_refuses_to_detach_under_a_pinned_descriptor() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // A second hard link stands in for a checkpoint's snapshot.
    let link = dir.path().join("checkpoint-link");
    std::fs::hard_link(&sst_path, &link)?;

    // No descriptor table: every Table pins one FD at recover time.
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .use_descriptor_table(None)
    .open()
    .expect("open pinned ecc tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    // The refused detach specifically: an UncorrectableBlock finding whose
    // reason names the unshare refusal, not any unrelated failure.
    assert!(
        report.errors.iter().any(|e| matches!(
            e,
            ScrubError::UncorrectableBlock { reason, .. }
                if reason.starts_with("unshare hard-linked SST for heal: ")
        )),
        "a refused detach must surface as an unshare finding: {report:?}",
    );
    assert_eq!(
        report.blocks_healed_in_place, 0,
        "no block may be healed when the detach is refused: {report:?}",
    );
    assert_eq!(
        std::fs::read(&sst_path)?,
        std::fs::read(&link)?,
        "the live path must stay byte-identical to its checkpoint link (no detach)",
    );
    Ok(())
}

/// The pre-write ATTRIBUTION probe must compare against the CURRENT
/// manifest digest, not the caller's captured view: a reconciliation
/// running with a view captured before the manifest was re-recorded
/// (here: a manifest rebuilt over freshly rotted bytes after an earlier
/// heal already refreshed it) sees a stale checksum, marks a legitimate
/// heal unattributable, and the fail-closed rule then refuses to refresh
/// a footer-less table forever — even though the file's pre-write digest
/// matched the manifest exactly.
#[test]
fn heal_attribution_compares_against_the_current_manifest_digest() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    // Footer-less: without attribution the fail-closed rule turns the
    // refusal into a permanent ChecksumRefreshFailed.
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Heal cycle one: rot, record the rotted digest, heal + refresh.
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;
    let stale_view = {
        let tree = open_ecc_tree(dir.path());
        let stale = {
            let binding = tree.version_history.read().latest_version();
            binding
                .version
                .iter_tables()
                .next()
                .expect("one table")
                .clone()
        };
        let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
        assert!(report.is_ok(), "the first heal reconciles: {report:?}");
        stale
    };

    // Rot a SECOND fault — in a DIFFERENT block, so the rotted digest
    // differs from the first cycle's — and re-record the manifest over the
    // rotted bytes: the CURRENT manifest matches the file while the
    // captured view still carries the digest recorded before the first
    // heal.
    let second_block = {
        let keyed = stale_view
            .block_index
            .iter()
            .nth(1)
            .expect("the fixture writes several data blocks")
            .expect("block index entry decodes");
        crate::table::BlockHandle::new(keyed.offset(), keyed.size())
    };
    corrupt_parity_trailer_byte(&sst_path, &second_block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    let tree = open_ecc_tree(dir.path());
    let report = scan_and_reconcile(
        &tree,
        &stale_view,
        &PatrolScrubOptions::default().heal_in_place(true),
    );
    assert!(
        report.blocks_healed_in_place >= 1,
        "the second fault is rebuilt in place: {report:?}",
    );
    assert!(
        report.is_ok(),
        "a heal whose pre-write digest matches the CURRENT manifest is \
         attributable and must reconcile: {report:?}",
    );
    Ok(())
}

/// A manifest-digest refresh that FAILS after an in-place heal must surface in
/// the scrub report, not vanish into a log line: the heal already rewrote the
/// SST's bytes, so with the refresh lost a manifest that carried a stale
/// (pre-heal) digest keeps flagging the healed file as corrupt on every later
/// `verify_integrity` — while the patrol report claims a clean heal.
#[test]
fn heal_in_place_reports_a_failed_checksum_refresh() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, block) = write_ecc_sst(dir.path());

    // Rot one parity-trailer byte, then let a manifest rebuild record the
    // digest of the ROTTED bytes, so the heal's reconciliation actually has
    // a mismatch to persist (against a manifest that already holds the
    // correct digest the reconciliation is a no-op and never touches the
    // edit log).
    corrupt_parity_trailer_byte(&sst_path, &block)?;
    rebuild_manifest_over_current_bytes(dir.path())?;

    // Fail the manifest edit-log open the refresh performs; the heal itself
    // touches only the SST under tables/.
    let (tree, injector) = open_ecc_tree_with_failing_edit_log(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    injector.clear();

    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted trailer is rebuilt in place: {report:?}",
    );
    assert!(
        report
            .errors
            .iter()
            .any(|e| matches!(e, ScrubError::ChecksumRefreshFailed { .. })),
        "a failed manifest-digest refresh must be a scrub finding, not a \
         swallowed log line: {report:?}",
    );
    // The public status must fail too: a caller following `is_ok()` would
    // otherwise treat the scrub as clean while the manifest keeps a stale
    // digest that flags the healed SST on every later integrity scan.
    assert!(
        !report.is_ok(),
        "a scrub whose findings include a failed checksum refresh is not ok",
    );
    Ok(())
}

/// A heal pass that fixes one block while ANOTHER block in the same SST stays
/// uncorrectable must NOT refresh the manifest's full-file checksum: the
/// refreshed digest would be computed over the current bytes — including the
/// still-corrupt block — so a later `verify_integrity` would pass on an SST
/// with known, unrepaired corruption. The digest may only be restamped once
/// the file is fully healed.
#[test]
fn heal_in_place_skips_the_checksum_refresh_while_corruption_remains() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let (sst_path, first) = write_ecc_sst(dir.path());

    // The SECOND data block, to wreck beyond the RS budget.
    let second = {
        let tree = open_ecc_tree(dir.path());
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("one table recovered");
        let mut it = table.block_index.iter();
        let _ = it.next().expect("first block").expect("decodes");
        let keyed = it.next().expect("second block").expect("decodes");
        crate::table::BlockHandle::new(keyed.offset(), keyed.size())
    };

    // Block 1: rot one parity-trailer byte (heal-in-place rebuilds it).
    corrupt_parity_trailer_byte(&sst_path, &first)?;

    // Block 2: wreck the whole payload+parity (uncorrectable, left for salvage).
    let mut bytes = std::fs::read(&sst_path)?;
    let payload_start = second.offset().0 as usize + Header::MIN_LEN;
    let payload_end = second.offset().0 as usize + second.size() as usize;
    for slot in bytes
        .get_mut(payload_start..payload_end)
        .expect("second block payload range in bounds")
    {
        *slot ^= 0xFF;
    }
    std::fs::write(&sst_path, &bytes)?;

    // Manifest rebuild records the digest of the CORRUPT bytes.
    rebuild_manifest_over_current_bytes(dir.path())?;

    // Heal pass: block 1's trailer is rebuilt, block 2 stays uncorrectable.
    let tree = open_ecc_tree(dir.path());
    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));
    assert!(
        report.blocks_healed_in_place >= 1,
        "the rotted trailer is rebuilt in place: {report:?}",
    );
    assert!(
        report.uncorrectable_blocks >= 1,
        "the wrecked block is reported uncorrectable: {report:?}",
    );

    // The digest must NOT have been restamped over the still-corrupt bytes:
    // the file no longer matches ANY trustworthy digest, and the integrity
    // scan must keep flagging it until the corruption is actually repaired.
    let integrity = crate::verify::verify_integrity(&tree);
    assert!(
        !integrity.is_ok(),
        "an SST with a known uncorrectable block must keep failing \
         verify_integrity — restamping its manifest checksum would mask the \
         corruption",
    );
    Ok(())
}

/// A clean encrypted, columnar, Page-ECC SST heals in place with no findings.
/// Its data blocks are sealed as
/// [`BlockType::Columnar`](crate::table::block::BlockType::Columnar) and
/// encrypted through the AAD block path; the heal read must decrypt, decompress,
/// and verify them without reporting a healthy block as uncorrectable. (The AAD
/// block-type byte is reconstructed from the on-disk frame, not the caller's
/// block-type argument, so the heal read decrypts correctly regardless of the
/// argument — this guards that the whole encrypted-columnar heal path stays
/// clean.)
#[cfg(all(feature = "columnar", feature = "encryption", zstd_any))]
#[test]
fn heal_in_place_leaves_a_clean_encrypted_columnar_sst_with_no_findings() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let enc: std::sync::Arc<dyn crate::encryption::EncryptionProvider> =
        std::sync::Arc::new(crate::Aes256GcmProvider::new(&[0x51; 32]));
    let crate::AnyTree::Standard(tree) = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .page_ecc(true)
    .ecc_scheme(EccScheme::ReedSolomon {
        data_shards: 8,
        parity_shards: 2,
    })
    .with_encryption(Some(enc))
    .open()
    .expect("open encrypted ecc tree") else {
        unreachable!("standard tree configured (no kv separation)");
    };
    // Columnar layout: the flush transposes the memtable into
    // `BlockType::Columnar` data blocks (encrypted through the tree's provider).
    tree.update_runtime_config(|cfg| cfg.columnar = true)?;

    for i in 0u64..2_000 {
        tree.insert(format!("key-{i:06}"), format!("v{i:06}"), i);
    }
    tree.flush_active_memtable(2_000).expect("flush");

    // Precondition: the flush produced an encrypted columnar SST (columnar
    // layout + ECC parity + an encryption provider), so the heal read exercises
    // the AAD block path over `BlockType::Columnar` blocks.
    {
        let binding = tree.version_history.read().latest_version();
        let table = binding
            .version
            .iter_tables()
            .next()
            .expect("flush produced one table");
        assert!(table.metadata.columnar, "the SST is columnar");
        assert!(table.metadata.ecc_params.is_some(), "the SST carries ECC");
        assert!(table.encryption.is_some(), "the SST is encrypted");
    }

    let report = patrol_scrub(&tree, &PatrolScrubOptions::default().heal_in_place(true));

    assert!(
        report.blocks_scanned >= 1,
        "the columnar SST has at least one data block to scrub: {report:?}",
    );
    assert_eq!(
        report.uncorrectable_blocks, 0,
        "a clean encrypted columnar block must decrypt and verify cleanly, \
         not be reported uncorrectable: {report:?}",
    );
    assert!(
        report.is_ok(),
        "a clean encrypted columnar SST heals with no findings: {report:?}",
    );
    Ok(())
}

/// A `{id}.heal-attest` sidecar left in `tables/` by a crashed heal refresh
/// must NOT break the next `Tree::open`: the table-folder scan skips it (it is
/// never a table file) instead of parsing its name as a `TableId` and returning
/// `Unrecoverable`. Deleting it here would forfeit the crashed-refresh recovery,
/// so the scan leaves it for the next scrub to consume.
#[test]
fn tree_open_skips_a_lingering_heal_attestation() -> crate::Result<()> {
    let dir = tempfile::tempdir()?;
    let sst_path = {
        let crate::AnyTree::Standard(tree) = crate::Config::new(
            dir.path(),
            SequenceNumberCounter::default(),
            SequenceNumberCounter::default(),
        )
        .open()?
        else {
            unreachable!("standard tree configured");
        };
        for i in 0u64..50 {
            tree.insert(format!("k{i:04}"), b"v", i);
        }
        tree.flush_active_memtable(50)?;
        let binding = tree.version_history.read().latest_version();
        let Some(table) = binding.version.iter_tables().next() else {
            panic!("flush produced one table");
        };
        (*table.path).clone()
    };

    // A crashed refresh leaves this sidecar next to the SST.
    std::fs::write(heal_attest_path(&sst_path), b"pending attestation")?;

    // Reopen: the sidecar must be skipped, not parsed as a table id.
    let reopened = crate::Config::new(
        dir.path(),
        SequenceNumberCounter::default(),
        SequenceNumberCounter::default(),
    )
    .open();
    assert!(
        reopened.is_ok(),
        "a lingering heal-attest sidecar must not break open: {:?}",
        reopened.err(),
    );
    assert!(
        heal_attest_path(&sst_path).exists(),
        "open must leave the pending attestation for the next scrub to consume",
    );
    Ok(())
}