zeppelin-embed 0.8.0

In-process vector, lexical, and hybrid search for macOS and Apple silicon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
use super::publication::{
    DurabilityEvent, RecordingVfs, property_fixture, record_physical_for_lease, snapshot_for_lease,
};
use crate::epoch::{ComputeUnits, EmbeddingRuntime, EmbeddingTower, Normalization};
use crate::lifecycle::durability::{CommitTier, DurabilityMode};
use crate::lifecycle::{CancelToken, OpenOptions, QueryControl, Store};
use crate::property_graph::staging::{StructuredOperation, StructuredWrite, WriteImage};
use crate::property_graph::staging::{WriteLimits, WriteMemory};
use crate::property_graph::storage::NativePreparationSource;
use crate::property_graph::storage::inventory::{
    force_next_contradictory_inventory_addition, force_next_incomplete_inventory_retirement,
    inventory_resume_after, validate_fold_conservation, verify_inventory_entry,
};
use crate::property_graph::storage::memory::StorageMemory;
use crate::property_graph::storage::reclaim::{
    DurableRunReader, ProtectedClass, ProtectedRecord, ProtectedValue, omit_mark_artifact_for_test,
    take_omitted_mark_emissions_for_test, validate_protected_stream,
};

use crate::property_graph::storage::tree::TreeKind;
use crate::property_graph::storage::tree::directory::{BlockSource, DirectoryCursor};
use crate::property_graph::wal::{ArtifactDescriptor, InventoryChange, InventoryState};
use crate::property_graph::{
    ApplicationKey, CanonicalContents, CanonicalEmbedding, EntityId, EntityKind, GraphName,
    GraphRevision, NodeRef,
};
use crate::vfs::Vfs;
use std::collections::BTreeMap;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::sync::{Arc, Barrier};

fn directory_image(path: &Path) -> BTreeMap<std::ffi::OsString, Vec<u8>> {
    std::fs::read_dir(path)
        .expect("read native directory")
        .map(|entry| {
            let entry = entry.expect("native directory entry");
            let name = entry.file_name();
            let bytes = std::fs::read(entry.path()).expect("read native file");
            (name, bytes)
        })
        .collect()
}

fn decode_persisted_manifest(payload: &[u8], owner: ArtifactDescriptor) -> Vec<InventoryChange> {
    assert_eq!(
        payload.get(..8),
        Some([b'Z', b'G', b'C', b'P', 2, 0, 1, 0].as_slice())
    );
    let count = u32::from_le_bytes(payload[8..12].try_into().expect("manifest count"));
    assert_eq!(payload.get(12..16), Some([0_u8; 4].as_slice()));
    assert_eq!(payload.len(), 16 + count as usize * 64);
    let mut output = Vec::new();
    for row in payload[16..].chunks_exact(64) {
        output.push(InventoryChange {
            object: ArtifactDescriptor {
                store: crate::property_graph::StoreInstanceId::new(u128::from_le_bytes(
                    row[0..16].try_into().expect("descriptor store"),
                ))
                .expect("nonzero descriptor store"),
                artifact: crate::property_graph::storage::artifact::ArtifactId::new(
                    u128::from_le_bytes(row[16..32].try_into().expect("descriptor artifact")),
                )
                .expect("nonzero descriptor artifact"),
                generation: crate::property_graph::GraphGeneration::new(u64::from_le_bytes(
                    row[32..40].try_into().expect("descriptor generation"),
                )),
                serial: u64::from_le_bytes(row[40..48].try_into().expect("descriptor serial")),
                bytes: u32::from_le_bytes(row[48..52].try_into().expect("descriptor bytes")),
                family: u16::from_le_bytes(row[52..54].try_into().expect("descriptor family")),
                version: u16::from_le_bytes(row[54..56].try_into().expect("descriptor version")),
                checksum: u64::from_le_bytes(row[56..64].try_into().expect("descriptor checksum")),
            },
            state: InventoryState::Retained,
        });
    }
    output.push(InventoryChange {
        object: owner,
        state: InventoryState::Retained,
    });
    output
}

fn prepared_union_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<InventoryChange> {
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 64).expect("preparation source");
    let mut resources = source.resources(128 * 1024 * 1024).expect("tree resources");
    let mut output = Vec::new();
    for required in lease.bundle().prepared_inventories() {
        let block = source
            .resolve(required.block, &mut resources)
            .expect("resolve persisted prepared inventory");
        assert_eq!(block.identity().artifact, required.object.artifact);
        assert_eq!(block.reference(), required.block);
        assert_eq!(block.file_length(), required.object.bytes as usize);
        assert_eq!(block.file_checksum(), required.object.checksum);
        output.extend(decode_persisted_manifest(block.payload(), required.object));
    }
    output.sort_unstable_by_key(|change| change.object.artifact);
    output.dedup_by(|right, left| {
        if left.object.artifact != right.object.artifact {
            return false;
        }
        assert_eq!(left.object, right.object, "contradictory persisted union");
        true
    });
    output
}

fn prepared_manifest_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
    required: crate::property_graph::wal::RequiredRef,
) -> Vec<InventoryChange> {
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 8).expect("preparation source");
    let mut resources = source.resources(16 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve selected prepared inventory");
    assert_eq!(block.reference(), required.block);
    assert_eq!(block.file_checksum(), required.object.checksum);
    decode_persisted_manifest(block.payload(), required.object)
}

fn complete_inventory_union_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<InventoryChange> {
    let mut output = rooted_inventory_for_lease(store, lease);
    output.extend(prepared_union_for_lease(store, lease));
    output.sort_unstable_by_key(|change| change.object.artifact);
    output.dedup_by(|right, left| {
        if left.object.artifact != right.object.artifact {
            return false;
        }
        assert_eq!(left.object, right.object, "contradictory complete union");
        true
    });
    let mut by_serial = output.clone();
    by_serial.sort_unstable_by_key(|change| change.object.serial);
    for pair in by_serial.windows(2) {
        assert!(
            pair[0].object.serial != pair[1].object.serial
                || pair[0].object.artifact == pair[1].object.artifact,
            "duplicate complete-union serial"
        );
    }
    output
}

fn rooted_inventory_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<InventoryChange> {
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 32).expect("preparation source");
    let mut resources = source.resources(128 * 1024 * 1024).expect("tree resources");
    let root = lease
        .bundle()
        .roots()
        .directory(TreeKind::ObjectInventory)
        .expect("inventory root");
    let mut cursor =
        DirectoryCursor::seek(&source, root, None, &mut resources).expect("inventory cursor");
    let mut output = Vec::new();
    while let Some(entry) = cursor.next_entry(&mut resources).expect("inventory entry") {
        output.push(verify_inventory_entry(root, entry, &mut resources).expect("inventory row"));
    }
    output
}

fn options() -> OpenOptions {
    OpenOptions::new()
        .with_durability(DurabilityMode::Durable, CommitTier::Durable)
        .with_max_resident_bytes(256 * 1024 * 1024)
}

pub(super) fn pending_reclaim_candidates(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<ArtifactDescriptor> {
    pending_reclaim_proof_for_lease(store, lease).1
}

pub(super) fn pending_reclaim_proof_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> (
    crate::property_graph::storage::reclaim::PendingIntentManifest,
    Vec<ArtifactDescriptor>,
) {
    let Some(required) = lease.bundle().reclaim() else {
        panic!("pending reclaim root");
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 1).expect("reclaim source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve reclaim state");
    let manifest =
        crate::property_graph::storage::reclaim::decode_pending_intent_manifest(block.payload())
            .expect("pending reclaim manifest");
    let candidates = (0..manifest.candidate_count)
        .map(|index| {
            crate::property_graph::storage::reclaim::pending_intent_candidate_at(
                block.payload(),
                index,
            )
            .expect("pending reclaim candidate")
        })
        .collect();
    (manifest, candidates)
}

fn create_reclaim_test_store(path: &Path, vfs: &Arc<RecordingVfs>) -> Store {
    let infrastructure: Arc<dyn Vfs> = vfs.clone();
    Store::create_native_graph_with_infrastructure(
        path,
        options(),
        None,
        infrastructure,
        Arc::new(crate::lifecycle::SystemMonotonicClock),
        &mut crate::property_graph::storage::allocation::OsEntropy,
    )
    .expect("fresh reclaim proof store")
}

pub(super) fn seed_reclaimable_manifest(store: &Store, name: &str) {
    let image = CanonicalContents::node(&mut [], &mut [], Some("reclaim proof"), None)
        .expect("reclaim proof node image");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "reclaim-proof", name)
                    .expect("reclaim proof key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("seed reclaim proof object");
    let first = store
        .admit_native_graph_maintenance()
        .expect("first reclaim proof admission");
    store
        .commit_native_graph_maintenance(&first, &QueryControl::Cancel(CancelToken::new()))
        .expect("first reclaim proof replacement");
    drop(first);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint reclaim proof history");
}

fn cap_one_inventory_addition() -> super::super::maintenance::MaintenanceLimits {
    super::super::maintenance::MaintenanceLimits {
        inventory_additions: 1,
        ..Default::default()
    }
}

#[test]
fn maintenance_work_budget_follows_inventory_bytes() {
    use crate::property_graph::storage::preparation_work_capture as capture;
    const MINIMUM: u64 = 1024 * 1024 * 1024;
    assert_eq!(
        super::super::maintenance::maintenance_work_limit(MINIMUM / 8 + 1)
            .expect("scaled work budget"),
        MINIMUM + 8
    );

    let parent = tempfile::tempdir().expect("maintenance budget parent");
    let path = parent.path().join("native");
    let store =
        Store::create_native_graph(&path, options(), None).expect("maintenance budget store");
    let image = CanonicalContents::node(&mut [], &mut [], Some("inventory"), None)
        .expect("maintenance budget node");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "budget", "seed")
                    .expect("maintenance budget key"),
                revision: GraphRevision::new(1).expect("maintenance budget revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("seed maintenance inventory");

    capture::start();
    commit_maintenance(&store).expect("maintenance from inventory-sized budget");
    let report = capture::take();
    let expected = (1024 * 1024 * 1024_u64).max(
        report
            .maintenance_inventory_bytes
            .checked_mul(8)
            .expect("test inventory byte total fits"),
    );
    assert!(report.maintenance_inventory_bytes > 0);
    assert_eq!(report.maintenance_work_limit, Some(expected));
    println!(
        "ZE-431 maintenance inventory_bytes={} work_limit={}",
        report.maintenance_inventory_bytes,
        report.maintenance_work_limit.unwrap()
    );
}

#[test]
fn maintenance_work_budget_overflow_is_work() {
    use crate::property_graph::storage::tree::directory::TreeError;
    assert!(matches!(
        super::super::maintenance::maintenance_work_limit(u64::MAX / 8 + 1),
        Err(super::super::NativeGraphError::Read(TreeError::Work))
    ));
}

#[test]
fn maintenance_start_resume_retire_receive_inventory_budget() {
    use crate::property_graph::storage::preparation_work_capture as capture;
    let (_history, store) = seed_crash_history();
    for phase in [
        "maintenance-start",
        "maintenance-resume-start",
        "maintenance-retirement-start",
    ] {
        capture::start();
        commit_maintenance(&store).expect("complete maintenance phase");
        let report = capture::take();
        assert!(report.phases.iter().any(|(name, _)| *name == phase));
        assert!(report.maintenance_inventory_bytes > 0, "{phase}");
        assert_eq!(
            report.maintenance_work_limit,
            Some(
                super::super::maintenance::maintenance_work_limit(
                    report.maintenance_inventory_bytes
                )
                .expect("inventory budget")
            ),
            "{phase}"
        );
    }
}

#[test]
fn maintenance_census_shares_work_limit_and_skips_fold_retry() {
    use crate::property_graph::storage::preparation_work_capture as capture;
    let parent = tempfile::tempdir().expect("census parent");
    let store = Store::create_native_graph(parent.path().join("native"), options(), None)
        .expect("census store");
    seed_reclaimable_manifest(&store, "census");
    // Make the base need a fold before the actual reclaim preparation.
    let image = CanonicalContents::node(&mut [], &mut [], Some("next"), None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "census", "next").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
    capture::start();
    commit_maintenance(&store).expect("census maintenance");
    let report = capture::take();
    let census: Vec<_> = report
        .phases
        .iter()
        .filter(|(name, _)| *name == "maintenance-census-end")
        .collect();
    assert_eq!(census.len(), 1, "fold retry must not run a census");
    assert!(census[0].1 > 0);
    assert_eq!(
        report
            .phases
            .iter()
            .find(|(name, _)| *name == "maintenance-start")
            .unwrap()
            .1,
        census[0].1,
        "census work must enter the preparation ledger"
    );
}

fn assert_live_files_unchanged(path: &Path, before: &BTreeMap<std::ffi::OsString, Vec<u8>>) {
    let after = directory_image(path);
    for (name, bytes) in before {
        assert_eq!(after.get(name), Some(bytes), "live file changed: {name:?}");
    }
}

fn durable_proof_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> (
    Vec<ProtectedRecord>,
    Vec<crate::property_graph::storage::artifact::ArtifactId>,
) {
    let capture = store
        .capture_native_read_roots()
        .expect("capture durable proof roots");
    let proof = *capture.proofs().last().expect("latest durable proof");
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("durable proof resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("durable proof memory");
    let memory =
        StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("durable proof storage");
    let mut resources =
        crate::property_graph::storage::tree::directory::TreeResources::for_prepare(
            &memory,
            64 * 1024 * 1024,
        )
        .expect("durable proof tree resources");
    let reader = super::super::maintenance::spill::NativeSpillReader::new(
        lease,
        &memory,
        proof.protected.binding.target_generation,
    )
    .expect("durable proof reader");
    let mut records = Vec::new();
    validate_protected_stream(
        proof.protected,
        &reader,
        &memory,
        &mut resources,
        |record, _| {
            records.push(record);
            Ok(())
        },
    )
    .expect("decode protected stream");
    let mut mark = DurableRunReader::new(proof.mark, &memory).expect("durable mark reader");
    let mut artifacts = Vec::new();
    while let Some(artifact) = mark
        .next(&reader, &mut resources)
        .expect("decode completed mark")
    {
        artifacts.push(artifact);
    }
    drop(capture);
    (records, artifacts)
}
#[test]
fn ze46_real_consolidation_preserves_exact_state_and_reopens() {
    run_ze46_real_consolidation_preserves_exact_state_and_reopens();
}

fn run_ze46_real_consolidation_preserves_exact_state_and_reopens() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let document = EmbeddingTower {
        model_id: "ze46-document".into(),
        model_version: "1".into(),
        weights_digest: vec![0x46, 0xa5],
        dims: 2,
        normalization: Normalization::None,
        prompt_prefix: "doc: ".into(),
        max_tokens: 32,
        runtime: EmbeddingRuntime::CpuReference,
        compute_units: ComputeUnits::Cpu,
        os_build: None,
    };
    let store = Store::create_native_graph(&path, options(), Some(document.clone()))
        .expect("fresh native store");
    let coordinates = [f32::from_bits(0x3f80_0046), f32::from_bits(0x8000_0000)];
    let peer_coordinates = [f32::from_bits(0x4000_0046), f32::from_bits(0x3f00_0000)];
    let receipts = crate::property_graph::with_local_refs(|refs| {
        let label = GraphName::new("Document").expect("label");
        let mut labels = [label];
        let embedding = CanonicalEmbedding::new(&document, &coordinates).expect("embedding");
        let mut properties = property_fixture();
        let first = CanonicalContents::node(
            &mut labels,
            &mut properties,
            Some("exact ze46 text"),
            Some(embedding),
        )
        .expect("first node");
        let peer_embedding =
            CanonicalEmbedding::new(&document, &peer_coordinates).expect("peer embedding");
        let second = CanonicalContents::node(
            &mut [],
            &mut [],
            Some("exact ze46 peer text"),
            Some(peer_embedding),
        )
        .expect("second node");
        let requests = [
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "app", "a").expect("node key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&first)),
            },
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "app", "b").expect("node key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&second)),
            },
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "app", "ab")
                    .expect("relationship key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).expect("node slot")),
                    target: NodeRef::Local(refs.node(1).expect("node slot")),
                    relationship_type: GraphName::new("LINKS").expect("relationship type"),
                    properties: &[],
                }),
            },
        ];
        store
            .apply_native_graph(&requests, &QueryControl::Cancel(CancelToken::new()))
            .expect("mixed graph commit")
    });
    let first = match receipts[0].entity {
        EntityId::Node(node) => node,
        EntityId::Relationship(_) => panic!("first receipt identity"),
    };
    let second = match receipts[1].entity {
        EntityId::Node(node) => node,
        EntityId::Relationship(_) => panic!("second receipt identity"),
    };
    let relationship = match receipts[2].entity {
        EntityId::Relationship(rel) => rel,
        EntityId::Node(_) => panic!("relationship receipt identity"),
    };

    let old_lazy = store.admit_native_read().expect("unmapped retained reader");
    let before_lease = store.admit_native_read().expect("before reader");
    let before_roots = before_lease.bundle().roots().references();
    let before_text_root = before_lease.bundle().text();
    let before_vector_root = before_lease.bundle().vector();
    let before = snapshot_for_lease(&store, &before_lease, first, second, relationship, None);
    let peer_before = snapshot_for_lease(&store, &before_lease, second, first, relationship, None);
    let before_record = record_physical_for_lease(&store, &before_lease, first);
    let before_peer_record = record_physical_for_lease(&store, &before_lease, second);
    drop(before_lease);
    let _selection = crate::property_graph::storage::consolidation::pin_selection_for_test(first);
    let admitted = store
        .admit_native_graph_maintenance()
        .expect("maintenance admission");
    let report = store
        .commit_native_graph_maintenance(&admitted, &QueryControl::Cancel(CancelToken::new()))
        .expect("maintenance commit");
    assert!(report.replaced_physical_refs > 0);
    assert!(report.new_pack_bytes > 0);
    assert_eq!(report.generation.get(), before.generation + 2);

    let current = store.admit_native_read().expect("current reader");
    let after_roots = current.bundle().roots().references();
    assert_eq!(current.bundle().text(), before_text_root);
    assert_eq!(current.bundle().vector(), before_vector_root);
    assert_ne!(
        after_roots[0], before_roots[0],
        "node directory did not move"
    );
    assert_ne!(after_roots[5], before_roots[5], "OUT range did not move");
    assert_ne!(after_roots[6], before_roots[6], "IN range did not move");
    let after = snapshot_for_lease(&store, &current, first, second, relationship, None);
    let peer_after = snapshot_for_lease(&store, &current, second, first, relationship, None);
    let after_record = record_physical_for_lease(&store, &current, first);
    let after_peer_record = record_physical_for_lease(&store, &current, second);
    assert_eq!(after.generation, before.generation + 2);
    assert_eq!(after.revision, before.revision);
    assert_eq!(after.original_generation, before.original_generation);
    assert_eq!(after.canonical, before.canonical);
    assert_eq!(after.text, before.text);
    assert_eq!(after.vector, coordinates.map(f32::to_bits));
    assert_eq!(after.out, before.out);
    assert_eq!(after.incoming, before.incoming);
    assert_eq!(after.sparse_text, before.sparse_text);
    assert_eq!(after.sparse_vector, before.sparse_vector);
    assert_eq!(peer_after.canonical, peer_before.canonical);
    assert_eq!(peer_after.text, peer_before.text);
    assert_eq!(peer_after.vector, peer_coordinates.map(f32::to_bits));
    assert_eq!(peer_after.sparse_text, peer_before.sparse_text);
    assert_eq!(peer_after.sparse_vector, peer_before.sparse_vector);
    assert_ne!(before_record, after_record);
    assert_eq!(
        before_peer_record, after_peer_record,
        "unselected peer record remains immutable"
    );
    drop(current);

    let old_after = snapshot_for_lease(&store, &old_lazy, first, second, relationship, None);
    assert_eq!(old_after, before);
    let old_peer_after = snapshot_for_lease(&store, &old_lazy, second, first, relationship, None);
    assert_eq!(old_peer_after, peer_before);
    drop(old_lazy);
    drop(admitted);
    store.close().expect("close before reopen");

    let reopened = Store::open_native_graph(&path, options(), Some(document.clone()))
        .expect("reopen maintenance state");
    let reopened_lease = reopened.admit_native_read().expect("reopened reader");
    let reopened_snapshot = snapshot_for_lease(
        &reopened,
        &reopened_lease,
        first,
        second,
        relationship,
        None,
    );
    assert_eq!(reopened_snapshot, after);
    drop(reopened_lease);

    let replay = crate::property_graph::with_local_refs(|refs| {
        let label = GraphName::new("Document").expect("label");
        let mut labels = [label];
        let embedding = CanonicalEmbedding::new(&document, &coordinates).expect("embedding");
        let mut properties = property_fixture();
        let first_image = CanonicalContents::node(
            &mut labels,
            &mut properties,
            Some("exact ze46 text"),
            Some(embedding),
        )
        .expect("first node");
        let peer_embedding =
            CanonicalEmbedding::new(&document, &peer_coordinates).expect("peer embedding");
        let second_image = CanonicalContents::node(
            &mut [],
            &mut [],
            Some("exact ze46 peer text"),
            Some(peer_embedding),
        )
        .expect("second node");
        let requests = [
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "app", "a").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&first_image)),
            },
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "app", "b").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&second_image)),
            },
            StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "app", "ab").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            },
        ];
        reopened
            .apply_native_graph(&requests, &QueryControl::Cancel(CancelToken::new()))
            .expect("exact keyed replay")
    });
    assert!(replay.iter().all(|receipt| receipt.replayed));
    assert!(
        replay
            .iter()
            .all(|receipt| receipt.generation.get() == before.original_generation)
    );
    reopened.close().expect("close reopened store");
}

/// The node directory's raw value for `node`: its physical record reference.
pub(crate) fn node_directory_value(
    store: &Store,
    lease: &super::super::NativeReadLease,
    node: crate::property_graph::NodeId,
) -> Vec<u8> {
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 8).expect("directory source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let root = lease
        .bundle()
        .roots()
        .directory(TreeKind::Nodes)
        .expect("node directory root");
    crate::property_graph::storage::tree::directory::lookup_entry(
        &source,
        root,
        &node.get().to_le_bytes(),
        &mut resources,
    )
    .expect("node directory lookup")
    .expect("node directory entry")
    .value()
    .to_vec()
}

#[test]
fn ze260_maintenance_moves_an_oversized_oldest_record_alone() {
    use crate::property_graph::{GraphProperty, PropertyData, PropertyValue};
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let large = "x".repeat(1024 * 1024 + 1);
    let mut properties = [GraphProperty::new(
        GraphName::new("large").unwrap(),
        PropertyValue::new(PropertyData::String(&large)).unwrap(),
    )];
    let image = CanonicalContents::node(&mut [], &mut properties, None, None).unwrap();
    let small = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    let garbage = "g".repeat(2 * 1024 * 1024);
    let mut garbage_properties = [GraphProperty::new(
        GraphName::new("garbage").unwrap(),
        PropertyValue::new(PropertyData::String(&garbage)).unwrap(),
    )];
    let garbage_image =
        CanonicalContents::node(&mut [], &mut garbage_properties, None, None).unwrap();
    let writes = [
        (&image, "large"),
        (&small, "small"),
        (&garbage_image, "garbage"),
    ]
    .map(|(image, name)| StructuredWrite {
        key: ApplicationKey::new(EntityKind::Node, "oversized", name).unwrap(),
        revision: GraphRevision::new(1).unwrap(),
        operation: StructuredOperation::Create,
        image: Some(WriteImage::Node(image)),
    });
    let receipts = store
        .apply_native_graph(&writes, &QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    let nodes = receipts
        .iter()
        .map(|receipt| match receipt.entity {
            EntityId::Node(node) => node,
            EntityId::Relationship(_) => panic!("expected node"),
        })
        .collect::<Vec<_>>();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "oversized", "garbage").unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Put(receipts[2].entity),
                image: Some(WriteImage::Node(&small)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
    let maintenance = || {
        let admission = store.admit_native_graph_maintenance().unwrap();
        store
            .commit_native_graph_maintenance_with_limits(
                &admission,
                &QueryControl::Cancel(CancelToken::new()),
                super::super::maintenance::MaintenanceLimits {
                    relocation_bytes: 1024 * 1024,
                    ..Default::default()
                },
            )
            .unwrap()
    };
    let records = || {
        let lease = store.admit_native_read().unwrap();
        nodes
            .iter()
            .map(|node| node_directory_value(&store, &lease, *node))
            .collect::<Vec<_>>()
    };
    let before = records();
    let first = maintenance();
    eprintln!(
        "oversized cycle 1: drained={}, copied={}",
        first.drained_packs, first.relocated_bytes
    );
    let after = records();
    assert_ne!(after[0], before[0], "oversized oldest record must move");
    assert_eq!(after[1], before[1], "oversized record must move alone");
    let second = maintenance();
    eprintln!(
        "oversized cycle 2: drained={}, copied={}",
        second.drained_packs, second.relocated_bytes
    );
    assert_ne!(records()[1], after[1], "remaining small record must move");
    store.close().unwrap();
}

#[test]
fn ze260_small_packs_merge_only_in_groups() {
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let mut nodes = Vec::new();
    let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    for batch in 0..15 {
        let receipts = store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "small-packs", &batch.to_string())
                        .unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .unwrap();
        let EntityId::Node(node) = receipts[0].entity else {
            panic!("node");
        };
        nodes.push(node);
        if batch == 11 {
            store
                .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
                .unwrap();
            let report = commit_maintenance(&store).unwrap();
            eprintln!(
                "small cycle 1: drained={}, copied={}",
                report.drained_packs, report.relocated_bytes
            );
            assert_eq!(report.drained_packs, 12);
        }
    }
    let records = || {
        let lease = store.admit_native_read().unwrap();
        nodes[..11]
            .iter()
            .map(|node| node_directory_value(&store, &lease, *node))
            .collect::<Vec<_>>()
    };
    let before = records();
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    // S6c's first preparation can leave an intent. Finish it before
    // measuring a second preparation; completion itself never drains packs.
    for _ in 0..4 {
        let pending = store
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_some();
        if !pending {
            break;
        }
        match commit_maintenance(&store) {
            Ok(_) | Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("finish prior intent: {error:?}"),
        }
    }
    assert!(
        store
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_none()
    );
    let report = commit_maintenance(&store).unwrap();
    eprintln!(
        "small cycle 2: drained={}, copied={}",
        report.drained_packs, report.relocated_bytes
    );
    assert_ne!(
        records(),
        before,
        "the fixture's leaf pages died, so the quarter-dead rule applies"
    );
    // Fully live small packs are different: seven wait, eight merge.
    {
        use crate::property_graph::storage::artifact::ArtifactId;
        use crate::property_graph::storage::consolidation::{PackCensus, select_drain};
        let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
        let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
        let mut census: Vec<_> = (1..=8)
            .map(|id| PackCensus {
                artifact: ArtifactId::new(id).unwrap(),
                serial: id as u64,
                bytes: 4096,
                live: 4000,
                live_pages: 0,
                live_records: 1,
                graph_live: true,
            })
            .collect();
        for count in 1..8 {
            assert!(
                select_drain(&mut census[..count], 8 * 1024 * 1024, &memory)
                    .unwrap()
                    .as_slice()
                    .is_empty()
            );
        }
        assert_eq!(
            select_drain(&mut census, 8 * 1024 * 1024, &memory)
                .unwrap()
                .as_slice()
                .len(),
            8
        );
    }
    store.close().unwrap();
}

#[test]
fn ze260_drain_never_recopies_a_maintenance_pack() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    for batch in 0..20 {
        crate::property_graph::with_local_refs(|refs| {
            let names: Vec<_> = (0..10).map(|n| format!("{batch}-{n}")).collect();
            let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
            let mut writes: Vec<_> = names
                .iter()
                .map(|name| StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "drain", name).unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                })
                .collect();
            writes.push(StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "drain", &names[0]).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            });
            store
                .apply_native_graph(&writes, &QueryControl::Cancel(CancelToken::new()))
                .unwrap();
        });
    }

    let values = || {
        let lease = store.admit_native_read().unwrap();
        let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
        let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
        let source = NativePreparationSource::new(&lease, &memory, 512).unwrap();
        let mut r = source.resources(128 * 1024 * 1024).unwrap();
        let mut values = Vec::new();
        for kind in [TreeKind::Nodes, TreeKind::Relationships] {
            let root = lease.bundle().roots().directory(kind).unwrap();
            let mut cursor = DirectoryCursor::seek(&source, root, None, &mut r).unwrap();
            while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
                values.push(entry.value().to_vec());
            }
        }
        let mut ranges = Vec::new();
        for kind in [TreeKind::OutRanges, TreeKind::InRanges] {
            let root = lease.bundle().roots().directory(kind).unwrap();
            let mut cursor = DirectoryCursor::seek(&source, root, None, &mut r).unwrap();
            while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
                let crate::property_graph::storage::tree::Key::Inline(key) = entry.key() else {
                    panic!("range key");
                };
                let descriptor =
                    crate::property_graph::storage::adjacency::RangeDescriptor::decode(
                        kind,
                        key,
                        entry.value(),
                    )
                    .unwrap();
                ranges.extend(
                    std::iter::once(descriptor.base())
                        .chain(descriptor.deltas())
                        .map(|reference| reference.artifact),
                );
            }
        }
        (values, ranges)
    };
    let original = values().0;
    let old_packs: std::collections::BTreeSet<_> = original[..190]
        .iter()
        .map(|value| {
            crate::property_graph::storage::payload::PayloadRef::decode(value)
                .unwrap()
                .reference()
                .artifact
        })
        .collect();
    assert_eq!(old_packs.len(), 19);
    let mut after_first = Vec::new();
    for cycle in 1..=4 {
        // Count preparations, not completion/retirement or checkpoint retries.
        for _ in 0..4 {
            let pending = store
                .admit_native_read()
                .unwrap()
                .bundle()
                .reclaim()
                .is_some();
            if !pending {
                break;
            }
            match commit_maintenance(&store) {
                Ok(_) | Err(super::super::NativeGraphError::StalePreparation) => {}
                Err(error) => panic!("finish prior intent: {error:?}"),
            }
        }
        assert!(
            store
                .admit_native_read()
                .unwrap()
                .bundle()
                .reclaim()
                .is_none()
        );
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        let report = commit_maintenance(&store).unwrap();
        let (current, ranges) = values();
        eprintln!(
            "cycle {cycle}: drained={}, copied={}, refs={}",
            report.drained_packs, report.relocated_bytes, report.replaced_physical_refs
        );
        assert_eq!(report.drained_packs, [19, 1, 0, 0][cycle - 1]);
        if cycle >= 3 {
            assert_eq!(report.relocated_bytes, 0);
        }
        if cycle == 1 {
            for value in current[..190].iter().chain(&current[200..219]) {
                assert!(
                    !old_packs.contains(
                        &crate::property_graph::storage::payload::PayloadRef::decode(value)
                            .unwrap()
                            .reference()
                            .artifact
                    )
                );
            }
            assert!(
                ranges.iter().all(|artifact| !old_packs.contains(artifact)),
                "range payload still pins a drained pack"
            );
            after_first = current;
        } else if cycle >= 3 {
            assert!(
                current[..190] == after_first[..190] && current[200..219] == after_first[200..219],
                "maintenance must not recopy drained records"
            );
        }
    }
    store.close().unwrap();
}

#[test]
fn ze260_maintenance_drains_the_oldest_pack_in_one_call() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    for batch in 0..20 {
        crate::property_graph::with_local_refs(|refs| {
            let names: Vec<_> = (0..10).map(|n| format!("{batch}-{n}")).collect();
            let image = CanonicalContents::node(&mut [], &mut [], Some("payload"), None).unwrap();
            let mut writes: Vec<_> = names
                .iter()
                .map(|name| StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "drain", name).unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                })
                .collect();
            writes.push(StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "drain", &names[0]).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            });
            store
                .apply_native_graph(&writes, &QueryControl::Cancel(CancelToken::new()))
                .unwrap();
        });
    }
    let records = |lease: &super::super::NativeReadLease, newer_than: Option<u64>| {
        use crate::property_graph::storage::{
            NativePreparationCatalog, payload::PayloadRef, records::verify_record,
            stream::PayloadSlice, tree::Key,
        };
        let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
        let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
        let source = NativePreparationSource::new(lease, &memory, 512).unwrap();
        let mut resources = source.resources(128 * 1024 * 1024).unwrap();
        let catalog = NativePreparationCatalog::open(&source, &mut resources).unwrap();
        let mut records = BTreeMap::new();
        let mut counts = [0; 2];
        for (index, kind) in [TreeKind::Nodes, TreeKind::Relationships]
            .into_iter()
            .enumerate()
        {
            let root = lease.bundle().roots().directory(kind).unwrap();
            let mut cursor = DirectoryCursor::seek(&source, root, None, &mut resources).unwrap();
            while let Some(entry) = cursor.next_entry(&mut resources).unwrap() {
                let Key::Inline(key) = entry.key() else {
                    panic!("entity key must be inline");
                };
                let id = u128::from_le_bytes(key.try_into().unwrap());
                let entity = if kind == TreeKind::Nodes {
                    EntityId::Node(crate::property_graph::NodeId::new(id).unwrap())
                } else {
                    EntityId::Relationship(crate::property_graph::RelId::new(id).unwrap())
                };
                let reference = PayloadRef::decode(entry.value()).unwrap();
                if let Some(oldest) = newer_than {
                    let block = source
                        .resolve(reference.reference(), &mut resources)
                        .unwrap();
                    assert!(
                        block.identity().creation_serial > oldest,
                        "record pack must be newer than oldest"
                    );
                }
                let record = verify_record(
                    PayloadSlice::new(
                        &source,
                        root.store(),
                        entry.creation_generation(),
                        reference,
                    ),
                    entity,
                    &catalog,
                    None,
                    &mut resources,
                )
                .unwrap();
                let mut canonical = vec![0; record.canonical_bytes().len() as usize];
                assert_eq!(
                    record
                        .canonical_bytes()
                        .read_at(0, &mut canonical, &mut resources)
                        .unwrap(),
                    canonical.len()
                );
                assert!(
                    records
                        .insert(entity, (record.revision().get(), canonical))
                        .is_none()
                );
                counts[index] += 1;
            }
        }
        assert_eq!(counts, [200, 20]);
        records
    };
    let lease = store.admit_native_read().unwrap();
    let oldest = prepared_union_for_lease(&store, &lease)
        .into_iter()
        .min_by_key(|change| change.object.serial)
        .unwrap()
        .object
        .serial;
    let before = records(&lease, None);
    drop(lease);
    let report = commit_maintenance(&store).unwrap();
    let lease = store.admit_native_read().unwrap();
    assert_eq!(records(&lease, Some(oldest)), before);
    assert!(report.replaced_physical_refs >= 33);
    drop(lease);
    store.close().unwrap();
    Store::open_native_graph(&path, options(), None)
        .unwrap()
        .close()
        .unwrap();
}

#[test]
fn ze260_maintenance_emits_each_tree_root_once_per_call() {
    run_ze260_maintenance_emits_each_tree_root_once_per_call();
}

fn run_ze260_maintenance_emits_each_tree_root_once_per_call() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    for batch in 0..20 {
        crate::property_graph::with_local_refs(|refs| {
            let names: Vec<_> = (0..10).map(|n| format!("{batch}-{n}")).collect();
            let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
            let mut writes: Vec<_> = names
                .iter()
                .map(|name| StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "drain", name).unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                })
                .collect();
            writes.push(StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "drain", &names[0]).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            });
            store
                .apply_native_graph(&writes, &QueryControl::Cancel(CancelToken::new()))
                .unwrap();
        });
    }
    use crate::property_graph::storage::artifact::{self, BlockKind, ContainerKind};
    use crate::property_graph::storage::tree::{Cell, decode_page};
    let before = directory_image(&path);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    let report = commit_maintenance(&store).unwrap();
    let mut emitted = BTreeMap::<u16, usize>::new();
    let mut all_pages = BTreeMap::<u16, usize>::new();
    let mut mixed = 0;
    let mut emitted_pages = std::collections::BTreeSet::new();
    for (name, bytes) in directory_image(&path) {
        if before.contains_key(&name) || !name.to_string_lossy().ends_with(".zgraph") {
            continue;
        }
        let family = u16::from_le_bytes(bytes[8..10].try_into().unwrap());
        assert_eq!(family, 17, "{name:?} is not a native graph object");
        let frame = artifact::decode(ContainerKind::Object, None, &bytes).unwrap();
        if frame.identity().generation != report.generation {
            continue;
        }
        let mut inventory = false;
        let mut other = false;
        let count = u32::from_le_bytes(bytes[80..84].try_into().unwrap());
        for i in 0..count as usize {
            let reference = frame.reference(i).unwrap();
            let block = frame.framed_block(reference).unwrap();
            if reference.kind == BlockKind::TreePage {
                let kind = u16::from_le_bytes(block.payload()[6..8].try_into().unwrap());
                let level = u16::from_le_bytes(block.payload()[16..18].try_into().unwrap());
                *all_pages.entry(kind).or_default() += 1;
                if kind == TreeKind::ObjectInventory as u16 {
                    inventory = true;
                } else {
                    other = true;
                    emitted_pages.insert((reference.artifact.get(), reference.offset));
                }
                if level > 0 {
                    *emitted.entry(kind).or_default() += 1;
                }
            } else {
                other = true;
            }
        }
        mixed += usize::from(inventory && other);
    }
    let lease = store.admit_native_read().unwrap();
    let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(&lease, &memory, 128).unwrap();
    let mut resources = source.resources(u64::MAX).unwrap();
    let mut counts = Vec::new();
    let mut reachable_pages = std::collections::BTreeSet::new();
    for kind in [
        TreeKind::Nodes,
        TreeKind::Relationships,
        TreeKind::KeyFences,
        TreeKind::Labels,
        TreeKind::RelationshipTypes,
        TreeKind::OutRanges,
        TreeKind::InRanges,
    ] {
        let mut pending: Vec<_> = lease
            .bundle()
            .roots()
            .directory(kind)
            .unwrap()
            .reference()
            .into_iter()
            .collect();
        let mut seen = std::collections::BTreeSet::new();
        let mut reachable = 0;
        while let Some(reference) = pending.pop() {
            if !seen.insert((reference.artifact.get(), reference.offset)) {
                continue;
            }
            reachable_pages.insert((reference.artifact.get(), reference.offset));
            let block = source.resolve(reference, &mut resources).unwrap();
            let page = decode_page(kind, block.payload()).unwrap();
            if page.header().level == 0 {
                continue;
            }
            reachable += 1;
            let count = u32::from_le_bytes(block.payload()[12..16].try_into().unwrap());
            for i in 0..count as usize {
                if let Cell::Branch { child, .. } = page.cell(i).unwrap() {
                    pending.push(child);
                }
            }
        }
        let emitted = emitted.get(&(kind as u16)).copied().unwrap_or(0);
        eprintln!(
            "{kind:?}: pages={} emitted_branches={emitted} reachable_branches={reachable}",
            all_pages.get(&(kind as u16)).copied().unwrap_or(0)
        );
        counts.push((kind, emitted, reachable));
    }
    eprintln!("mixed_inventory_objects={mixed}");
    let dead_pages = emitted_pages.difference(&reachable_pages).count();
    eprintln!("dead_graph_pages={dead_pages}");
    assert_eq!(dead_pages, 0, "graph pages must not be dead at birth");
    assert_eq!(mixed, 0, "inventory must have its own lifetime stream");
    for (kind, emitted, reachable) in counts {
        assert_eq!(emitted, reachable, "dead-at-birth branch in {kind:?}");
    }
}

fn reclaim_payload_file_count(path: &Path) -> usize {
    use crate::property_graph::storage::artifact::{self, BlockKind, ContainerKind};
    std::fs::read_dir(path)
        .unwrap()
        .filter(|entry| {
            let entry = entry.as_ref().unwrap();
            if entry
                .path()
                .extension()
                .is_some_and(|extension| extension == "zgraph")
            {
                let bytes = std::fs::read(entry.path()).unwrap();
                let frame = artifact::decode(ContainerKind::Object, None, &bytes).unwrap();
                // A sole commit participant is immutable checkpoint/maintenance
                // control evidence, not a data pack. Count mixed packs as data.
                if frame.reference(0).unwrap().kind == BlockKind::CommitParticipant
                    && frame.reference(1).is_err()
                {
                    return false;
                }
            }
            true
        })
        .count()
}

fn assert_idle_reclaim_progress(
    before_bytes: u64,
    sizes: &[(u64, usize)],
    payload_files: &[usize],
) {
    assert!(sizes[1].0 <= sizes[0].0, "cycle two grew store bytes");
    assert!(
        payload_files[1] <= payload_files[0],
        "cycle two grew payload file count"
    );
    // Unified-WAL checkpointing can reclaim the 1.5 MB in cycle one.
    // Retain the original cycle-two reduction when cycle one still holds it.
    if sizes[0].0 >= 1_500_000 {
        assert!(sizes[0].0 - sizes[1].0 >= 1_500_000);
        assert!(sizes[1].1 < sizes[0].1);
    }
    assert!(before_bytes - sizes[1].0 >= 1_500_000);
    // Compare completed cycles 5 through 8 (sizes is zero-indexed).
    for cycle in 5..8 {
        assert_eq!(sizes[cycle].1, sizes[cycle - 1].1);
        assert!(sizes[cycle].0.abs_diff(sizes[cycle - 1].0) <= 8_192);
    }
    assert!(sizes[7].0 <= 810_000);
    assert!(sizes[7].1 <= 55);
}

#[test]
fn reclaim_progress_rejects_a_growing_second_cycle() {
    // Mutation of the real test's measured trace: all absolute budgets and
    // late stabilization checks pass, but cycle two undoes reclaim progress.
    for second in [(600_000, 45), (600_000, 40), (400_000, 45)] {
        let mut sizes = vec![(400_000, 40); 8];
        sizes[1..].fill(second);
        assert!(
            std::panic::catch_unwind(|| assert_idle_reclaim_progress(
                3_000_000,
                &sizes,
                &sizes.iter().map(|(_, files)| *files).collect::<Vec<_>>()
            ))
            .is_err(),
            "growing trace {sizes:?} escaped the reclaim comparator"
        );
    }
    let mut shrinking = vec![(300_000, 39); 8];
    shrinking[0] = (400_000, 40);
    assert_idle_reclaim_progress(3_000_000, &shrinking, &[40, 39, 39, 39, 39, 39, 39, 39]);
}

#[test]
fn ze260_idle_maintenance_reaches_a_fixed_point() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    for batch in 0..20 {
        crate::property_graph::with_local_refs(|refs| {
            let names: Vec<_> = (0..10).map(|n| format!("{batch}-{n}")).collect();
            let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
            let mut writes: Vec<_> = names
                .iter()
                .map(|name| StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "drain", name).unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                })
                .collect();
            writes.push(StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "drain", &names[0]).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            });
            store
                .apply_native_graph(&writes, &QueryControl::Cancel(CancelToken::new()))
                .unwrap();
        });
    }
    let records = |store: &Store, lease: &super::super::NativeReadLease| {
        use crate::property_graph::query::resources::QueryMemory;
        use crate::property_graph::query::runtime::{RuntimeContext, RuntimeLimits};
        use crate::property_graph::storage::tree::directory::TreeResources;
        use crate::property_graph::storage::{
            GraphReadView, NativeCatalog, NativeQuerySource, NativeReadCapability,
        };
        let shared = crate::property_graph::resources::GraphResources::from_store(store).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let mut result = BTreeMap::new();
        for entity in
            (1..=200)
                .map(|id| EntityId::Node(crate::property_graph::NodeId::new(id).unwrap()))
                .chain((1..=20).map(|id| {
                    EntityId::Relationship(crate::property_graph::RelId::new(id).unwrap())
                }))
        {
            let memory = QueryMemory::new(&shared, 8 * 1024 * 1024).unwrap();
            let mut runtime =
                RuntimeContext::new(lease, &control, &memory, RuntimeLimits::default()).unwrap();
            let capability = NativeReadCapability::admit(lease, &runtime).unwrap();
            let mut resources = TreeResources::for_query(&mut runtime).unwrap();
            let source = NativeQuerySource::new(capability, &resources, 16).unwrap();
            let catalog = NativeCatalog::open(&source, &mut resources).unwrap();
            drop(resources);
            let view = GraphReadView::new(&source, &catalog).unwrap();
            let mut resources = TreeResources::for_query(&mut runtime).unwrap();
            let mut capture =
                |record: &crate::property_graph::storage::records::RecordView<'_, _>,
                 resources: &mut TreeResources<'_>| {
                    let mut canonical = vec![0; record.canonical_bytes().len() as usize];
                    assert_eq!(
                        record
                            .canonical_bytes()
                            .read_at(0, &mut canonical, resources)
                            .unwrap(),
                        canonical.len()
                    );
                    assert!(
                        result
                            .insert(record.incarnation(), (record.revision().get(), canonical))
                            .is_none()
                    );
                };
            match entity {
                EntityId::Node(id) => {
                    let node = view.lookup_node(id, &mut resources).unwrap().unwrap();
                    capture(node.record(), &mut resources);
                }
                EntityId::Relationship(id) => {
                    let relationship = view
                        .lookup_relationship(id, &mut resources)
                        .unwrap()
                        .unwrap();
                    capture(relationship.record(), &mut resources);
                }
            }
        }
        result
    };
    let bytes = || {
        std::fs::read_dir(&path)
            .unwrap()
            .map(|entry| entry.unwrap().metadata().unwrap().len())
            .sum::<u64>()
    };
    let lease = store.admit_native_read().unwrap();
    let oldest = prepared_union_for_lease(&store, &lease)
        .into_iter()
        .min_by_key(|change| change.object.serial)
        .unwrap()
        .object
        .artifact;
    let oldest_path = crate::property_graph::storage::allocation::artifact_path(&path, oldest);
    let before = records(&store, &lease);
    drop(lease);
    let before_bytes = bytes();
    let mut removed = 0;
    let mut subtypes = Vec::new();
    const MAX_COMPLETED_CYCLES: usize = 8;
    let mut completed_cycles = 0;
    let mut first_cycle_bytes = None;
    let mut sizes = Vec::new();
    let mut payload_files = Vec::new();
    let mut previous_removed = 0;
    // One preparation call plus intent, completion and retirement per cycle.
    for _ in 0..MAX_COMPLETED_CYCLES * 4 {
        // Historical WAL roots protect original packs until checkpointed.
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        removed += commit_maintenance(&store).unwrap().removed_bytes;
        let admission = store.admit_native_graph_maintenance().unwrap();
        if admission.lease.bundle().reclaim().is_some() {
            subtypes.push(
                super::super::maintenance::active_reclaim_subtype(
                    &store,
                    &admission,
                    &QueryControl::Cancel(CancelToken::new()),
                )
                .unwrap(),
            );
        } else if subtypes.last() == Some(&3) {
            subtypes.push(0);
            completed_cycles += 1;
            eprintln!(
                "S6_MUST_MAKE_IDLE_CYCLES_NET_NEGATIVE cycle={completed_cycles} bytes={} growth={} files={} payload_files={} removed_bytes={}",
                bytes(),
                i128::from(bytes()) - i128::from(before_bytes),
                std::fs::read_dir(&path).unwrap().count(),
                reclaim_payload_file_count(&path),
                removed - previous_removed,
            );
            sizes.push((bytes(), std::fs::read_dir(&path).unwrap().count()));
            payload_files.push(reclaim_payload_file_count(&path));
            previous_removed = removed;
            first_cycle_bytes.get_or_insert_with(bytes);
            if completed_cycles == MAX_COMPLETED_CYCLES {
                break;
            }
        }
    }
    assert_eq!(completed_cycles, 8);
    assert_idle_reclaim_progress(before_bytes, &sizes, &payload_files);
    eprintln!(
        "ZE260_S5 before_bytes={before_bytes} after_bytes={} removed_bytes={removed} completed_cycles={completed_cycles} max_completed_cycles={MAX_COMPLETED_CYCLES} first_cycle_bytes={first_cycle_bytes:?} subtypes={subtypes:?}",
        bytes()
    );
    assert!(
        (1..=MAX_COMPLETED_CYCLES).contains(&completed_cycles),
        "must finish within the completed-cycle bound"
    );
    assert!(
        subtypes.windows(3).any(|states| states == [2, 3, 0]),
        "intent, completion, retirement must complete"
    );
    assert_eq!(subtypes.last(), Some(&0), "final cycle must be retired");
    assert!(removed > 0, "full cycles removed no bytes");
    assert!(
        !oldest_path.exists(),
        "oldest append-only pack remains live"
    );
    store.close().unwrap();
    let reopened = Store::open_native_graph(&path, options(), None).unwrap();
    let lease = reopened.admit_native_read().unwrap();
    assert_eq!(records(&reopened, &lease), before);
    drop(lease);
    reopened.close().unwrap();
}

#[test]
fn ze46_consolidation_rotates_through_every_node() {
    run_ze46_consolidation_rotates_through_every_node();
}

fn run_ze46_consolidation_rotates_through_every_node() {
    // Relocation must move every node before moving one again. A bounded
    // call may move several nodes; this three-node store needs at most three.
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    let mut nodes = Vec::new();
    for name in ["a", "b", "c"] {
        let image = CanonicalContents::node(&mut [], &mut [], Some(name), None).expect("node");
        let receipt = store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "rotate", name).expect("key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("create node");
        match receipt[0].entity {
            EntityId::Node(node) => nodes.push(node),
            EntityId::Relationship(_) => panic!("node receipt identity"),
        }
    }
    let records = |store: &Store| {
        let lease = store.admit_native_read().expect("record reader");
        nodes
            .iter()
            .map(|node| node_directory_value(store, &lease, *node))
            .collect::<Vec<_>>()
    };
    let original = records(&store);
    let mut previous = original.clone();
    let mut moved = vec![false; nodes.len()];
    for call in 0..nodes.len() {
        let report = commit_maintenance(&store).expect("rotating maintenance");
        assert!(report.replaced_physical_refs > 0);
        let current = records(&store);
        let changed: Vec<_> = (0..nodes.len())
            .filter(|index| current[*index] != previous[*index])
            .collect();
        assert!(!changed.is_empty(), "call {call} moved no nodes");
        for index in changed {
            assert!(
                !moved[index],
                "call {call} moved node {index} again before the others"
            );
            moved[index] = true;
        }
        previous = current;
        if moved.iter().all(|moved| *moved) {
            break;
        }
    }
    assert!(moved.iter().all(|moved| *moved));
    assert!(
        records(&store)
            .iter()
            .zip(&original)
            .all(|(now, before)| now != before)
    );
    store.close().expect("close rotating store");
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen");
    assert_eq!(records(&reopened), previous);
    reopened.close().expect("close reopened store");
}

#[test]
fn ze46_range_consolidation_keeps_self_loops_and_parallel_edges() {
    run_ze46_range_consolidation_keeps_self_loops_and_parallel_edges();
}

/// A self-loop and two parallel edges of one type, plus an edge of a second
/// type, written in separate commits so their ranges carry pending deltas.
/// Consolidation turns pending deltas into bounded bases one range per call;
/// OUT and IN expansions must stay exactly equal throughout and after reopen.
fn run_ze46_range_consolidation_keeps_self_loops_and_parallel_edges() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    let mut nodes = Vec::new();
    for name in ["hub", "leaf"] {
        let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node");
        let receipt = store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "edges", name).expect("key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("create node");
        match receipt[0].entity {
            EntityId::Node(node) => nodes.push(node),
            EntityId::Relationship(_) => panic!("node receipt identity"),
        }
    }
    let (hub, leaf) = (nodes[0], nodes[1]);
    for (name, source, target, relationship_type) in [
        ("self", hub, hub, "LINKS"),
        ("parallel-a", hub, leaf, "LINKS"),
        ("parallel-b", hub, leaf, "LINKS"),
        ("other-type", leaf, hub, "OWNS"),
    ] {
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Relationship, "edges", name).expect("key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Relationship {
                        source: NodeRef::Existing(source),
                        target: NodeRef::Existing(target),
                        relationship_type: GraphName::new(relationship_type).expect("type"),
                        properties: &[],
                    }),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("create relationship");
    }
    let expansions = |store: &Store| {
        let lease = store.admit_native_read().expect("expansion reader");
        [hub, leaf].map(|node| {
            let mut rows = super::publication::out_rows_for_lease(store, &lease, node, hub);
            rows.sort_by_key(|row| row.rel);
            rows
        })
    };
    let before = expansions(&store);
    assert_eq!(before[0].len(), 3, "self-loop and both parallel edges");
    assert_eq!(before[1].len(), 1);
    assert!(
        before[0]
            .iter()
            .any(|row| row.source == hub && row.target == hub)
    );
    assert_eq!(
        before[0].iter().filter(|row| row.target == leaf).count(),
        2,
        "parallel relationships stay distinct"
    );
    for round in 0..6 {
        commit_maintenance(&store)
            .unwrap_or_else(|error| panic!("range round {round} failed: {error:?}"));
        assert_eq!(
            expansions(&store),
            before,
            "round {round} changed an expansion"
        );
    }
    store.close().expect("close edge store");
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen edge store");
    assert_eq!(expansions(&reopened), before);
    reopened.close().expect("close reopened edge store");
}

#[test]
fn ze46_maintenance_accepts_empty_and_deleted_first_node_states() {
    run_ze46_maintenance_accepts_empty_and_deleted_first_node_states();
}

fn run_ze46_maintenance_accepts_empty_and_deleted_first_node_states() {
    // A never-written store is a valid maintenance base with nothing to do:
    // success, no publication, no byte changed.
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    let before = directory_image(&path);
    let report = commit_maintenance(&store).expect("maintenance over the empty graph");
    assert_eq!(report.generation.get(), 1);
    assert_eq!(report.replaced_physical_refs, 0);
    assert_eq!(report.removed_bytes, 0);
    assert_eq!(directory_image(&path), before);

    // The lowest node id is deleted; the next live node is the one to move.
    fn key(name: &str) -> ApplicationKey<'_> {
        ApplicationKey::new(EntityKind::Node, "first", name).expect("key")
    }
    let image = CanonicalContents::node(&mut [], &mut [], Some("kept"), None).expect("node");
    let mut created = Vec::new();
    for name in ["deleted", "kept"] {
        let receipt = store
            .apply_native_graph(
                &[StructuredWrite {
                    key: key(name),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("create node");
        created.push(receipt[0].entity);
    }
    assert!(created[0] < created[1], "the deleted node sorts first");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: key("deleted"),
                revision: GraphRevision::new(2).expect("revision"),
                operation: StructuredOperation::Delete(
                    created[0],
                    crate::property_graph::GraphDeleteMode::Restrict,
                ),
                image: None,
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("delete the first node");
    let report = commit_maintenance(&store).expect("maintenance past a deleted first node");
    assert!(report.replaced_physical_refs > 0);
    store.close().expect("close first-node store");
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen");
    reopened.close().expect("close reopened store");
}

#[test]
fn ze46_repeated_maintenance_releases_durable_proof_protection() {
    run_ze46_repeated_maintenance_releases_durable_proof_protection();
}

fn run_ze46_repeated_maintenance_releases_durable_proof_protection() {
    // Each maintenance commit records its proof in the writer's fixed
    // 64-entry protection table. A checkpoint cuts the WAL envelope that named
    // the proof, so the entry must go unless a reclaim cycle still roots it.
    // Without the release, long-running maintenance fills the table for good.
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    seed_reclaimable_manifest(&store, "repeat");
    let protections = |store: &Store| {
        store
            .native_graph
            .writer
            .lock()
            .expect("native writer")
            .as_ref()
            .expect("installed writer")
            .durable_protected
            .iter()
            .map(|proof| proof.intent.is_some())
            .collect::<Vec<_>>()
    };
    let mut committed = 0_usize;
    for round in 0..48 {
        match commit_maintenance(&store) {
            Ok(_) => committed += 1,
            Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("maintenance round {round} failed: {error:?}"),
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("checkpoint after maintenance");
        let open_cycle = store
            .admit_native_read()
            .expect("round reader")
            .bundle()
            .reclaim()
            .is_some();
        let held = protections(&store);
        if open_cycle {
            assert!(
                held.iter().all(|intent| *intent),
                "round {round}: a proof without an intent outlived its WAL envelope"
            );
        } else {
            assert!(
                held.is_empty(),
                "round {round}: {} proofs protected with no open reclaim cycle",
                held.len()
            );
        }
        assert!(
            held.len() <= 2,
            "round {round}: {} proofs protected",
            held.len()
        );
    }
    assert!(
        committed > 24,
        "only {committed} maintenance commits succeeded"
    );
    store.close().expect("close repeated-maintenance store");
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen");
    reopened.close().expect("close reopened store");
}

#[test]
fn ze46_stale_preparation_rejects_without_publication_or_foreign_cleanup() {
    run_ze46_stale_preparation_rejects_without_publication_or_foreign_cleanup();
}

fn run_ze46_stale_preparation_rejects_without_publication_or_foreign_cleanup() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    let first = CanonicalContents::node(&mut [], &mut [], Some("base"), None).expect("node");
    let first_request = [StructuredWrite {
        key: ApplicationKey::new(EntityKind::Node, "stale", "base").expect("base key"),
        revision: GraphRevision::new(1).expect("revision"),
        operation: StructuredOperation::Create,
        image: Some(WriteImage::Node(&first)),
    }];
    store
        .apply_native_graph(&first_request, &QueryControl::Cancel(CancelToken::new()))
        .expect("base write");
    let admission = store
        .admit_native_graph_maintenance()
        .expect("maintenance admission");

    let second = CanonicalContents::node(&mut [], &mut [], Some("foreground"), None)
        .expect("foreground node");
    let second_request = [StructuredWrite {
        key: ApplicationKey::new(EntityKind::Node, "stale", "foreground").expect("foreground key"),
        revision: GraphRevision::new(1).expect("revision"),
        operation: StructuredOperation::Create,
        image: Some(WriteImage::Node(&second)),
    }];
    store
        .apply_native_graph(&second_request, &QueryControl::Cancel(CancelToken::new()))
        .expect("foreground changed write");
    let foreign = path.join("graph-object-ffffffffffffffffffffffffffffffff.zgraph");
    std::fs::write(&foreign, b"foreign-collision-bytes").expect("foreign collision");
    let before = directory_image(&path);
    let generation = store
        .admit_native_read()
        .expect("reader before stale commit")
        .bundle()
        .base()
        .generation;

    let error = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect_err("changed base must make preparation stale");
    assert!(
        matches!(error, super::super::NativeGraphError::StalePreparation),
        "changed base returned {error:?}"
    );
    super::publication::record_verified_fault();
    assert_eq!(directory_image(&path), before);
    assert_eq!(
        std::fs::read(&foreign).expect("foreign collision remains"),
        b"foreign-collision-bytes"
    );
    assert_eq!(
        store
            .admit_native_read()
            .expect("reader after stale refusal")
            .bundle()
            .base()
            .generation,
        generation
    );
    drop(admission);
    store.close().expect("close stale store");

    // Late branch: the foreground commit lands after this preparation has
    // created its first private file, so only the recheck under the writer
    // lock can refuse it. Then a checkpoint alone replaces the admitted bundle.
    let late_parent = super::tempfile::tempdir().expect("late stale parent");
    let path = late_parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = Arc::new(create_reclaim_test_store(&path, &vfs));
    store
        .apply_native_graph(&first_request, &QueryControl::Cancel(CancelToken::new()))
        .expect("late base write");
    // Arm the stale-preparation callback after the new mandatory fold;
    // the callback must interrupt private proof creation, not checkpoint I/O.
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("fold before preparation hook");
    let serial_before = store
        .capture_native_read_roots()
        .expect("pre-preparation capture")
        .serial_fence();
    let admission = store
        .admit_native_graph_maintenance()
        .expect("late maintenance admission");
    let before = directory_image(&path);
    let foreground = Arc::clone(&store);
    vfs.after_next_create(move || {
        let second = CanonicalContents::node(&mut [], &mut [], Some("foreground"), None)
            .expect("foreground node");
        let receipt = foreground
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "stale", "foreground")
                        .expect("foreground key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&second)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("foreground commit during paused preparation");
        assert_eq!(receipt[0].generation.get(), 4);
    });
    vfs.take();
    let error = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect_err("base changed after private allocation");
    assert!(
        matches!(error, super::super::NativeGraphError::StalePreparation),
        "late changed base returned {error:?}"
    );
    super::publication::record_verified_fault();
    assert!(!vfs.after_create_is_armed(), "foreground commit never ran");
    drop(admission);
    let events = vfs.take();
    assert!(
        events
            .iter()
            .all(|event| !matches!(event, DurabilityEvent::Delete(_))),
        "stale preparation deleted a file: {events:?}"
    );
    let capture = store
        .capture_native_read_roots()
        .expect("post-stale capture");
    assert!(
        capture.serial_fence() > serial_before,
        "the preparation burned its own serials before the recheck"
    );
    assert_eq!(capture.bundle_count(), 1);
    assert!(
        capture.leases().is_empty(),
        "stale preparation kept a lease"
    );
    assert!(
        capture.spills().is_empty(),
        "stale preparation kept a spill registration"
    );
    drop(capture);
    let current = store.admit_native_read().expect("reader after late stale");
    assert_eq!(current.bundle().base().generation.get(), 4);
    assert!(current.bundle().reclaim().is_none());
    let checkpoint_base = current.bundle().base().fold;
    drop(current);
    for (name, bytes) in &before {
        let after = std::fs::read(path.join(name)).expect("preexisting file");
        if name == "wal.ze" {
            assert!(after.starts_with(bytes), "WAL prefix changed");
        } else {
            assert_eq!(&after, bytes, "stale preparation changed {name:?}");
        }
    }

    let admission = store
        .admit_native_graph_maintenance()
        .expect("checkpoint-branch admission");
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint replaces the admitted bundle");
    let before = directory_image(&path);
    let error = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect_err("checkpoint replacement must make preparation stale");
    assert!(
        matches!(error, super::super::NativeGraphError::StalePreparation),
        "checkpoint replacement returned {error:?}"
    );
    super::publication::record_verified_fault();
    drop(admission);
    assert_eq!(directory_image(&path), before);
    let current = store
        .admit_native_read()
        .expect("reader after checkpoint stale");
    assert_ne!(current.bundle().base().fold, checkpoint_base);
    assert_eq!(current.bundle().base().generation.get(), 4);
    drop(current);

    // Own serial burns alone never make a preparation stale.
    let admission = store
        .admit_native_graph_maintenance()
        .expect("clean admission");
    let report = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect("own allocations do not stale the preparation");
    assert_eq!(report.generation.get(), 6);
    drop(admission);
    let store = Arc::into_inner(store).expect("sole late store owner");
    store.close().expect("close late stale store");
}

#[test]
fn ze46_atomic_capture_excludes_new_and_inflight_allocations() {
    run_ze46_atomic_capture_excludes_new_and_inflight_allocations();
}

fn run_ze46_atomic_capture_excludes_new_and_inflight_allocations() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store =
        Arc::new(Store::create_native_graph(&path, options(), None).expect("fresh native store"));
    let image =
        CanonicalContents::node(&mut [], &mut [], Some("capture"), None).expect("capture node");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "capture", "base").expect("capture key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("capture seed write");
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint capture seed");

    let base = store.admit_native_read().expect("capture base lease");
    let descriptor = complete_inventory_union_for_lease(&store, &base)
        .first()
        .copied()
        .expect("authentic finalized allocation")
        .object;
    let registered = [InventoryChange {
        object: descriptor,
        state: InventoryState::Prepared,
    }];
    let prepared = base
        .register_prepared(&registered)
        .expect("register finalized preparation");
    let spill = base.register_spill().expect("register precreate spill");
    spill
        .begin_data(descriptor, None)
        .expect("publish exact in-flight descriptor before create");

    let initial = store
        .capture_native_read_roots()
        .expect("capture prepared and in-flight owners");
    assert!(initial.contains_lease(&base));
    assert!(initial.contains_prepared(descriptor));
    assert!(initial.spills().iter().any(|entry| {
        entry.admission_token == base.token()
            && entry.head.is_none()
            && entry.pending == [Some(descriptor), None]
    }));

    let entered = Arc::new(Barrier::new(2));
    let release = Arc::new(Barrier::new(2));
    store
        .native_graph
        .state
        .lock()
        .expect("publication state")
        .admission_hook = Some((Arc::clone(&entered), Arc::clone(&release)));
    std::thread::scope(|scope| {
        let read_store = Arc::clone(&store);
        let racing = scope.spawn(move || {
            read_store
                .admit_native_read()
                .expect("barrier-controlled read admission")
        });
        entered.wait();
        let capture_store = Arc::clone(&store);
        let capture = scope.spawn(move || {
            capture_store
                .capture_native_read_roots()
                .expect("capture racing admission")
        });
        release.wait();
        let racing = racing.join().expect("admission thread");
        let captured = capture.join().expect("capture thread");
        assert!(
            captured.contains_lease(&racing),
            "the read is registered before capture can pass publication exclusion"
        );
        assert!(captured.contains_prepared(descriptor));
        assert!(captured.spills().iter().any(|entry| {
            entry.admission_token == base.token() && entry.pending == [Some(descriptor), None]
        }));
        drop(racing);
        assert!(
            captured
                .leases()
                .iter()
                .any(|lease| lease.token() != base.token() && lease.check_active().is_ok()),
            "capture retains the racing owner through sweep completion"
        );
    });

    drop(initial);
    drop(spill);
    drop(prepared);
    let released = store
        .capture_native_read_roots()
        .expect("capture after preparation abort");
    assert!(!released.contains_prepared(descriptor));
    assert!(released.spills().is_empty());
    drop(released);
    drop(base);
    Arc::try_unwrap(store)
        .unwrap_or_else(|_| panic!("capture store Arc leaked"))
        .close()
        .expect("close capture store");
}

#[test]
fn ze46_inventory_fold_conserves_complete_allocation_union() {
    crate::property_graph::storage::tree::directory::tests::inventory_fold_page_count();
    run_ze46_inventory_fold_conserves_complete_allocation_union();
}

fn run_ze46_inventory_fold_conserves_complete_allocation_union() {
    assert_eq!(
        inventory_resume_after(255_u128.to_le_bytes()),
        Some(256_u128.to_le_bytes())
    );
    assert_eq!(inventory_resume_after(u128::MAX.to_le_bytes()), None);
    // This test measures the inventory-fold cap independently of orphan adoption.
    let _adoption = super::super::maintenance::orphans::suspend_adoption_for_test();
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    for (key, text) in [("one", "first manifest"), ("two", "second manifest")] {
        let image = CanonicalContents::node(&mut [], &mut [], Some(text), None).expect("node");
        let request = [StructuredWrite {
            key: ApplicationKey::new(EntityKind::Node, "inventory", key).expect("key"),
            revision: GraphRevision::new(1).expect("revision"),
            operation: StructuredOperation::Create,
            image: Some(WriteImage::Node(&image)),
        }];
        store
            .apply_native_graph(&request, &QueryControl::Cancel(CancelToken::new()))
            .expect("manifest-producing write");
    }
    let before = store.admit_native_read().expect("reader before fold");
    assert_eq!(before.bundle().prepared_inventories().len(), 2);
    let original_manifests = before.bundle().prepared_inventories().to_vec();
    let first_manifest = prepared_manifest_for_lease(&store, &before, original_manifests[0]);
    let expected = complete_inventory_union_for_lease(&store, &before);
    assert!(
        first_manifest.len() >= 2,
        "first manifest has an allocation and its owner"
    );
    assert!(expected.len() >= 4, "two manifests plus their allocations");
    drop(before);

    for (arm, label) in [
        (
            force_next_incomplete_inventory_retirement as fn(),
            "incomplete retirement",
        ),
        (
            force_next_contradictory_inventory_addition as fn(),
            "contradictory addition",
        ),
    ] {
        let before_refusal = directory_image(&path);
        let admitted = store
            .admit_native_graph_maintenance()
            .expect("negative-control maintenance admission");
        arm();
        assert!(
            store
                .commit_native_graph_maintenance_with_limits(
                    &admitted,
                    &QueryControl::Cancel(CancelToken::new()),
                    cap_one_inventory_addition(),
                )
                .is_err(),
            "{label} must fail the bound producer before commit"
        );
        super::publication::record_verified_fault();
        drop(admitted);
        assert_eq!(
            directory_image(&path),
            before_refusal,
            "{label} refusal cannot publish files or WAL"
        );
    }

    let admitted = store
        .admit_native_graph_maintenance()
        .expect("maintenance admission");
    store
        .commit_native_graph_maintenance_with_limits(
            &admitted,
            &QueryControl::Cancel(CancelToken::new()),
            cap_one_inventory_addition(),
        )
        .expect("inventory-folding maintenance");
    drop(admitted);
    let after = store.admit_native_read().expect("reader after fold");
    assert_eq!(
        after
            .bundle()
            .prepared_inventories()
            .get(..original_manifests.len()),
        Some(original_manifests.as_slice()),
        "a partial slice retains the selected and unrelated manifests"
    );
    let actual = rooted_inventory_for_lease(&store, &after);
    assert_eq!(actual.len(), 1, "cap-one slice adds one rooted descriptor");
    let current_manifest_union = prepared_union_for_lease(&store, &after);
    let inventory_page = after.bundle().roots().references()[7].expect("inventory page");
    assert!(
        current_manifest_union
            .iter()
            .any(|change| change.object.artifact == inventory_page.artifact),
        "new inventory pages remain in the current prepared manifest"
    );
    assert!(current_manifest_union.iter().any(|change| {
        after
            .bundle()
            .prepared_inventories()
            .iter()
            .any(|manifest| manifest.object == change.object)
    }));
    let first_union = complete_inventory_union_for_lease(&store, &after);
    for descriptor in &expected {
        assert!(
            first_union
                .iter()
                .any(|current| current.object == descriptor.object),
            "partial fold conserves the admitted allocation union"
        );
    }
    drop(after);
    store.close().expect("close partially folded store");

    let store = Store::open_native_graph(&path, options(), None).expect("replay partial fold");
    let replayed = store
        .admit_native_read()
        .expect("reader after partial replay");
    assert_eq!(
        replayed
            .bundle()
            .prepared_inventories()
            .get(..original_manifests.len()),
        Some(original_manifests.as_slice())
    );
    assert_eq!(rooted_inventory_for_lease(&store, &replayed).len(), 1);
    // Keep the reader's declared prepared allocations live while checking
    // inventory-fold conservation, independently of the reclaim tests.

    let mut slices = 1_usize;
    let mut previous_covered = 1_usize;
    let mut previous_union = first_union;
    loop {
        let admitted = store
            .admit_native_graph_maintenance()
            .expect("resumed maintenance admission");
        store
            .commit_native_graph_maintenance_with_limits(
                &admitted,
                &QueryControl::Cancel(CancelToken::new()),
                cap_one_inventory_addition(),
            )
            .expect("resumed cap-one inventory fold");
        drop(admitted);
        slices += 1;
        let lease = store
            .admit_native_read()
            .expect("reader after resumed fold");
        let rooted = rooted_inventory_for_lease(&store, &lease);
        let covered = first_manifest
            .iter()
            .filter(|expected| rooted.iter().any(|actual| actual.object == expected.object))
            .count();
        assert_eq!(
            covered,
            previous_covered + 1,
            "cap-one adds one exact descriptor"
        );
        previous_covered = covered;
        let current_union = complete_inventory_union_for_lease(&store, &lease);
        for descriptor in &previous_union {
            assert!(
                current_union
                    .iter()
                    .any(|current| current.object == descriptor.object),
                "each partial fold conserves the complete prior union"
            );
        }
        previous_union = current_union;
        let retired = !lease
            .bundle()
            .prepared_inventories()
            .contains(&original_manifests[0]);
        assert!(
            lease
                .bundle()
                .prepared_inventories()
                .contains(&original_manifests[1]),
            "unrelated manifest remains referenced"
        );
        drop(lease);
        if retired {
            break;
        }
        assert!(
            slices <= first_manifest.len(),
            "bounded fold must make durable progress"
        );
    }
    drop(replayed);
    assert!(slices >= 2, "fold required multiple bounded slices");
    let complete = store.admit_native_read().expect("reader after retirement");
    let rooted = rooted_inventory_for_lease(&store, &complete);
    let mut folded_first: Vec<_> = first_manifest
        .iter()
        .filter_map(|expected| {
            rooted
                .iter()
                .find(|actual| actual.object.artifact == expected.object.artifact)
                .copied()
        })
        .collect();
    folded_first.sort_unstable_by_key(|change| change.object.artifact);
    let mut expected_first = first_manifest.clone();
    expected_first.sort_unstable_by_key(|change| change.object.artifact);
    validate_fold_conservation(&expected_first, &folded_first)
        .expect("retirement retained every selected descriptor and owner");
    let before_checkpoint = complete_inventory_union_for_lease(&store, &complete);
    drop(complete);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint folded inventory");
    store.close().expect("close folded inventory store");

    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen folded store");
    let lease = reopened.admit_native_read().expect("reopened reader");
    assert_eq!(
        complete_inventory_union_for_lease(&reopened, &lease)
            .iter()
            .map(|change| change.object)
            .collect::<Vec<_>>(),
        before_checkpoint
            .iter()
            .map(|change| change.object)
            .collect::<Vec<_>>(),
        "checkpoint/reopen preserves complete allocation union"
    );
    drop(lease);
    reopened.close().expect("close reopened inventory store");
}

#[test]
fn ze46_inventory_fold_drains_a_manifest_backlog() {
    run_ze46_inventory_fold_drains_a_manifest_backlog();
}

fn run_ze46_inventory_fold_drains_a_manifest_backlog() {
    // Every commit appends one prepared manifest. Maintenance adds one of
    // its own, so it must retire several per call or the list never shrinks.
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    // Build the declared backlog before the explicit fold under test.
    store
        .set_native_graph_maintenance_policy(crate::property_graph::GraphMaintenancePolicy {
            automatic: false,
            ..Default::default()
        })
        .expect("isolate explicit backlog fold");
    const WRITES: usize = 40;
    for index in 0..WRITES {
        let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node image");
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "backlog", &index.to_string())
                        .expect("backlog key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("backlog write");
    }
    let manifests = |store: &Store| {
        store
            .admit_native_read()
            .expect("manifest reader")
            .bundle()
            .prepared_inventories()
            .len()
    };
    assert_eq!(manifests(&store), WRITES);
    // Cut the WAL first: the proof retraces every uncheckpointed state
    // (ZE-163), which would dominate this case without changing the fold.
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint the backlog");
    assert_eq!(manifests(&store), WRITES);
    let before = {
        let lease = store.admit_native_read().expect("union reader");
        complete_inventory_union_for_lease(&store, &lease)
    };

    // Released WAL protection also starts reclaim cycles here. Their resume
    // and clear steps each add a manifest without folding, so the count is
    // not monotonic; the fold still has to win over the whole run.
    let mut calls = 0_usize;
    let mut peak = WRITES;
    while manifests(&store) > 4 {
        match commit_maintenance(&store) {
            Ok(_) | Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("draining maintenance call {calls} failed: {error:?}"),
        }
        calls += 1;
        peak = peak.max(manifests(&store));
        assert!(
            calls <= WRITES,
            "{} manifests remain after {calls} calls: the backlog does not drain",
            manifests(&store)
        );
    }
    assert!(peak <= WRITES + 1, "the backlog grew to {peak} manifests");
    assert_eq!(calls, 1, "one S6c fold must drain forty commit manifests");

    // Retirement moves bookkeeping into the rooted tree; it never loses it.
    // A row may leave only with its file, through a completed reclaim cycle.
    let lease = store.admit_native_read().expect("drained union reader");
    let after = complete_inventory_union_for_lease(&store, &lease);
    let mut reclaimed = 0_usize;
    for change in &before {
        let kept = after.iter().any(|kept| kept.object == change.object);
        let on_disk = crate::property_graph::storage::allocation::artifact_path(
            &path,
            change.object.artifact,
        )
        .exists();
        assert!(
            kept || !on_disk,
            "drain lost the bookkeeping of a file that still exists: {:?}",
            change.object
        );
        reclaimed += usize::from(!kept);
    }
    assert!(reclaimed < before.len(), "every allocation was reclaimed");
    drop(lease);
    store.close().expect("close drained store");
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen drained store");
    assert!(manifests(&reopened) <= 4);
    reopened.close().expect("close reopened drained store");
}

#[test]
fn ze316_completed_reclaim_survives_foreground_commit() {
    let (history, store) = seed_crash_history();
    store
        .set_native_graph_maintenance_policy(crate::property_graph::GraphMaintenancePolicy {
            automatic: false,
            ..Default::default()
        })
        .expect("disable automatic maintenance");
    let control = QueryControl::Cancel(CancelToken::new());
    commit_maintenance(&store).expect("publish pending intent");
    let completed = commit_maintenance(&store).expect("complete reclaim");
    assert!(completed.removed_bytes > 0);
    let completion = store
        .admit_native_read()
        .unwrap()
        .bundle()
        .reclaim()
        .unwrap();
    let embedding = CanonicalEmbedding::new(&history.document, &[0.5_f32, 1.0_f32])
        .expect("foreground peer embedding");
    let image = CanonicalContents::node(&mut [], &mut [], Some("foreground peer"), Some(embedding))
        .unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "crash", "peer").unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Put(EntityId::Node(history.peer)),
                image: Some(WriteImage::Node(&image)),
            }],
            &control,
        )
        .expect("foreground mutation after completion");
    let lease = store.admit_native_read().unwrap();
    assert_eq!(lease.bundle().reclaim(), Some(completion));
    assert!(completion.object.generation < lease.bundle().base().generation);
    drop(lease);
    let oracle = history.oracle(&store);
    store
        .checkpoint_native_graph(&control)
        .expect("checkpoint completion");
    commit_maintenance(&store).expect("retire carried-forward completion");
    assert!(
        store
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_none()
    );
    assert_same_logical_state(&oracle, &history.oracle(&store));
    store.close().unwrap();
    drop(store);
    let reopened = history.open(options()).expect("reopen retired completion");
    assert!(
        reopened
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_none()
    );
    assert_same_logical_state(&oracle, &history.oracle(&reopened));
    reopened.close().unwrap();
}

#[test]
fn ze46_checkpoint_during_an_open_reclaim_cycle_reopens() {
    run_ze46_checkpoint_during_an_open_reclaim_cycle_reopens();
}

fn run_ze46_checkpoint_during_an_open_reclaim_cycle_reopens() {
    // A foreground checkpoint (explicit, or the writer's 64-envelope policy)
    // can land at any point of a reclaim cycle. Every such state must reopen.
    for stage in ["pending intent", "completion"] {
        let (history, store) = seed_crash_history();
        let oracle = history.oracle(&store);
        commit_maintenance(&store).expect("durable reclaim intent");
        if stage == "completion" {
            commit_maintenance(&store).expect("in-process resume");
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("checkpoint inside the reclaim cycle");
        store.close().expect("close mid-cycle store");
        let reopened = history
            .open(options())
            .unwrap_or_else(|error| panic!("reopen after checkpoint at {stage}: {error:?}"));
        assert_same_logical_state(&oracle, &history.oracle(&reopened));
        reopened.close().expect("close reopened mid-cycle store");
    }

    // A foreground write may also land between the intent and its resume.
    // The cycle must still finish, in this process and after a reopen.
    for reopen_first in [false, true] {
        let (history, mut store) = seed_crash_history();
        commit_maintenance(&store).expect("durable reclaim intent");
        let pending = store.admit_native_read().expect("pending reader");
        let candidates = pending_reclaim_candidates(&store, &pending);
        drop(pending);
        let image = CanonicalContents::node(&mut [], &mut [], Some("late"), None).expect("node");
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "crash", "late").expect("key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("foreground write inside the reclaim cycle");
        if reopen_first {
            store
                .close()
                .expect("close store with a write after the intent");
            store = history
                .open(options())
                .unwrap_or_else(|error| panic!("reopen with a write after the intent: {error:?}"));
        } else {
            commit_maintenance(&store).expect("resume after a foreground write");
        }
        for candidate in &candidates {
            assert!(
                !reclaim_candidate_path(&history.path, candidate).exists(),
                "reopen_first={reopen_first}: pending target survived"
            );
        }
        store.close().expect("close finished cycle store");
    }
}

#[test]
fn ze46_reconciles_real_prewal_orphans_without_touching_unknown_files() {
    run_ze46_reconciles_real_prewal_orphans_without_touching_unknown_files();
}

fn run_ze46_reconciles_real_prewal_orphans_without_touching_unknown_files() {
    use super::publication::FaultPoint;
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    let write = |name: &str| {
        let image = CanonicalContents::node(&mut [], &mut [], Some(name), None).expect("node");
        store.apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "orphans", name).expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
    };
    write("first").expect("first commit");

    // Real crash debris: each fault fires inside a real write, before any WAL
    // inventory names the new files.
    let mut debris = Vec::new();
    for (point, label) in [
        (FaultPoint::ObjectSync, "complete"),
        (FaultPoint::PartialCreate, "partial"),
        (FaultPoint::Create, "headerless"),
    ] {
        let before = directory_image(&path);
        vfs.arm_fault(point);
        let Err(error) = write("second") else {
            panic!("{label} fault did not fail the write");
        };
        assert!(
            matches!(error, super::super::NativeGraphError::Io { .. }),
            "{label}: {error:?}"
        );
        vfs.assert_fired_once();
        let created: Vec<_> = directory_image(&path)
            .into_iter()
            .filter(|(name, _)| !before.contains_key(name))
            .collect();
        assert!(!created.is_empty(), "{label} fault left no file");
        debris.push((label, created));
    }
    write("second").expect("clean retry");
    // ZE-46 reclaims the complete orphan; ZE-165 reclaims the interrupted
    // create beside it. The headerless prefix is retained by both.
    let complete: Vec<_> = debris[0].1.iter().chain(&debris[1].1).cloned().collect();
    let mut retained: BTreeMap<std::ffi::OsString, Vec<u8>> = debris[2].1.iter().cloned().collect();
    assert!(
        debris[1].1.iter().all(|(_, bytes)| bytes.len() >= 96),
        "the partial create keeps an intact header"
    );
    assert!(
        debris[2]
            .1
            .iter()
            .all(|(_, bytes)| bytes == b"foreign-owner")
    );

    // Files cleanup must never touch.
    let (orphan_name, orphan_bytes) = complete.first().cloned().expect("complete orphan");
    retained.insert("notes.txt".into(), b"not a native name".to_vec());
    let mut unknown_family = orphan_bytes.clone();
    unknown_family[8] = 99;
    retained.insert(
        "graph-0000000000000000000000000000f00d.zgraph".into(),
        unknown_family,
    );
    let foreign_parent = super::tempfile::tempdir().expect("foreign parent");
    let foreign_path = foreign_parent.path().join("native");
    let foreign_store =
        Store::create_native_graph(&foreign_path, options(), None).expect("foreign store");
    let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("foreign node");
    foreign_store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "foreign", "node").expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("foreign commit");
    foreign_store.close().expect("close foreign store");
    let (foreign_name, foreign_bytes) = directory_image(&foreign_path)
        .into_iter()
        .find(|(name, _)| name.to_string_lossy().ends_with(".zgraph"))
        .expect("foreign object");
    retained.insert(foreign_name, foreign_bytes);
    for (name, bytes) in &retained {
        if !path.join(name).exists() {
            std::fs::write(path.join(name), bytes).expect("plant retained file");
        }
    }

    // Maintenance with checkpoints between calls. Every unlink must name a
    // target of the pending intent that was durable before it.
    let (lists_before, children_before) = vfs.enumeration_calls();
    let mut removed_bytes = 0_u64;
    let mut deleted: BTreeMap<std::ffi::OsString, u64> = BTreeMap::new();
    let mut first_spill_files: Option<Vec<std::ffi::OsString>> = None;
    for round in 0..40 {
        let sizes: BTreeMap<_, _> = directory_image(&path)
            .into_iter()
            .map(|(name, bytes)| (name, bytes.len() as u64))
            .collect();
        let pending: Vec<_> = {
            let lease = store.admit_native_read().expect("round reader");
            pending_reclaim_targets_or_empty_root(&store, &lease)
        };
        vfs.take();
        match commit_maintenance(&store) {
            Ok(report) => removed_bytes += report.removed_bytes,
            Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("orphan round {round} failed: {error:?}"),
        }
        for unlinked in delete_events(&vfs.take()) {
            let name = unlinked.file_name().expect("deleted name").to_os_string();
            assert!(
                pending.contains(&unlinked),
                "round {round} unlinked {name:?} without a durable intent naming it"
            );
            let size = *sizes.get(&name).expect("deleted file existed");
            assert!(deleted.insert(name, size).is_none(), "double unlink");
        }
        if first_spill_files.is_none() {
            first_spill_files = Some(
                directory_image(&path)
                    .into_keys()
                    .filter(|name| !sizes.contains_key(name))
                    .collect(),
            );
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("checkpoint between orphan rounds");
        if complete.iter().all(|(name, _)| deleted.contains_key(name))
            && first_spill_files
                .as_ref()
                .is_some_and(|files| files.iter().any(|name| deleted.contains_key(name)))
        {
            break;
        }
    }
    for (name, bytes) in &complete {
        assert_eq!(
            deleted.get(name),
            Some(&(bytes.len() as u64)),
            "complete pre-WAL orphan {name:?} was not reclaimed"
        );
    }
    let first_spill_files = first_spill_files.expect("first round private files");
    assert!(!first_spill_files.is_empty());
    assert!(
        first_spill_files
            .iter()
            .any(|name| deleted.contains_key(name)),
        "no retired spill or proof file of the first round was ever reclaimed"
    );
    assert_eq!(removed_bytes, deleted.values().sum::<u64>());
    for (name, bytes) in &retained {
        assert_eq!(
            std::fs::read(path.join(name)).ok().as_ref(),
            Some(bytes),
            "cleanup touched {name:?}"
        );
    }
    let (lists_after, children_after) = vfs.enumeration_calls();
    assert_eq!(
        lists_after, lists_before,
        "orphan selection loaded a directory list"
    );
    assert!(children_after > children_before);
    let _ = orphan_name;

    // Both committed nodes survive, and the store reopens once the two files
    // that recovery itself refuses (foreign store, unknown family) are gone.
    store.close().expect("close orphan store");
    for name in retained.keys() {
        let bytes = &retained[name];
        if bytes.len() >= 96 && bytes != b"foreign-owner" {
            std::fs::remove_file(path.join(name)).expect("remove refused fixture file");
        }
    }
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen orphan store");
    assert_eq!(
        reopened
            .admit_native_read()
            .expect("reopened reader")
            .bundle()
            .high_waters()
            .node,
        2
    );
    reopened.close().expect("close reopened orphan store");
}

#[test]
fn ze46_orphan_adoption_waits_for_a_quiescent_history() {
    run_ze46_orphan_adoption_waits_for_a_quiescent_history();
}

fn run_ze46_orphan_adoption_waits_for_a_quiescent_history() {
    let (history, store) = seed_crash_history();
    let before = store.admit_native_read().unwrap().bundle().base().fold;
    commit_maintenance(&store).unwrap();
    let current = store.admit_native_read().unwrap();
    let (manifest, candidates) = pending_reclaim_proof_for_lease(&store, &current);
    assert!(candidates.iter().all(|candidate| candidate.family == 17));
    assert_eq!(manifest.binding.sequence, before.envelope_sequence);
    assert_eq!(current.bundle().base().fold, before);
    super::super::recovery::validate_reclaim_proof_for_test(
        &store,
        current.bundle(),
        &QueryControl::Cancel(CancelToken::new()),
    )
    .unwrap();
    drop(current);
    store.close().unwrap();
    let reopened = history.open(options()).unwrap();
    reopened.close().unwrap();
}
/// Pending-intent candidates, or nothing when no intent is rooted.
fn pending_reclaim_candidates_or_empty_root(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<ArtifactDescriptor> {
    let Some(required) = lease.bundle().reclaim() else {
        return Vec::new();
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 1).expect("reclaim source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve reclaim state");
    match crate::property_graph::storage::reclaim::decode_pending_intent_manifest(block.payload()) {
        Ok(manifest) => (0..manifest.candidate_count)
            .map(|index| {
                crate::property_graph::storage::reclaim::pending_intent_candidate_at(
                    block.payload(),
                    index,
                )
                .expect("pending candidate")
            })
            .collect(),
        Err(_) => Vec::new(),
    }
}

pub(super) fn reclaim_candidate_path(
    directory: &Path,
    candidate: &ArtifactDescriptor,
) -> std::path::PathBuf {
    crate::property_graph::storage::allocation::artifact_path(directory, candidate.artifact)
}

/// Every artifact the rooted pending intent authorizes an unlink for: the
/// genuine object candidates plus ZE-165's tagged partial-target partition.
fn pending_reclaim_targets_or_empty_root(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<std::path::PathBuf> {
    let Some(required) = lease.bundle().reclaim() else {
        return Vec::new();
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 1).expect("reclaim source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve reclaim state");
    let payload = block.payload();
    match crate::property_graph::storage::reclaim::decode_pending_intent_manifest(payload) {
        Ok(manifest) => (0..manifest.candidate_count)
            .map(|index| {
                reclaim_candidate_path(
                    lease.bundle().directory(),
                    &crate::property_graph::storage::reclaim::pending_intent_candidate_at(
                        payload, index,
                    )
                    .expect("pending candidate"),
                )
            })
            .chain((0..manifest.partial_count).map(|index| {
                crate::property_graph::storage::allocation::artifact_path(
                    lease.bundle().directory(),
                    crate::property_graph::storage::reclaim::pending_intent_partial_at(
                        payload, index,
                    )
                    .expect("pending partial target")
                    .artifact,
                )
            }))
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// The tagged partial partition of the rooted pending intent, or nothing when
/// no intent is rooted.
fn pending_reclaim_partials_or_empty_root(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<crate::property_graph::storage::reclaim::PartialTarget> {
    let Some(required) = lease.bundle().reclaim() else {
        return Vec::new();
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("shared resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("write memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 1).expect("reclaim source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve reclaim state");
    let payload = block.payload();
    match crate::property_graph::storage::reclaim::decode_pending_intent_manifest(payload) {
        Ok(manifest) => (0..manifest.partial_count)
            .map(|index| {
                crate::property_graph::storage::reclaim::pending_intent_partial_at(payload, index)
                    .expect("pending partial target")
            })
            .collect(),
        Err(_) => Vec::new(),
    }
}

#[test]
fn ze165_reclaims_a_partial_create_and_retains_every_other_prefix() {
    run_ze165_reclaims_a_partial_create_and_retains_every_other_prefix();
}

/// ZE-165. A real `PartialCreate` fault leaves a file whose 96-byte header is
/// intact but whose body is not. It can never carry a whole-file checksum, so
/// ZE-46 could not adopt it and retained it. Here a later completed proof
/// selects it into the intent's tagged partial partition, and the unlink
/// follows that durable intent.
///
/// Three prefixes that look similar must survive byte-identical: a headerless
/// one from a `Create` collision, a foreign store's *interrupted* create whose
/// header shape is identical but whose store id is not, and a non-native name.
fn run_ze165_reclaims_a_partial_create_and_retains_every_other_prefix() {
    use super::publication::FaultPoint;
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    let write = |name: &str| {
        let image = CanonicalContents::node(&mut [], &mut [], Some(name), None).expect("node");
        store.apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "partials", name).expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
    };
    write("first").expect("first commit");

    // Real crash debris, produced by the fault VFS inside a real write.
    let mut debris = Vec::new();
    for (point, label) in [
        (FaultPoint::PartialCreate, "partial"),
        (FaultPoint::Create, "headerless"),
    ] {
        let before = directory_image(&path);
        vfs.arm_fault(point);
        let Err(error) = write("second") else {
            panic!("{label} fault did not fail the write");
        };
        assert!(
            matches!(error, super::super::NativeGraphError::Io { .. }),
            "{label}: {error:?}"
        );
        vfs.assert_fired_once();
        let created: Vec<_> = directory_image(&path)
            .into_iter()
            .filter(|(name, _)| !before.contains_key(name))
            .collect();
        assert_eq!(created.len(), 1, "{label} fault left {created:?}");
        debris.push(created.into_iter().next().expect("one debris file"));
    }
    write("second").expect("clean retry");
    let (partial_name, partial_bytes) = debris.first().cloned().expect("partial debris");
    let (headerless_name, headerless_bytes) = debris.get(1).cloned().expect("headerless debris");
    assert!(
        partial_bytes.len() >= 96,
        "the partial create must keep an intact header"
    );
    assert!(
        headerless_bytes.len() < 96,
        "the headerless prefix must be shorter than one header"
    );
    let partial_artifact = artifact_of_name(&partial_name);

    // Files reclamation must never touch. The foreign partial has the exact
    // header shape of the reclaimable one and differs only in its store id.
    let mut retained: BTreeMap<std::ffi::OsString, Vec<u8>> =
        [(headerless_name.clone(), headerless_bytes)]
            .into_iter()
            .collect();
    retained.insert("notes.txt".into(), b"not a native name".to_vec());
    let foreign_parent = super::tempfile::tempdir().expect("foreign parent");
    let foreign_path = foreign_parent.path().join("native");
    let foreign_store =
        Store::create_native_graph(&foreign_path, options(), None).expect("foreign store");
    let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("foreign node");
    foreign_store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "foreign", "node").expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("foreign commit");
    foreign_store.close().expect("close foreign store");
    let (foreign_name, foreign_bytes) = directory_image(&foreign_path)
        .into_iter()
        .find(|(name, bytes)| name.to_string_lossy().ends_with(".zgraph") && bytes.len() > 200)
        .expect("foreign object");
    let foreign_partial = foreign_bytes
        .get(..foreign_bytes.len() / 2)
        .expect("foreign prefix")
        .to_vec();
    assert!(foreign_partial.len() >= 96);
    retained.insert(foreign_name, foreign_partial);
    for (name, bytes) in &retained {
        // The headerless prefix is already on disk: the fault left it there.
        if !path.join(name).exists() {
            std::fs::write(path.join(name), bytes).expect("plant retained file");
        }
    }

    // Maintenance with checkpoints between calls. Every unlink must name a
    // target of the pending intent that was durable before it ran.
    let mut removed_bytes = 0_u64;
    let mut deleted: BTreeMap<std::ffi::OsString, u64> = BTreeMap::new();
    let mut authorizing: Option<crate::property_graph::storage::reclaim::PartialTarget> = None;
    for round in 0..40 {
        let sizes: BTreeMap<_, _> = directory_image(&path)
            .into_iter()
            .map(|(name, bytes)| (name, bytes.len() as u64))
            .collect();
        let (targets, partials) = {
            let lease = store.admit_native_read().expect("round reader");
            (
                pending_reclaim_targets_or_empty_root(&store, &lease),
                pending_reclaim_partials_or_empty_root(&store, &lease),
            )
        };
        vfs.take();
        match commit_maintenance(&store) {
            Ok(report) => removed_bytes += report.removed_bytes,
            Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("partial round {round} failed: {error:?}"),
        }
        for unlinked in delete_events(&vfs.take()) {
            let name = unlinked.file_name().expect("deleted name").to_os_string();
            assert!(
                targets.contains(&unlinked),
                "round {round} unlinked {name:?} without a durable intent naming it"
            );
            if name == partial_name {
                authorizing = partials
                    .iter()
                    .copied()
                    .find(|target| target.artifact == partial_artifact);
            }
            let size = *sizes.get(&name).expect("deleted file existed");
            assert!(deleted.insert(name, size).is_none(), "double unlink");
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("checkpoint between partial rounds");
        if deleted.contains_key(&partial_name) {
            break;
        }
    }

    // The interrupted create was reclaimed, and the intent that authorized it
    // recorded the bytes actually observed rather than any declared length.
    assert_eq!(
        deleted.get(&partial_name),
        Some(&(partial_bytes.len() as u64)),
        "the partial create was not reclaimed"
    );
    let authorizing = authorizing.expect("no partial target authorized the unlink");
    assert_eq!(authorizing.artifact, partial_artifact);
    assert_eq!(authorizing.observed, partial_bytes.len() as u64);
    assert!(
        authorizing.declared > authorizing.observed,
        "an interrupted prefix declares more than it holds"
    );
    assert_eq!(
        authorizing.digest,
        xxhash_rust::xxh3::xxh3_64(&partial_bytes),
        "the intent digested bytes other than the ones on disk"
    );
    assert_eq!(removed_bytes, deleted.values().sum::<u64>());

    // Every look-alike prefix is still there, byte for byte.
    for (name, bytes) in &retained {
        assert_eq!(
            std::fs::read(path.join(name)).ok().as_ref(),
            Some(bytes),
            "reclamation touched {name:?}"
        );
    }

    store.close().expect("close partial store");
    for name in retained.keys() {
        if retained[name].len() >= 96 {
            std::fs::remove_file(path.join(name)).expect("remove refused fixture file");
        }
    }
    let reopened = Store::open_native_graph(&path, options(), None).expect("reopen partial store");
    assert_eq!(
        reopened
            .admit_native_read()
            .expect("reopened reader")
            .bundle()
            .high_waters()
            .node,
        2
    );
    reopened.close().expect("close reopened partial store");
}

/// The artifact id a canonical `graph-<32 hex>.zgraph` name encodes.
fn artifact_of_name(
    name: &std::ffi::OsStr,
) -> crate::property_graph::storage::artifact::ArtifactId {
    let text = name.to_string_lossy();
    let digits = text
        .strip_prefix("graph-")
        .and_then(|rest| rest.strip_suffix(".zgraph"))
        .expect("canonical native object name");
    crate::property_graph::storage::artifact::ArtifactId::new(
        u128::from_str_radix(digits, 16).expect("artifact digits"),
    )
    .expect("artifact id")
}

#[test]
fn ze46_spill_merge_and_incomplete_mark_never_delete_candidates() {
    run_ze46_spill_merge_and_incomplete_mark_never_delete_candidates();
}

fn run_ze46_spill_merge_and_incomplete_mark_never_delete_candidates() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    for (key, text) in [
        ("multi-a", "first physical object"),
        ("multi-b", "second physical object"),
        ("multi-c", "third physical object"),
    ] {
        let image =
            CanonicalContents::node(&mut [], &mut [], Some(text), None).expect("node image");
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "spill", key)
                        .expect("application key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("separate physical graph commit");
    }
    let graph_admission = store
        .admit_native_graph_maintenance()
        .expect("multi-object maintenance admission");
    let graph_report = store
        .commit_native_graph_maintenance(
            &graph_admission,
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("multi-object bounded trace maintenance");
    assert!(graph_report.replaced_physical_refs > 0);
    drop(graph_admission);
    let admission = store
        .admit_native_graph_maintenance()
        .expect("maintenance admission");
    let before = directory_image(&path);

    let report =
        super::super::maintenance::run_spill_probe(&store, &admission, &[9, 2, 7, 2, 5], 2)
            .expect("durable spill/merge probe");
    assert_eq!(report.ordered, vec![2, 5, 7, 9]);
    assert!(report.spill_runs >= 2, "test cap forced multiple disk runs");
    assert!(report.merges >= 1, "multiple disk runs forced a real merge");
    assert!(
        report.max_batch <= 2,
        "sort memory obeyed the requested cap"
    );
    assert!(report.created_objects >= 4);
    assert_eq!(report.created_objects % 2, 0);
    assert!(report.disk_bytes > 0);
    assert!(report.maximum_encoded_backing < 8 * 1024);
    assert!(report.charged_peak_bytes <= 4 * 1024 * 1024);
    assert!(report.read_windows > 0);
    assert!(report.maximum_mapped_window < 8 * 1024);
    assert!(report.released_each_read_window);
    assert!(
        report.mapped_bytes_released,
        "isolated probe released every scoped mapping before return"
    );
    assert_eq!(report.captured_head, report.allocation_head);
    assert_eq!(report.captured_pending, [None; 2]);
    let after = directory_image(&path);
    let created: Vec<_> = after
        .iter()
        .filter(|(name, _)| !before.contains_key(*name))
        .collect();
    assert_eq!(created.len() as u64, report.created_objects);
    assert_eq!(
        created
            .iter()
            .map(|(_, bytes)| bytes.len() as u64)
            .sum::<u64>(),
        report.disk_bytes
    );

    let run_name = format!(
        "graph-{:032x}.zgraph",
        report.run.root.object.artifact.get()
    );
    let run_bytes = after
        .get(&std::ffi::OsString::from(run_name))
        .expect("durable run root bytes");
    let frame = crate::property_graph::storage::artifact::decode(
        crate::property_graph::storage::artifact::ContainerKind::Object,
        Some((
            report.run.root.object.store,
            report.run.root.object.artifact,
        )),
        run_bytes,
    )
    .expect("reopen framed run root");
    let block = frame
        .framed_block(report.run.root.block)
        .expect("reopen exact run block");
    assert_eq!(
        block.payload().get(..8),
        Some(b"ZGCP\x04\0\x01\0".as_slice())
    );

    let allocation = report.allocation_head.expect("allocation head");
    let allocation_name = format!("graph-{:032x}.zgraph", allocation.object.artifact.get());
    let allocation_bytes = after
        .get(&std::ffi::OsString::from(allocation_name))
        .expect("durable allocation root bytes");
    let allocation_frame = crate::property_graph::storage::artifact::decode(
        crate::property_graph::storage::artifact::ContainerKind::Object,
        Some((allocation.object.store, allocation.object.artifact)),
        allocation_bytes,
    )
    .expect("reopen framed allocation root");
    assert_eq!(
        allocation_frame
            .framed_block(allocation.block)
            .expect("reopen exact allocation block")
            .payload()
            .get(..8),
        Some(b"ZGCP\x05\0\x01\0".as_slice())
    );

    drop(admission);
    store.close().expect("close spill store");

    // Each refusal fires on the real maintenance path while one eligible
    // reclaim candidate waits, so a refusal that deleted or published
    // anything would be visible. The clean counterpart then selects it.
    let refusal_parent = super::tempfile::tempdir().expect("refusal parent");
    let path = refusal_parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    seed_reclaimable_manifest(&store, "refusal");
    let (base_generation, sparse_path, sparse_offset) = {
        let lease = store.admit_native_read().expect("refusal base reader");
        assert!(lease.bundle().reclaim().is_none());
        let text = lease
            .bundle()
            .roots()
            .directory(TreeKind::Nodes)
            .unwrap()
            .reference()
            .expect("actual node root");
        (
            lease.bundle().base().generation,
            path.join(format!("graph-{:032x}.zgraph", text.artifact.get())),
            text.offset + u64::from(text.length) / 2,
        )
    };
    // Source and artifact-proof reuse reduced this fixture's charged work:
    // census and fold end near 68K, and the graph mark runs 69K..317K.
    // The explicit 150K limit still refuses inside the graph mark, while
    // 4 KiB refuses before it. Both must override the inventory-sized default.
    for refusal in [
        "memory",
        "work before the mark",
        "work during the graph mark",
        "cancel after the first spill create",
        "spill create collision",
        "spill disk-full partial create",
        "corrupt sparse root artifact",
    ] {
        let before = directory_image(&path);
        let token = CancelToken::new();
        let control = QueryControl::Cancel(token.clone());
        let mut limits = super::super::maintenance::MaintenanceLimits::default();
        let mut restore = None;
        match refusal {
            "memory" => limits.storage_bytes = 256 * 1024,
            "work before the mark" => limits.work = Some(4 * 1024),
            "work during the graph mark" => limits.work = Some(150_000),
            "cancel after the first spill create" => {
                let token = token.clone();
                vfs.after_next_create(move || token.cancel());
            }
            "spill create collision" => vfs.arm_fault(super::publication::FaultPoint::Create),
            "spill disk-full partial create" => {
                vfs.arm_fault(super::publication::FaultPoint::PartialCreate);
            }
            _ => {
                let mut file = std::fs::OpenOptions::new()
                    .read(true)
                    .write(true)
                    .open(&sparse_path)
                    .expect("open sparse root artifact");
                let mut byte = [0_u8; 1];
                file.seek(SeekFrom::Start(sparse_offset)).expect("seek");
                file.read_exact(&mut byte).expect("read sparse byte");
                file.seek(SeekFrom::Start(sparse_offset)).expect("seek");
                file.write_all(&[byte[0] ^ 0xff])
                    .expect("corrupt sparse byte");
                restore = Some(byte[0]);
            }
        }
        vfs.take();
        let admission = store
            .admit_native_graph_maintenance()
            .expect("refusal maintenance admission");
        let error = store
            .commit_native_graph_maintenance_with_limits(&admission, &control, limits)
            .expect_err(refusal);
        drop(admission);
        if let Some(byte) = restore {
            let mut file = std::fs::OpenOptions::new()
                .write(true)
                .open(&sparse_path)
                .expect("reopen sparse root artifact");
            file.seek(SeekFrom::Start(sparse_offset)).expect("seek");
            file.write_all(&[byte]).expect("restore sparse byte");
        }
        use super::super::NativeGraphError as E;
        use crate::property_graph::storage::tree::directory::TreeError as T;
        let typed = match refusal {
            "memory" => matches!(error, E::Read(T::Memory)),
            "work before the mark" | "work during the graph mark" => {
                matches!(error, E::Read(T::Work))
            }
            "cancel after the first spill create" => {
                assert!(!vfs.after_create_is_armed(), "cancel hook never fired");
                matches!(error, E::Read(T::Control(_)))
            }
            "spill create collision" | "spill disk-full partial create" => {
                vfs.assert_fired_once();
                matches!(error, E::Io { .. })
            }
            _ => matches!(error, E::Read(T::Format(_))),
        };
        assert!(typed, "{refusal} returned {error:?}");
        if !matches!(
            refusal,
            "spill create collision" | "spill disk-full partial create"
        ) {
            super::publication::record_verified_fault();
        }
        let events = vfs.take();
        assert!(
            events
                .iter()
                .all(|event| !matches!(event, DurabilityEvent::Delete(_))),
            "{refusal} refusal deleted a file: {events:?}"
        );
        assert_live_files_unchanged(&path, &before);
        let lease = store.admit_native_read().expect("reader after refusal");
        assert_eq!(
            lease.bundle().base().generation,
            base_generation,
            "{refusal} published a generation"
        );
        assert!(
            lease.bundle().reclaim().is_none(),
            "{refusal} published a reclaim intent"
        );
    }

    // Clean counterpart: same store, default budgets, no fault. The candidate
    // that every refusal left alone is now selected, and still not deleted
    // before its intent is durable.
    let before = directory_image(&path);
    vfs.take();
    let admission = store
        .admit_native_graph_maintenance()
        .expect("clean counterpart admission");
    let report = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect("clean counterpart maintenance");
    drop(admission);
    assert_eq!(report.generation.get(), base_generation.get() + 2);
    assert_eq!(report.removed_bytes, 0);
    assert!(
        vfs.take()
            .iter()
            .all(|event| !matches!(event, DurabilityEvent::Delete(_)))
    );
    // The committed Maintenance envelope extends the active WAL; every other
    // preexisting byte stays where it was.
    let after = directory_image(&path);
    let mut grown = 0_usize;
    for (name, bytes) in &before {
        let current = after.get(name).expect("preexisting file survives");
        if name == "wal.ze" {
            assert!(current.starts_with(bytes), "WAL prefix changed: {name:?}");
            grown += usize::from(current.len() > bytes.len());
        } else {
            assert_eq!(current, bytes, "live file changed: {name:?}");
        }
    }
    assert_eq!(grown, 1, "exactly the active WAL takes the envelope");
    let pending = store.admit_native_read().expect("clean pending reader");
    let candidates = pending_reclaim_candidates(&store, &pending);
    assert!(
        !candidates.is_empty(),
        "the refusals ran without an eligible candidate"
    );
    for candidate in &candidates {
        let name = reclaim_candidate_path(&path, candidate)
            .file_name()
            .unwrap()
            .to_os_string();
        assert!(
            before.contains_key(&name),
            "candidate postdates the refusals"
        );
    }
    drop(pending);
    store.close().expect("close refusal store");
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CrashCell {
    Control,
    BeforeIntent,
    BeforeFirstUnlink,
    AfterOneUnlink,
    DirectorySync,
    BeforeCompletion,
    LostCompletionAck,
}

struct CrashHistory {
    provenance_phases: Vec<Ze166FenceEvidence>,
    _parent: super::tempfile::TempDir,
    path: std::path::PathBuf,
    vfs: Arc<RecordingVfs>,
    document: EmbeddingTower,
    first: crate::property_graph::NodeId,
    peer: crate::property_graph::NodeId,
    relationship: crate::property_graph::RelId,
}

impl CrashHistory {
    fn open(&self, options: OpenOptions) -> Result<Store, super::super::NativeGraphError> {
        let infrastructure: Arc<dyn Vfs> = self.vfs.clone();
        Store::open_native_graph_with_infrastructure(
            &self.path,
            options,
            Some(self.document.clone()),
            infrastructure,
            Arc::new(crate::lifecycle::SystemMonotonicClock),
        )
    }

    fn oracle(&self, store: &Store) -> [super::publication::GenerationSnapshot; 2] {
        let lease = store.admit_native_read().expect("oracle reader");
        [
            snapshot_for_lease(
                store,
                &lease,
                self.first,
                self.peer,
                self.relationship,
                None,
            ),
            snapshot_for_lease(
                store,
                &lease,
                self.peer,
                self.first,
                self.relationship,
                None,
            ),
        ]
    }
}

fn assert_same_logical_state(
    before: &[super::publication::GenerationSnapshot; 2],
    after: &[super::publication::GenerationSnapshot; 2],
) {
    for (before, after) in before.iter().zip(after) {
        assert!(after.generation >= before.generation);
        assert_eq!(after.revision, before.revision);
        assert_eq!(after.original_generation, before.original_generation);
        assert_eq!(after.canonical, before.canonical);
        assert_eq!(after.text, before.text);
        assert_eq!(after.vector, before.vector);
        assert_eq!(after.old_relationship, before.old_relationship);
        assert_eq!(after.out, before.out);
        assert_eq!(after.incoming, before.incoming);
        assert_eq!(after.sparse_text, before.sparse_text);
        assert_eq!(after.sparse_vector, before.sparse_vector);
    }
}

/// The one keyed request of the crash-table history. Applying it again after
/// any maintenance must replay the original receipts.
fn apply_crash_history_writes(
    store: &Store,
    document: &EmbeddingTower,
) -> super::super::write::NativePreparedResult<super::super::write::ReceiptRegistration> {
    crate::property_graph::with_local_refs(|refs| {
        let first_embedding =
            CanonicalEmbedding::new(document, &[0.25_f32, 0.75_f32]).expect("embedding");
        let first =
            CanonicalContents::node(&mut [], &mut [], Some("crash first"), Some(first_embedding))
                .expect("first node");
        let peer_embedding =
            CanonicalEmbedding::new(document, &[0.5_f32, 1.0_f32]).expect("peer embedding");
        let peer =
            CanonicalContents::node(&mut [], &mut [], Some("crash peer"), Some(peer_embedding))
                .expect("peer node");
        store
            .apply_native_graph(
                &[
                    StructuredWrite {
                        key: ApplicationKey::new(EntityKind::Node, "crash", "first")
                            .expect("first key"),
                        revision: GraphRevision::new(1).expect("revision"),
                        operation: StructuredOperation::Create,
                        image: Some(WriteImage::Node(&first)),
                    },
                    StructuredWrite {
                        key: ApplicationKey::new(EntityKind::Node, "crash", "peer")
                            .expect("peer key"),
                        revision: GraphRevision::new(1).expect("revision"),
                        operation: StructuredOperation::Create,
                        image: Some(WriteImage::Node(&peer)),
                    },
                    StructuredWrite {
                        key: ApplicationKey::new(EntityKind::Relationship, "crash", "edge")
                            .expect("relationship key"),
                        revision: GraphRevision::new(1).expect("revision"),
                        operation: StructuredOperation::Create,
                        image: Some(WriteImage::Relationship {
                            source: NodeRef::Local(refs.node(0).expect("first local node")),
                            target: NodeRef::Local(refs.node(1).expect("peer local node")),
                            relationship_type: GraphName::new("LINKS").expect("type"),
                            properties: &[],
                        }),
                    },
                ],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("seed crash-table history")
    })
}

/// Two embedded nodes and one edge, two physical replacements, then a
/// checkpoint: the next maintenance has several dead whole objects to select.
fn seed_crash_history() -> (CrashHistory, Store) {
    let parent = super::tempfile::tempdir().expect("crash parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let infrastructure: Arc<dyn Vfs> = vfs.clone();
    let document = EmbeddingTower {
        model_id: "ze46-crash-table".into(),
        model_version: "1".into(),
        weights_digest: vec![0x46, 0x09],
        dims: 2,
        normalization: Normalization::None,
        prompt_prefix: "doc: ".into(),
        max_tokens: 32,
        runtime: EmbeddingRuntime::CpuReference,
        compute_units: ComputeUnits::Cpu,
        os_build: None,
    };
    let store = Store::create_native_graph_with_infrastructure(
        &path,
        options(),
        Some(document.clone()),
        infrastructure,
        Arc::new(crate::lifecycle::SystemMonotonicClock),
        &mut crate::property_graph::storage::allocation::OsEntropy,
    )
    .expect("fresh crash-table store");
    let receipts = apply_crash_history_writes(&store, &document);
    // A second committed allocation gives AfterOneUnlink two native-object
    // candidates in addition to legacy checkpoint/WAL history.
    let spare =
        CanonicalContents::node(&mut [], &mut [], Some("second dead allocation"), None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "crash", "spare").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&spare)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
    let mut provenance_phases = vec![ze166_fence_evidence(&store)];
    let node = |index: usize| match receipts[index].entity {
        EntityId::Node(node) => node,
        EntityId::Relationship(_) => panic!("node receipt identity"),
    };
    let relationship = match receipts[2].entity {
        EntityId::Relationship(relationship) => relationship,
        EntityId::Node(_) => panic!("relationship receipt identity"),
    };
    for _ in 0..1 {
        let admission = store
            .admit_native_graph_maintenance()
            .expect("crash-table replacement admission");
        store
            .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
            .expect("crash-table physical replacement");
    }
    provenance_phases.push(ze166_fence_evidence(&store));
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint releases crash-table WAL protection");
    provenance_phases.push(ze166_fence_evidence(&store));
    (
        CrashHistory {
            provenance_phases,
            _parent: parent,
            path,
            vfs,
            document,
            first: node(0),
            peer: node(1),
            relationship,
        },
        store,
    )
}

pub(super) fn commit_maintenance(
    store: &Store,
) -> Result<super::super::maintenance::NativeMaintenanceReport, super::super::NativeGraphError> {
    let admission = store
        .admit_native_graph_maintenance()
        .expect("maintenance admission");
    let before = admission.lease.bundle();
    let result = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()));
    if matches!(
        result,
        Err(super::super::NativeGraphError::StalePreparation)
    ) {
        let current = store
            .admit_native_graph_maintenance()
            .expect("folded admission");
        let after = current.lease.bundle();
        // A bounded retry is only for the documented retirement fold. Every
        // assertion below still applies to the accepted attempt's result.
        if after.base().generation != before.base().generation
            || after.sequence() != before.sequence()
            || after.base().fold == before.base().fold
        {
            return result;
        }
        return store
            .commit_native_graph_maintenance(&current, &QueryControl::Cancel(CancelToken::new()));
    }
    result
}

fn delete_events(events: &[DurabilityEvent]) -> Vec<std::path::PathBuf> {
    events
        .iter()
        .filter_map(|event| match event {
            DurabilityEvent::Delete(path) => Some(path.clone()),
            _ => None,
        })
        .collect()
}

fn run_reclaim_crash_cell(cell: CrashCell) {
    let _ = run_reclaim_crash_cell_observed(cell, false);
}
fn run_reclaim_crash_cell_observed(
    cell: CrashCell,
    retain: bool,
) -> crate::graph_commit_recovery_test_support::ReclaimEvidence {
    run_reclaim_crash_cell_fenced(cell, retain, false)
}

#[test]
fn a_reclaim_unlink_error_fences_the_shared_writers_until_reopen() {
    let _ = run_reclaim_crash_cell_fenced(CrashCell::AfterOneUnlink, false, true);
}

fn run_reclaim_crash_cell_fenced(
    cell: CrashCell,
    retain: bool,
    check_fence: bool,
) -> crate::graph_commit_recovery_test_support::ReclaimEvidence {
    use super::publication::FaultPoint;
    let (history, mut store) = seed_crash_history();
    let vfs = Arc::clone(&history.vfs);
    let oracle = history.oracle(&store);
    let mut error_observation = None;
    let input_image = directory_image(&history.path);

    if cell == CrashCell::BeforeIntent {
        let before = directory_image(&history.path);
        vfs.take();
        vfs.arm_fault(FaultPoint::Append);
        let error = commit_maintenance(&store).expect_err("intent WAL append fault");
        error_observation = Some(
            format!("{error:?}").replace(&history.path.to_string_lossy().to_string(), "<store>"),
        );
        assert!(
            matches!(
                error,
                super::super::NativeGraphError::CommitIndeterminate { .. }
            ),
            "{error:?}"
        );
        vfs.assert_fired_once();
        assert!(delete_events(&vfs.take()).is_empty());
        assert_live_files_unchanged(&history.path, &before);
        store.close().expect("close store stopped before intent");
        store = history
            .open(options())
            .expect("reopen without durable intent");
        let lease = store.admit_native_read().expect("no-intent reader");
        assert!(lease.bundle().reclaim().is_none(), "intent was not durable");
        drop(lease);
        assert!(delete_events(&vfs.take()).is_empty());
        assert_live_files_unchanged(&history.path, &before);
    }

    vfs.take();
    let intent = commit_maintenance(&store).expect("durable reclaim intent");
    assert_eq!(intent.removed_bytes, 0);
    assert!(delete_events(&vfs.take()).is_empty());
    let pending = store.admit_native_read().expect("pending reader");
    let candidates = pending_reclaim_candidates(&store, &pending);
    let inventory_pending = format!(
        "{:?}",
        complete_inventory_union_for_lease(&store, &pending)
            .into_iter()
            .filter(|r| candidates.iter().any(|c| c.artifact == r.object.artifact))
            .collect::<Vec<_>>()
    );
    let pending_proof = format!("{:?}", pending_reclaim_proof_for_lease(&store, &pending));
    drop(pending);
    // Unlink authority must be in the manifest before the unlink/sync faults.
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("fold pending proof before reclaim faults");
    if retain {
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("retain the folded pending proof");
    }
    let checkpoint = store.admit_native_read().unwrap();
    let replayed_proof = format!("{:?}", pending_reclaim_proof_for_lease(&store, &checkpoint));
    let inventory_replayed = format!(
        "{:?}",
        complete_inventory_union_for_lease(&store, &checkpoint)
            .into_iter()
            .filter(|r| candidates.iter().any(|c| c.artifact == r.object.artifact))
            .collect::<Vec<_>>()
    );
    drop(checkpoint);
    assert!(
        candidates.len() >= 2,
        "one unlink must leave work: {candidates:?}"
    );
    let targets: Vec<_> = candidates
        .iter()
        .map(|candidate| reclaim_candidate_path(&history.path, candidate))
        .collect();
    let candidate_bytes: u64 = candidates
        .iter()
        .map(|candidate| u64::from(candidate.bytes))
        .sum();
    for (target, candidate) in targets.iter().zip(&candidates) {
        assert_eq!(
            std::fs::metadata(target).expect("pending target").len(),
            u64::from(candidate.bytes),
            "intent names the exact on-disk length"
        );
    }

    // The fault fires inside the real resume operation of the open store.
    match cell {
        CrashCell::Control | CrashCell::BeforeIntent => {}
        CrashCell::BeforeFirstUnlink => vfs.arm_fault(FaultPoint::Delete),
        CrashCell::AfterOneUnlink => vfs.arm_fault_after(FaultPoint::Delete, 1),
        CrashCell::DirectorySync => vfs.arm_fault(FaultPoint::DirectorySync),
        CrashCell::BeforeCompletion => vfs.arm_fault(FaultPoint::Append),
        CrashCell::LostCompletionAck => vfs.arm_fault(FaultPoint::WalSync),
    }
    let faulted = !matches!(cell, CrashCell::Control | CrashCell::BeforeIntent);
    let resumed = commit_maintenance(&store);
    let first_events = vfs.take();
    let first_deletes = delete_events(&first_events);
    if faulted {
        let error = resumed.expect_err("armed resume fault");
        error_observation = Some(
            format!("{error:?}").replace(&history.path.to_string_lossy().to_string(), "<store>"),
        );
        vfs.assert_fired_once();
        let expected_deletes = match cell {
            CrashCell::BeforeFirstUnlink => 0,
            CrashCell::AfterOneUnlink => 1,
            _ => targets.len(),
        };
        assert_eq!(first_deletes.len(), expected_deletes, "{cell:?}: {error:?}");
    } else {
        let report = resumed.expect("clean in-process resume");
        assert_eq!(report.reclaimed_bytes, candidate_bytes);
        assert_eq!(report.removed_bytes, candidate_bytes);
        assert_eq!(report.already_missing, 0);
        assert_eq!(first_deletes.len(), targets.len());
    }
    assert_unlink_order(&first_events, cell);
    if check_fence {
        super::recovery::assert_shared_writer_stopped(&store);
        vfs.take(); // Discard the refused writers' private preparation events.
    }
    store.close().expect("close crashed reclaim store");

    // Read-only recovery adopts whatever partition the crash left and
    // performs no VFS mutation at all, not even a same-byte rewrite.
    let before_read_only = directory_image(&history.path);
    let read_only = history
        .open(
            OpenOptions::read_only()
                .with_durability(DurabilityMode::Durable, CommitTier::Durable)
                .with_max_resident_bytes(256 * 1024 * 1024),
        )
        .expect("read-only recovery over the crashed partition");
    assert_same_logical_state(&oracle, &history.oracle(&read_only));
    read_only.close().expect("close read-only crashed store");
    let read_only_events = vfs.take();
    assert!(
        read_only_events.is_empty(),
        "{cell:?}: read-only recovery mutated the VFS: {read_only_events:?}"
    );
    assert_eq!(directory_image(&history.path), before_read_only);

    // Writable recovery resumes exactly the unlinks that are still owed.
    let writable = history.open(options()).expect("writable resume");
    let resume_events = vfs.take();
    let resume_deletes = delete_events(&resume_events);
    let mut all_deletes = first_deletes.clone();
    all_deletes.extend(resume_deletes.iter().cloned());
    all_deletes.sort();
    let mut expected = targets.clone();
    expected.sort();
    assert_eq!(
        all_deletes, expected,
        "{cell:?}: each target unlinks exactly once"
    );
    assert_unlink_order(&resume_events, cell);
    for target in &targets {
        assert!(!target.exists(), "{cell:?}: completed target survives");
    }
    let completed = writable.admit_native_read().expect("completion reader");
    let (completion, completed_candidates) = completed_reclaim_for_lease(&writable, &completed);
    assert_eq!(completion.completed_count, candidates.len());
    assert_eq!(completion.remaining_count, 0);
    assert_eq!(completed_candidates, candidates);
    drop(completed);
    assert_same_logical_state(&oracle, &history.oracle(&writable));
    let mut provenance_phases = history.provenance_phases.clone();
    provenance_phases.push(ze166_fence_evidence(&writable));
    let retry = apply_crash_history_writes(&writable, &history.document);
    assert!(retry.iter().all(|r| r.replayed));
    let retry_receipts = format!("{:?}", retry.iter().collect::<Vec<_>>());
    let completion_observation = format!("{completion:?} {completed_candidates:?}");
    writable.close().expect("close resumed reclaim store");
    let final_image = directory_image(&history.path);
    let reopened = history.open(options()).expect("idempotent reopen");
    assert!(delete_events(&vfs.take()).is_empty());
    reopened.close().expect("close idempotent reopen");
    for (name, bytes) in &final_image {
        if name != "wal.ze" {
            assert_eq!(directory_image(&history.path).get(name), Some(bytes));
        }
    }
    crate::graph_commit_recovery_test_support::ReclaimEvidence {
        cell: format!("{cell:?}"),
        provenance_phases,
        inventory_pending,
        inventory_replayed,
        pending_proof,
        replayed_proof,
        completion: completion_observation,
        retry_receipts,
        error: error_observation,
        input_image: input_image
            .into_iter()
            .map(|(n, b)| (n.to_string_lossy().into_owned(), b))
            .collect(),
        durable_image: final_image
            .into_iter()
            .map(|(n, b)| (n.to_string_lossy().into_owned(), b))
            .collect(),
        fires: u64::from(cell != CrashCell::Control),
        controls: u64::from(cell == CrashCell::Control),
    }
}

/// The event right after the last unlink is the directory Full-sync: no
/// completion object or WAL byte may be written while an unlink is volatile.
/// The completion commit issues directory syncs of its own, so only
/// adjacency distinguishes the required sync from those.
fn assert_unlink_order(events: &[DurabilityEvent], cell: CrashCell) {
    let Some(last_delete) = events
        .iter()
        .rposition(|event| matches!(event, DurabilityEvent::Delete(_)))
    else {
        return;
    };
    let after = events.get(last_delete + 1..).unwrap_or_default();
    if let Some(next) = after.first() {
        assert!(
            matches!(next, DurabilityEvent::Sync(path, crate::vfs::SyncKind::Full) if path.is_dir()),
            "{cell:?}: {next:?} follows the last unlink before a directory Full-sync"
        );
    }
    let first_delete = events
        .iter()
        .position(|event| matches!(event, DurabilityEvent::Delete(_)))
        .unwrap_or(last_delete);
    assert!(
        events[first_delete..=last_delete]
            .iter()
            .all(|event| matches!(event, DurabilityEvent::Delete(_))),
        "{cell:?}: unlinks interleave with other durable work: {events:?}"
    );
}

fn completed_reclaim_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> (
    crate::property_graph::storage::reclaim::CompletedIntentManifest,
    Vec<ArtifactDescriptor>,
) {
    let required = lease
        .bundle()
        .reclaim()
        .expect("durable reclaim completion");
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("completion resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("completion memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage memory");
    let source = NativePreparationSource::new(lease, &memory, 1).expect("completion source");
    let mut resources = source.resources(32 * 1024 * 1024).expect("tree resources");
    let block = source
        .resolve(required.block, &mut resources)
        .expect("resolve reclaim completion");
    let manifest =
        crate::property_graph::storage::reclaim::decode_completed_intent_manifest(block.payload())
            .expect("decode reclaim completion");
    let candidates = (0..manifest.completed_count)
        .map(|index| {
            crate::property_graph::storage::reclaim::completed_intent_candidate_at(
                block.payload(),
                index,
            )
            .expect("completed candidate")
        })
        .collect();
    (manifest, candidates)
}

#[test]
fn ze46_intent_unlink_sync_completion_crashes_resume_idempotently() {
    run_ze46_intent_unlink_sync_completion_crashes_resume_idempotently();
}

fn run_ze46_intent_unlink_sync_completion_crashes_resume_idempotently() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("fresh native store");
    let image =
        CanonicalContents::node(&mut [], &mut [], Some("reclaim me"), None).expect("node image");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "reclaim", "node")
                    .expect("application key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("seed reclaim object");
    let seeded = store.admit_native_read().expect("seeded reclaim reader");
    let superseded_manifest = seeded
        .bundle()
        .prepared_inventories()
        .first()
        .copied()
        .expect("seeded prepared manifest")
        .object;
    drop(seeded);
    let first = store
        .admit_native_graph_maintenance()
        .expect("first maintenance admission");
    store
        .commit_native_graph_maintenance(&first, &QueryControl::Cancel(CancelToken::new()))
        .expect("first physical replacement");
    drop(first);
    let replaced = store.admit_native_read().expect("replaced graph reader");
    assert!(
        !replaced
            .bundle()
            .prepared_inventories()
            .iter()
            .any(|required| required.object == superseded_manifest),
        "completed fold retires the superseded manifest root"
    );
    assert!(
        rooted_inventory_for_lease(&store, &replaced)
            .iter()
            .any(|change| change.object == superseded_manifest),
        "retired manifest remains in the allocation inventory"
    );
    drop(replaced);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint releases historical WAL protection");

    let second = store
        .admit_native_graph_maintenance()
        .expect("intent maintenance admission");
    let intent_report = store
        .commit_native_graph_maintenance(&second, &QueryControl::Cancel(CancelToken::new()))
        .expect("durable reclaim intent");
    drop(second);
    assert_eq!(intent_report.removed_bytes, 0);
    let pending = store.admit_native_read().expect("pending reclaim reader");
    let candidates = pending_reclaim_candidates(&store, &pending);
    assert!(
        !candidates.is_empty(),
        "real dead objects entered the intent"
    );
    assert!(
        candidates.contains(&superseded_manifest),
        "superseded manifest is the named whole dead allocation"
    );
    for candidate in &candidates {
        assert!(
            reclaim_candidate_path(&path, candidate).exists(),
            "intent commit precedes unlink"
        );
    }
    drop(pending);
    store.close().expect("close pending reclaim store");

    let read_options = OpenOptions::read_only()
        .with_durability(DurabilityMode::Durable, CommitTier::Durable)
        .with_max_resident_bytes(256 * 1024 * 1024);
    let before_read_only = directory_image(&path);
    let read_only = Store::open_native_graph(&path, read_options, None)
        .expect("read-only pending reclaim recovery");
    assert_eq!(directory_image(&path), before_read_only);
    read_only.close().expect("close read-only pending reclaim");

    let writable = Store::open_native_graph(&path, options(), None)
        .expect("writable pending reclaim recovery");
    for candidate in &candidates {
        assert!(
            !reclaim_candidate_path(&path, candidate).exists(),
            "completed target is physically absent"
        );
    }
    let completed = writable
        .admit_native_read()
        .expect("automatically resumed reclaim reader");
    let completion = completed
        .bundle()
        .reclaim()
        .expect("durable reclaim completion");
    let shared = crate::property_graph::resources::GraphResources::from_store(&writable)
        .expect("shared completion resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("completion memory");
    let memory =
        StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("completion storage memory");
    let source = NativePreparationSource::new(&completed, &memory, 1).expect("completion source");
    let mut resources = source
        .resources(32 * 1024 * 1024)
        .expect("completion resources");
    let block = source
        .resolve(completion.block, &mut resources)
        .expect("resolve reclaim completion");
    let manifest =
        crate::property_graph::storage::reclaim::decode_completed_intent_manifest(block.payload())
            .expect("decode reclaim completion");
    assert_eq!(manifest.completed_count, candidates.len());
    assert_eq!(manifest.remaining_count, 0);
    drop(completed);
    let checkpoint_admission = writable
        .admit_native_graph_maintenance()
        .expect("completed reclaim checkpoint admission");
    let error = writable
        .commit_native_graph_maintenance(
            &checkpoint_admission,
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect_err("completion checkpoint replaces its admission");
    assert!(matches!(
        error,
        super::super::NativeGraphError::StalePreparation
    ));
    drop(checkpoint_admission);
    let checkpointed = writable
        .admit_native_read()
        .expect("checkpointed completion reader");
    assert_eq!(
        checkpointed.bundle().base().fold.envelope_sequence,
        checkpointed.bundle().sequence()
    );
    assert!(checkpointed.bundle().reclaim().is_some());
    drop(checkpointed);
    let clear_admission = writable
        .admit_native_graph_maintenance()
        .expect("completed reclaim clear admission");
    writable
        .commit_native_graph_maintenance(
            &clear_admission,
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("clear and checkpoint completed reclaim");
    drop(clear_admission);
    let cleared = writable
        .admit_native_read()
        .expect("cleared reclaim reader");
    assert!(cleared.bundle().reclaim().is_none());
    assert_eq!(
        cleared.bundle().base().fold.envelope_sequence,
        cleared.bundle().sequence()
    );
    drop(cleared);
    writable.close().expect("close completed reclaim store");
    let reopened =
        Store::open_native_graph(&path, options(), None).expect("reopen completed reclaim store");
    reopened.close().expect("close reopened reclaim store");

    for cell in [
        CrashCell::Control,
        CrashCell::BeforeIntent,
        CrashCell::BeforeFirstUnlink,
        CrashCell::AfterOneUnlink,
        CrashCell::DirectorySync,
        CrashCell::BeforeCompletion,
        CrashCell::LostCompletionAck,
    ] {
        run_reclaim_crash_cell(cell);
    }
}

#[test]
fn ze46_readonly_pending_reclaim_and_checkpoint_retirement_are_exact() {
    run_ze46_readonly_pending_reclaim_and_checkpoint_retirement_are_exact();
}

fn run_ze46_readonly_pending_reclaim_and_checkpoint_retirement_are_exact() {
    // The partly unlinked read-only cell lives in the crash table, which
    // asserts zero VFS events and identical bytes for that partition.
    run_reclaim_crash_cell(CrashCell::AfterOneUnlink);

    let (history, store) = seed_crash_history();
    let oracle = history.oracle(&store);
    let held = store.admit_native_read().expect("held pre-intent reader");
    let held_snapshot = |store: &Store| {
        snapshot_for_lease(
            store,
            &held,
            history.first,
            history.peer,
            history.relationship,
            None,
        )
    };
    let held_before = held_snapshot(&store);
    let proof_path = |required: crate::property_graph::wal::RequiredRef| {
        crate::property_graph::storage::allocation::artifact_path(
            &history.path,
            required.object.artifact,
        )
    };

    commit_maintenance(&store).expect("durable reclaim intent");
    let pending = store.admit_native_read().expect("pending reader");
    let intent = pending.bundle().reclaim().expect("pending intent root");
    drop(pending);
    let resumed = commit_maintenance(&store).expect("in-process resume");
    assert!(resumed.removed_bytes > 0);
    assert_eq!(
        held_snapshot(&store),
        held_before,
        "unlink reached a held reader"
    );
    let completed = store.admit_native_read().expect("completed reader");
    let completion = completed.bundle().reclaim().expect("completion root");
    assert_ne!(completion, intent);
    assert_ne!(
        completed.bundle().base().fold.envelope_sequence,
        completed.bundle().sequence(),
        "completion is WAL-only before its checkpoint"
    );
    drop(completed);

    // Retirement step one checkpoints the completion and replaces its own
    // admission. The proof stays rooted and on disk.
    let admission = store.admit_native_graph_maintenance().unwrap();
    let error = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()))
        .expect_err("completion checkpoint");
    drop(admission);
    assert!(
        matches!(error, super::super::NativeGraphError::StalePreparation),
        "{error:?}"
    );
    let checkpointed = store
        .admit_native_read()
        .expect("checkpointed completion reader");
    assert_eq!(checkpointed.bundle().reclaim(), Some(completion));
    assert_eq!(
        checkpointed.bundle().base().fold.envelope_sequence,
        checkpointed.bundle().sequence()
    );
    drop(checkpointed);
    for required in [intent, completion] {
        assert!(
            proof_path(required).exists(),
            "proof vanished before retirement"
        );
    }
    assert_eq!(held_snapshot(&store), held_before);

    // Step two clears the checkpointed completion. Only now is the proof
    // unrooted; the held reader still reads its original bytes.
    let cleared_report = commit_maintenance(&store).expect("clear completed reclaim");
    assert_eq!(cleared_report.removed_bytes, 0);
    let cleared = store.admit_native_read().expect("cleared reader");
    assert!(cleared.bundle().reclaim().is_none());
    assert_eq!(
        cleared.bundle().base().fold.envelope_sequence,
        cleared.bundle().sequence()
    );
    drop(cleared);
    assert_eq!(held_snapshot(&store), held_before);
    assert_same_logical_state(&oracle, &history.oracle(&store));

    // The retired intent page is unrooted garbage with no inventory row. A
    // quiescent maintenance adopts it as bookkeeping; the next cycle unlinks
    // it through a durable intent like any other object.
    let retired_intent = proof_path(intent);
    assert!(retired_intent.exists());
    for _ in 0..24 {
        if !retired_intent.exists() {
            break;
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("checkpoint between retirement rounds");
        match commit_maintenance(&store) {
            Ok(_) | Err(super::super::NativeGraphError::StalePreparation) => {}
            Err(error) => panic!("post-retirement maintenance failed: {error:?}"),
        }
        assert_eq!(held_snapshot(&store), held_before);
    }
    assert!(
        !retired_intent.exists(),
        "the retired reclaim intent page was never reclaimed"
    );
    assert_same_logical_state(&oracle, &history.oracle(&store));
    drop(held);
    store.close().expect("close retirement store");

    // Reclaim folds before capture, including at the legacy 64-envelope boundary.
    let parent = super::tempfile::tempdir().expect("boundary parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    // Pin the maintenance/checkpoint envelope boundary without automatic folds.
    store
        .set_native_graph_maintenance_policy(crate::property_graph::GraphMaintenancePolicy {
            automatic: false,
            ..Default::default()
        })
        .expect("isolate 64-envelope maintenance boundary");
    let envelopes = |store: &Store| {
        store
            .native_graph
            .writer
            .lock()
            .expect("native writer")
            .as_ref()
            .expect("installed writer")
            .complete_envelopes
    };
    for index in 0..64 {
        let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node image");
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "boundary", &index.to_string())
                        .expect("boundary key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new()),
            )
            .expect("boundary write");
    }
    assert_eq!(envelopes(&store), 64);
    let before = store.admit_native_read().expect("pre-boundary reader");
    let sequence = before.bundle().sequence();
    let generation = before.bundle().base().generation;
    drop(before);
    commit_maintenance(&store).expect("fold then capture at the envelope limit");
    assert_eq!(envelopes(&store), 1);
    let capture = store
        .capture_native_read_roots()
        .expect("post-boundary capture");
    let wal = capture.wal().expect("post-boundary WAL");
    assert!(wal.bytes() > crate::property_graph::wal::HEADER_BYTES);
    assert_eq!(capture.bundles().first().unwrap().sequence(), sequence + 1);
    drop(capture);
    let after = store.admit_native_read().expect("post-boundary reader");
    assert_eq!(after.bundle().sequence(), sequence + 1);
    assert_eq!(after.bundle().base().generation.get(), generation.get() + 2);
    assert_eq!(after.bundle().base().fold.envelope_sequence, sequence);
    assert_eq!(
        after.bundle().base().fold.manifest_generation,
        generation.get() + 1
    );
    drop(after);
    store.close().expect("close boundary store");
}

#[test]
fn ze46_corrupt_or_incomplete_reclaim_proof_refuses_before_mutation() {
    run_ze46_corrupt_or_incomplete_reclaim_proof_refuses_before_mutation();
}

fn run_ze46_corrupt_or_incomplete_reclaim_proof_refuses_before_mutation() {
    let parent = super::tempfile::tempdir().expect("temporary parent");
    let path = parent.path().join("omitted-live-root");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    seed_reclaimable_manifest(&store, "omitted-live-root");

    let admission = store
        .admit_native_graph_maintenance()
        .expect("omitted-root maintenance admission");
    let live = admission.lease.bundle().catalog().block;
    assert!(
        complete_inventory_union_for_lease(&store, &admission.lease)
            .iter()
            .any(|change| change.object.artifact == live.artifact),
        "selected live catalog is an authentic inventory descriptor"
    );
    let before = directory_image(&path);
    vfs.take();
    omit_mark_artifact_for_test(live.artifact);
    let result = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()));
    let omitted = take_omitted_mark_emissions_for_test();
    assert!(omitted > 0, "directed omission reached the live mark edge");
    assert!(
        matches!(
            &result,
            Err(super::super::NativeGraphError::Read(
                crate::property_graph::storage::tree::directory::TreeError::Invalid(
                    "protected root is absent from completed mark"
                )
            ))
        ),
        "a protected live root omitted from the completed mark must refuse: {result:?}"
    );
    assert_live_files_unchanged(&path, &before);
    assert!(
        vfs.take()
            .iter()
            .all(|event| !matches!(event, DurabilityEvent::Delete(_))),
        "invalid proof must never unlink a candidate"
    );
    drop(admission);
    store.close().expect("close refused reclaim proof store");

    let missing_path = parent.path().join("missing-mark-stream");
    let missing_vfs = Arc::new(RecordingVfs::default());
    let missing_store = create_reclaim_test_store(&missing_path, &missing_vfs);
    seed_reclaimable_manifest(&missing_store, "missing-mark-stream");
    let pending_admission = missing_store
        .admit_native_graph_maintenance()
        .expect("missing-stream intent admission");
    missing_store
        .commit_native_graph_maintenance(
            &pending_admission,
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("real pending intent for missing-stream control");
    drop(pending_admission);
    let pending = missing_store
        .admit_native_read()
        .expect("missing-stream pending reader");
    let (manifest, candidates) = pending_reclaim_proof_for_lease(&missing_store, &pending);
    assert!(
        !candidates.is_empty(),
        "real pending intent has a candidate"
    );
    drop(pending);
    missing_store
        .close()
        .expect("close missing-stream pending store");

    let mark_path = crate::property_graph::storage::allocation::artifact_path(
        &missing_path,
        manifest.mark.root.object.artifact,
    );
    let mark_bytes = std::fs::read(&mark_path).expect("completed mark root bytes");
    std::fs::remove_file(&mark_path).expect("remove completed mark root");
    let missing_before = directory_image(&missing_path);
    missing_vfs.take();
    let infrastructure: Arc<dyn Vfs> = missing_vfs.clone();
    let reopened = Store::open_native_graph_with_infrastructure(
        &missing_path,
        options(),
        None,
        infrastructure,
        Arc::new(crate::lifecycle::SystemMonotonicClock),
    );
    if let Ok(store) = reopened {
        store.close().expect("close unexpectedly admitted store");
        panic!("missing completed mark stream was admitted");
    }
    assert_eq!(directory_image(&missing_path), missing_before);
    assert!(
        missing_vfs
            .take()
            .iter()
            .all(|event| matches!(event, DurabilityEvent::OpenAppend(_))),
        "missing proof stream must refuse before any VFS mutation"
    );
    std::fs::write(mark_path, mark_bytes).expect("restore completed mark root");
}

#[test]
fn ze46_protected_union_keeps_partial_packs_and_actual_sparse_refs() {
    run_ze46_protected_union_keeps_partial_packs_and_actual_sparse_refs();
}

fn run_ze46_protected_union_keeps_partial_packs_and_actual_sparse_refs() {
    let (history, store) = seed_crash_history();
    settle_reclaim_for_test(&store);
    let _selection =
        crate::property_graph::storage::consolidation::pin_selection_for_test(history.first);
    let control = QueryControl::Cancel(CancelToken::new());
    let reader = store.admit_native_read().unwrap();
    let old = snapshot_for_lease(
        &store,
        &reader,
        history.first,
        history.peer,
        history.relationship,
        None,
    );
    let old_record = record_physical_for_lease(&store, &reader, history.first);

    let protected_allocations = complete_inventory_union_for_lease(&store, &reader);
    let registration = reader.register_prepared(&protected_allocations).unwrap();
    // Supersede the reader's sparse leaves before capturing the new proof.
    ze163_keyed_write(
        &store,
        &history.document,
        "crash",
        "first",
        2,
        StructuredOperation::Put(EntityId::Node(history.first)),
        "current sparse leaf differs from retained reader",
        [0.9, 0.1],
    );
    // A real reader and preparation survive a later fold without history retrace.
    store.checkpoint_native_graph(&control).unwrap();
    commit_maintenance(&store).unwrap();
    let current = store.admit_native_read().unwrap();
    let (records, mark) = durable_proof_for_lease(&store, &current);
    assert!(
        records
            .iter()
            .all(|record| record.class != ProtectedClass::Reader
                || matches!(record.value, ProtectedValue::Required(_)))
    );
    assert!(records.iter().any(|record| record.class == ProtectedClass::Reader
        && matches!(record.value, ProtectedValue::Required(required) if required.block == old_record.reference())));
    assert!(
        mark.contains(&old_record.reference().artifact),
        "retained record closure missing"
    );
    for change in &protected_allocations {
        assert!(records.contains(&ProtectedRecord::descriptor(
            ProtectedClass::PreparedAllocation,
            change.object
        )));
        assert!(mark.contains(&change.object.artifact));
    }
    let candidates = pending_reclaim_candidates_or_empty_root(&store, &current);
    assert!(candidates.iter().all(|candidate| {
        candidate.family == 17
            && protected_allocations
                .iter()
                .all(|change| change.object != *candidate)
    }));
    assert_eq!(
        snapshot_for_lease(
            &store,
            &reader,
            history.first,
            history.peer,
            history.relationship,
            None
        ),
        old
    );
    drop(current);
    drop(registration);
    drop(reader);
    // Release makes whole dead allocations eligible; the crash matrix checks
    // their exact descriptors, unlink ordering and repeated recovery.
    store.close().unwrap();
    let reopened = history.open(options()).unwrap();
    let expected = history.oracle(&reopened);
    commit_maintenance(&reopened).unwrap();
    assert_same_logical_state(&expected, &history.oracle(&reopened));
    reopened.close().unwrap();
}
#[test]
fn older_wal_manifest_retention_without_explicit_registration() {
    run_older_wal_manifest_retention_without_explicit_registration();
}

fn run_older_wal_manifest_retention_without_explicit_registration() {
    // The former WAL-only authority is now carried by the proof itself.
    run_self_contained_proof();
}
#[cfg(feature = "test-seams")]
#[test]
fn ze46_reclaim_oracle_catches_early_unlink_and_missing_wal_protection() {
    run_ze46_reclaim_oracle_catches_early_unlink_and_missing_wal_protection();
}

/// The two guards an unsafe reclaimer would break, then the observations the
/// independent runner comparator consumes. Planted production defects make
/// this case fail for the intended reason: an unlink before the durable
/// intent breaks the before-intent crash cell, and a mark that skips the
/// uncheckpointed WAL references breaks the WAL-only witness.
#[cfg(feature = "test-seams")]
fn run_ze46_reclaim_oracle_catches_early_unlink_and_missing_wal_protection() {
    run_older_wal_manifest_retention_without_explicit_registration();
    run_reclaim_crash_cell(CrashCell::BeforeIntent);
    wal_only_witness_is_guarded_and_never_selected();
    let state = observe_reclaim_cycle();
    assert_eq!(
        state.relationships,
        vec![crate::graph_read_view_test_support::ObservedRelationship {
            rel: 1,
            source: state.first_node,
            target: state.second_node,
            relationship_type: 1,
        }],
        "the committed relationship did not survive the reclaim cycle"
    );
    assert!(
        state.replayed,
        "the original request was not an exact replay"
    );
    assert_eq!(
        state.replay_generation, 2,
        "replay lost its original generation"
    );
    assert!(state.removed_bytes > 0);
    assert_eq!(state.removed_bytes, state.unlinked_file_bytes);
}

/// A manifest that only the uncheckpointed WAL still protects. With its mark
/// edge omitted the independent guard refuses before any mutation; with the
/// real mark it is never a candidate and its bytes never change.
#[cfg(feature = "test-seams")]
fn wal_only_witness_is_guarded_and_never_selected() {
    run_ze46_corrupt_or_incomplete_reclaim_proof_refuses_before_mutation();
}
/// One single-node create, keyed by group and index, so a ZE-163 history is
/// a run of one-envelope commits over an otherwise fixed store.
fn ze163_base_write(store: &Store, group: &str, index: usize) {
    let text = format!("ze163 {group} row {index}");
    let image =
        CanonicalContents::node(&mut [], &mut [], Some(&text), None).expect("ze163 node image");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, group, &index.to_string())
                    .expect("ze163 key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("ze163 write");
}

/// ZE-163: one durable proof walks one captured state completely per bundle,
/// the bundle's checkpoint, plus the bundle's own target roots. Every
/// uncheckpointed envelope between them contributes only its change
/// references and the roots replay maps before it replays that envelope, so
/// proof cost follows the changed paths and not the history length, on the
/// producer and again on every reopen over the pending reclaim.
#[test]
fn ze163_proof_work_grows_with_changed_paths_not_with_history_length() {
    run_ze163_proof_work_grows_with_changed_paths_not_with_history_length();
}

fn run_ze163_proof_work_grows_with_changed_paths_not_with_history_length() {
    const HISTORY: [usize; 3] = [1, 4, 16];
    const BASE_ROWS: usize = 40;
    let mut producer_traces = Vec::new();
    let mut recovery_traces = Vec::new();
    let mut proof_work = Vec::new();
    for envelopes in HISTORY {
        let parent = super::tempfile::tempdir().expect("ze163 parent");
        let path = parent.path().join("native");
        let vfs = Arc::new(RecordingVfs::default());
        let store = create_reclaim_test_store(&path, &vfs);
        // A fixed base, large enough that one full traversal costs far more
        // than one single-node envelope's own rewritten root paths.
        for index in 0..BASE_ROWS {
            ze163_base_write(&store, "ze163-base", index);
        }
        // One replacement before the checkpoint leaves reclaimable packs, so
        // the measured maintenance publishes a real pending intent and the
        // reopen below has an authority to revalidate.
        commit_maintenance(&store).expect("ze163 base replacement");
        settle_reclaim_for_test(&store);
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .expect("ze163 base checkpoint");
        for index in 0..envelopes {
            ze163_base_write(&store, "ze163-tail", index);
        }
        let _ = crate::lifecycle::native_graph::recovery::take_state_trace_count_for_test();
        commit_maintenance(&store).expect("ze163 maintenance");
        producer_traces
            .push(crate::lifecycle::native_graph::recovery::take_state_trace_count_for_test());
        proof_work.push(
            store
                .native_graph
                .proof_work
                .load(std::sync::atomic::Ordering::Acquire),
        );
        {
            let lease = store.admit_native_read().expect("ze163 pending reader");
            assert!(
                lease.bundle().reclaim().is_some(),
                "the measured maintenance must publish a pending reclaim intent"
            );
            drop(lease);
        }
        store.close().expect("ze163 close");
        let _ = crate::lifecycle::native_graph::recovery::take_state_trace_count_for_test();
        let reopened =
            Store::open_native_graph(&path, options(), None).expect("ze163 reopen over reclaim");
        recovery_traces
            .push(crate::lifecycle::native_graph::recovery::take_state_trace_count_for_test());
        reopened.close().expect("ze163 close reopened");
    }
    let report = format!(
        "history={HISTORY:?} producer={producer_traces:?} \
         recovery={recovery_traces:?} work={proof_work:?}"
    );
    println!("ze163 proof work: {report}");
    assert_eq!(
        producer_traces,
        vec![0_u64, 0, 0],
        "capture after fold needs no producer history replay: {report}"
    );
    // Current and PreparedBase bind the same captured state, authenticated
    // and completely traced once; no historical state is retraced.
    assert_eq!(
        recovery_traces,
        vec![1_u64, 1, 1],
        "recovery retrace count must not follow history length: {report}"
    );
    let base = *proof_work.first().expect("ze163 base work");
    let longest = *proof_work.last().expect("ze163 longest work");
    assert!(
        longest.saturating_sub(base) <= base / 2,
        "marginal proof work must stay under half of one traversal: {report}"
    );
}

/// ZE-163: `validate_mark_reference` used to walk the whole completed mark
/// once per traced reference. `DurableRunReader::contains` answers the same
/// question with one page read per run level, so the cost of proving a
/// reference live no longer follows the mark's length.
#[test]
fn ze163_mark_membership_is_a_bounded_descent_not_a_run_scan() {
    run_ze163_mark_membership_is_a_bounded_descent_not_a_run_scan();
}

fn run_ze163_mark_membership_is_a_bounded_descent_not_a_run_scan() {
    let parent = super::tempfile::tempdir().expect("ze163 mark parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("ze163 mark store");
    ze163_base_write(&store, "ze163-mark", 0);
    let admission = store
        .admit_native_graph_maintenance()
        .expect("ze163 mark admission");
    // Enough ids to fill several leaf pages, so a run scan and a
    // root-to-leaf descent cost visibly different numbers of pages.
    let input: Vec<u128> = (1..=2048).collect();
    let report = super::super::maintenance::run_spill_probe(&store, &admission, &input, 256)
        .expect("ze163 membership probe");
    let descent = u64::from(report.run.height() + 1);
    let report_line = format!(
        "height={} descent={descent} walk_pages={} queries={} membership_pages={}",
        report.run.height(),
        report.walk_page_reads,
        report.membership_queries,
        report.membership_page_reads
    );
    println!("ze163 mark membership: {report_line}");
    assert_eq!(report.ordered.len(), input.len(), "{report_line}");
    assert!(report.membership_queries > 0, "{report_line}");
    assert!(
        report.run.height() >= 1,
        "the probe must build a multi-level run: {report_line}"
    );
    assert!(
        report.membership_page_reads <= report.membership_queries * descent,
        "each membership question reads at most one page per level: {report_line}"
    );
    assert!(
        report.walk_page_reads >= 3 * descent,
        "a run scan must cost several descents, or the gate proves nothing: \
         {report_line}"
    );
    drop(admission);
    store.close().expect("ze163 close mark store");
}

/// ZE-187: a plain store that checkpoints, writes uncheckpointed tail
/// envelopes, and then runs a complete reclaim cycle (one maintenance that
/// publishes the pending intent, one that completes it) must still reopen.
/// Those tail envelopes predate the intent, so their inventories still list
/// the candidates as `Retained`; that superseded claim may not make open
/// demand a file the completed reclaim legitimately unlinked. The control
/// below keeps the real claim loud: an artifact the published state still
/// inventories is a typed `NotFound` when it is absent.
#[test]
fn ze187_plain_store_reopens_after_a_completed_reclaim() {
    run_ze187_plain_store_reopens_after_a_completed_reclaim();
}

fn run_ze187_plain_store_reopens_after_a_completed_reclaim() {
    let parent = super::tempfile::tempdir().expect("ze187 parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    for index in 0..24 {
        ze163_base_write(&store, "ze187-base", index);
    }
    commit_maintenance(&store).expect("ze187 base replacement");
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("ze187 checkpoint");
    for index in 0..3 {
        ze163_base_write(&store, "ze187-tail", index);
    }
    vfs.take();
    commit_maintenance(&store).expect("ze187 pending maintenance");
    let pending_deletes = delete_events(&vfs.take());
    commit_maintenance(&store).expect("ze187 completing maintenance");
    let completing_deletes = delete_events(&vfs.take());
    println!(
        "ze187 deletes: pending={} completing={}",
        pending_deletes.len(),
        completing_deletes.len()
    );
    assert!(
        pending_deletes.is_empty(),
        "the first maintenance only publishes the intent: {pending_deletes:?}"
    );
    assert!(
        !completing_deletes.is_empty(),
        "the second maintenance must complete the reclaim"
    );
    store.close().expect("ze187 close");
    let reopened = Store::open_native_graph(&path, options(), None)
        .expect("ze187 reopen after a completed reclaim");
    // The liveness proof moved to the published state; it did not become a
    // best-effort skip. An artifact that state still inventories must stay a
    // loud typed error when it is absent.
    let victim = {
        let lease = reopened.admit_native_read().expect("ze187 witness lease");
        let inventory = rooted_inventory_for_lease(&reopened, &lease);
        let victim = inventory
            .iter()
            .find(|change| {
                change.state == InventoryState::Retained
                    && crate::property_graph::storage::allocation::artifact_path(
                        &path,
                        change.object.artifact,
                    )
                    .exists()
            })
            .map(|change| change.object.artifact)
            .expect("ze187 live inventoried artifact");
        drop(lease);
        victim
    };
    reopened.close().expect("ze187 close reopened");
    let victim_path = crate::property_graph::storage::allocation::artifact_path(&path, victim);
    std::fs::remove_file(&victim_path).expect("ze187 remove a live artifact");
    let Err(error) = Store::open_native_graph(&path, options(), None) else {
        panic!("ze187 a missing live artifact must refuse");
    };
    assert!(
        matches!(
            &error,
            super::super::NativeGraphError::Store(crate::lifecycle::StoreError::Io { path: missing, source })
                if missing == &victim_path && source.kind() == std::io::ErrorKind::NotFound
        ),
        "{error:?}"
    );
}

fn ze163_document_tower() -> EmbeddingTower {
    EmbeddingTower {
        model_id: "ze163-witness".into(),
        model_version: "1".into(),
        weights_digest: vec![0x16, 0x03],
        dims: 2,
        normalization: Normalization::None,
        prompt_prefix: "doc: ".into(),
        max_tokens: 32,
        runtime: EmbeddingRuntime::CpuReference,
        compute_units: ComputeUnits::Cpu,
        os_build: None,
    }
}

fn ze163_witness_store(path: &Path, vfs: &Arc<RecordingVfs>, document: &EmbeddingTower) -> Store {
    let infrastructure: Arc<dyn Vfs> = vfs.clone();
    Store::create_native_graph_with_infrastructure(
        path,
        options(),
        Some(document.clone()),
        infrastructure,
        Arc::new(crate::lifecycle::SystemMonotonicClock),
        &mut crate::property_graph::storage::allocation::OsEntropy,
    )
    .expect("ze163 witness store")
}

#[allow(
    clippy::too_many_arguments,
    reason = "one complete keyed write, spelled out so each fixture row is \
              readable at its call site"
)]
fn ze163_keyed_write(
    store: &Store,
    document: &EmbeddingTower,
    group: &str,
    key: &str,
    revision: u64,
    operation: StructuredOperation,
    text: &str,
    coordinates: [f32; 2],
) -> EntityId {
    let embedding = CanonicalEmbedding::new(document, &coordinates).expect("keyed embedding");
    let image = CanonicalContents::node(&mut [], &mut [], Some(text), Some(embedding))
        .expect("keyed image");
    let receipts = store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, group, key).expect("keyed key"),
                revision: GraphRevision::new(revision).expect("keyed revision"),
                operation,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .expect("keyed write");
    receipts[0].entity
}

/// One checkpoint, then at least three uncheckpointed one-node envelopes over
/// the same key, so a middle envelope's records are superseded before the
/// target state is reached.
fn ze163_seed_superseded_history(store: &Store, document: &EmbeddingTower) {
    for index in 0..24 {
        ze163_keyed_write(
            store,
            document,
            "ze163-base",
            &index.to_string(),
            1,
            StructuredOperation::Create,
            &format!("ze163 witness base row {index} with some words"),
            [index as f32 / 32.0, 1.0 - index as f32 / 32.0],
        );
    }
    // A replacement before the checkpoint leaves reclaimable packs, so the
    // measured maintenance publishes a real pending intent.
    commit_maintenance(store).expect("ze163 witness base replacement");
    settle_reclaim_for_test(store);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("ze163 witness checkpoint");
    let mid = match ze163_keyed_write(
        store,
        document,
        "ze163-mid",
        "mid",
        1,
        StructuredOperation::Create,
        "witness mid revision one alpha beta gamma",
        [0.11, 0.89],
    ) {
        EntityId::Node(node) => node,
        EntityId::Relationship(_) => panic!("ze163 witness mid identity"),
    };
    // Envelope two is the middle state. Envelope three rewrites the same key,
    // so every page envelope two wrote for it is superseded before the target.
    for (revision, word) in [(2_u64, "delta"), (3, "epsilon")] {
        ze163_keyed_write(
            store,
            document,
            "ze163-mid",
            "mid",
            revision,
            StructuredOperation::Put(EntityId::Node(mid)),
            &format!("witness mid revision {revision} {word} zeta eta theta"),
            [0.11 * revision as f32, 0.5],
        );
    }
}

/// What the removed per-intermediate-state retrace used to reach, measured
/// against what ZE-163 kept.
struct Ze163Witness {
    states: usize,
    /// Artifacts that neither the checkpoint's nor the target's complete
    /// traversal reaches, so only the intermediate history names them.
    intermediate_only: std::collections::BTreeSet<u128>,
    /// Of those, the ones the surviving cover does not reach either. The
    /// surviving cover is the checkpoint trace, the target trace, every
    /// state's `Roots` trace and every envelope's change references.
    uncovered: std::collections::BTreeSet<u128>,
}

/// Traces one captured bundle twice per state, at both `CapturedTraceDepth`
/// values, and reports which artifacts the deeper trace was the only witness
/// for. The measurement excludes `writer.protected`, the current bundle's own
/// trace and the durable proof roots, all of which the production mark also
/// emits, so an empty `uncovered` set is a conservative result.
fn ze163_witness_report(store: &Store, lease: &super::super::NativeReadLease) -> Ze163Witness {
    use std::collections::BTreeSet;
    type Ref = crate::property_graph::storage::artifact::PhysicalRef;
    type Res<'a> = crate::property_graph::storage::tree::directory::TreeResources<'a>;
    type Err = crate::property_graph::storage::tree::directory::TreeError;

    struct Captured {
        sequence: u64,
        edge: bool,
        roots: BTreeSet<u128>,
        complete: BTreeSet<u128>,
        changes: BTreeSet<u128>,
    }

    let bundle = lease.bundle();
    let control = QueryControl::Cancel(CancelToken::new());
    let shared = crate::property_graph::resources::GraphResources::from_store(store)
        .expect("ze163 witness shared");
    let write_memory =
        WriteMemory::new(&shared, WriteLimits::default()).expect("ze163 witness write memory");
    let memory = StorageMemory::new(&write_memory, &control, 32 * 1024 * 1024)
        .expect("ze163 witness memory");
    let mut resources =
        crate::property_graph::storage::tree::directory::TreeResources::for_prepare(
            &memory,
            crate::property_graph::storage::reclaim::MARK_WORK_LIMIT,
        )
        .expect("ze163 witness resources");
    let expected = crate::property_graph::catalog::GraphInterpretation::new(
        bundle.lexical(),
        bundle.document(),
    )
    .expect("ze163 witness interpretation");

    let mut per_state: Vec<Captured> = Vec::new();
    super::super::recovery::visit_captured_state(
        store,
        bundle.directory(),
        bundle,
        bundle.sequence(),
        &control,
        |visit, wal_resources| {
            let (state, changes, is_checkpoint) = match visit {
                super::super::recovery::CapturedStateVisit::Checkpoint { state, .. } => {
                    (state, None, true)
                }
                super::super::recovery::CapturedStateVisit::Envelope { state, changes, .. } => {
                    (state, Some(changes), false)
                }
            };
            let mut change_set: BTreeSet<u128> = BTreeSet::new();
            if let Some(changes) = changes {
                let mut visit_change = |reference: Ref, _res: &mut Res<'_>| -> Result<(), Err> {
                    change_set.insert(reference.artifact.get());
                    Ok(())
                };
                super::super::recovery::trace_captured_change_references(
                    store,
                    bundle.directory(),
                    state,
                    changes,
                    wal_resources,
                    &memory,
                    &mut resources,
                    &mut visit_change,
                )?;
            }
            let mut roots: BTreeSet<u128> = BTreeSet::new();
            let mut complete: BTreeSet<u128> = BTreeSet::new();
            for (depth, sink) in [
                (
                    super::super::recovery::CapturedTraceDepth::Roots,
                    &mut roots,
                ),
                (
                    super::super::recovery::CapturedTraceDepth::Complete,
                    &mut complete,
                ),
            ] {
                let mut visit_depth = |reference: Ref, _res: &mut Res<'_>| -> Result<(), Err> {
                    sink.insert(reference.artifact.get());
                    Ok(())
                };
                super::super::recovery::trace_captured_state_references(
                    store,
                    bundle.directory(),
                    bundle.catalog(),
                    state,
                    expected,
                    bundle.document(),
                    &memory,
                    depth,
                    &mut resources,
                    &mut visit_depth,
                )?;
            }
            per_state.push(Captured {
                sequence: state.sequence,
                edge: is_checkpoint || state.sequence == bundle.sequence(),
                roots,
                complete,
                changes: change_set,
            });
            Ok(())
        },
    )
    .expect("ze163 witness captured walk");
    drop(resources);

    let mut edges: BTreeSet<u128> = BTreeSet::new();
    let mut surviving: BTreeSet<u128> = BTreeSet::new();
    for entry in &per_state {
        surviving.extend(entry.changes.iter().copied());
        surviving.extend(entry.roots.iter().copied());
        if entry.edge {
            edges.extend(entry.complete.iter().copied());
            surviving.extend(entry.complete.iter().copied());
        }
    }
    let mut intermediate_only: BTreeSet<u128> = BTreeSet::new();
    let mut uncovered: BTreeSet<u128> = BTreeSet::new();
    for entry in &per_state {
        if entry.edge {
            continue;
        }
        intermediate_only.extend(entry.complete.difference(&edges).copied());
        uncovered.extend(entry.complete.difference(&surviving).copied());
    }
    println!(
        "ze163 witness: states={} edges={} surviving={} intermediate_only={} uncovered={}",
        per_state.len(),
        edges.len(),
        surviving.len(),
        intermediate_only.len(),
        uncovered.len()
    );
    for entry in &per_state {
        println!(
            "ze163 witness state seq={} edge={} roots={} complete={} changes={}",
            entry.sequence,
            entry.edge,
            entry.roots.len(),
            entry.complete.len(),
            entry.changes.len()
        );
    }
    Ze163Witness {
        states: per_state.len(),
        intermediate_only,
        uncovered,
    }
}

/// Plants the mark omission for one artifact and runs maintenance over it.
/// The omission must fire and nothing may be unlinked; whether the producer
/// refuses or defers the refusal to the next open is the caller's assertion.
fn ze163_plant_omitted_mark(
    store: &Store,
    vfs: &Arc<RecordingVfs>,
    artifact: crate::property_graph::storage::artifact::ArtifactId,
) -> Option<super::super::NativeGraphError> {
    vfs.take();
    omit_mark_artifact_for_test(artifact);
    let result = commit_maintenance(store);
    let fired = take_omitted_mark_emissions_for_test();
    let error = match result {
        Ok(report) => {
            assert_eq!(report.removed_bytes, 0, "a planted omission removed bytes");
            None
        }
        Err(error) => Some(error),
    };
    println!(
        "ze163 witness omission: fired={fired} refused={}",
        error.is_some()
    );
    assert!(
        delete_events(&vfs.take()).is_empty(),
        "a planted omission deleted a file"
    );
    assert!(fired > 0, "the planted omission never fired");
    error
}

fn ze163_assert_absent_from_mark_refusal(error: &super::super::NativeGraphError) {
    let message = match error {
        super::super::NativeGraphError::Read(
            crate::property_graph::storage::tree::directory::TreeError::Invalid(message),
        ) => *message,
        other => panic!("unexpected refusal: {other:?}"),
    };
    assert!(
        message == "protected root is absent from completed mark"
            || message == "captured live reference absent from completed mark",
        "unexpected refusal message: {message}"
    );
    println!("ze163 witness refusal: {message}");
}

/// A real superseded intermediate state needs no proof coverage after its
/// chain is folded. The fixture first proves that intermediate-only artifacts
/// exist, then verifies their mark omission needs no emission and still reopens.
#[test]
fn intermediate_only_history_is_unneeded_after_fold() {
    let parent = super::tempfile::tempdir().expect("ze163 current parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let document = ze163_document_tower();
    let store = ze163_witness_store(&path, &vfs, &document);
    ze163_seed_superseded_history(&store, &document);

    let lease = store.admit_native_read().expect("ze163 current reader");
    let report = ze163_witness_report(&store, &lease);
    drop(lease);
    assert!(
        report.states >= 4,
        "the fixture needs a checkpoint and at least three uncheckpointed \
         envelopes: states={}",
        report.states
    );
    assert!(
        !report.intermediate_only.is_empty(),
        "the fixture never allocated an artifact only an intermediate state \
         reaches, so this control proves nothing"
    );
    assert!(
        report.uncovered.is_empty(),
        "an intermediate state reached an artifact that the checkpoint trace, \
         the target trace, the retained roots and the change references do \
         not: {:032x?}",
        report.uncovered
    );

    let witness = crate::property_graph::storage::artifact::ArtifactId::new(
        *report
            .intermediate_only
            .first()
            .expect("intermediate-only artifact"),
    )
    .expect("nonzero witness artifact");
    let witness_path = crate::property_graph::storage::allocation::artifact_path(&path, witness);
    let witness_bytes = std::fs::read(&witness_path).expect("ze163 witness bytes");

    omit_mark_artifact_for_test(witness);
    commit_maintenance(&store).expect("fold then capture current state");
    assert_eq!(
        take_omitted_mark_emissions_for_test(),
        0,
        "an intermediate-only artifact must need no mark edge after fold"
    );
    let current = store.admit_native_read().unwrap();
    let (_, marked) = durable_proof_for_lease(&store, &current);
    assert!(!marked.contains(&witness));
    assert_eq!(
        current.bundle().base().fold.envelope_sequence,
        current.bundle().sequence() - 1
    );
    drop(current);
    store.close().unwrap();
    Store::open_native_graph(&path, options(), Some(document))
        .unwrap()
        .close()
        .unwrap();
    let _ = witness_bytes;
}

/// One real reclaim round over a witness artifact, ending at the reopen over
/// the published pending intent. `retained`, when present, is held across the
/// whole round and released only before the close.
///
fn ze163_survives_a_pending_reclaim_round(
    store: Store,
    path: &Path,
    document: &EmbeddingTower,
    witness: crate::property_graph::storage::artifact::ArtifactId,
    witness_bytes: &[u8],
    retained: Option<super::super::NativeReadLease>,
) {
    let witness_path = crate::property_graph::storage::allocation::artifact_path(path, witness);
    commit_maintenance(&store).expect("ze163 maintenance with the real mark");
    let lease = store.admit_native_read().expect("ze163 round reader");
    assert!(
        lease.bundle().reclaim().is_some(),
        "the maintenance must publish a real pending reclaim intent, or this \
         round proves nothing about deletion authority"
    );
    assert!(
        !pending_reclaim_candidates_or_empty_root(&store, &lease)
            .iter()
            .any(|candidate| candidate.artifact == witness),
        "the intermediate-envelope artifact became a reclaim candidate"
    );
    drop(lease);
    assert_eq!(
        std::fs::read(&witness_path).expect("ze163 witness survives"),
        witness_bytes
    );
    drop(retained);
    store.close().expect("ze163 close");
    let reopened = Store::open_native_graph(path, options(), Some(document.clone()))
        .expect("ze163 reopen over the pending intent");
    assert_eq!(
        std::fs::read(&witness_path).expect("ze163 witness after reopen"),
        witness_bytes
    );
    reopened.close().expect("ze163 close reopened");
}

/// The same superseded-intermediate history, pinned by a retained reader
/// lease that is held across a checkpoint. `writer.protected` is rebuilt from
/// the uncheckpointed WAL, so after that checkpoint it no longer names this
/// history and cannot be the cover here.
fn ze163_reader_history_fixture(
    path: &Path,
    vfs: &Arc<RecordingVfs>,
    document: &EmbeddingTower,
) -> (Store, super::super::NativeReadLease) {
    let store = ze163_witness_store(path, vfs, document);
    ze163_seed_superseded_history(&store, document);
    let retained = store.admit_native_read().expect("ze163 retained reader");
    let retained_root = retained.bundle().base().fold;
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("ze163 checkpoint over the retained history");
    ze163_keyed_write(
        &store,
        document,
        "ze163-tail",
        "tail",
        1,
        StructuredOperation::Create,
        "witness tail row iota kappa lambda",
        [0.55, 0.45],
    );
    ze163_keyed_write(
        &store,
        document,
        "ze163-mid",
        "mid",
        4,
        StructuredOperation::Put(EntityId::Node(
            crate::property_graph::NodeId::new(25).unwrap(),
        )),
        "new current contents supersede the retained reader leaf",
        [0.9, 0.1],
    );
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    let current = store.admit_native_read().expect("ze163 current reader");
    assert_ne!(
        current.bundle().base().fold,
        retained_root,
        "the checkpoint did not move the writer past the retained history"
    );
    drop(current);
    (store, retained)
}

fn ze163_reader_witness(
    store: &Store,
    path: &Path,
    retained: &super::super::NativeReadLease,
) -> (
    crate::property_graph::storage::artifact::ArtifactId,
    Vec<u8>,
) {
    let node = crate::property_graph::NodeId::new(25).unwrap();
    let retained_value = node_directory_value(store, retained, node);
    let witness = crate::property_graph::storage::payload::PayloadRef::decode(&retained_value)
        .unwrap()
        .reference()
        .artifact;
    let current = store.admit_native_read().unwrap();
    let current_value = node_directory_value(store, &current, node);
    let current_artifact =
        crate::property_graph::storage::payload::PayloadRef::decode(&current_value)
            .unwrap()
            .reference()
            .artifact;
    assert_ne!(
        witness, current_artifact,
        "the witness must belong only to the retained view"
    );
    drop(current);
    let witness_path = crate::property_graph::storage::allocation::artifact_path(path, witness);
    let bytes = std::fs::read(&witness_path).expect("ze163 reader witness bytes");
    let writer_protected: Vec<crate::property_graph::storage::artifact::ArtifactId> = store
        .native_graph
        .writer
        .lock()
        .expect("ze163 writer state")
        .as_ref()
        .expect("ze163 writer")
        .protected
        .iter()
        .map(|descriptor| descriptor.artifact)
        .collect();
    assert!(
        !writer_protected.contains(&witness),
        "the checkpoint left this reader-history artifact in writer.protected, \
         so the reader-class leg would only retest the Current cover"
    );
    (witness, bytes)
}

#[test]
fn retained_reader_leaf_survives_without_history_retrace() {
    let parent = super::tempfile::tempdir().expect("ze163 reader parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let document = ze163_document_tower();
    let (store, retained) = ze163_reader_history_fixture(&path, &vfs, &document);
    let (witness, witness_bytes) = ze163_reader_witness(&store, &path, &retained);

    // The lease stays held across the whole reclaim round: the point is that
    // this history is the reader's, not the writer's.
    ze163_survives_a_pending_reclaim_round(
        store,
        &path,
        &document,
        witness,
        &witness_bytes,
        Some(retained),
    );
}

/// Omit an actual retained reader leaf from the completed mark. Its Required
/// record must reject the proof before any candidate is unlinked.
#[test]
fn omitted_reader_leaf_refuses_before_any_unlink() {
    let parent = super::tempfile::tempdir().expect("ze163 plant parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let document = ze163_document_tower();
    let (store, retained) = ze163_reader_history_fixture(&path, &vfs, &document);
    let (witness, witness_bytes) = ze163_reader_witness(&store, &path, &retained);
    let witness_path = crate::property_graph::storage::allocation::artifact_path(&path, witness);

    let before = directory_image(&path);
    let refusal = ze163_plant_omitted_mark(&store, &vfs, witness);
    match refusal {
        Some(error) => {
            ze163_assert_absent_from_mark_refusal(&error);
            assert_live_files_unchanged(&path, &before);
            drop(retained);
            store.close().expect("ze163 plant close");
        }
        None => {
            // The producer accepted the omission. The durable mark now lacks
            // a reference the retained reader history still names, so the
            // next open over it must refuse rather than reclaim anything.
            drop(retained);
            store.close().expect("ze163 plant close");
            match Store::open_native_graph(&path, options(), Some(document.clone())) {
                Ok(reopened) => {
                    reopened.close().expect("ze163 plant close reopened");
                    panic!(
                        "a mark missing a reader-history reference reopened \
                         without a refusal"
                    );
                }
                Err(error) => println!("ze163 reader reopen refusal: {error:?}"),
            }
        }
    }
    assert_eq!(
        std::fs::read(&witness_path).expect("ze163 plant witness survives"),
        witness_bytes
    );
}

/// One real reclaim cycle, a reopen and a replay of the original keyed
/// request, reported as plain observations for an independent comparator.
#[cfg(feature = "test-seams")]
fn observe_reclaim_cycle() -> crate::graph_reclaim_test_support::ReclaimState {
    let (history, store) = seed_crash_history();
    let vfs = Arc::clone(&history.vfs);
    commit_maintenance(&store).expect("durable reclaim intent");
    let pending = store.admit_native_read().expect("pending reader");
    let candidates = pending_reclaim_candidates(&store, &pending);
    drop(pending);
    let unlinked_file_bytes = candidates
        .iter()
        .map(|candidate| {
            std::fs::metadata(reclaim_candidate_path(&history.path, candidate))
                .expect("pending target")
                .len()
        })
        .sum();
    vfs.take();
    let report = commit_maintenance(&store).expect("reclaim resume");
    assert_eq!(delete_events(&vfs.take()).len(), candidates.len());
    store.close().expect("close reclaimed store");
    let reopened = history.open(options()).expect("reopen reclaimed store");
    let lease = reopened.admit_native_read().expect("reopened reader");
    let relationships =
        super::publication::out_rows_for_lease(&reopened, &lease, history.first, history.peer)
            .into_iter()
            .map(
                |row| crate::graph_read_view_test_support::ObservedRelationship {
                    rel: row.rel.get(),
                    source: row.source.get(),
                    target: row.target.get(),
                    relationship_type: row.relationship_type.get(),
                },
            )
            .collect();
    drop(lease);
    let replay = apply_crash_history_writes(&reopened, &history.document);
    let state = crate::graph_reclaim_test_support::ReclaimState {
        first_node: history.first.get(),
        second_node: history.peer.get(),
        relationships,
        replay_generation: replay[0].generation.get(),
        replayed: replay.iter().all(|receipt| receipt.replayed),
        removed_bytes: report.removed_bytes,
        unlinked_file_bytes,
    };
    reopened.close().expect("close replayed store");
    state
}

/// The directed production paths behind ZE-46 acceptance. A receipt is pushed
/// only after its body returned, so a receipt proves its assertions passed.
#[cfg(feature = "test-seams")]
pub(super) fn run_actual_probe(seed: u64) -> crate::graph_reclaim_test_support::ReclaimProbeReport {
    use super::publication::{reset_verified_faults, take_verified_faults};
    let bodies: [(&'static str, u64, fn()); 15] = [
        ("property-graph.reclaim.fold-before-capture.fire", 1, || {
            run_fold_before_capture(true);
            run_fold_before_capture(false);
        }),
        (
            "property-graph.reclaim.fold-before-capture.clean",
            1,
            || run_fold_before_capture(false),
        ),
        (
            "property-graph.reclaim.maintenance-output",
            1,
            run_ze260_maintenance_emits_each_tree_root_once_per_call,
        ),
        (
            "property-graph.reclaim.superseded-history",
            1,
            run_ze260_superseded_history_is_reclaimed_after_reader_drops,
        ),
        ("property-graph.reclaim.physical-replacement", 2, || {
            run_ze46_real_consolidation_preserves_exact_state_and_reopens();
            run_ze46_consolidation_rotates_through_every_node();
        }),
        (
            "property-graph.reclaim.stale-recheck",
            1,
            run_ze46_stale_preparation_rejects_without_publication_or_foreign_cleanup,
        ),
        ("property-graph.reclaim.inventory-fold", 2, || {
            run_ze46_inventory_fold_conserves_complete_allocation_union();
            run_ze46_inventory_fold_drains_a_manifest_backlog();
        }),
        (
            "property-graph.reclaim.protected-union",
            1,
            run_ze46_protected_union_keeps_partial_packs_and_actual_sparse_refs,
        ),
        (
            "property-graph.reclaim.wal-only",
            1,
            run_older_wal_manifest_retention_without_explicit_registration,
        ),
        (
            "property-graph.reclaim.spill-refusal",
            1,
            run_ze46_spill_merge_and_incomplete_mark_never_delete_candidates,
        ),
        ("property-graph.reclaim.orphan", 2, || {
            run_ze46_reconciles_real_prewal_orphans_without_touching_unknown_files();
            run_ze46_orphan_adoption_waits_for_a_quiescent_history();
        }),
        (
            "property-graph.reclaim.page-relocation",
            1,
            run_ze260_page_relocation_keeps_intent_before_unlink,
        ),
        ("property-graph.reclaim.intent-unlink-completion", 2, || {
            run_ze46_intent_unlink_sync_completion_crashes_resume_idempotently();
            run_ze46_checkpoint_during_an_open_reclaim_cycle_reopens();
        }),
        (
            "property-graph.reclaim.corrupt-proof",
            1,
            run_ze46_corrupt_or_incomplete_reclaim_proof_refuses_before_mutation,
        ),
        (
            "property-graph.reclaim.read-only-retirement",
            1,
            run_ze46_readonly_pending_reclaim_and_checkpoint_retirement_are_exact,
        ),
    ];
    let mut host_budget = (0, 0, 0, false);
    let mut receipts = Vec::new();
    for (key, clean_controls, body) in bodies {
        reset_verified_faults();
        body();
        receipts.push(crate::graph_read_view_test_support::PathReceipt {
            key,
            fires: take_verified_faults(),
            clean_controls,
        });
    }
    for (kind, key) in [
        (0, "property-graph.reclaim.host-budget"),
        (1, "property-graph.reclaim.host-create"),
        (2, "property-graph.reclaim.host-unlink"),
    ] {
        reset_verified_faults();
        let observed = maintain::run_fault_case(kind);
        if kind == 0 {
            host_budget = observed;
        }
        let fires = if kind == 0 {
            u64::from(observed.3)
        } else {
            take_verified_faults()
        };
        receipts.push(crate::graph_read_view_test_support::PathReceipt {
            key,
            fires,
            clean_controls: 1,
        });
    }
    run_ze176_race_probe(seed);
    let detach_sweep = run_ze46_detach_sweeps_bounded_edges_and_preserves_fences();
    receipts.push(crate::graph_read_view_test_support::PathReceipt {
        key: "property-graph.reclaim.detach-sweep",
        fires: 0,
        clean_controls: 1,
    });
    crate::graph_reclaim_test_support::ReclaimProbeReport {
        receipts,
        state: observe_reclaim_cycle(),
        detach_sweep,
        host_budget,
    }
}

#[test]
fn ze260_hundred_node_batches_write_bounded_pages() {
    use crate::property_graph::storage::artifact::{self, BlockKind, ContainerKind};
    let directory = tempfile::tempdir().unwrap();
    let path = directory.path().join("store");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    let mut previous = directory_image(&path);
    for batch in 0..20 {
        let keys: Vec<_> = (0..100)
            .map(|n| format!("node-{:04}", batch * 100 + n))
            .collect();
        let edge = format!("edge-{batch}");
        let mut labels = [GraphName::new("Document").unwrap()];
        let mut properties = property_fixture();
        properties.truncate(1);
        let image = CanonicalContents::node(
            &mut labels,
            &mut properties,
            Some("bounded graph text"),
            None,
        )
        .unwrap();
        crate::property_graph::with_local_refs(|refs| {
            let mut requests: Vec<_> = keys
                .iter()
                .map(|key| StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "app", key).unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                })
                .collect();
            requests.push(StructuredWrite {
                key: ApplicationKey::new(EntityKind::Relationship, "app", &edge).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Relationship {
                    source: NodeRef::Local(refs.node(0).unwrap()),
                    target: NodeRef::Local(refs.node(1).unwrap()),
                    relationship_type: GraphName::new("LINKS").unwrap(),
                    properties: &[],
                }),
            });
            store
                .apply_native_graph(&requests, &QueryControl::Cancel(CancelToken::new()))
                .unwrap();
        });
        let next = directory_image(&path);
        let mut pages = 0;
        let mut bytes = 0;
        let mut files = 0;
        for (name, data) in &next {
            if previous.contains_key(name) || !name.to_string_lossy().ends_with(".zgraph") {
                continue;
            }
            files += 1;
            bytes += data.len();
            let frame = artifact::decode(ContainerKind::Object, None, data).unwrap();
            let mut index = 0;
            while let Ok(reference) = frame.reference(index) {
                pages += usize::from(reference.kind == BlockKind::TreePage);
                index += 1;
            }
        }
        eprintln!(
            "ZE260 batch={} nodes=100 pages={pages} bytes={bytes} files={files}",
            batch + 1
        );
        assert!(
            pages <= 24,
            "batch {batch}: {pages} TreePage blocks, {bytes} bytes, {files} files"
        );
        assert!(bytes <= 512 * 1024, "batch {batch}: {bytes} bytes");
        previous = next;
    }
}

fn ze260_add_unlabelled_node(store: &Store, name: &str) {
    let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "s6a-garbage", name).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
}

#[test]
fn ze260_maintenance_copies_an_unchanged_membership_page() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    let mut labels = [GraphName::new("AppendOnly").unwrap()];
    let image = CanonicalContents::node(&mut labels, &mut [], None, None).unwrap();
    let key = "unchanged".repeat(64);
    let writes = [StructuredWrite {
        key: ApplicationKey::new(EntityKind::Node, "pages", &key).unwrap(),
        revision: GraphRevision::new(1).unwrap(),
        operation: StructuredOperation::Create,
        image: Some(WriteImage::Node(&image)),
    }];
    let control = QueryControl::Cancel(CancelToken::new());
    let original = store.apply_native_graph(&writes, &control).unwrap();
    let before = store
        .admit_native_read()
        .unwrap()
        .bundle()
        .roots()
        .directory(TreeKind::Labels)
        .unwrap()
        .reference();
    ze260_add_unlabelled_node(&store, "membership");
    commit_maintenance(&store).unwrap();
    let after = store
        .admit_native_read()
        .unwrap()
        .bundle()
        .roots()
        .directory(TreeKind::Labels)
        .unwrap()
        .reference();
    assert_ne!(
        before, after,
        "unchanged membership page must leave the old pack"
    );
    store.close().unwrap();
    let reopened = Store::open_native_graph(&path, options(), None).unwrap();
    let replay = reopened.apply_native_graph(&writes, &control).unwrap();
    assert!(replay[0].replayed);
    assert_eq!(replay[0].generation, original[0].generation);
    reopened.close().unwrap();
}

#[test]
fn ze260_maintenance_retargets_oldest_fence_payloads() {
    use crate::property_graph::storage::{NativePreparationCatalog, records::verify_fence_entry};
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "pages", "payload").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
    let lease = store.admit_native_read().unwrap();
    let oldest = prepared_union_for_lease(&store, &lease)
        .into_iter()
        .min_by_key(|change| change.object.serial)
        .unwrap()
        .object
        .artifact;
    drop(lease);
    ze260_add_unlabelled_node(&store, "fence");
    commit_maintenance(&store).unwrap();
    let lease = store.admit_native_read().unwrap();
    let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(&lease, &memory, 64).unwrap();
    let mut resources = source.resources(128 * 1024 * 1024).unwrap();
    let catalog = NativePreparationCatalog::open(&source, &mut resources).unwrap();
    let root = lease
        .bundle()
        .roots()
        .directory(TreeKind::KeyFences)
        .unwrap();
    let mut cursor = DirectoryCursor::seek(&source, root, None, &mut resources).unwrap();
    let mut count = 0;
    while let Some(entry) = cursor.next_entry(&mut resources).unwrap() {
        let fence =
            verify_fence_entry(&source, root, entry, &catalog, None, &mut resources).unwrap();
        let (provenance, canonical) = fence.required_payloads();
        assert_ne!(
            provenance.reference().artifact,
            oldest,
            "fence provenance still pins oldest pack"
        );
        assert_ne!(
            canonical.unwrap().reference().artifact,
            oldest,
            "fence canonical still pins oldest pack"
        );
        count += 1;
    }
    assert_eq!(count, 2);
}

#[test]
fn ze260_page_relocation_keeps_intent_before_unlink() {
    run_ze260_page_relocation_keeps_intent_before_unlink();
}

fn run_ze260_page_relocation_keeps_intent_before_unlink() {
    use super::publication::FaultPoint;
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    let mut labels = [GraphName::new("AppendOnly").unwrap()];
    let image = CanonicalContents::node(&mut labels, &mut [], None, None).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "pages", "fault").unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &control,
        )
        .unwrap();
    commit_maintenance(&store).unwrap();
    store.checkpoint_native_graph(&control).unwrap();
    let before = store
        .admit_native_read()
        .unwrap()
        .bundle()
        .roots()
        .directory(TreeKind::Labels)
        .unwrap()
        .reference();
    ze260_add_unlabelled_node(&store, "intent");
    vfs.take();
    vfs.arm_fault(FaultPoint::Delete);
    let intent = commit_maintenance(&store).unwrap();
    assert_eq!(intent.removed_bytes, 0);
    assert!(
        delete_events(&vfs.take()).is_empty(),
        "unlink before durable intent"
    );
    let pending = store.admit_native_read().unwrap();
    assert!(pending.bundle().reclaim().is_some());
    assert_ne!(
        before,
        pending
            .bundle()
            .roots()
            .directory(TreeKind::Labels)
            .unwrap()
            .reference()
    );
    drop(pending);
    commit_maintenance(&store).expect_err("scheduled Delete must fire");
    vfs.assert_fired_once();
    assert!(delete_events(&vfs.take()).is_empty());
    store.close().unwrap();
    let infrastructure: Arc<dyn Vfs> = vfs.clone();
    let reopened = Store::open_native_graph_with_infrastructure(
        &path,
        options(),
        None,
        infrastructure,
        Arc::new(crate::lifecycle::SystemMonotonicClock),
    )
    .unwrap();
    assert!(
        !delete_events(&vfs.take()).is_empty(),
        "writable recovery must resume the authorized unlinks"
    );
    reopened
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    commit_maintenance(&reopened).unwrap();
    reopened.close().unwrap();
}

#[test]
fn ze260_duplicate_heavy_mark_uses_one_run() {
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let admission = store.admit_native_graph_maintenance().unwrap();
    let input: Vec<u128> = (0..24).flat_map(|_| 1..=65).collect();
    let report =
        super::super::maintenance::run_spill_probe(&store, &admission, &input, 256).unwrap();
    assert_eq!(report.ordered, (1..=65).collect::<Vec<_>>());
    assert_eq!(report.spill_runs, 1);
    assert_eq!(report.merges, 0);
    assert_eq!(report.created_objects, 2);
}

#[test]
fn a_retired_artifact_proof_is_dropped_on_unlink() {
    use crate::property_graph::resources::GraphResources;
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    ze163_base_write(&store, "proof-unlink", 0);
    let old = store.admit_native_read().unwrap();
    let reference = old
        .bundle()
        .roots()
        .directory(TreeKind::Nodes)
        .unwrap()
        .reference()
        .unwrap();
    {
        let shared = GraphResources::from_store(&store).unwrap();
        let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let storage = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).unwrap();
        let source = NativePreparationSource::new(&old, &storage, 64).unwrap();
        let mut resources = source.resources(u64::MAX).unwrap();
        source
            .with_block(reference, &mut resources, |_, _| Ok(()))
            .unwrap();
    }
    assert!(
        store
            .native_graph
            .validated_proof(reference.artifact)
            .unwrap()
            .is_some()
    );
    let victim =
        crate::property_graph::storage::allocation::artifact_path(&path, reference.artifact);
    drop(old);
    ze163_base_write(&store, "proof-unlink", 1);
    let mut removed = 0;
    for _ in 0..24 {
        removed += commit_maintenance(&store).unwrap().removed_bytes;
        if !victim.exists() {
            break;
        }
    }
    assert!(removed > 0);
    assert!(!victim.exists(), "retired root must be unlinked");
    assert!(
        store
            .native_graph
            .validated_proof(reference.artifact)
            .unwrap()
            .is_none()
    );
    store.close().unwrap();
}

#[test]
fn ze260_superseded_history_is_reclaimed_after_reader_drops() {
    run_ze260_superseded_history_is_reclaimed_after_reader_drops();
}

fn run_ze260_superseded_history_is_reclaimed_after_reader_drops() {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    ze163_base_write(&store, "history", 0);
    let old = store.admit_native_read().unwrap();
    let root = old
        .bundle()
        .roots()
        .directory(TreeKind::Nodes)
        .unwrap()
        .reference()
        .expect("old node root");
    let root_path = crate::property_graph::storage::allocation::artifact_path(&path, root.artifact);
    let control = QueryControl::Cancel(CancelToken::new());
    let image = CanonicalContents::node(&mut [], &mut [], Some("replacement"), None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "history", "0").unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Put(EntityId::Node(
                    crate::property_graph::NodeId::new(1).unwrap(),
                )),
                image: Some(WriteImage::Node(&image)),
            }],
            &control,
        )
        .unwrap();
    for _ in 0..3 {
        commit_maintenance(&store).unwrap();
        let current = store.admit_native_read().unwrap();
        let candidates = pending_reclaim_candidates_or_empty_root(&store, &current);
        assert!(candidates.iter().all(|candidate| candidate.family == 17));
        assert!(
            !candidates
                .iter()
                .any(|candidate| candidate.artifact == root.artifact)
        );
        assert!(root_path.exists());
    }
    drop(old);
    let mut selected = None;
    for _ in 0..12 {
        commit_maintenance(&store).unwrap();
        let current = store.admit_native_read().unwrap();
        let candidates = pending_reclaim_candidates_or_empty_root(&store, &current);
        if let Some(index) = candidates
            .iter()
            .position(|candidate| candidate.artifact == root.artifact)
        {
            selected = Some(
                candidates
                    .iter()
                    .take(index)
                    .filter(|candidate| {
                        crate::property_graph::storage::allocation::artifact_path(
                            &path,
                            candidate.artifact,
                        )
                        .exists()
                    })
                    .count(),
            );
            break;
        }
    }
    let skip = selected
        .expect("old immutable root must become an intent candidate after its reader releases");
    assert!(root_path.exists(), "selection must precede unlink");
    vfs.arm_fault_after(super::publication::FaultPoint::Delete, skip as u64);
    let error = commit_maintenance(&store).expect_err("scheduled retired-root Delete refusal");
    assert!(
        matches!(&error, super::super::NativeGraphError::Io { path, .. } if path == &root_path),
        "{error:?}"
    );
    vfs.assert_fired_once();
    assert!(root_path.exists(), "the refused participant must remain");
    assert!(
        path.join("wal.ze").exists(),
        "the Store WAL is never a graph reclaim candidate"
    );
    store.close().unwrap();
    let reopened = Store::open_native_graph(&path, options(), None).unwrap();
    assert!(
        !root_path.exists(),
        "writable recovery must complete the retired-root unlink"
    );
    assert!(path.join("wal.ze").exists());
    reopened.close().unwrap();
}

// Retain a real nonempty admission and its readable publication while
// reproducing close's drained writer at each maintenance branch.
fn ze201_retained_maintenance_drained_writer(phase: u8) {
    for state in [
        crate::lifecycle::StoreState::Closing,
        crate::lifecycle::StoreState::Closed,
    ] {
        let (_history, store) = seed_crash_history();
        let control = QueryControl::Cancel(CancelToken::new());
        if phase >= 1 {
            commit_maintenance(&store).expect("pending intent");
        }
        if phase >= 2 {
            commit_maintenance(&store).expect("completion");
        }
        if phase >= 3 {
            assert!(matches!(
                store.commit_native_graph_maintenance(
                    &store.admit_native_graph_maintenance().unwrap(),
                    &control
                ),
                Err(super::super::NativeGraphError::StalePreparation)
            ));
        }
        let admission = store
            .admit_native_graph_maintenance()
            .expect("retain admission");
        let before = Arc::clone(admission.lease.bundle());
        assert!(before.sequence() > 0);
        assert_eq!(before.reclaim().is_some(), phase > 0);
        if phase >= 2 {
            assert_eq!(
                before.base().fold.envelope_sequence == before.sequence(),
                phase == 3
            );
        }
        let error = if phase == 0 {
            let entered = Arc::new(std::sync::Barrier::new(2));
            let release = Arc::new(std::sync::Barrier::new(2));
            *store.state.lock().expect("state") = crate::lifecycle::StoreState::Open;
            store
                .native_graph
                .state
                .lock()
                .expect("publication")
                .maintenance_writer_hook = Some((Arc::clone(&entered), Arc::clone(&release)));
            std::thread::scope(|scope| {
                let attempt =
                    scope.spawn(|| store.commit_native_graph_maintenance(&admission, &control));
                entered.wait();
                store
                    .native_graph
                    .drain_writer_for_close()
                    .expect("drain writer");
                *store.state.lock().expect("state") = state;
                release.wait();
                attempt.join().expect("join").expect_err("drained writer")
            })
        } else {
            store
                .native_graph
                .drain_writer_for_close()
                .expect("drain writer");
            *store.state.lock().expect("state") = state;
            store
                .commit_native_graph_maintenance(&admission, &control)
                .expect_err("drained writer")
        };
        assert!(
            matches!(
                (&error, state),
                (
                    super::super::NativeGraphError::Store(crate::lifecycle::StoreError::Closing),
                    crate::lifecycle::StoreState::Closing
                ) | (
                    super::super::NativeGraphError::Store(crate::lifecycle::StoreError::Closed),
                    crate::lifecycle::StoreState::Closed
                )
            ),
            "{error:?}"
        );
        assert!(
            store
                .native_graph
                .is_current_bundle(&before)
                .expect("publication")
        );
        *store.state.lock().expect("state") = crate::lifecycle::StoreState::Open;
        drop(admission);
        store.close().expect("cleanup");
    }
}

#[test]
fn ze201_retained_maintenance_commit_is_closed() {
    ze201_retained_maintenance_drained_writer(0);
}
#[test]
fn ze201_pending_reclaim_completion_is_closed() {
    ze201_retained_maintenance_drained_writer(1);
}
#[test]
fn ze201_retirement_checkpoint_is_closed() {
    ze201_retained_maintenance_drained_writer(2);
}
#[test]
fn ze201_retirement_clear_is_closed() {
    ze201_retained_maintenance_drained_writer(3);
}

#[test]
fn ze188_retirement_reopens_after_trailing_checkpoint_failure() {
    use super::publication::FaultPoint;
    let (history, store) = seed_crash_history();
    let oracle = history.oracle(&store);
    commit_maintenance(&store).expect("publish reclaim intent");
    history.vfs.take();
    let completed = commit_maintenance(&store).expect("complete reclaim");
    assert!(completed.removed_bytes > 0);
    let deleted = delete_events(&history.vfs.take());
    assert!(!deleted.is_empty());
    assert!(deleted.iter().all(|path| !path.exists()));
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("checkpoint completed reclaim");
    let before = directory_image(&history.path);
    history.vfs.arm_fault(FaultPoint::OpenAppend);
    commit_maintenance(&store).expect_err("trailing checkpoint must fail");
    history.vfs.assert_fired_once();
    let lease = store.admit_native_read().expect("cleared state");
    assert!(lease.bundle().reclaim().is_none());
    drop(lease);
    assert_same_logical_state(&oracle, &history.oracle(&store));
    let after = directory_image(&history.path);
    let selector = std::ffi::OsStr::new("graph-root.ze");
    assert_eq!(after.get(selector), before.get(selector));
    drop(store);
    let readonly = history
        .open(
            OpenOptions::read_only()
                .with_durability(DurabilityMode::Durable, CommitTier::Durable)
                .with_max_resident_bytes(256 * 1024 * 1024),
        )
        .expect("read-only reopen after interrupted retirement");
    assert_same_logical_state(&oracle, &history.oracle(&readonly));
    readonly.close().expect("close read-only");
    let writable = history
        .open(options())
        .expect("writable reopen after interrupted retirement");
    assert_same_logical_state(&oracle, &history.oracle(&writable));
    writable.close().expect("close writable");
}

fn graph_references_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<crate::property_graph::storage::artifact::PhysicalRef> {
    let shared =
        crate::property_graph::resources::GraphResources::from_store(store).expect("resources");
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).expect("memory");
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).expect("storage");
    let source = NativePreparationSource::new(lease, &memory, 64).expect("source");
    let mut resources = source.resources(64 * 1024 * 1024).expect("work");
    let catalog =
        crate::property_graph::storage::NativePreparationCatalog::open(&source, &mut resources)
            .expect("catalog");
    let mut scratch = crate::property_graph::storage::adjacency::RangeScratch::for_prepare(
        &memory,
        &mut resources,
    )
    .expect("scratch");
    let mut references = Vec::new();
    crate::property_graph::storage::reclaim::trace_graph_state(
        &source, &catalog, lease.bundle().roots(), lease.bundle().sequence(),
        lease.bundle().document(), &mut scratch,
        &mut |reference, _: &mut crate::property_graph::storage::tree::directory::TreeResources<'_>| {
            references.push(reference);
            Ok(())
        }, &mut resources,
    ).expect("graph trace");
    references
}

fn record_references_for_lease(
    store: &Store,
    lease: &super::super::NativeReadLease,
) -> Vec<crate::property_graph::storage::artifact::PhysicalRef> {
    let shared = crate::property_graph::resources::GraphResources::from_store(store).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let memory = StorageMemory::new(&writer, &control, 8 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(lease, &memory, 64).unwrap();
    let mut resources = source.resources(64 * 1024 * 1024).unwrap();
    let roots = lease.bundle().roots();
    let root = roots
        .directory(crate::property_graph::storage::tree::TreeKind::Nodes)
        .unwrap();
    let mut cursor = crate::property_graph::storage::tree::directory::DirectoryCursor::seek(
        &source,
        root,
        None,
        &mut resources,
    )
    .unwrap();
    let mut references = Vec::new();
    while let Some(entry) = cursor.next_entry(&mut resources).unwrap() {
        let payload =
            crate::property_graph::storage::payload::PayloadRef::decode(entry.value()).unwrap();
        references.push(payload.reference());
    }
    references
}

#[test]
fn ze189_inventory_only_artifact_is_required_on_reopen() {
    use super::publication::FaultPoint;
    let parent = super::tempfile::tempdir().expect("parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    ze163_base_write(&store, "ze189", 0);
    let before = directory_image(&path);
    vfs.arm_fault(FaultPoint::ObjectSync);
    let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node");
    assert!(
        store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "ze189", "orphan").expect("key"),
                    revision: GraphRevision::new(1).expect("revision"),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &QueryControl::Cancel(CancelToken::new())
            )
            .is_err(),
        "complete pre-WAL orphan fault"
    );
    vfs.assert_fired_once();
    let orphans: Vec<_> = directory_image(&path)
        .into_iter()
        .filter(|(name, _)| {
            !before.contains_key(name) && name.to_string_lossy().ends_with(".zgraph")
        })
        .collect();
    assert!(!orphans.is_empty());
    ze163_base_write(&store, "ze189", 1);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .expect("advance durable fences before adoption");
    let checkpoint = store.admit_native_read().expect("checkpoint inventory");
    let checkpoint_inventory = complete_inventory_union_for_lease(&store, &checkpoint);
    drop(checkpoint);
    let selector = std::fs::read(path.join("manifest.ze")).expect("selector");
    commit_maintenance(&store).expect("adopt orphan without checkpoint");
    assert_eq!(
        std::fs::read(path.join("manifest.ze")).expect("selector after adoption"),
        selector
    );
    let lease = store.admit_native_read().expect("adopted inventory");
    let inventory = rooted_inventory_for_lease(&store, &lease);
    let victim = inventory
        .iter()
        .find(|change| {
            change.state == InventoryState::Retained
                && orphans.iter().any(|(name, _)| {
                    crate::property_graph::storage::allocation::artifact_path(
                        &path,
                        change.object.artifact,
                    ) == path.join(name)
                })
        })
        .expect("complete orphan adopted as Retained")
        .object;
    assert!(
        !checkpoint_inventory
            .iter()
            .any(|change| change.object == victim)
    );
    assert!(
        !graph_references_for_lease(&store, &lease)
            .iter()
            .any(|reference| reference.artifact == victim.artifact)
    );
    assert!(
        !record_references_for_lease(&store, &lease)
            .iter()
            .any(|reference| reference.artifact == victim.artifact)
    );
    if lease.bundle().reclaim().is_some() {
        assert!(!pending_reclaim_candidates(&store, &lease).contains(&victim));
    }
    let generation = lease.bundle().base().generation;
    drop(lease);
    drop(store);
    let intact = Store::open_native_graph(
        &path,
        OpenOptions::read_only()
            .with_durability(DurabilityMode::Durable, CommitTier::Durable)
            .with_max_resident_bytes(256 * 1024 * 1024),
        None,
    )
    .expect("intact orphan reopens");
    let lease = intact.admit_native_read().expect("intact generation");
    assert_eq!(lease.bundle().base().generation, generation);
    drop(lease);
    intact.close().expect("close intact read-only");
    let victim_path =
        crate::property_graph::storage::allocation::artifact_path(&path, victim.artifact);
    std::fs::remove_file(&victim_path).expect("remove inventory-only artifact");
    let Err(error) = Store::open_native_graph(&path, options(), None) else {
        panic!("inventory-only missing artifact incorrectly reopened");
    };
    assert!(
        matches!(&error, super::super::NativeGraphError::Store(crate::lifecycle::StoreError::Io { path: missing, source })
        if missing == &victim_path && source.kind() == std::io::ErrorKind::NotFound),
        "{error:?}"
    );
}

#[test]
fn ze186_reader_graph_only_artifact_survives_reclaim() {
    let parent = tempfile::tempdir().expect("parent");
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    let control = QueryControl::Cancel(CancelToken::new());
    let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node");
    let names: Vec<_> = (0..64).map(|n| format!("node-{n:04}")).collect();
    let mut nodes = Vec::new();
    for batch in names.chunks(8) {
        let writes: Vec<_> = batch
            .iter()
            .map(|name| StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze186", name).expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            })
            .collect();
        let receipts = store.apply_native_graph(&writes, &control).expect("seed");
        nodes.extend(receipts.iter().copied());
    }
    store
        .checkpoint_native_graph(&control)
        .expect("reader checkpoint");
    let reader = store.admit_native_read().expect("retained reader");
    let old = graph_references_for_lease(&store, &reader);
    let EntityId::Node(node) = nodes[0].entity else {
        panic!("node")
    };
    let lazy_value = node_directory_value(&store, &reader, node);
    for (batch, receipts) in names.chunks(8).zip(nodes.chunks(8)) {
        let writes: Vec<_> = batch
            .iter()
            .zip(receipts)
            .map(|(name, receipt)| StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze186", name).expect("key"),
                revision: GraphRevision::new(2).expect("revision"),
                operation: StructuredOperation::Put(receipt.entity),
                image: Some(WriteImage::Node(&image)),
            })
            .collect();
        store
            .apply_native_graph(&writes, &control)
            .expect("replace");
    }
    store
        .checkpoint_native_graph(&control)
        .expect("current checkpoint");
    let current = store.admit_native_read().expect("current");
    {
        let capture = store.capture_native_read_roots().expect("registrations");
        assert_eq!(capture.bundles().len(), 2);
        assert!(capture.prepared().is_empty());
    }
    let mut other: Vec<_> = graph_references_for_lease(&store, &current)
        .iter()
        .map(|r| r.artifact)
        .collect();
    {
        let lease = &current;
        other.extend(
            record_references_for_lease(&store, lease)
                .iter()
                .map(|r| r.artifact),
        );
        other.extend(
            std::iter::once(lease.bundle().catalog())
                .chain(lease.bundle().wal_roots().slots.into_iter().flatten())
                .chain(
                    [
                        Some(lease.bundle().catalog()),
                        lease.bundle().text(),
                        lease.bundle().vector(),
                        lease.bundle().reclaim(),
                    ]
                    .into_iter()
                    .flatten(),
                )
                .chain(lease.bundle().prepared_inventories().iter().copied())
                .map(|r| r.object.artifact),
        );
    }
    // At each target checkpoint, history emits its manifest checkpoint state.
    for lease in [&reader, &current] {
        let mut checkpoints = 0;
        super::super::recovery::visit_captured_state(
            &store,
            &path,
            lease.bundle(),
            lease.bundle().sequence(),
            &control,
            |visit, _| {
                match visit {
                    super::super::recovery::CapturedStateVisit::Checkpoint { state, .. } => {
                        assert_eq!(state.sequence, lease.bundle().sequence());
                        checkpoints += 1;
                    }
                    super::super::recovery::CapturedStateVisit::Envelope { .. } => {
                        panic!("unexpected history envelope")
                    }
                }
                Ok(())
            },
        )
        .expect("history isolation");
        assert_eq!(checkpoints, 1);
    }
    let mut witnesses: Vec<_> = old
        .iter()
        .filter(|r| !other.contains(&r.artifact))
        .map(|r| r.artifact)
        .collect();
    witnesses.sort_unstable();
    witnesses.dedup();
    let witness_bytes: Vec<_> = witnesses
        .iter()
        .map(|artifact| {
            let file = crate::property_graph::storage::allocation::artifact_path(&path, *artifact);
            let bytes = std::fs::read(&file).expect("witness bytes");
            (file, bytes)
        })
        .collect();
    assert!(
        !witnesses.is_empty(),
        "no Reader-only pack among {} graph references",
        old.len()
    );
    // The lighter witness is an old node-record pack. Its directory
    // reference is indirect; no direct root or sparse trace protects it.
    eprintln!("ZE186 witness packs: {}", witnesses.len());
    let before = directory_image(&path);
    drop(current);
    vfs.take();
    let mut removed = 0;
    for _ in 0..3 {
        removed += commit_maintenance(&store)
            .expect("reclaim under reader")
            .removed_bytes;
    }
    assert!(removed > 0, "reclaim must unlink unrelated packs");
    let proof = store.admit_native_read().expect("proof");
    let (_, mark) = durable_proof_for_lease(&store, &proof);
    for witness in witnesses {
        assert!(
            mark.contains(&witness),
            "Reader-only witness absent from mark: {witness:?}"
        );
    }
    for (file, bytes) in witness_bytes {
        assert_eq!(std::fs::read(file).expect("surviving witness"), bytes);
    }
    for deleted in delete_events(&vfs.take()) {
        assert!(!deleted.exists());
        assert!(before.contains_key(deleted.file_name().expect("filename")));
    }
    assert_eq!(node_directory_value(&store, &reader, node), lazy_value);
    assert_eq!(graph_references_for_lease(&store, &reader), old);
    eprintln!("ZE186 removed bytes: {removed}");
}

#[cfg(feature = "test-seams")]
fn ze176_replace_old(store: &Store, index: usize) {
    let image = CanonicalContents::node(&mut [], &mut [], Some("replacement"), None).unwrap();
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze176-old", &index.to_string())
                    .unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Put(EntityId::Node(
                    crate::property_graph::NodeId::new(1).unwrap(),
                )),
                image: Some(WriteImage::Node(&image)),
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
}

fn ze176_schedule(seed: u64, raced: bool) -> (u64, Vec<u8>, bool, bool) {
    use crate::property_graph::query::resources::QueryMemory;
    use crate::property_graph::query::runtime::{RuntimeContext, RuntimeLimits};
    use crate::property_graph::storage::tree::directory::TreeResources;
    use crate::property_graph::storage::{
        GraphReadView, NativeCatalog, NativeQuerySource, NativeReadCapability,
    };
    use std::sync::atomic::{AtomicU64, Ordering};

    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = Arc::new(create_reclaim_test_store(&path, &vfs));
    let index = (seed % 1000) as usize;
    ze163_base_write(&store, "ze176-old", index);
    let old = if raced {
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Barrier::new(2));
        store.native_graph.state.lock().unwrap().admission_hook =
            Some((entered.clone(), release.clone()));
        std::thread::scope(|scope| {
            let reader = scope.spawn(|| store.admit_native_read().unwrap());
            entered.wait();
            let capture = scope.spawn(|| store.capture_native_read_roots().unwrap());
            release.wait();
            let old = reader.join().unwrap();
            let captured = capture.join().unwrap();
            assert!(captured.contains_lease(&old));
            old
        })
    } else {
        let old = store.admit_native_read().unwrap();
        assert!(
            store
                .capture_native_read_roots()
                .unwrap()
                .contains_lease(&old)
        );
        old
    };
    let root = old
        .bundle()
        .roots()
        .directory(TreeKind::Nodes)
        .unwrap()
        .reference()
        .expect("old node root");
    let root_path = crate::property_graph::storage::allocation::artifact_path(&path, root.artifact);
    let wal_path = path.join("wal.ze");

    // Publish after the first private preparation artifact; force the real
    // writer recheck, and prove that this stale attempt cannot unlink.
    let creates = Arc::new(AtomicU64::new(0));
    let counter = creates.clone();
    if raced {
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        let admission = store.admit_native_graph_maintenance().unwrap();
        let foreground = store.clone();
        vfs.after_next_create(move || {
            counter.fetch_add(1, Ordering::Relaxed);
            ze176_replace_old(&foreground, index);
        });
        let entered = Arc::new(Barrier::new(2));
        let release = Arc::new(Barrier::new(2));
        store
            .native_graph
            .state
            .lock()
            .unwrap()
            .maintenance_writer_hook = Some((entered.clone(), release.clone()));
        vfs.take();
        let error = std::thread::scope(|scope| {
            let attempt = scope.spawn(|| {
                store.commit_native_graph_maintenance(
                    &admission,
                    &QueryControl::Cancel(CancelToken::new()),
                )
            });
            entered.wait();
            release.wait();
            attempt
                .join()
                .unwrap()
                .expect_err("publication must invalidate preparation")
        });
        assert!(
            matches!(error, super::super::NativeGraphError::StalePreparation),
            "{error:?}"
        );
        assert_eq!(creates.load(Ordering::Relaxed), 1);
        assert!(
            delete_events(&vfs.take()).is_empty(),
            "stale attempt deleted an artifact"
        );
    } else {
        ze176_replace_old(&store, index);
        vfs.after_next_create(move || {
            counter.fetch_add(1, Ordering::Relaxed);
        });
        commit_maintenance(&store).unwrap();
        assert_eq!(creates.load(Ordering::Relaxed), 1);
    }
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    for _ in 0..3 {
        // Completed reclaim retirement requires a checkpoint at its generation.
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        commit_maintenance(&store).unwrap();
        let lease = store.admit_native_read().unwrap();
        assert!(
            !pending_reclaim_candidates_or_empty_root(&store, &lease)
                .iter()
                .any(|c| c.artifact == root.artifact)
        );
        assert!(root_path.exists() && wal_path.exists());
    }

    // No source has ever been constructed for `old`. Resolve its exact
    // node-tree block for the first time after maintenance, then read content.
    let generation = old.bundle().base().generation.get();
    let canonical = {
        let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
        let memory = QueryMemory::new(&shared, 8 * 1024 * 1024).unwrap();
        let control = QueryControl::Cancel(CancelToken::new());
        let mut runtime =
            RuntimeContext::new(&old, &control, &memory, RuntimeLimits::default()).unwrap();
        let capability = NativeReadCapability::admit(&old, &runtime).unwrap();
        let mut resources = TreeResources::for_query(&mut runtime).unwrap();
        let source = NativeQuerySource::new(capability, &resources, 16).unwrap();
        let before = store.stats().unwrap().mapped_bytes;
        source
            .resolve(
                old.bundle().roots().references()[0].unwrap(),
                &mut resources,
            )
            .unwrap();
        assert!(
            store.stats().unwrap().mapped_bytes > before,
            "old root did not lazily map"
        );
        let catalog = NativeCatalog::open(&source, &mut resources).unwrap();
        drop(resources);
        let view = GraphReadView::new(&source, &catalog).unwrap();
        let mut resources = TreeResources::for_query(&mut runtime).unwrap();
        let node = crate::property_graph::NodeId::new(1).unwrap();
        let record = view.lookup_node(node, &mut resources).unwrap().unwrap();
        let mut canonical = vec![0; record.record().canonical_bytes().len() as usize];
        assert_eq!(
            record
                .record()
                .canonical_bytes()
                .read_at(0, &mut canonical, &mut resources)
                .unwrap(),
            canonical.len()
        );
        let text = view.stored_text(node, &mut resources).unwrap().unwrap();
        let mut bytes = vec![0; text.len() as usize];
        assert_eq!(
            text.read_at(0, &mut bytes, &mut resources).unwrap(),
            bytes.len()
        );
        assert_eq!(bytes, format!("ze163 ze176-old row {index}").as_bytes());
        assert_eq!(generation, 2);
        canonical
    };
    drop(old);

    // Reuse ZE-260's bounded retirement fixture, without its unrelated
    // digest corruption and Delete-fault qualification.
    let mut selected = false;
    for _ in 0..6 {
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        vfs.take();
        commit_maintenance(&store).unwrap();
        let lease = store.admit_native_read().unwrap();
        let candidates = pending_reclaim_candidates_or_empty_root(&store, &lease);
        if candidates.iter().any(|c| c.artifact == root.artifact) {
            assert!(candidates.iter().any(|c| c.artifact == root.artifact));
            assert!(
                delete_events(&vfs.take()).is_empty(),
                "unlink before intent"
            );
            selected = true;
            break;
        }
    }
    assert!(selected, "old text root never became a reclaim candidate");
    vfs.take();
    commit_maintenance(&store).unwrap();
    let deleted = delete_events(&vfs.take());
    assert!(deleted.contains(&root_path));
    assert!(!deleted.contains(&wal_path));
    assert!(!root_path.exists() && wal_path.exists());
    Arc::try_unwrap(store)
        .unwrap_or_else(|_| panic!("race store leaked"))
        .close()
        .unwrap();
    (
        generation,
        canonical,
        !root_path.exists(),
        wal_path.exists(),
    )
}

#[cfg(feature = "test-seams")]
pub(super) fn run_ze176_race_probe(
    seed: u64,
) -> crate::graph_reclaim_test_support::RaceProbeReport {
    let observation = ze176_schedule(seed, true);
    let control = ze176_schedule(seed, false);
    assert_eq!(observation, control, "same-seed serialized race control");
    crate::graph_reclaim_test_support::RaceProbeReport {
        observation,
        control,
    }
}

#[cfg(feature = "test-seams")]
#[test]
fn ze176_race_probe_preserves_reader_and_reclaim_contracts() {
    let report = run_ze176_race_probe(7);
    assert_eq!(report.observation, report.control);
    assert_eq!(report.observation.0, 2);
    assert!(report.observation.2 && report.observation.3);
}

/// Reuse the existing real reclaim partitions, each beside a fresh clean control.
#[cfg(feature = "test-seams")]
pub(crate) fn run_ze41_reclaim_boundaries() -> Vec<crate::graph_read_view_test_support::PathReceipt>
{
    use super::publication::{reset_verified_faults, take_verified_faults};
    [
        (
            "property-graph.recovery.commit.reclaim-unlink",
            CrashCell::BeforeFirstUnlink,
        ),
        (
            "property-graph.recovery.commit.reclaim-sync",
            CrashCell::DirectorySync,
        ),
        (
            "property-graph.recovery.commit.reclaim-completion",
            CrashCell::LostCompletionAck,
        ),
    ]
    .into_iter()
    .map(|(key, cell)| {
        reset_verified_faults();
        run_reclaim_crash_cell(cell);
        let fires = take_verified_faults();
        assert_eq!(fires, 1, "{key}");
        reset_verified_faults();
        run_reclaim_crash_cell(CrashCell::Control);
        assert_eq!(take_verified_faults(), 0);
        crate::graph_read_view_test_support::PathReceipt {
            key,
            fires,
            clean_controls: 1,
        }
    })
    .collect()
}

fn ze166_fixture(
    store: &Store,
) -> (
    crate::property_graph::NodeId,
    crate::property_graph::NodeId,
    Vec<crate::property_graph::staging::ItemReceipt>,
) {
    let control = QueryControl::Cancel(CancelToken::new());
    let image = CanonicalContents::node(&mut [], &mut [], None, None).expect("node");
    let nodes = store
        .apply_native_graph(
            &["a", "b"].map(|name| StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze166", name).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }),
            &control,
        )
        .unwrap();
    let EntityId::Node(a) = nodes[0].entity else {
        panic!("node")
    };
    let EntityId::Node(b) = nodes[1].entity else {
        panic!("node")
    };
    let receipts = store
        .apply_native_graph(&[ze166_relationship(a, b)], &control)
        .unwrap();
    (a, b, receipts.to_vec())
}

fn ze166_relationship(
    a: crate::property_graph::NodeId,
    b: crate::property_graph::NodeId,
) -> StructuredWrite<'static, 'static> {
    StructuredWrite {
        key: ApplicationKey::new(EntityKind::Relationship, "ze166", "ab").unwrap(),
        revision: GraphRevision::new(1).unwrap(),
        operation: StructuredOperation::Create,
        image: Some(WriteImage::Relationship {
            source: NodeRef::Existing(a),
            target: NodeRef::Existing(b),
            relationship_type: GraphName::new("LINKS").unwrap(),
            properties: &[],
        }),
    }
}

fn ze166_detach(store: &Store, a: crate::property_graph::NodeId) {
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze166", "a").unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Delete(
                    EntityId::Node(a),
                    crate::property_graph::GraphDeleteMode::Detach,
                ),
                image: None,
            }],
            &QueryControl::Cancel(CancelToken::new()),
        )
        .unwrap();
}

#[test]
fn ze166_detached_relationship_install_retry_preserves_receipt() {
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let (a, b, original) = ze166_fixture(&store);
    let control = QueryControl::Cancel(CancelToken::new());
    ze166_detach(&store, a);
    let replay = store
        .apply_native_graph(&[ze166_relationship(a, b)], &control)
        .expect("authenticated original install replay after DETACH");
    assert!(replay[0].replayed);
    assert_eq!(replay[0].entity, original[0].entity);
    assert_eq!(replay[0].generation, original[0].generation);
    assert_eq!(replay[0].revision, original[0].revision);
}

fn ze166_key_lookup(
    store: &Store,
    lease: &super::super::NativeReadLease,
    name: &str,
) -> Result<Option<EntityId>, crate::property_graph::storage::tree::directory::TreeError> {
    use crate::property_graph::query::{
        resources::QueryMemory,
        runtime::{RuntimeContext, RuntimeLimits},
    };
    use crate::property_graph::storage::tree::directory::TreeResources;
    use crate::property_graph::storage::{
        GraphReadView, NativeCatalog, NativeQuerySource, NativeReadCapability,
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store).unwrap();
    let memory = QueryMemory::new(&shared, 8 * 1024 * 1024).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let mut runtime =
        RuntimeContext::new(lease, &control, &memory, RuntimeLimits::default()).unwrap();
    let capability = NativeReadCapability::admit(lease, &runtime).unwrap();
    let mut resources = TreeResources::for_query(&mut runtime).unwrap();
    let source = NativeQuerySource::new(capability, &resources, 64).unwrap();
    let catalog = NativeCatalog::open(&source, &mut resources).unwrap();
    drop(resources);
    let view = GraphReadView::new(&source, &catalog).unwrap();
    let mut resources = TreeResources::for_query(&mut runtime).unwrap();
    view.lookup_application_key(
        ApplicationKey::new(EntityKind::Relationship, "ze166", name).unwrap(),
        &mut resources,
    )
}

type Ze166FenceEvidence = BTreeMap<Vec<u8>, (Vec<u8>, Option<Vec<u8>>)>;

fn ze166_fence_evidence(store: &Store) -> Ze166FenceEvidence {
    use crate::property_graph::storage::{
        records::verify_fence_entry, stream::PayloadSlice, tree::Key,
    };
    let lease = store.admit_native_read().unwrap();
    let shared = crate::property_graph::resources::GraphResources::from_store(store).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let memory = StorageMemory::new(&writer, &control, 16 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(&lease, &memory, 64).unwrap();
    let mut r = source.resources(64 * 1024 * 1024).unwrap();
    let catalog =
        crate::property_graph::storage::NativePreparationCatalog::open(&source, &mut r).unwrap();
    let roots = lease.bundle().roots();
    let root = roots.directory(TreeKind::KeyFences).unwrap();
    let mut cursor = DirectoryCursor::seek(&source, root, None, &mut r).unwrap();
    let mut result = BTreeMap::new();
    while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
        let Key::Inline(key) = entry.key() else {
            panic!("key")
        };
        let fence = verify_fence_entry(
            &source,
            root,
            entry,
            &catalog,
            lease.bundle().document(),
            &mut r,
        )
        .unwrap();
        let (provenance, canonical) = fence.required_payloads();
        let mut read = |payload: crate::property_graph::storage::payload::PayloadRef| {
            let slice =
                PayloadSlice::new(&source, roots.store(), entry.creation_generation(), payload);
            let mut bytes = vec![0; slice.len() as usize];
            assert_eq!(slice.read_at(0, &mut bytes, &mut r).unwrap(), bytes.len());
            bytes
        };
        result.insert(key.to_vec(), (read(provenance), canonical.map(read)));
    }
    result
}

fn ze166_physical(
    store: &Store,
    lease: &super::super::NativeReadLease,
    a: crate::property_graph::NodeId,
) -> (Vec<u128>, bool, usize, u64, u64) {
    use crate::property_graph::storage::{
        records::verify_fence_entry,
        tree::{Key, directory::lookup_entry},
    };
    let shared = crate::property_graph::resources::GraphResources::from_store(store).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let memory = StorageMemory::new(&writer, &control, 16 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(lease, &memory, 64).unwrap();
    let mut r = source.resources(64 * 1024 * 1024).unwrap();
    let roots = lease.bundle().roots();
    let mut rels = Vec::new();
    let mut cursor = DirectoryCursor::seek(
        &source,
        roots.directory(TreeKind::Relationships).unwrap(),
        None,
        &mut r,
    )
    .unwrap();
    while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
        let Key::Inline(key) = entry.key() else {
            panic!("key")
        };
        rels.push(u128::from_le_bytes(key.try_into().unwrap()));
    }
    for kind in [TreeKind::OutRanges, TreeKind::InRanges] {
        let root = roots.directory(kind).unwrap();
        let mut cursor = DirectoryCursor::seek(&source, root, None, &mut r).unwrap();
        let mut scratch =
            crate::property_graph::storage::adjacency::RangeScratch::for_prepare(&memory, &mut r)
                .unwrap();
        let mut edges = Vec::new();
        while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
            let range = crate::property_graph::storage::adjacency::validate_range(
                &source,
                root,
                entry,
                lease.bundle().sequence(),
                &mut scratch,
                &mut r,
            )
            .unwrap();
            edges.extend(range.edges().iter().map(|edge| edge.rel.get()));
        }
        edges.sort_unstable();
        assert_eq!(
            edges, rels,
            "physical OUT/IN match exact surviving relationships"
        );
    }
    let tombstone = lookup_entry(
        &source,
        roots.directory(TreeKind::Nodes).unwrap(),
        &a.get().to_le_bytes(),
        &mut r,
    )
    .unwrap()
    .is_some();
    let mut types = 0;
    let mut cursor = DirectoryCursor::seek(
        &source,
        roots.directory(TreeKind::RelationshipTypes).unwrap(),
        None,
        &mut r,
    )
    .unwrap();
    while cursor.next_entry(&mut r).unwrap().is_some() {
        types += 1;
    }
    let catalog =
        crate::property_graph::storage::NativePreparationCatalog::open(&source, &mut r).unwrap();
    let root = roots.directory(TreeKind::KeyFences).unwrap();
    let mut cursor = DirectoryCursor::seek(&source, root, None, &mut r).unwrap();
    let mut payloads = std::collections::BTreeSet::new();
    let mut packs = std::collections::BTreeSet::new();
    let mut payload_bytes = 0;
    while let Some(entry) = cursor.next_entry(&mut r).unwrap() {
        let fence = verify_fence_entry(&source, root, entry, &catalog, None, &mut r).unwrap();
        let (kind, id) = match fence.incarnation() {
            EntityId::Node(id) => (TreeKind::Nodes, id.get()),
            EntityId::Relationship(id) => (TreeKind::Relationships, id.get()),
        };
        if lookup_entry(
            &source,
            roots.directory(kind).unwrap(),
            &id.to_le_bytes(),
            &mut r,
        )
        .unwrap()
        .is_some()
        {
            continue;
        }
        let (provenance, canonical) = fence.required_payloads();
        for payload in std::iter::once(provenance).chain(canonical) {
            if payloads.insert((payload.reference().artifact, payload.reference().offset)) {
                payload_bytes += payload.len();
            }
            packs.insert(payload.reference().artifact);
        }
    }
    let pack_bytes = packs
        .iter()
        .map(|id| {
            std::fs::metadata(
                store
                    .directory
                    .join(format!("graph-{:032x}.zgraph", id.get())),
            )
            .unwrap()
            .len()
        })
        .sum();
    (rels, tombstone, types, payload_bytes, pack_bytes)
}

#[test]
fn ze46_detach_sweeps_bounded_edges_and_preserves_fences() {
    run_ze46_detach_sweeps_bounded_edges_and_preserves_fences();
}

fn run_ze46_detach_sweeps_bounded_edges_and_preserves_fences() -> (bool, u64) {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).unwrap();
    let (a, b, original) = ze166_fixture(&store);
    let control = QueryControl::Cancel(CancelToken::new());
    let extras = [("parallel", a, b), ("loop", a, a), ("survivor", b, b)].map(|(key, from, to)| {
        let mut request = ze166_relationship(from, to);
        request.key = ApplicationKey::new(EntityKind::Relationship, "ze166", key).unwrap();
        request
    });
    let extra = store
        .apply_native_graph(&extras, &control)
        .unwrap()
        .to_vec();
    let old = store.admit_native_read().unwrap();
    assert_eq!(
        ze166_key_lookup(&store, &old, "ab").unwrap(),
        Some(original[0].entity)
    );
    ze166_detach(&store, a);
    let evidence = ze166_fence_evidence(&store);
    let mut changed = ze166_relationship(a, b);
    changed.operation = StructuredOperation::Put(original[0].entity);
    changed.revision = GraphRevision::new(2).unwrap();
    assert!(matches!(
        store.apply_native_graph(&[changed], &control),
        Err(super::super::NativeGraphError::Stage(
            crate::property_graph::staging::StageError::Endpoint
        ))
    ));
    for pass in 0..3 {
        for _ in 0..3 {
            let pending = store.admit_native_read().unwrap();
            if pending.bundle().reclaim().is_none() {
                break;
            }
            drop(pending);
            commit_maintenance(&store).unwrap();
        }
        assert!(
            store
                .admit_native_read()
                .unwrap()
                .bundle()
                .reclaim()
                .is_none()
        );
        let admission = store.admit_native_graph_maintenance().unwrap();
        store
            .commit_native_graph_maintenance_with_limits(
                &admission,
                &control,
                super::super::maintenance::MaintenanceLimits {
                    sweep_limit: 1,
                    ..Default::default()
                },
            )
            .unwrap();
        let lease = store.admit_native_read().unwrap();
        let (rels, tombstone, types, _, _) = ze166_physical(&store, &lease, a);
        assert_eq!(rels.len(), 3 - pass, "one hidden edge per slice");
        assert_eq!(types, rels.len());
        assert_eq!(
            ze166_fence_evidence(&store),
            evidence,
            "exact original canonical/provenance streams survive every slice"
        );
        assert_eq!(
            tombstone,
            pass < 2,
            "tombstone remains until last physical incident"
        );
        assert_eq!(ze166_key_lookup(&store, &lease, "ab").unwrap(), None);
        assert_eq!(
            ze166_key_lookup(&store, &lease, "survivor").unwrap(),
            Some(extra[2].entity)
        );
    }
    assert_eq!(
        ze166_key_lookup(&store, &old, "ab").unwrap(),
        Some(original[0].entity)
    );
    assert_eq!(
        ze166_key_lookup(&store, &old, "loop").unwrap(),
        Some(extra[1].entity)
    );
    drop(old);
    // Reopen once with maintenance in the WAL, then once from a checkpoint.
    store.close().unwrap();
    drop(store);
    let store = Store::open_native_graph(&path, options(), None).expect("replay bounded sweeps");
    store.checkpoint_native_graph(&control).unwrap();
    store.close().unwrap();
    drop(store);
    let store = Store::open_native_graph(&path, options(), None).expect("checkpoint swept graph");
    assert_eq!(ze166_fence_evidence(&store), evidence);
    let lease = store.admit_native_read().unwrap();
    let (_, _, _, payload, packs) = ze166_physical(&store, &lease, a);
    eprintln!(
        "ZE-166 after sweep evidence-only replay payload bytes={payload}; whole containing pack bytes={packs}"
    );
    drop(lease);
    let replay = store
        .apply_native_graph(&[ze166_relationship(a, b)], &control)
        .unwrap();
    assert_eq!(
        ze166_key_lookup(&store, &store.admit_native_read().unwrap(), "ab").unwrap(),
        None
    );
    assert!(replay[0].replayed);
    assert_eq!(replay[0].generation, original[0].generation);
    assert_eq!(replay[0].entity, original[0].entity);
    let sweep_observation = (
        ze166_key_lookup(&store, &store.admit_native_read().unwrap(), "ab")
            .unwrap()
            .is_some(),
        replay[0].generation.get(),
    );
    drop(replay);
    let deletion = StructuredWrite {
        key: ApplicationKey::new(EntityKind::Relationship, "ze166", "ab").unwrap(),
        revision: GraphRevision::new(2).unwrap(),
        operation: StructuredOperation::Delete(
            original[0].entity,
            crate::property_graph::GraphDeleteMode::Restrict,
        ),
        image: None,
    };
    let deleted = store
        .apply_native_graph(&[deletion], &control)
        .unwrap()
        .to_vec();
    let replay = store.apply_native_graph(&[deletion], &control).unwrap();
    assert!(replay[0].replayed);
    assert_eq!(replay[0].generation, deleted[0].generation);
    drop(replay);
    let node_delete = StructuredWrite {
        key: ApplicationKey::new(EntityKind::Node, "ze166", "a").unwrap(),
        revision: GraphRevision::new(2).unwrap(),
        operation: StructuredOperation::Delete(
            EntityId::Node(a),
            crate::property_graph::GraphDeleteMode::Detach,
        ),
        image: None,
    };
    let retry = store.apply_native_graph(&[node_delete], &control).unwrap();
    assert!(retry[0].replayed);
    assert_eq!(retry[0].generation.get(), 5);
    drop(retry);
    let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    let recreated = store
        .apply_native_graph(
            &[StructuredWrite {
                key: node_delete.key,
                revision: GraphRevision::new(3).unwrap(),
                operation: StructuredOperation::Recreate(GraphRevision::new(2).unwrap()),
                image: Some(WriteImage::Node(&image)),
            }],
            &control,
        )
        .unwrap();
    let EntityId::Node(fresh) = recreated[0].entity else {
        panic!("node")
    };
    assert_ne!(a, fresh);
    drop(recreated);
    let mut recreate = ze166_relationship(fresh, b);
    recreate.revision = GraphRevision::new(3).unwrap();
    recreate.operation = StructuredOperation::Recreate(GraphRevision::new(2).unwrap());
    let recreated = store.apply_native_graph(&[recreate], &control).unwrap();
    assert_ne!(recreated[0].entity, original[0].entity);
    drop(recreated);
    let lease = store.admit_native_read().unwrap();
    let (_, _, _, payload, packs) = ze166_physical(&store, &lease, a);
    eprintln!(
        "ZE-166 evidence-only replay payload bytes={payload}; whole containing pack bytes={packs}"
    );
    drop(lease);
    store.close().unwrap();
    drop(store);
    let reopened = Store::open_native_graph(&path, options(), None)
        .expect("replay explicit swept Delete and Recreate");
    reopened.close().unwrap();
    ze166_both_live_missing_relationship_is_corruption();
    sweep_observation
}

fn ze166_both_live_missing_relationship_is_corruption() {
    use crate::property_graph::storage::tree::directory::DirectoryRoot;
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("corrupt"), options(), None).unwrap();
    let (a, b, _) = ze166_fixture(&store);
    store
        .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
        .unwrap();
    let old = store.admit_native_read().unwrap();
    let bundle = old.bundle();
    let mut roots = bundle.roots();
    roots
        .replace(DirectoryRoot::empty(
            roots.store(),
            TreeKind::Relationships,
            roots.generation(),
        ))
        .unwrap();
    let mut wal_roots = bundle.wal_roots();
    wal_roots.slots[1] = None;
    let input = super::super::NativeGraphBundleInput {
        base: bundle.base(),
        roots,
        wal_roots,
        sequence: bundle.sequence(),
        catalog: bundle.catalog(),
        vector: bundle.vector(),
        text: bundle.text(),
        reclaim: bundle.reclaim(),
        high_waters: bundle.high_waters(),
        prepared_inventories: bundle.prepared_inventories().to_vec(),
        lexical: bundle.lexical(),
        document: None,
    };
    drop(old);
    store.install_native_graph_for_test(input).unwrap();
    let lease = store.admit_native_read().unwrap();
    assert!(matches!(
        ze166_key_lookup(&store, &lease, "ab"),
        Err(
            crate::property_graph::storage::tree::directory::TreeError::Invalid(
                "missing relationship has two live endpoints"
            )
        )
    ));
    assert!(
        store
            .apply_native_graph(
                &[ze166_relationship(a, b)],
                &QueryControl::Cancel(CancelToken::new())
            )
            .is_err()
    );
}

#[test]
fn ze166_sweep_work_is_independent_of_unrelated_relationships() {
    use crate::property_graph::storage::consolidation::{
        SWEEP_WORK, select_finished_tombstones, select_hidden_relationships,
    };
    let measure = |relationships: usize| {
        let parent = super::tempfile::tempdir().unwrap();
        let path = parent.path().join("native");
        let store = Store::create_native_graph(&path, options(), None).unwrap();
        let (a, b, _) = ze166_fixture(&store);
        let control = QueryControl::Cancel(CancelToken::new());
        for chunk in (0..relationships).collect::<Vec<_>>().chunks(32) {
            let names: Vec<_> = chunk.iter().map(|id| format!("live-{id}")).collect();
            let requests: Vec<_> = names
                .iter()
                .map(|name| {
                    let mut request = ze166_relationship(b, b);
                    request.key =
                        ApplicationKey::new(EntityKind::Relationship, "ze166", name).unwrap();
                    request
                })
                .collect();
            store.apply_native_graph(&requests, &control).unwrap();
        }
        ze166_detach(&store, a);
        SWEEP_WORK.with(|counter| counter.set([0; 4]));
        {
            let lease = store.admit_native_read().unwrap();
            let shared =
                crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
            let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
            let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
            let source = NativePreparationSource::new(&lease, &memory, 64).unwrap();
            let mut r = source.resources(256 * 1024 * 1024).unwrap();
            let catalog =
                crate::property_graph::storage::NativePreparationCatalog::open(&source, &mut r)
                    .unwrap();
            let roots = lease.bundle().roots();
            let mut resume = None;
            let swept = select_hidden_relationships(
                &source,
                roots,
                &catalog,
                None,
                128,
                &mut resume,
                &memory,
                &mut r,
            )
            .unwrap();
            select_finished_tombstones(
                &source,
                roots,
                &catalog,
                None,
                swept.as_slice(),
                128,
                lease.bundle().sequence(),
                &mut None,
                &memory,
                &mut r,
            )
            .unwrap();
            if relationships > 128 {
                let before = SWEEP_WORK.with(|counter| counter.get()[0]);
                assert!(resume.is_some());
                let rest = select_hidden_relationships(
                    &source,
                    roots,
                    &catalog,
                    None,
                    128,
                    &mut resume,
                    &memory,
                    &mut r,
                )
                .unwrap();
                assert!(rest.as_slice().is_empty());
                assert!(resume.is_none());
                let after = SWEEP_WORK.with(|counter| counter.get()[0]);
                assert_eq!(after - before, (relationships + 1 - 128) as u64);
                SWEEP_WORK.with(|counter| {
                    let mut counts = counter.get();
                    counts[0] = before;
                    counter.set(counts);
                });
            }
        }
        let selection = SWEEP_WORK.with(|counter| counter.get());
        for _ in 0..12 {
            store
                .commit_native_graph_maintenance(
                    &store.admit_native_graph_maintenance().unwrap(),
                    &control,
                )
                .unwrap();
            let lease = store.admit_native_read().unwrap();
            if !ze166_physical(&store, &lease, a).1 {
                break;
            }
        }
        assert!(!ze166_physical(&store, &store.admit_native_read().unwrap(), a).1);
        store.checkpoint_native_graph(&control).unwrap();
        store.close().unwrap();
        drop(store);
        SWEEP_WORK.with(|counter| counter.set([0; 4]));
        let store = Store::open_native_graph(&path, options(), None).unwrap();
        let open = SWEEP_WORK.with(|counter| counter.get()[2]);
        store.close().unwrap();
        (selection[0], selection[1], open)
    };
    let small = measure(16);
    let large = measure(160);
    eprintln!("ZE-166 work R=16 {small:?}; R=160 {large:?}");
    assert_eq!(
        small.1, large.1,
        "per-tombstone incident work scales with R"
    );
    assert_eq!(small.2, large.2, "swept-node open validation scales with R");
    assert!(large.0 <= 128, "hidden selection exceeds its visit budget");
    ze166_assert_blocked_tombstone_budget();
}

// Every visited tombstone here is blocked. Selection must still stop and
// resume, rather than chasing 128 successful removals through the whole tree.
#[cfg(test)]
fn ze166_assert_blocked_tombstone_budget() {
    use crate::property_graph::storage::consolidation::{SWEEP_WORK, select_finished_tombstones};
    let parent = super::tempfile::tempdir().unwrap();
    let store = Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
    let control = QueryControl::Cancel(CancelToken::new());
    let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
    let names: Vec<_> = (0..130).map(|id| format!("blocked-{id}")).collect();
    for chunk in names.chunks(32) {
        let nodes: Vec<_> = chunk
            .iter()
            .map(|name| StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze166", name).unwrap(),
                revision: GraphRevision::new(1).unwrap(),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            })
            .collect();
        let receipts = store.apply_native_graph(&nodes, &control).unwrap();
        let edges: Vec<_> = chunk
            .iter()
            .zip(receipts.iter())
            .map(|(name, receipt)| {
                let EntityId::Node(node) = receipt.entity else {
                    panic!("node");
                };
                let mut edge = ze166_relationship(node, node);
                edge.key = ApplicationKey::new(EntityKind::Relationship, "ze166", name).unwrap();
                edge
            })
            .collect();
        store.apply_native_graph(&edges, &control).unwrap();
        let deletes: Vec<_> = chunk
            .iter()
            .zip(receipts.iter())
            .map(|(name, receipt)| StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "ze166", name).unwrap(),
                revision: GraphRevision::new(2).unwrap(),
                operation: StructuredOperation::Delete(
                    receipt.entity,
                    crate::property_graph::GraphDeleteMode::Detach,
                ),
                image: None,
            })
            .collect();
        store.apply_native_graph(&deletes, &control).unwrap();
    }
    let lease = store.admit_native_read().unwrap();
    let shared = crate::property_graph::resources::GraphResources::from_store(&store).unwrap();
    let writer = WriteMemory::new(&shared, WriteLimits::default()).unwrap();
    let memory = StorageMemory::new(&writer, &control, 32 * 1024 * 1024).unwrap();
    let source = NativePreparationSource::new(&lease, &memory, 64).unwrap();
    let mut r = source.resources(256 * 1024 * 1024).unwrap();
    let catalog =
        crate::property_graph::storage::NativePreparationCatalog::open(&source, &mut r).unwrap();
    let mut resume = None;
    for expected in [128, 2] {
        SWEEP_WORK.with(|counter| counter.set([0; 4]));
        let selected = select_finished_tombstones(
            &source,
            lease.bundle().roots(),
            &catalog,
            None,
            &[],
            128,
            lease.bundle().sequence(),
            &mut resume,
            &memory,
            &mut r,
        )
        .unwrap();
        assert!(selected.as_slice().is_empty());
        assert_eq!(SWEEP_WORK.with(|counter| counter.get()[3]), expected);
    }
    assert!(resume.is_none());
}

#[cfg(feature = "test-seams")]
pub(crate) fn run_ze75_reclaim_evidence(
    seed: u64,
) -> Vec<crate::graph_commit_recovery_test_support::ReclaimEvidence> {
    use super::publication::{reset_verified_faults, take_verified_faults};
    [
        CrashCell::BeforeIntent,
        CrashCell::BeforeFirstUnlink,
        CrashCell::AfterOneUnlink,
        CrashCell::DirectorySync,
        CrashCell::BeforeCompletion,
        CrashCell::LostCompletionAck,
        CrashCell::Control,
    ]
    .into_iter()
    .map(|cell| {
        reset_verified_faults();
        let mut report =
            crate::graph_commit_recovery_test_support::with_qualification_nonces(seed, || {
                run_reclaim_crash_cell_observed(cell, true)
            });
        report.fires = take_verified_faults();
        report
    })
    .collect()
}

#[test]
fn proof_validates_from_its_captured_base_without_any_wal_bytes() {
    run_self_contained_proof();
}

fn run_self_contained_proof() {
    let parent = super::tempfile::tempdir().expect("parent");
    let path = parent.path().join("native");
    let store = Store::create_native_graph(&path, options(), None).expect("store");
    let control = QueryControl::Cancel(CancelToken::new());
    let image = CanonicalContents::node(&mut [], &mut [], Some("captured"), None).expect("image");
    store
        .apply_native_graph(
            &[StructuredWrite {
                key: ApplicationKey::new(EntityKind::Node, "captured", "node").expect("key"),
                revision: GraphRevision::new(1).expect("revision"),
                operation: StructuredOperation::Create,
                image: Some(WriteImage::Node(&image)),
            }],
            &control,
        )
        .expect("write");
    for _ in 0..4 {
        let current = store.admit_native_read().expect("current");
        if current.bundle().reclaim().is_some() {
            break;
        }
        drop(current);
        store.checkpoint_native_graph(&control).expect("fold");
        let admission = store.admit_native_graph_maintenance().expect("admission");
        store
            .commit_native_graph_maintenance(&admission, &control)
            .expect("maintenance");
    }
    let current = store.admit_native_read().expect("pending");
    assert!(current.bundle().reclaim().is_some(), "real pending proof");
    super::super::recovery::validate_reclaim_proof_for_test(&store, current.bundle(), &control)
        .expect("proof before deleting WAL");
    use crate::vfs::crash::{CrashVfs, MemoryVfs};
    let memory = MemoryVfs::new();
    let before = directory_image(&path);
    let mut wals = Vec::new();
    for (name, bytes) in &before {
        let file = path.join(name);
        memory.insert(&file, bytes.clone()).expect("seed CrashVfs");
        if name == "wal.ze" {
            wals.push(file);
        }
    }
    assert!(!wals.is_empty());
    let crash = CrashVfs::new(memory).expect("CrashVfs");
    for wal in &wals {
        crash.delete(wal).expect("delete graph WAL in CrashVfs");
    }
    let states = crash.crash_states().expect("delete crash states");
    assert!(!states.was_capped());
    let complete = states
        .iter()
        .find(|state| state.includes_complete_operation_sequence(wals.len()))
        .expect("completed deletes")
        .vfs()
        .files()
        .expect("crash image");
    assert!(wals.iter().all(|wal| !complete.contains_key(wal)));
    // Native mappings require disk files; materialize this CrashVfs image.
    for name in before.keys() {
        if !complete.contains_key(&path.join(name)) {
            std::fs::remove_file(path.join(name)).expect("materialize deletion");
        }
    }
    super::super::recovery::validate_reclaim_proof_for_test(&store, current.bundle(), &control)
        .expect("self-contained proof without WAL");
}

#[test]
fn every_crash_state_of_intent_unlink_complete_resumes() {
    run_ze46_intent_unlink_sync_completion_crashes_resume_idempotently();
}

#[test]
fn an_old_pending_reclaim_proof_is_refused_without_mutation() {
    let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/graph-reclaim/pre-ze380-pending");
    for access in [
        crate::lifecycle::AccessMode::ReadOnly,
        crate::lifecycle::AccessMode::ReadWrite,
    ] {
        let parent = super::tempfile::tempdir().unwrap();
        let path = parent.path().join("native");
        std::fs::create_dir(&path).unwrap();
        for entry in std::fs::read_dir(&fixture).unwrap() {
            let entry = entry.unwrap();
            if entry.file_name() != "README.md" {
                std::fs::copy(entry.path(), path.join(entry.file_name())).unwrap();
            }
        }
        let before = directory_image(&path);
        let vfs = Arc::new(RecordingVfs::default());
        let infrastructure: Arc<dyn Vfs> = vfs.clone();
        let result = Store::open_native_graph_with_infrastructure(
            &path,
            options().with_access_mode(access),
            None,
            infrastructure,
            Arc::new(crate::lifecycle::SystemMonotonicClock),
        );
        assert!(
            matches!(
                result,
                Err(super::super::NativeGraphError::Store(
                    crate::lifecycle::StoreError::NativeGraphDirectory { .. }
                ))
            ),
            "old pending proof must be refused before resume"
        );
        assert_eq!(
            directory_image(&path),
            before,
            "old binary must still be able to resume"
        );
        assert!(delete_events(&vfs.take()).is_empty());
    }
}

fn run_fold_before_capture(fault: bool) {
    let parent = super::tempfile::tempdir().unwrap();
    let path = parent.path().join("native");
    let vfs = Arc::new(RecordingVfs::default());
    let store = create_reclaim_test_store(&path, &vfs);
    ze163_base_write(&store, "fold-capture", 0);
    let admission = store.admit_native_graph_maintenance().unwrap();
    let sequence = admission.lease.bundle().sequence();
    let generation = admission.lease.bundle().base().generation;
    assert!(admission.lease.bundle().base().fold.envelope_sequence < sequence);
    vfs.take();
    if fault {
        vfs.arm_fault(super::publication::FaultPoint::Rename);
    }
    let result = store
        .commit_native_graph_maintenance(&admission, &QueryControl::Cancel(CancelToken::new()));
    if fault {
        assert!(result.is_err(), "fold manifest rename must refuse");
        vfs.assert_fired_once();
        let current = store.admit_native_read().unwrap();
        assert_eq!(current.bundle().sequence(), sequence);
        assert_eq!(current.bundle().base().generation, generation);
        assert_eq!(current.bundle().high_waters().node, 1);
        let events = vfs.take();
        assert!(delete_events(&events).is_empty());
        assert!(!events.iter().any(
            |event| matches!(event, DurabilityEvent::Rename(_, to) if to.ends_with("manifest.ze"))
        ));
        assert!(!events.iter().any(|event| matches!(event, DurabilityEvent::Create(file) if file.extension().is_some_and(|extension| extension == "zgraph"))), "captured proof must follow the manifest commit");
    } else {
        result.unwrap();
        let current = store.admit_native_read().unwrap();
        assert_eq!(current.bundle().base().fold.envelope_sequence, sequence);
        assert_eq!(
            current.bundle().base().fold.manifest_generation,
            generation.get() + 1
        );
        assert_eq!(current.bundle().high_waters().node, 1);
        let events = vfs.take();
        let fold = events.iter().position(|event| matches!(event, DurabilityEvent::Rename(_, to) if to.ends_with("manifest.ze"))).unwrap();
        let mut captured_count = 0;
        for (index, event) in events.iter().enumerate() {
            if let DurabilityEvent::Create(file) = event
                && file
                    .extension()
                    .is_some_and(|extension| extension == "zgraph")
            {
                let bytes = std::fs::read(file).unwrap();
                if bytes[8..10] != 17_u16.to_le_bytes() {
                    continue;
                }
                let frame = crate::property_graph::storage::artifact::decode(
                    crate::property_graph::storage::artifact::ContainerKind::Object,
                    None,
                    &bytes,
                )
                .unwrap();
                let block = frame.framed_block(frame.reference(0).unwrap()).unwrap();
                if block.payload().get(..8) == Some([b'Z', b'G', b'C', b'P', 7, 0, 1, 0].as_slice())
                {
                    let mut cancelled = || false;
                    let mut resources = crate::property_graph::wal::WalResources::new(
                        u64::MAX,
                        crate::property_graph::wal::STACK_RESERVATION_BYTES,
                        &mut cancelled,
                    )
                    .unwrap();
                    let base = crate::property_graph::storage::reclaim::decode_captured_base(
                        block.payload(),
                        &mut resources,
                    )
                    .unwrap();
                    assert_eq!(base.binding.sequence, sequence);
                    assert_eq!(base.state.generation, generation);
                    assert_eq!(base.fold, current.bundle().base().fold);
                    assert!(fold < index, "fold publication must precede capture");
                    captured_count += 1;
                }
            }
        }
        assert_eq!(captured_count, 1);
        assert!(delete_events(&events).is_empty());
    }
    drop(admission);
    store.close().unwrap();
}

#[test]
fn reclaim_fold_before_capture_refuses_then_clean_control_passes() {
    run_fold_before_capture(true);
    run_fold_before_capture(false);
}

fn settle_reclaim_for_test(store: &Store) {
    for _ in 0..4 {
        if store
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_none()
        {
            return;
        }
        commit_maintenance(store).unwrap();
    }
    assert!(
        store
            .admit_native_read()
            .unwrap()
            .bundle()
            .reclaim()
            .is_none()
    );
}

#[cfg(any(test, feature = "test-seams"))]
pub(crate) mod maintain {
    use super::*;
    use crate::tier::{MaintenanceBudget, MaintenanceStatus};
    use std::time::Duration;

    fn budget(bytes: u64) -> MaintenanceBudget {
        MaintenanceBudget {
            wall_time: Duration::from_secs(60),
            bytes,
        }
    }

    #[cfg(test)]
    fn segment_store(
        path: &Path,
        vfs: Arc<RecordingVfs>,
        clock: Arc<crate::lifecycle::ManualMonotonicClock>,
    ) -> Store {
        let document = EmbeddingTower {
            model_id: "sift-profile-fixture".into(),
            model_version: "1".into(),
            weights_digest: vec![0x16],
            dims: 128,
            normalization: Normalization::None,
            prompt_prefix: String::new(),
            max_tokens: 512,
            runtime: EmbeddingRuntime::CpuReference,
            compute_units: ComputeUnits::Cpu,
            os_build: None,
        };
        let epoch = crate::epoch::StoreEpoch {
            embedding: crate::epoch::EmbeddingEpoch {
                query: document.clone(),
                document,
                alignment_digest: Vec::new(),
            },
            tokenizer: crate::fts::tokenizer::TokenizerConfig::text_default().epoch(),
        };
        Store::open_with_test_dependencies(
            path,
            options().with_epoch(epoch),
            crate::lifecycle::StoreTestDependencies::new(vfs, clock),
        )
        .unwrap()
    }

    #[cfg(test)]
    fn due_segment(store: &Store, tag: u8) {
        use crate::lifecycle::{InMemorySegment, InMemorySegmentFactors};
        use crate::meta::{AliveSet, ColumnStoreBuilder, Schema};
        let vectors = (0..4)
            .flat_map(|row| std::iter::repeat_n(row as f32, 128))
            .collect::<Vec<_>>();
        let mut codes = vec![0; 4 * 64];
        let factors = vectors
            .chunks_exact(128)
            .zip(codes.chunks_exact_mut(64))
            .map(|(row, encoded)| crate::quant::quantize_bit4(row, encoded).unwrap())
            .collect();
        let mut columns = ColumnStoreBuilder::new(Schema::new(Vec::new()).unwrap());
        for row in 0..4 {
            columns.push_row(row, &[]).unwrap();
        }
        let columns = columns.finish().unwrap();
        let alive = AliveSet::new(4);
        let prepared = store
            .prepare_segment(InMemorySegment {
                id: crate::segment::SegmentId::new(u64::from(tag), [tag; 10]),
                scheme: 4,
                dims: 128,
                codes,
                factors: InMemorySegmentFactors::Bit4(factors),
                rescore: vectors,
                columns: &columns,
                alive: &alive,
            })
            .unwrap();
        store.seal_snapshot(prepared).unwrap();
    }

    #[cfg(test)]
    fn thresholds() -> crate::tier::TierThresholds {
        crate::tier::TierThresholds { graph_min_rows: 1 }
    }

    #[test]
    fn reports_graph_steps_in_the_maintenance_report() {
        let parent = super::super::tempfile::tempdir().unwrap();
        let path = parent.path().join("native");
        let store = segment_store(
            &path,
            Arc::new(RecordingVfs::default()),
            Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
        );
        store.enable_graph().unwrap();
        due_segment(&store, 1);
        ze260_add_unlabelled_node(&store, "host-maintenance");
        let before = store.snapshot().unwrap().generation();
        let report = store.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        assert_eq!(report.graphs_built, 1);
        assert!(
            matches!(report.status, MaintenanceStatus::Complete),
            "{report:?}"
        );
        assert!(
            store.snapshot().unwrap().generation() > before,
            "Store::maintain must publish due property graph maintenance: {report:?}"
        );
        assert!(report.bytes_consumed > 0);
        assert!(report.graph_steps > 0 && report.graph_steps <= 4);
        assert!(report.graph.unwrap().cycle_complete);
        assert_eq!(
            report.generation,
            Some(store.snapshot().unwrap().generation())
        );
    }
    #[test]
    fn automatic_reclaim_debt_still_triggers_after_32_commits() {
        use crate::property_graph::GraphMaintenancePolicy;
        use std::sync::atomic::Ordering;
        let parent = super::super::tempfile::tempdir().unwrap();
        let store =
            Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
        for index in 0..31 {
            ze260_add_unlabelled_node(&store, &format!("cadence-{index}"));
        }
        assert!(!store.native_graph_maintenance_due().unwrap());
        ze260_add_unlabelled_node(&store, "cadence-31");
        assert!(store.native_graph_maintenance_due().unwrap());
        assert_eq!(
            store
                .native_graph
                .commits_since_reclaim
                .load(Ordering::Relaxed),
            32
        );
        // Replaying the same write must neither run maintenance nor reset debt.
        ze260_add_unlabelled_node(&store, "cadence-31");
        assert_eq!(
            store
                .native_graph
                .commits_since_reclaim
                .load(Ordering::Relaxed),
            32
        );
        let before = store.snapshot().unwrap().generation();
        let control = QueryControl::Cancel(CancelToken::new());
        assert!(store.apply_native_graph(&[], &control).unwrap().is_empty());
        let mut labels = [GraphName::new("Different").unwrap()];
        let conflicting = CanonicalContents::node(&mut labels, &mut [], None, None).unwrap();
        assert!(
            store
                .apply_native_graph(
                    &[StructuredWrite {
                        key: ApplicationKey::new(EntityKind::Node, "s6a-garbage", "cadence-31")
                            .unwrap(),
                        revision: GraphRevision::new(1).unwrap(),
                        operation: StructuredOperation::Create,
                        image: Some(WriteImage::Node(&conflicting)),
                    }],
                    &control
                )
                .is_err()
        );
        assert_eq!(store.snapshot().unwrap().generation(), before);
        assert_eq!(
            store
                .native_graph
                .commits_since_reclaim
                .load(Ordering::Relaxed),
            32
        );
        let image = CanonicalContents::node(&mut [], &mut [], None, None).unwrap();
        let changed = store
            .apply_native_graph(
                &[StructuredWrite {
                    key: ApplicationKey::new(EntityKind::Node, "s6a-garbage", "cadence-32")
                        .unwrap(),
                    revision: GraphRevision::new(1).unwrap(),
                    operation: StructuredOperation::Create,
                    image: Some(WriteImage::Node(&image)),
                }],
                &control,
            )
            .unwrap();
        assert!(
            changed[0].generation.get() > before + 1,
            "maintenance must run before the changed write"
        );
        assert_eq!(
            store.snapshot().unwrap().generation(),
            changed[0].generation.get()
        );
        store
            .native_graph
            .pack_bytes_since_reclaim
            .store(64 * 1024 * 1024, Ordering::Relaxed);
        assert!(store.native_graph_maintenance_due().unwrap());
        store
            .set_native_graph_maintenance_policy(GraphMaintenancePolicy {
                automatic: false,
                reclaim_after_bytes: 64 * 1024 * 1024,
            })
            .unwrap();
        assert!(!store.native_graph_maintenance_due().unwrap());
    }

    #[test]
    fn segment_and_graph_share_one_budget() {
        let parent = super::super::tempfile::tempdir().unwrap();
        let store =
            Store::create_native_graph(parent.path().join("native"), options(), None).unwrap();
        let empty = store.maintain(budget(1));
        assert!(
            matches!(empty.status, MaintenanceStatus::Complete),
            "{empty:?}"
        );
        assert_eq!(empty.bytes_consumed, 0);
        assert_eq!(empty.generation, None);
        ze260_add_unlabelled_node(&store, "budget");
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        for bytes in [0, 1, 256] {
            let before = store.snapshot().unwrap().generation();
            let report = store.maintain(budget(bytes));
            assert!(
                matches!(report.status, MaintenanceStatus::BudgetExhausted),
                "{report:?}"
            );
            assert!(report.bytes_consumed <= bytes, "{report:?}");
            assert_eq!(store.snapshot().unwrap().generation(), before);
            ze260_add_unlabelled_node(&store, "budget"); // definite refusals must not poison the writer
        }
        let report = store.maintain(budget(64 * 1024 * 1024));
        assert!(
            matches!(report.status, MaintenanceStatus::Complete),
            "{report:?}"
        );
        let segment_only = segment_store(
            &parent.path().join("segment-only"),
            Arc::new(RecordingVfs::default()),
            Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
        );
        due_segment(&segment_only, 1);
        let segment_report =
            segment_only.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        assert_eq!(segment_report.graphs_built, 1);
        assert_eq!(segment_report.graph_steps, 0);
        assert!(segment_report.graph.is_none());
        let combined = segment_store(
            &parent.path().join("combined"),
            Arc::new(RecordingVfs::default()),
            Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
        );
        combined.enable_graph().unwrap();
        due_segment(&combined, 1);
        ze260_add_unlabelled_node(&combined, "combined");
        let exhausted = combined.maintain_with_test_thresholds(budget(1), thresholds());
        assert!(matches!(
            exhausted.status,
            MaintenanceStatus::BudgetExhausted
        ));
        assert_eq!(exhausted.graph_steps, 0);
        let shared = combined
            .maintain_with_test_thresholds(budget(segment_report.bytes_consumed + 1), thresholds());
        assert!(
            matches!(shared.status, MaintenanceStatus::BudgetExhausted),
            "{shared:?}"
        );
        assert_eq!(shared.graphs_built, 1);
        assert_eq!(
            shared.graph_steps, 0,
            "graph must receive one remaining byte, not the original allowance"
        );
        assert_eq!(shared.bytes_consumed, segment_report.bytes_consumed);
    }

    #[test]
    fn pending_reclaim_and_spills_cannot_bypass_the_budget() {
        let (history, store) = seed_crash_history();
        let before = store.snapshot().unwrap().generation();
        let report = store.maintain(budget(1));
        assert!(
            matches!(report.status, MaintenanceStatus::BudgetExhausted),
            "{report:?}"
        );
        assert!(report.bytes_consumed <= 1);
        let after = store.snapshot().unwrap().generation();
        assert_eq!(
            report.generation,
            (after > before).then_some(after),
            "a checkpoint preceding exhaustion is still a publication"
        );
        let oracle = history.oracle(&store);
        // Real pending intent from the established reclaim fixture.
        commit_maintenance(&store).unwrap();
        assert!(
            store
                .admit_native_read()
                .unwrap()
                .bundle()
                .reclaim()
                .is_some()
        );
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        let image = directory_image(&history.path);
        for bytes in [1, 4096] {
            history.vfs.clear_events();
            let report = store.maintain(budget(bytes));
            assert!(
                matches!(report.status, MaintenanceStatus::BudgetExhausted),
                "{report:?}"
            );
            assert!(report.bytes_consumed <= bytes);
            assert_eq!(
                directory_image(&history.path),
                image,
                "completion admission precedes unlink"
            );
        }
        let stopped = store.maintain(budget(32 * 1024));
        assert!(
            matches!(stopped.status, MaintenanceStatus::BudgetExhausted),
            "{stopped:?}"
        );
        assert!(stopped.bytes_consumed > 0 && stopped.bytes_consumed <= 32 * 1024);
        let report = store.maintain(budget(64 * 1024 * 1024));
        assert!(
            matches!(report.status, MaintenanceStatus::Complete),
            "{report:?}"
        );
        assert!(report.graph.unwrap().cycle_complete);
        assert!(
            store
                .admit_native_read()
                .unwrap()
                .bundle()
                .reclaim()
                .is_none()
        );
        assert_same_logical_state(&oracle, &history.oracle(&store));
    }

    #[test]
    fn failure_preserves_completed_phase_counters() {
        use super::super::publication::FaultPoint;
        let parent = super::super::tempfile::tempdir().unwrap();
        let vfs = Arc::new(RecordingVfs::default());
        let clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
        let path = parent.path().join("native");
        let store = segment_store(&path, vfs.clone(), clock);
        store.enable_graph().unwrap();
        due_segment(&store, 1);
        ze260_add_unlabelled_node(&store, "failure");
        let fault_vfs = vfs.clone();
        vfs.after_next_create(move || fault_vfs.arm_fault(FaultPoint::PartialCreate));
        let report = store.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        vfs.assert_fired_once();
        assert!(
            matches!(
                report.status,
                MaintenanceStatus::Failed(crate::tier::MaintenanceError::PropertyGraph(_))
            ),
            "{report:?}"
        );
        assert_eq!(report.graphs_built, 1);
        assert!(report.bytes_consumed > 0);
        assert_eq!(
            report.generation,
            Some(store.snapshot().unwrap().generation())
        );
        assert!(
            store
                .apply_native_graph(&[], &QueryControl::Cancel(CancelToken::new()))
                .is_err(),
            "durable create failure must fence shared writes"
        );
        store.close().unwrap();
        let readonly = Store::open_with_test_dependencies(
            &path,
            OpenOptions::read_only().with_epoch(store.epoch.clone().unwrap()),
            crate::lifecycle::StoreTestDependencies::new(
                vfs.clone(),
                Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
            ),
        )
        .unwrap();
        vfs.clear_events();
        assert!(matches!(
            readonly.maintain(budget(64 * 1024 * 1024)).status,
            MaintenanceStatus::Failed(_)
        ));
        readonly.close().unwrap();
        assert!(matches!(
            readonly.maintain(budget(64 * 1024 * 1024)).status,
            MaintenanceStatus::Failed(_)
        ));
        assert!(vfs.take().is_empty());
    }

    #[test]
    fn segment_deadline_is_not_restarted_for_graph_work() {
        let parent = super::super::tempfile::tempdir().unwrap();
        let vfs = Arc::new(RecordingVfs::default());
        let clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
        let store = segment_store(&parent.path().join("native"), vfs.clone(), clock.clone());
        store.enable_graph().unwrap();
        due_segment(&store, 1);
        ze260_add_unlabelled_node(&store, "deadline");
        let mut publications = 0;
        vfs.clear_events();
        vfs.after_selector_sync(move || {
            publications += 1;
            if publications == 5 {
                clock.advance(Duration::from_secs(60));
            }
            Ok(())
        });
        let report = store.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        assert!(
            matches!(report.status, MaintenanceStatus::BudgetExhausted),
            "{report:?}"
        );
        assert_eq!(report.graphs_built, 1);
        assert_eq!(report.passes_applied, 4);
        assert_eq!(report.graph_steps, 0);
        assert!(!vfs.take().iter().any(|event| matches!(event, DurabilityEvent::Create(path) if path.extension().is_some_and(|extension| extension == "zgraph"))));
        assert!(report.generation.is_some());
        ze260_add_unlabelled_node(&store, "deadline-control");
    }

    #[test]
    fn segment_failure_preserves_published_progress() {
        use super::super::publication::FaultPoint;
        let parent = super::super::tempfile::tempdir().unwrap();
        let control_vfs = Arc::new(RecordingVfs::default());
        let clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
        let control = segment_store(
            &parent.path().join("control"),
            control_vfs.clone(),
            clock.clone(),
        );
        due_segment(&control, 1);
        control_vfs.after_selector_sync(move || {
            clock.advance(Duration::from_secs(60));
            Ok(())
        });
        let initial = control.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        assert!(
            matches!(initial.status, MaintenanceStatus::BudgetExhausted),
            "{initial:?}"
        );
        assert_eq!(initial.graphs_built, 1);
        assert_eq!(initial.passes_applied, 0);
        let vfs = Arc::new(RecordingVfs::default());
        let store = segment_store(
            &parent.path().join("native"),
            vfs.clone(),
            Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
        );
        due_segment(&store, 1);
        vfs.arm_fault_after(FaultPoint::ManifestWrite, 1);
        let report = store.maintain_with_test_thresholds(budget(64 * 1024 * 1024), thresholds());
        vfs.assert_fired_once();
        assert!(
            matches!(report.status, MaintenanceStatus::Failed(_)),
            "{report:?}"
        );
        assert_eq!(
            report.graphs_built, 1,
            "a later segment failure must preserve the first publication"
        );
        assert!(report.bytes_consumed > 0);
        assert!(
            report.bytes_consumed > initial.bytes_consumed,
            "a failed refinement publication must retain its completed work charge: {report:?}; initial={initial:?}"
        );
        assert_eq!(
            report.generation,
            Some(store.snapshot().unwrap().generation())
        );
    }

    #[cfg(test)]
    fn advance_after_creates(
        vfs: Arc<RecordingVfs>,
        clock: Arc<crate::lifecycle::ManualMonotonicClock>,
        remaining: usize,
    ) {
        let hook_vfs = vfs.clone();
        vfs.after_next_create(move || {
            if remaining == 1 {
                clock.advance(Duration::from_secs(60));
            } else {
                advance_after_creates(hook_vfs, clock, remaining - 1);
            }
        });
    }

    #[test]
    fn an_admitted_graph_publication_finishes_after_the_deadline() {
        let parent = super::super::tempfile::tempdir().unwrap();
        let mut creates = 0;
        for fault in [false, true] {
            let vfs = Arc::new(RecordingVfs::default());
            let clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
            let path = parent
                .path()
                .join(if fault { "expired" } else { "control" });
            let store = Store::open_with_test_dependencies(
                &path,
                options(),
                crate::lifecycle::StoreTestDependencies::new(vfs.clone(), clock.clone()),
            )
            .unwrap();
            store.enable_graph().unwrap();
            ze260_add_unlabelled_node(&store, "admitted");
            store
                .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
                .unwrap();
            vfs.clear_events();
            if fault {
                advance_after_creates(vfs.clone(), clock, creates);
            }
            let report = store.maintain(budget(64 * 1024 * 1024));
            assert!(
                matches!(report.status, MaintenanceStatus::Complete),
                "{report:?}"
            );
            assert!(report.graph.unwrap().cycle_complete);
            if !fault {
                creates = vfs.take().iter().filter(|event| matches!(event, DurabilityEvent::Create(path) if path.extension().is_some_and(|extension| extension == "zgraph"))).count();
                assert!(creates > 0);
            }
            ze260_add_unlabelled_node(&store, "admitted-control");
        }
    }

    #[test]
    fn retirement_publication_finishes_after_the_deadline() {
        let mut creates = 0;
        for fault in [false, true] {
            let (history, mut store) = seed_crash_history();
            commit_maintenance(&store).unwrap();
            store
                .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
                .unwrap();
            let clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
            store.clock = clock.clone();
            history.vfs.clear_events();
            if fault {
                advance_after_creates(history.vfs.clone(), clock, creates);
            }
            let report = store.maintain(budget(64 * 1024 * 1024));
            assert!(
                matches!(report.status, MaintenanceStatus::Complete),
                "{report:?}"
            );
            assert!(report.graph.unwrap().cycle_complete);
            assert_eq!(
                report.generation,
                Some(store.snapshot().unwrap().generation())
            );
            assert_eq!(
                store
                    .native_graph
                    .commits_since_reclaim
                    .load(std::sync::atomic::Ordering::Relaxed),
                0
            );
            if !fault {
                creates = history.vfs.take().iter().filter(|event| matches!(event, DurabilityEvent::Create(path) if path.extension().is_some_and(|extension| extension == "zgraph"))).count();
                assert!(creates > 0);
            }
        }
    }

    #[test]
    fn deadline_during_pending_reclaim_leaves_the_writer_resumable() {
        struct AfterUnlink {
            vfs: Arc<RecordingVfs>,
            clock: crate::lifecycle::ManualMonotonicClock,
            fired: std::sync::atomic::AtomicBool,
        }
        impl crate::lifecycle::MonotonicClock for AfterUnlink {
            fn now(&self) -> std::time::Instant {
                if self
                    .vfs
                    .take()
                    .iter()
                    .any(|event| matches!(event, DurabilityEvent::Delete(_)))
                {
                    self.fired.store(true, std::sync::atomic::Ordering::Relaxed);
                    self.clock.advance(Duration::from_secs(60));
                }
                self.clock.now()
            }
        }
        let (history, mut store) = seed_crash_history();
        let oracle = history.oracle(&store);
        commit_maintenance(&store).unwrap();
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        history.vfs.clear_events();
        let clock = Arc::new(AfterUnlink {
            vfs: history.vfs.clone(),
            clock: crate::lifecycle::ManualMonotonicClock::new(),
            fired: std::sync::atomic::AtomicBool::new(false),
        });
        store.clock = clock.clone();
        let report = store.maintain(budget(64 * 1024 * 1024));
        assert!(clock.fired.load(std::sync::atomic::Ordering::Relaxed));
        assert!(
            matches!(report.status, MaintenanceStatus::BudgetExhausted),
            "{report:?}"
        );
        assert!(report.bytes_consumed <= 64 * 1024 * 1024);
        apply_crash_history_writes(&store, &history.document);
        store.clock = Arc::new(crate::lifecycle::ManualMonotonicClock::new());
        let resumed = store.maintain(budget(64 * 1024 * 1024));
        assert!(
            matches!(resumed.status, MaintenanceStatus::Complete),
            "{resumed:?}"
        );
        assert_same_logical_state(&oracle, &history.oracle(&store));
    }

    /// An admitted artifact charge survives close before publication.
    #[test]
    fn closing_after_graph_work_retains_the_admitted_charge() {
        let parent = super::super::tempfile::tempdir().unwrap();
        let vfs = Arc::new(RecordingVfs::default());
        let store = Arc::new(
            Store::open_with_test_dependencies(
                parent.path().join("native"),
                options(),
                crate::lifecycle::StoreTestDependencies::new(
                    vfs.clone(),
                    Arc::new(crate::lifecycle::ManualMonotonicClock::new()),
                ),
            )
            .unwrap(),
        );
        store.enable_graph().unwrap();
        ze260_add_unlabelled_node(&store, "close-charge");
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        let release = Arc::new(std::sync::Barrier::new(2));
        let closer_release = release.clone();
        let closer = store.clone();
        let (closing_tx, closing_rx) = std::sync::mpsc::channel();
        let (worker_tx, worker_rx) = std::sync::mpsc::channel();
        vfs.after_next_create(move || {
            let worker = std::thread::spawn(move || {
                closer.close_with_final_writer(|| {
                    closing_tx.send(()).unwrap();
                    closer_release.wait();
                })
            });
            worker_tx.send(worker).unwrap();
            closing_rx.recv().unwrap();
        });
        let report = store.maintain(budget(64 * 1024 * 1024));
        release.wait();
        worker_rx.recv().unwrap().join().unwrap().unwrap();
        assert!(
            matches!(report.status, MaintenanceStatus::Failed(_)),
            "{report:?}"
        );
        assert!(
            report.bytes_consumed > 0 && report.bytes_consumed <= 64 * 1024 * 1024,
            "closing must not erase admitted graph work: {report:?}"
        );
        assert_eq!(report.generation, None);
    }

    /// Real host byte refusal and graph create/unlink faults, followed by reopen.
    pub(crate) fn run_fault_case(kind: u8) -> (u64, u64, u64, bool) {
        use super::super::publication::FaultPoint;
        let (history, store) = seed_crash_history();
        let oracle = history.oracle(&store);
        if kind == 2 {
            commit_maintenance(&store).unwrap();
            assert!(
                store
                    .admit_native_read()
                    .unwrap()
                    .bundle()
                    .reclaim()
                    .is_some()
            );
        }
        store
            .checkpoint_native_graph(&QueryControl::Cancel(CancelToken::new()))
            .unwrap();
        let limit = if kind == 0 { 1 } else { 64 * 1024 * 1024 };
        match kind {
            0 => {}
            1 => history.vfs.arm_fault(FaultPoint::PartialCreate),
            2 => history.vfs.arm_fault(FaultPoint::Delete),
            _ => panic!("unknown host maintenance fault shape"),
        }
        let report = store.maintain(budget(limit));
        let exhausted = matches!(report.status, MaintenanceStatus::BudgetExhausted);
        let observed = (limit, report.bytes_consumed, report.graph_steps, exhausted);
        assert!(report.bytes_consumed <= limit, "{report:?}");
        if kind == 0 {
            assert!(exhausted, "{report:?}");
            // A no-write byte refusal leaves this writer usable.
            apply_crash_history_writes(&store, &history.document);
        } else {
            history.vfs.assert_fired_once();
            assert!(
                matches!(
                    report.status,
                    MaintenanceStatus::Failed(crate::tier::MaintenanceError::PropertyGraph(_))
                ),
                "{report:?}"
            );
            assert!(
                store
                    .apply_native_graph(&[], &QueryControl::Cancel(CancelToken::new()))
                    .is_err()
            );
        }
        store.close().unwrap();
        let reopened = history.open(options()).unwrap();
        assert_same_logical_state(&oracle, &history.oracle(&reopened));
        let mut complete = false;
        for _ in 0..2 {
            let control = reopened.maintain(budget(64 * 1024 * 1024));
            assert!(
                !matches!(control.status, MaintenanceStatus::Failed(_)),
                "{control:?}"
            );
            if matches!(control.status, MaintenanceStatus::Complete) {
                complete = true;
                break;
            }
        }
        assert!(complete, "larger host budget must resume the same work");
        assert_same_logical_state(&oracle, &history.oracle(&reopened));
        reopened.close().unwrap();
        observed
    }
}