zakura-state 11.0.0

State contextual verification and storage code for the Zakura node. Internal crate, published to support cargo install zakura
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
use super::*;

#[test]
fn cached_finalized_continuation_still_chooses_the_nearest_locator() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(7);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd5; 32]);
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(first) = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the initial path is available");
    };
    assert!(matches!(
        reader
            .read_retained_path(source, 7, first.lease_id, scope, path[2].hash, 1)
            .unwrap(),
        RetainedPathReadOutcome::Page(_)
    ));
    finalize_serving_test_path(&runtime, &db, &path[3..]);
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(next) = reader
        .acquire_retained_path(source, 7, target, &[path[3].hash, path[4].hash], scope)
        .unwrap()
    else {
        panic!("a cache miss can use the nearest finalized locator");
    };
    assert_eq!(next.common_ancestor.hash, path[4].hash);
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, next.lease_id, scope, path[4].hash, 1)
        .unwrap()
    else {
        panic!("the nearest finalized suffix is available");
    };
    assert_eq!(page.headers[0].hash(), target);
    assert!(page.complete);
}

#[test]
fn idle_continuation_indexes_are_bounded_and_cannot_block_new_readers() {
    let (runtime, _db, _, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    for marker in 0..=MAX_RETAINED_PATH_LEASES {
        let source = SourceId::from_digest([u8::try_from(marker).unwrap(); 32]);
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
            .unwrap()
        else {
            panic!("idle continuations cannot consume active capacity");
        };
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(source, 7, lease.lease_id, scope, path[2].hash, 1)
            .unwrap()
        else {
            panic!("the first page is available");
        };
        assert!(!page.complete);
        let leases = runtime.leases.lock().unwrap();
        assert!(leases.by_peer.is_empty());
        assert!(leases.continuations.len() <= MAX_RETAINED_PATH_LEASES);
    }
    {
        let leases = runtime.leases.lock().unwrap();
        assert_eq!(leases.continuations.len(), MAX_RETAINED_PATH_LEASES);
        assert!(!leases
            .continuations
            .contains_key(&SourceId::from_digest([0; 32])));
    }
    // An evicted index is only a cache miss, even when the request is a continuation.
    // Ordinary slots fill first, and the last short path uses the reserve.
    for marker in 0..MAX_RETAINED_PATH_LEASES {
        let source = SourceId::from_digest([u8::try_from(marker).unwrap(); 32]);
        assert!(matches!(
            reader
                .acquire_retained_path(source, 7, target, &[path[3].hash], scope)
                .unwrap(),
            RetainedPathLeaseOutcome::Acquired(_)
        ));
    }
    assert!(matches!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xff; 32]),
                7,
                target,
                &[path[3].hash],
                scope
            )
            .unwrap(),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
}

#[test]
fn continuation_cache_matches_session_target_and_first_locator() {
    let (runtime, _db, _, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd3; 32]);
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    for (session, next_target, locators, ancestor) in [
        (8, target, vec![path[3].hash], path[3].hash),
        (7, path[4].hash, vec![path[3].hash], path[3].hash),
        (7, target, vec![path[2].hash, path[3].hash], path[3].hash),
    ] {
        let RetainedPathLeaseOutcome::Acquired(first) = reader
            .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
            .unwrap()
        else {
            panic!("the initial page has capacity");
        };
        let original = runtime
            .leases
            .lock()
            .unwrap()
            .get(source, 7, first.lease_id, Instant::now())
            .unwrap()
            .retained_path;
        assert!(matches!(
            reader
                .read_retained_path(source, 7, first.lease_id, scope, path[2].hash, 1)
                .unwrap(),
            RetainedPathReadOutcome::Page(_)
        ));
        let next_scope =
            HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), next_target);
        let RetainedPathLeaseOutcome::Acquired(next) = reader
            .acquire_retained_path(source, session, next_target, &locators, next_scope)
            .unwrap()
        else {
            panic!("a mismatched cache entry must fall back to normal acquisition");
        };
        assert_eq!(next.common_ancestor.hash, ancestor);
        let fresh = runtime
            .leases
            .lock()
            .unwrap()
            .get(source, session, next.lease_id, Instant::now())
            .unwrap();
        assert!(!Arc::ptr_eq(&original, &fresh.retained_path));
        assert!(!reader
            .release_retained_path(source, 7, first.lease_id, scope)
            .unwrap());
        assert!(reader
            .release_retained_path(source, session, next.lease_id, next_scope)
            .unwrap());
    }
}

#[test]
fn continuation_index_survives_its_target_moving_to_finalized_storage() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(7);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd4; 32]);
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(first) = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the retained target is available");
    };
    let original = runtime
        .leases
        .lock()
        .unwrap()
        .get(source, 7, first.lease_id, Instant::now())
        .unwrap()
        .retained_path;
    assert!(matches!(
        reader
            .read_retained_path(source, 7, first.lease_id, scope, path[2].hash, 1)
            .unwrap(),
        RetainedPathReadOutcome::Page(_)
    ));
    finalize_serving_test_path(&runtime, &db, &path[3..]);
    assert!(runtime.store.header_node(target).unwrap().is_none());
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(next) = reader
        .acquire_retained_path(source, 7, target, &[path[3].hash], scope)
        .unwrap()
    else {
        panic!("the finalized target can reuse its bounded index");
    };
    let resumed = runtime
        .leases
        .lock()
        .unwrap()
        .get(source, 7, next.lease_id, Instant::now())
        .unwrap();
    assert!(Arc::ptr_eq(&original, &resumed.retained_path));
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, next.lease_id, scope, path[3].hash, 2)
        .unwrap()
    else {
        panic!("the remaining canonical headers are still available");
    };
    assert_eq!(
        page.headers,
        vec![path[4].header.clone(), path[5].header.clone()]
    );
    assert!(page.complete);
    assert!(runtime.leases.lock().unwrap().continuations.is_empty());
}

#[test]
fn continuations_reuse_the_path_index_through_finality_and_late_cleanup() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(64);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd2; 32]);
    let target = path.last().unwrap().hash;
    let mut after = path[2].hash;
    let mut original_path = None;
    let mut previous_lease = None;
    for expected in &path[3..] {
        if expected.height == block::Height(10) {
            finalize_serving_test_path(&runtime, &db, &path[3..20]);
        }
        let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(source, 7, target, &[after], scope)
            .unwrap()
        else {
            panic!("every continuation has capacity");
        };
        let cursor = runtime
            .leases
            .lock()
            .unwrap()
            .get(source, 7, lease.lease_id, Instant::now())
            .unwrap();
        if let Some(original) = &original_path {
            assert!(
                Arc::ptr_eq(original, &cursor.retained_path),
                "continuations must reuse the immutable path index, not rebuild it"
            );
        } else {
            original_path = Some(cursor.retained_path.clone());
        }
        if let Some((old_id, old_scope)) = previous_lease {
            assert!(!reader
                .release_retained_path(source, 7, old_id, old_scope)
                .unwrap());
        }
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(source, 7, lease.lease_id, scope, after, 1)
            .unwrap()
        else {
            panic!("the exact next page remains available");
        };
        assert_eq!(
            page.headers.as_slice(),
            std::slice::from_ref(&expected.header)
        );
        assert_eq!(page.complete, expected.hash == target);
        assert!(runtime.leases.lock().unwrap().by_peer.is_empty());
        previous_lease = Some((lease.lease_id, scope));
        after = expected.hash;
    }
}

#[test]
fn completed_page_releases_capacity_before_continuation_and_late_cleanup() {
    let (runtime, _db, _, path) = reconciled_store_with_finalized_prefix(5);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd1; 32]);
    let target = path[4].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(first) = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the first page has capacity");
    };
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, first.lease_id, scope, path[2].hash, 1)
        .unwrap()
    else {
        panic!("the first page remains available");
    };
    assert!(!page.complete);
    let RetainedPathLeaseOutcome::Acquired(second) = reader
        .acquire_retained_path(source, 7, target, &[path[3].hash], scope)
        .unwrap()
    else {
        panic!("the continuation must acquire before cleanup of the first page runs");
    };
    assert_ne!(second.lease_id, first.lease_id);
    assert!(!reader
        .release_retained_path(source, 7, first.lease_id, scope)
        .unwrap());
    assert_eq!(
        reader
            .read_retained_path(source, 7, first.lease_id, scope, path[3].hash, 1)
            .unwrap(),
        RetainedPathReadOutcome::Unavailable,
        "the consumed lease cannot race the new reader",
    );
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, second.lease_id, scope, path[3].hash, 1)
        .unwrap()
    else {
        panic!("late cleanup must not revoke the continuation");
    };
    assert_eq!(page.headers[0].hash(), target);
    assert!(page.complete);
    assert!(runtime.leases.lock().unwrap().by_peer.is_empty());
}

#[test]
fn serving_leases_do_not_block_a_better_work_branch() {
    let (engine_config, anchor, metadata) = fixture();
    let store = HeaderChainStore::new(open(&Config::ephemeral(), engine_config.network()));
    store.initialize(metadata, anchor.clone()).unwrap();
    let (runtime, _) = store.startup(&engine_config).unwrap();
    let reader = runtime.reader();
    let parent = Frontier::new(anchor.height, anchor.hash);
    let validation = reader.validation_context(anchor.hash).unwrap().unwrap();
    let rules = HeaderRules::for_validation_lease(&validation).unwrap();
    let context = TransitionContext {
        config: &engine_config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };
    let insert = |headers: &[Arc<block::Header>]| {
        let snapshot = runtime.publisher().snapshot();
        let target = headers.last().unwrap().hash();
        runtime
            .apply(
                TransitionRequest {
                    expected_version: snapshot.state_version,
                    event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
                        owner: header_owner(&snapshot, target, 1, 1),
                        source: SourceId::from_digest([0xee; 32]),
                        parent_hash: parent.hash,
                        target_tip_hash: target,
                        completion: TargetCompletion::TargetComplete {
                            common_ancestor: parent,
                        },
                        batch: zakura_header_chain::prepare_headers(
                            HeaderBatchInput::new(headers),
                            parent,
                            &rules,
                            &SystemClock,
                        )
                        .unwrap(),
                        aux: Vec::new(),
                    })),
                },
                &context,
            )
            .unwrap()
    };
    let mut captured_paths = Vec::new();
    for index in 0..zakura_header_chain::MAX_CANDIDATE_TIPS_V1 {
        let marker = u8::try_from(index).unwrap();
        let mut header = *anchor.header;
        header.previous_block_hash = parent.hash;
        header.time += chrono::Duration::seconds(1);
        header.nonce.0[0] = marker;
        let header = Arc::new(header);
        assert_eq!(
            insert(std::slice::from_ref(&header)),
            ApplyResult::Committed
        );
        let source = SourceId::from_digest([marker; 32]);
        let scope = zakura_header_chain::HeaderWorkAuthority::for_target(
            &runtime.publisher().snapshot(),
            header.hash(),
        );
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(source, 7, header.hash(), &[parent.hash], scope)
            .unwrap()
        else {
            panic!("every candidate tip fits in the general serving capacity");
        };
        let cursor = runtime
            .leases
            .lock()
            .unwrap()
            .get(source, 7, lease.lease_id, Instant::now())
            .unwrap();
        let captured = reader.capture_path_read(&cursor, 1).unwrap();
        captured_paths.push((cursor, captured));
    }

    let mut first = *anchor.header;
    first.previous_block_hash = parent.hash;
    first.time += chrono::Duration::seconds(1);
    first.nonce.0[0] = 0xff;
    let first = Arc::new(first);
    let mut second = *first;
    second.previous_block_hash = first.hash();
    second.time += chrono::Duration::seconds(1);
    let second = Arc::new(second);
    let target = Frontier::new(block::Height(2), second.hash());
    assert_eq!(
        insert(&[first, second]),
        ApplyResult::Committed,
        "peer serving leases must not veto admission of the better-work branch",
    );
    let snapshot = runtime.publisher().snapshot();
    assert_eq!(snapshot.frontiers.header_best, target);
    assert!(!snapshot.alarms.resource_stalled);

    let (cursor, captured) = captured_paths
        .iter()
        .find(|(cursor, _)| {
            runtime
                .store
                .header_node(cursor.target.hash)
                .unwrap()
                .is_none()
        })
        .expect("retention evicts an old fork to admit the better branch");
    assert_eq!(
        reader
            .read_retained_path(
                cursor.peer,
                7,
                cursor.lease_id,
                cursor.scope,
                parent.hash,
                1
            )
            .unwrap(),
        RetainedPathReadOutcome::Unavailable,
    );
    let (page, _, _) = captured.read_page(cursor, 1).unwrap().unwrap();
    assert_eq!(page.headers[0].hash(), cursor.target.hash);
    assert!(
        page.complete,
        "an already captured page survives pruning coherently"
    );
}

#[test]
fn selected_chain_membership_spans_the_finalized_boundary_and_follows_a_reorg() {
    use zakura_node_services::header_chain::SelectedChainMembership::{
        NotRetained, NotSelected, Selected,
    };
    // Heights 1 through 3 are finalized, and 4 through 6 are retained above them.
    let (runtime, db, genesis, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let membership = |header: &VerifiedHeaderRef| {
        reader
            .selected_chain_membership(header.hash)
            .expect("the membership query reads coherent state")
    };
    let selected = |header: &VerifiedHeaderRef| Selected(Frontier::new(header.height, header.hash));
    for header in std::iter::once(&genesis).chain(&path) {
        assert_eq!(membership(header), selected(header));
    }
    assert_eq!(
        reader
            .selected_chain_membership(block::Hash([0xab; 32]))
            .unwrap(),
        NotRetained
    );

    // Finality moves to height 5, so height 4 now answers from the finalized index.
    finalize_serving_test_path(&runtime, &db, &path[3..5]);
    assert_eq!(
        runtime.publisher().snapshot().frontiers.finalized,
        Frontier::new(path[4].height, path[4].hash)
    );
    assert!(
        runtime
            .transition_engine
            .lock()
            .unwrap()
            .graph()
            .header_node(path[3].hash)
            .is_none(),
        "finality pruned height 4 from the retained graph"
    );
    for header in std::iter::once(&genesis).chain(&path) {
        assert_eq!(membership(header), selected(header));
    }

    // A two-header branch from height 5 has more work and replaces height 6.
    let validation = reader.validation_context(path[4].hash).unwrap().unwrap();
    let rules = HeaderRules::for_validation_lease(&validation).unwrap();
    let parent = Frontier::new(path[4].height, path[4].hash);
    let mut branch = Vec::new();
    let mut previous = path[4].header.clone();
    for marker in [0xf1, 0xf2] {
        let mut header = *previous;
        header.previous_block_hash = previous.hash();
        header.time += chrono::Duration::seconds(1);
        header.nonce.0[31] = marker;
        let header = Arc::new(header);
        branch.push(header.clone());
        previous = header;
    }
    let snapshot = runtime.publisher().snapshot();
    let target = previous.hash();
    assert_eq!(
        runtime
            .apply(
                TransitionRequest {
                    expected_version: snapshot.state_version,
                    event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
                        owner: header_owner(&snapshot, target, 1, 1),
                        source: SourceId::from_digest([0xee; 32]),
                        parent_hash: parent.hash,
                        target_tip_hash: target,
                        completion: TargetCompletion::TargetComplete {
                            common_ancestor: parent,
                        },
                        batch: zakura_header_chain::prepare_headers(
                            HeaderBatchInput::new(&branch),
                            parent,
                            &rules,
                            &SystemClock,
                        )
                        .unwrap(),
                        aux: Vec::new(),
                    })),
                },
                &TransitionContext {
                    config: &runtime.config,
                    clock: &SystemClock,
                    full_state_authority: None,
                    retention_references: &[],
                },
            )
            .unwrap(),
        ApplyResult::Committed
    );
    assert_eq!(
        runtime.publisher().snapshot().frontiers.header_best.hash,
        target
    );
    assert_eq!(membership(&path[5]), NotSelected);
    for header in std::iter::once(&genesis).chain(&path[..5]) {
        assert_eq!(membership(header), selected(header));
    }
    for (header, height) in branch.iter().zip([6, 7]) {
        assert_eq!(
            reader.selected_chain_membership(header.hash()).unwrap(),
            Selected(Frontier::new(block::Height(height), header.hash()))
        );
    }
}

#[test]
fn atomic_finality_context_can_use_a_newly_staged_anchor_path() {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let store = HeaderChainStore::new(open(&db_config, engine_config.network()));
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");

    // Stage one node past the retained predecessor span, so the context cap
    // binds whatever difficulty averaging window this build uses.
    let predecessor_span = zakura_header_chain::MAX_POW_PREDECESSOR_CONTEXT_SPAN;
    let staged_len =
        u32::try_from(predecessor_span + 1).expect("the retained predecessor span fits in u32");

    let mut nodes = Vec::new();
    let mut parent = anchor;
    for height in 1..=staged_len {
        let mut header = *parent.header;
        header.previous_block_hash = parent.hash;
        header.time += chrono::Duration::seconds(1);
        header.nonce.0[0] = u8::try_from(height).expect("the staged test path is shorter than 256");
        let header = Arc::new(header);
        let hash = header.hash();
        let node = HeaderNode::from_durable_parts(
            header,
            hash,
            parent.hash,
            block::Height(height),
            parent.block_work,
            parent
                .work_coordinate()
                .checked_add(parent.block_work)
                .expect("the short staged path cannot exhaust cumulative work"),
            HeaderValidationState::Valid,
            Default::default(),
            BodyValidationState::Unknown,
            Vec::new(),
        )
        .expect("the staged node fields are coherent");
        parent = node.clone();
        nodes.push(node);
    }
    let staged: HashMap<_, _> = nodes.iter().map(|node| (node.hash, node)).collect();
    let contexts = authenticated_context_headers(&store, parent.hash, Some(&staged))
        .expect("the atomic batch can authenticate context from its staged node overlay");
    assert_eq!(contexts.len(), predecessor_span);
    assert_eq!(
        contexts.first().map(|context| context.height),
        Some(block::Height(1))
    );
    assert_eq!(
        contexts.last().map(|context| context.height),
        Some(block::Height(staged_len - 1))
    );
    assert_eq!(
        parent.header.previous_block_hash,
        contexts
            .last()
            .expect("the context is nonempty")
            .header
            .hash()
    );
}

#[test]
fn publisher_mirror_stays_absent_until_attachment_then_tracks_commits() {
    let (_, _, metadata) = fixture();
    let initial = metadata.snapshot();
    let publisher = Publisher::new(initial.clone());
    let (mirror_sender, mirror_receiver) = watch::channel(None);

    assert_eq!(*mirror_receiver.borrow(), None);

    publisher.mirror_to(mirror_sender);
    assert_eq!(*mirror_receiver.borrow(), Some(initial.clone()));

    let mut committed = initial;
    committed.state_version = StateVersion::new(2);
    publisher.publish(committed.clone(), TransitionEffect::none());
    assert_eq!(*mirror_receiver.borrow(), Some(committed));
}

#[test]
fn coherent_reader_builds_locator_from_the_durable_selected_projection() {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let store = HeaderChainStore::new(open(&db_config, engine_config.network()));
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");
    let (runtime, _) = store
        .startup(&engine_config)
        .expect("the initialized store audits");

    let reader = runtime.reader();
    let durable = reader
        .selected_locator()
        .expect("the durable selected projection is coherent");
    let committed = reader
        .committed_selected_locator()
        .expect("the committed selected projection is coherent");
    assert_eq!(committed, durable);
    assert_eq!(
        durable.entries(),
        &[Frontier::new(anchor.height, anchor.hash)]
    );
}

#[test]
fn body_refill_snapshot_holds_the_complete_transition_barrier() {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let store = HeaderChainStore::new(open(&db_config, engine_config.network()));
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");
    let (runtime, _) = store
        .startup(&engine_config)
        .expect("the initialized store audits");
    let reader = runtime.reader();
    let cloned_reader = reader.clone();

    assert!(Arc::ptr_eq(&reader.config, &cloned_reader.config));

    let (full_state, selected_projection) = reader
        .with_selected_projection(|| {
            assert!(reader.store.writer.try_lock().is_err());
            assert!(reader.transition_engine.try_lock().is_err());
            Frontier::new(anchor.height, anchor.hash)
        })
        .expect("the body refill snapshot is coherent");

    assert_eq!(full_state, Frontier::new(anchor.height, anchor.hash));
    assert_eq!(selected_projection, vec![full_state]);
}

#[test]
fn body_refill_does_not_attach_committed_sizes_to_another_fork() {
    use crate::arbitrary::Prepare;
    use crate::tests::setup::{new_state_with_mainnet_genesis, transaction_v4_from_coinbase};
    use zakura_chain::serialization::ZcashSerialize;

    let _init_guard = zakura_test::init();
    let (engine_config, anchor, metadata) = mainnet_fixture();
    let (finalized, mut full_state, _) = new_state_with_mainnet_genesis();
    let store = HeaderChainStore::new(finalized.db.header_chain_disk_db());
    store
        .initialize(metadata, anchor.clone())
        .expect("header schema initializes");

    let mut old: block::Block = zakura_test::vectors::BLOCK_MAINNET_1_BYTES
        .zcash_deserialize_into()
        .expect("height one parses");
    let selected_header = old.header.clone();
    let mut old_header = *old.header;
    old_header.nonce.0[0] ^= 1;
    old.header = Arc::new(old_header);
    // The state fixture requires a modern coinbase transaction version.
    old.transactions[0] = transaction_v4_from_coinbase(&old.transactions[0]).into();
    let old = Arc::new(old);
    full_state
        .commit_new_chain(old.clone().prepare(), &finalized)
        .expect("old branch commits");

    let selected_hash = selected_header.hash();
    let (runtime, _) = store
        .startup_reconciled(
            &engine_config,
            Frontier::new(anchor.height, anchor.hash),
            Vec::new(),
            vec![VerifiedHeaderRef {
                height: block::Height(1),
                hash: selected_hash,
                header: selected_header,
            }],
        )
        .expect("selected fork restores");

    let old_size = u32::try_from(
        old.zcash_serialize_to_vec()
            .expect("old block serializes")
            .len(),
    )
    .expect("test block size fits u32");
    assert_eq!(
        crate::service::read::block_info(
            full_state.best_chain(),
            &finalized.db,
            old.hash().into(),
        )
        .map(|info| info.size()),
        Some(old_size),
        "the old branch has a confirmed size at the same height",
    );
    let metadata = crate::service::missing_block_body_metadata(
        || full_state.best_chain(),
        &finalized.db,
        Some(&runtime.reader()),
        block::Height(2),
        10,
    )
    .expect("fork refill metadata reads");
    assert_eq!(metadata.anchor, Frontier::new(anchor.height, anchor.hash));
    assert_eq!(
        metadata.blocks,
        vec![(block::Height(1), selected_hash, None)],
        "a selected fork must not inherit the other block's confirmed size"
    );
}

#[test]
fn selected_body_window_reads_four_thousand_hashes_in_one_coherent_range() {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let store = HeaderChainStore::new(open(&db_config, engine_config.network()));
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");

    let genesis = VerifiedHeaderRef {
        height: anchor.height,
        hash: anchor.hash,
        header: anchor.header.clone(),
    };
    let mut parent = genesis.clone();
    let mut restored = Vec::new();
    for height in 1_u32..=4_000 {
        let mut header = *parent.header;
        header.previous_block_hash = parent.hash;
        header.time += chrono::Duration::seconds(1);
        header.nonce.0[..4].copy_from_slice(&height.to_le_bytes());
        let header = Arc::new(header);
        let child = VerifiedHeaderRef {
            height: block::Height(height),
            hash: header.hash(),
            header,
        };
        parent = child.clone();
        restored.push(child);
    }

    let (runtime, _) = store
        .startup_reconciled(
            &engine_config,
            Frontier::new(genesis.height, genesis.hash),
            Vec::new(),
            restored.clone(),
        )
        .expect("the genesis-finalized scratch path reconciles");
    let selected = runtime
        .reader()
        .selected_hashes(block::Height(1), 4_000)
        .expect("the full block-sync window is one coherent projection read");

    assert_eq!(selected.len(), 4_000);
    assert_eq!(
        selected.first().copied(),
        Some(Frontier::new(restored[0].height, restored[0].hash))
    );
    assert_eq!(
        selected.last().copied(),
        restored
            .last()
            .map(|header| Frontier::new(header.height, header.hash))
    );
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(5, NonZeroU64::new(6).expect("six is nonzero"));
    let repair = runtime
        .reader()
        .vct_repair_context(owner, block::Height(1))
        .expect("the long selected repair context is coherent")
        .expect("the empty selected range needs repair");
    assert_eq!(repair.selected_header_count(), 4_000);
    assert_eq!(
        repair.request_target(),
        Frontier::new(restored[3_999].height, restored[3_999].hash)
    );
}

/// A reconciled store over a genesis and `path_len` descendant headers.
///
/// The genesis and the first three path headers are finalized and indexed in the canonical
/// finalized columns. Remaining headers sit in the retained graph above the finalized frontier.
/// Returns the runtime, its open database, the genesis header, and the requested path.
fn reconciled_store_with_finalized_prefix(
    path_len: u32,
) -> (
    HeaderChainRuntime,
    DiskDb,
    VerifiedHeaderRef,
    Vec<VerifiedHeaderRef>,
) {
    reconciled_store_with_finality(path_len, 3)
}

fn reconciled_store_with_finality(
    path_len: u32,
    finalized_count: usize,
) -> (
    HeaderChainRuntime,
    DiskDb,
    VerifiedHeaderRef,
    Vec<VerifiedHeaderRef>,
) {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let db = open(&db_config, engine_config.network());
    let store = HeaderChainStore::new(db.clone());
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");

    let genesis = VerifiedHeaderRef {
        height: anchor.height,
        hash: anchor.hash,
        header: anchor.header.clone(),
    };
    let mut path = Vec::new();
    let mut parent = genesis.clone();
    for marker in 1..=path_len {
        let mut header = *parent.header;
        header.previous_block_hash = parent.hash;
        header.time += chrono::Duration::seconds(1);
        header.nonce.0[..4].copy_from_slice(&marker.to_le_bytes());
        let header = Arc::new(header);
        let height = parent
            .height
            .next()
            .expect("the four-header fixture stays in range");
        let hash = header.hash();
        let child = VerifiedHeaderRef {
            height,
            hash,
            header,
        };
        path.push(child.clone());
        parent = child;
    }

    let hash_by_height = db
        .cf_handle("hash_by_height")
        .expect("the finalized hash index exists");
    let height_by_hash = db
        .cf_handle("height_by_hash")
        .expect("the finalized height index exists");
    let block_header_by_height = db
        .cf_handle("block_header_by_height")
        .expect("the finalized header column exists");
    let mut batch = DiskWriteBatch::new();
    for header in std::iter::once(&genesis).chain(path[..finalized_count].iter()) {
        batch.zs_insert(&hash_by_height, header.height, header.hash);
        batch.zs_insert(&height_by_hash, header.hash, header.height);
        batch.zs_insert(
            &block_header_by_height,
            header.height,
            header.header.as_ref(),
        );
    }
    db.write(batch)
        .expect("the canonical finalized header fixture commits");

    let finalized = Frontier::new(
        path[finalized_count - 1].height,
        path[finalized_count - 1].hash,
    );
    let (runtime, _) = store
        .startup_reconciled(
            &engine_config,
            finalized,
            path[..finalized_count].to_vec(),
            path[finalized_count..].to_vec(),
        )
        .expect("the finalized prefix and retained suffix reconcile");
    (runtime, db, genesis, path)
}

#[test]
fn repair_context_range_is_bounded_by_reclaimable_capacity() {
    let (mut runtime, _db, _genesis, path) = reconciled_store_with_finalized_prefix(6);
    // Even an empty store cannot retain a range larger than its aggregate limit.
    runtime.set_auxiliary_limits_for_test(1, 1);
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(7, NonZeroU64::new(8).unwrap());
    for index in [3, 4, 5] {
        let context = runtime
            .reader()
            .vct_repair_context(owner, path[index].height)
            .unwrap()
            .unwrap();
        assert!(context.admission_capacity_available);
        assert_eq!(context.selected_header_count(), 1);
        assert_eq!(
            context.target,
            Frontier::new(path[index].height, path[index].hash)
        );
    }
}

#[test]
fn repair_context_reconstructs_rejected_input_after_engine_hydration() {
    let (mut runtime, db, _genesis, path) = reconciled_store_with_finalized_prefix(5);
    runtime.set_auxiliary_limits_for_test(1, 3);
    let target = Frontier::new(path[3].height, path[3].hash);
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(7, NonZeroU64::new(8).expect("eight is nonzero"));
    let before = runtime
        .reader()
        .vct_repair_context(owner, target.height)
        .expect("the initial repair context is coherent")
        .expect("the retained selected target needs a repair context");
    let input = zakura_header_chain::TreeAuxRecordV1 {
        height: target.height,
        sapling_root: Default::default(),
        orchard_root: Default::default(),
        ironwood_root: Default::default(),
        sapling_tx_count: 1,
        orchard_tx_count: 2,
        ironwood_tx_count: 3,
        auth_data_root: zakura_chain::block::merkle::AuthDataRoot::from([4; 32]),
    };
    let rejected = AuxDelivery::new(
        EvidenceId::from_digest([0x91; 32]),
        target.hash,
        SourceId::from_digest([0x92; 32]),
        owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(input),
    )
    .test_only_with_outcome(2, [Some([0x93; 32]), None], Some(path[4].hash))
    .expect("the rejected auxiliary outcome is coherent");
    let mut target_node = runtime
        .store
        .header_node(target.hash)
        .expect("the selected target row decodes")
        .expect("the selected target remains retained");
    target_node.aux_delivery_ids.push(rejected.delivery_id);
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .put_value(
            &mut batch,
            HEADER_NODE_BY_HASH,
            target.hash.0,
            &HeaderNodeDisk::from_domain(&target_node),
        )
        .expect("the selected target with rejection evidence encodes");
    runtime
        .store
        .put_value(
            &mut batch,
            HEADER_AUX_DELIVERY,
            HeaderAuxDeliveryKey {
                header: target.hash,
                delivery: rejected.delivery_id,
            }
            .as_bytes(),
            &rejected,
        )
        .expect("the rejected auxiliary outcome encodes");
    runtime
        .store
        .db
        .write(batch)
        .expect("the durable rejection fixture commits");

    let engine_config = runtime.config.clone();
    drop(runtime);
    let (runtime, _) = HeaderChainStore::new(db)
        .startup(&engine_config)
        .expect("startup reconstructs the durable delivery base and rejection constraints");
    let recovered = runtime
        .reader()
        .vct_repair_context(owner, target.height)
        .expect("the recovered repair context is coherent")
        .expect("the recovered selected target still needs repair");

    assert_ne!(recovered.episode, before.episode);
    assert!(
        recovered.admission_capacity_available,
        "a full recovered input bucket permits a selected replacement"
    );
    assert!(recovered.excludes(input));
    assert!(recovered.retains_payload(input));
    assert!(recovered.retains_source(rejected.source));

    let parent = Frontier::new(path[2].height, path[2].hash);
    let lease = runtime
        .reader()
        .validation_context(parent.hash)
        .expect("the repair parent validation context is coherent")
        .expect("the repair parent remains retained");
    let rules = HeaderRules::for_validation_lease(&lease)
        .expect("the repair parent produces validation rules");
    let headers = [path[3].header.clone()];
    let batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(&headers),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the replacement header passes deterministic preparation");
    let mut replacement_input = input;
    replacement_input.sapling_tx_count = replacement_input.sapling_tx_count.saturating_add(1);
    let source = SourceId::from_digest([0x94; 32]);
    let replacement = AuxDelivery::new(
        EvidenceId::from_digest([0x95; 32]),
        target.hash,
        source,
        owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(replacement_input),
    );
    let repair_request = |episode, delivery: AuxDelivery| TransitionRequest {
        expected_version: StateVersion::default(),
        event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
            owner: owner.into(),
            source: delivery.source,
            parent_hash: parent.hash,
            target_tip_hash: target.hash,
            completion: TargetCompletion::SelectedAuxiliaryRepair {
                common_ancestor: parent,
                selected_target: target,
                episode,
            },
            batch: batch.clone(),
            aux: vec![delivery],
        })),
    };
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };

    let normal_headers = [path[3].header.clone(), path[4].header.clone()];
    let normal_batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(&normal_headers),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the duplicate normal path passes deterministic preparation");
    let normal_owner = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        path[4].hash,
    )
    .bind(9, NonZeroU64::new(10).expect("ten is nonzero"));
    let repeated = AuxDelivery::new(
        EvidenceId::from_digest([0x96; 32]),
        target.hash,
        source,
        normal_owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(input),
    );
    let successor = AuxDelivery::new(
        EvidenceId::from_digest([0x97; 32]),
        path[4].hash,
        source,
        normal_owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        None,
    );
    assert!(matches!(
        runtime
            .apply(
                TransitionRequest {
                    expected_version: StateVersion::default(),
                    event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
                        owner: normal_owner.into(),
                        source,
                        parent_hash: parent.hash,
                        target_tip_hash: path[4].hash,
                        completion: TargetCompletion::TargetComplete {
                            common_ancestor: parent,
                        },
                        batch: normal_batch,
                        aux: vec![repeated, successor],
                    })),
                },
                &context,
            )
            .expect("rejected semantic input is a normal stale apply outcome"),
        ApplyResult::Stale(_)
    ));
    assert!(runtime
        .store
        .aux_deliveries(target.hash)
        .expect("the target delivery rows remain readable")
        .iter()
        .all(|delivery| delivery.delivery_id != repeated.delivery_id));

    assert!(matches!(
        runtime
            .apply(repair_request(before.episode, replacement), &context)
            .expect("a stale repair episode is a normal apply outcome"),
        ApplyResult::Stale(_)
    ));
    assert!(runtime
        .store
        .aux_deliveries(target.hash)
        .expect("the target delivery rows remain readable")
        .iter()
        .all(|delivery| delivery.delivery_id != replacement.delivery_id));

    let same_source_replacement = AuxDelivery::new(
        EvidenceId::from_digest([0x98; 32]),
        target.hash,
        rejected.source,
        owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(replacement_input),
    );
    assert!(matches!(
        runtime
            .apply(
                repair_request(recovered.episode, same_source_replacement),
                &context,
            )
            .expect("a retained supplier cannot consume another rooted slot"),
        ApplyResult::Stale(_)
    ));
    assert!(runtime
        .store
        .aux_deliveries(target.hash)
        .expect("the target delivery rows remain readable")
        .iter()
        .all(|delivery| delivery.delivery_id != same_source_replacement.delivery_id));
    let duplicate_input = AuxDelivery::new(
        EvidenceId::from_digest([0x99; 32]),
        target.hash,
        source,
        owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(input),
    );
    assert!(matches!(
        runtime
            .apply(repair_request(recovered.episode, duplicate_input), &context)
            .expect("a retained semantic input cannot complete the repair again"),
        ApplyResult::Stale(_)
    ));
    assert!(matches!(
        runtime
            .apply(repair_request(recovered.episode, replacement), &context)
            .expect("the current repair episode can apply replacement input"),
        ApplyResult::Committed
    ));
}

#[test]
fn selected_range_repair_rejects_atomically_then_commits_every_delivery() {
    let (runtime, _db, _genesis, path) = reconciled_store_with_finalized_prefix(5);
    let parent = Frontier::new(path[2].height, path[2].hash);
    let targets = [
        Frontier::new(path[3].height, path[3].hash),
        Frontier::new(path[4].height, path[4].hash),
    ];
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(17, NonZeroU64::new(18).expect("eighteen is nonzero"));
    let repair = runtime
        .reader()
        .vct_repair_context(owner, targets[0].height)
        .expect("the range repair context is coherent")
        .expect("the selected empty range needs repair");
    assert_eq!(repair.selected_header_count(), targets.len());
    assert_eq!(repair.request_target(), targets[1]);

    let lease = runtime
        .reader()
        .validation_context(parent.hash)
        .expect("the repair parent validation context is coherent")
        .expect("the repair parent remains retained");
    let rules =
        HeaderRules::for_validation_lease(&lease).expect("the repair parent produces header rules");
    let headers = [path[3].header.clone(), path[4].header.clone()];
    let batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(&headers),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the selected range passes deterministic preparation");
    let source = SourceId::from_digest([0xa1; 32]);
    let delivery = |index: usize, height| {
        let marker = u8::try_from(index).expect("the delivery index fits u8");
        AuxDelivery::new(
            EvidenceId::from_digest([0xa2_u8.saturating_add(marker); 32]),
            targets[index].hash,
            source,
            owner.into(),
            zakura_header_chain::BodySizeHint::Unknown,
            Some(zakura_header_chain::TreeAuxRecordV1 {
                height,
                sapling_root: Default::default(),
                orchard_root: Default::default(),
                ironwood_root: Default::default(),
                sapling_tx_count: u64::try_from(index).expect("the delivery index fits u64"),
                orchard_tx_count: 0,
                ironwood_tx_count: 0,
                auth_data_root: zakura_chain::block::merkle::AuthDataRoot::from(
                    [0xa4_u8.saturating_add(marker); 32],
                ),
            }),
        )
    };
    let request = |aux| TransitionRequest {
        expected_version: StateVersion::default(),
        event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
            owner: owner.into(),
            source,
            parent_hash: parent.hash,
            target_tip_hash: targets[1].hash,
            completion: TargetCompletion::SelectedAuxiliaryRepair {
                common_ancestor: parent,
                selected_target: targets[1],
                episode: repair.episode,
            },
            batch: batch.clone(),
            aux,
        })),
    };
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };

    let malformed = request(vec![
        delivery(0, targets[0].height),
        delivery(1, targets[0].height),
    ]);
    assert!(runtime.apply(malformed, &context).is_err());
    for target in targets {
        assert!(runtime
            .store
            .aux_deliveries(target.hash)
            .expect("the target auxiliary rows remain readable")
            .is_empty());
    }

    assert!(matches!(
        runtime
            .apply(
                request(vec![
                    delivery(0, targets[0].height),
                    delivery(1, targets[1].height),
                ]),
                &context,
            )
            .expect("the complete repair range applies"),
        ApplyResult::Committed
    ));
    for target in targets {
        assert_eq!(
            runtime
                .store
                .aux_deliveries(target.hash)
                .expect("the committed target auxiliary rows are readable")
                .len(),
            1
        );
    }
}

/// Store each delivery as durable input on its retained header and refresh the runtime mirror.
///
/// Each delivery must name a distinct header.
fn retain_aux_deliveries_for_test(runtime: &HeaderChainRuntime, deliveries: &[AuxDelivery]) {
    let mut batch = DiskWriteBatch::new();
    for delivery in deliveries {
        let mut node = runtime
            .store
            .header_node(delivery.header_hash)
            .expect("the retained header row decodes")
            .expect("the delivery header is retained");
        node.aux_delivery_ids.push(delivery.delivery_id);
        runtime
            .store
            .put_value(
                &mut batch,
                HEADER_NODE_BY_HASH,
                delivery.header_hash.0,
                &HeaderNodeDisk::from_domain(&node),
            )
            .expect("the header with auxiliary input encodes");
        runtime
            .store
            .put_value(
                &mut batch,
                HEADER_AUX_DELIVERY,
                HeaderAuxDeliveryKey {
                    header: delivery.header_hash,
                    delivery: delivery.delivery_id,
                }
                .as_bytes(),
                delivery,
            )
            .expect("the auxiliary delivery encodes");
    }
    runtime
        .store
        .db
        .write(batch)
        .expect("the auxiliary input fixture commits");
    *runtime
        .transition_engine
        .lock()
        .expect("the transition engine mutex is not poisoned") =
        load_transition_engine(&runtime.store)
            .expect("the direct durable test fixture refreshes the runtime mirror");
}

/// Repair three headers that hold rootless near-tip rows in one range, below one rooted header.
///
/// `aggregate_limit` replaces the aggregate input limit. Returns the durable rows of each
/// repaired target and the number of durable rows in the store.
fn repair_rootless_near_tip_range(
    aggregate_limit: Option<usize>,
) -> (Vec<Vec<AuxDelivery>>, usize) {
    let (mut runtime, _db, _genesis, path) = reconciled_store_with_finalized_prefix(8);
    if let Some(total) = aggregate_limit {
        let per_header = runtime.config.limits.max_aux_deliveries_per_header.get();
        runtime.set_auxiliary_limits_for_test(per_header, total);
    }
    let parent = Frontier::new(path[2].height, path[2].hash);
    let targets: Vec<_> = path[3..6]
        .iter()
        .map(|header| Frontier::new(header.height, header.hash))
        .collect();
    let rooted_header = Frontier::new(path[6].height, path[6].hash);
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(37, NonZeroU64::new(38).expect("thirty-eight is nonzero"));
    let near_tip_owner =
        zakura_header_chain::HeaderWorkAuthority::for_target(&snapshot, path[7].hash)
            .bind(39, NonZeroU64::new(40).expect("forty is nonzero"));
    let near_tip_source = SourceId::from_digest([0xc1; 32]);
    let record = |height: block::Height, marker: u8| zakura_header_chain::TreeAuxRecordV1 {
        height,
        sapling_root: Default::default(),
        orchard_root: Default::default(),
        ironwood_root: Default::default(),
        sapling_tx_count: u64::from(marker),
        orchard_tx_count: 0,
        ironwood_tx_count: 0,
        auth_data_root: zakura_chain::block::merkle::AuthDataRoot::from([marker; 32]),
    };
    let mut near_tip_input: Vec<_> = targets
        .iter()
        .zip(0xc2_u8..)
        .map(|(target, marker)| {
            AuxDelivery::new(
                EvidenceId::from_digest([marker; 32]),
                target.hash,
                near_tip_source,
                near_tip_owner.into(),
                zakura_header_chain::BodySizeHint::Unknown,
                None,
            )
        })
        .collect();
    near_tip_input.push(AuxDelivery::new(
        EvidenceId::from_digest([0xc8; 32]),
        rooted_header.hash,
        near_tip_source,
        near_tip_owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(record(rooted_header.height, 0xc9)),
    ));
    retain_aux_deliveries_for_test(&runtime, &near_tip_input);

    let repair = runtime
        .reader()
        .vct_repair_context(owner, targets[0].height)
        .expect("the rootless range repair context is coherent")
        .expect("the rootless selected range needs repair");
    assert_eq!(
        repair.selected_header_count(),
        targets.len(),
        "the range stops before the first rooted row"
    );
    assert_eq!(repair.request_target(), targets[2]);
    assert_eq!(
        runtime
            .reader()
            .vct_repair_context(owner, rooted_header.height)
            .expect("the rooted repair context is coherent")
            .expect("the rooted target remains repairable")
            .selected_header_count(),
        1,
        "rooted input still constrains its replacement to one target"
    );

    let lease = runtime
        .reader()
        .validation_context(parent.hash)
        .expect("the repair parent validation context is coherent")
        .expect("the repair parent remains retained");
    let rules =
        HeaderRules::for_validation_lease(&lease).expect("the repair parent produces header rules");
    let headers: Vec<_> = path[3..6]
        .iter()
        .map(|header| header.header.clone())
        .collect();
    let batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(&headers),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the selected range passes deterministic preparation");
    let source = SourceId::from_digest([0xca; 32]);
    let replacements = targets
        .iter()
        .zip(0xcb_u8..)
        .map(|(target, marker)| {
            AuxDelivery::new(
                EvidenceId::from_digest([marker; 32]),
                target.hash,
                source,
                owner.into(),
                zakura_header_chain::BodySizeHint::Unknown,
                Some(record(target.height, marker)),
            )
        })
        .collect();
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };
    assert!(matches!(
        runtime
            .apply(
                TransitionRequest {
                    expected_version: StateVersion::default(),
                    event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
                        owner: owner.into(),
                        source,
                        parent_hash: parent.hash,
                        target_tip_hash: targets[2].hash,
                        completion: TargetCompletion::SelectedAuxiliaryRepair {
                            common_ancestor: parent,
                            selected_target: targets[2],
                            episode: repair.episode,
                        },
                        batch,
                        aux: replacements,
                    })),
                },
                &context,
            )
            .expect("the rootless range repair applies"),
        ApplyResult::Committed
    ));
    let rows = targets
        .iter()
        .map(|target| {
            runtime
                .store
                .aux_deliveries(target.hash)
                .expect("the repaired target rows are readable")
        })
        .collect();
    let total = runtime
        .store
        .load_aux_deliveries()
        .expect("the durable input rows are readable")
        .len();
    (rows, total)
}

#[test]
fn repair_range_spans_rootless_near_tip_input() {
    // Suppliers attach roots only to their finalized prefix, so headers received near the
    // network tip keep rootless rows. When a later handoff moves above those headers, one repair
    // must still cover them all instead of one header per round trip.
    let (rows, _) = repair_rootless_near_tip_range(None);
    for rows in rows {
        assert_eq!(rows.len(), 2, "the repair adds a rooted row");
        assert!(rows.iter().any(|row| row.tree_aux.is_some()));
    }
}

#[test]
fn saturated_rootless_range_repair_retains_every_root() {
    // The four near-tip rows leave one free aggregate slot. The two lowest targets sit in the
    // commit window, so their rows are protected, and the range admits three new roots by
    // reclaiming the two rows above it. Aggregate pressure must evict those older rows, never a
    // root that the range repair just supplied.
    let (rows, total) = repair_rootless_near_tip_range(Some(5));
    assert_eq!(total, 5, "the repair stays within the aggregate limit");
    let repair_source = SourceId::from_digest([0xca; 32]);
    for rows in &rows {
        assert!(
            rows.iter()
                .any(|row| row.source == repair_source && row.tree_aux.is_some()),
            "every target retains its new root"
        );
    }
    assert_eq!(rows[2].len(), 1, "eviction removes the suffix rootless row");
}

#[test]
fn one_header_range_prefix_keeps_its_state_bound_episode() {
    let (runtime, _db, _genesis, path) = reconciled_store_with_finalized_prefix(5);
    let parent = Frontier::new(path[2].height, path[2].hash);
    let target = Frontier::new(path[3].height, path[3].hash);
    let successor = Frontier::new(path[4].height, path[4].hash);
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(27, NonZeroU64::new(28).expect("twenty-eight is nonzero"));
    let range = runtime
        .reader()
        .vct_repair_context(owner, target.height)
        .expect("the range repair context is coherent")
        .expect("the selected empty range needs repair");
    let prefix = range
        .bounded_prefix(1)
        .expect("the one-header range prefix exists");
    let stale_episode = zakura_header_chain::VctRepairContext::from_durable_rows(
        target,
        HeaderLocator::for_continuation(parent),
        StateVersion::new(snapshot.state_version.get().saturating_add(1)),
        Some(successor.hash),
        true,
        &[],
    )
    .expect("the stale exact context is coherent")
    .extend_empty_selected_range(&[], Some(successor.hash))
    .expect("the stale one-header range is coherent")
    .episode;

    let lease = runtime
        .reader()
        .validation_context(parent.hash)
        .expect("the repair parent validation context is coherent")
        .expect("the repair parent remains retained");
    let rules =
        HeaderRules::for_validation_lease(&lease).expect("the repair parent produces header rules");
    let batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(std::slice::from_ref(&path[3].header)),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the selected prefix passes deterministic preparation");
    let source = SourceId::from_digest([0xb1; 32]);
    let request = |episode| TransitionRequest {
        expected_version: StateVersion::default(),
        event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
            owner: owner.into(),
            source,
            parent_hash: parent.hash,
            target_tip_hash: target.hash,
            completion: TargetCompletion::SelectedAuxiliaryRepair {
                common_ancestor: parent,
                selected_target: target,
                episode,
            },
            batch: batch.clone(),
            aux: vec![AuxDelivery::new(
                EvidenceId::from_digest([0xb2; 32]),
                target.hash,
                source,
                owner.into(),
                zakura_header_chain::BodySizeHint::Unknown,
                Some(zakura_header_chain::TreeAuxRecordV1 {
                    height: target.height,
                    sapling_root: Default::default(),
                    orchard_root: Default::default(),
                    ironwood_root: Default::default(),
                    sapling_tx_count: 1,
                    orchard_tx_count: 0,
                    ironwood_tx_count: 0,
                    auth_data_root: [0xb3; 32].into(),
                }),
            )],
        })),
    };
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };

    assert!(matches!(
        runtime
            .apply(request(stale_episode), &context)
            .expect("a stale range episode is a normal apply outcome"),
        ApplyResult::Stale(_)
    ));
    assert!(runtime
        .store
        .aux_deliveries(target.hash)
        .expect("the stale target auxiliary rows remain readable")
        .is_empty());
    assert!(matches!(
        runtime
            .apply(request(prefix.episode), &context)
            .expect("the current one-header range prefix applies"),
        ApplyResult::Committed
    ));
}

#[tokio::test(start_paused = true)]
async fn retained_path_serves_a_locator_before_the_header_retention_window() {
    let (runtime, db, genesis, path) = reconciled_store_with_finalized_prefix(4);
    let hash_by_height = db
        .cf_handle("hash_by_height")
        .expect("the finalized hash index exists");
    let reader = runtime.reader();
    let target = Frontier::new(path[3].height, path[3].hash);
    let scope = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        target.hash,
    );
    let RetainedPathLeaseOutcome::Acquired(mut lease) = reader
        .acquire_retained_path(
            SourceId::from_digest([0x71; 32]),
            9,
            target.hash,
            &[genesis.hash],
            scope,
        )
        .expect("the finalized locator is a coherent retained path")
    else {
        panic!("the finalized locator should acquire a lease");
    };
    assert_eq!(
        lease.common_ancestor,
        Frontier::new(genesis.height, genesis.hash)
    );

    let owner = SourceId::from_digest([0x71; 32]);
    let mut after = genesis.hash;
    for (expected, complete) in path.iter().zip([false, false, false, true]) {
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(owner, 9, lease.lease_id, scope, after, 1)
            .expect("the historical path page is coherent")
        else {
            panic!("the historical path lease should remain available");
        };
        assert_eq!(
            page.headers.as_slice(),
            std::slice::from_ref(&expected.header)
        );
        assert_eq!(page.aux_deliveries, vec![Vec::new()]);
        assert_eq!(page.complete, complete);
        after = expected.hash;
        if !complete {
            let RetainedPathLeaseOutcome::Acquired(next) = reader
                .acquire_retained_path(owner, 9, target.hash, &[after], scope)
                .unwrap()
            else {
                panic!("the next page can acquire fresh capacity");
            };
            lease = next;
        }
    }
    assert!(!reader
        .release_retained_path(owner, 9, lease.lease_id, scope)
        .expect("the one-header-page cursor releases"));

    for (marker, page_count) in [(0x72, 2), (0x73, 3)] {
        let page_owner = SourceId::from_digest([marker; 32]);
        let RetainedPathLeaseOutcome::Acquired(mut lease) = reader
            .acquire_retained_path(page_owner, 9, target.hash, &[genesis.hash], scope)
            .expect("the tier-boundary page cursor acquires")
        else {
            panic!("the tier-boundary cursor should be retained");
        };
        let mut after = genesis.hash;
        let mut served = Vec::new();
        loop {
            let RetainedPathReadOutcome::Page(page) = reader
                .read_retained_path(page_owner, 9, lease.lease_id, scope, after, page_count)
                .expect("the page spanning the storage-tier boundary is coherent")
            else {
                panic!("the tier-boundary cursor should remain available");
            };
            served.extend(page.headers.iter().map(|header| header.hash()));
            if page.complete {
                break;
            }
            after = page
                .headers
                .last()
                .expect("an incomplete page contains at least one header")
                .hash();
            let RetainedPathLeaseOutcome::Acquired(next) = reader
                .acquire_retained_path(page_owner, 9, target.hash, &[after], scope)
                .unwrap()
            else {
                panic!("the next page can acquire across the storage boundary");
            };
            lease = next;
        }
        assert_eq!(
            served,
            path.iter().map(|header| header.hash).collect::<Vec<_>>(),
            "page counts ending at and after the tier boundary serve one canonical sequence",
        );
    }

    let retry_owner = SourceId::from_digest([0x74; 32]);
    let RetainedPathLeaseOutcome::Acquired(retry_lease) = reader
        .acquire_retained_path(retry_owner, 9, target.hash, &[genesis.hash], scope)
        .expect("the corruption-retry cursor acquires")
    else {
        panic!("the corruption-retry cursor should be retained");
    };
    let mut corrupt = DiskWriteBatch::new();
    corrupt.zs_delete(&hash_by_height, path[0].height);
    db.write(corrupt)
        .expect("the test removes one finalized path hash");
    assert!(reader
        .read_retained_path(retry_owner, 9, retry_lease.lease_id, scope, genesis.hash, 1,)
        .is_err());
    let mut restore = DiskWriteBatch::new();
    restore.zs_insert(&hash_by_height, path[0].height, path[0].hash);
    db.write(restore)
        .expect("the test restores the finalized path hash");
    let RetainedPathReadOutcome::Page(retried) = reader
        .read_retained_path(retry_owner, 9, retry_lease.lease_id, scope, genesis.hash, 1)
        .expect("a repaired local row can retry the same cursor position")
    else {
        panic!("the failed page did not advance the cursor");
    };
    assert_eq!(retried.headers[0].hash(), path[0].hash);

    let expiry_owner = SourceId::from_digest([0x75; 32]);
    let RetainedPathLeaseOutcome::Acquired(expiry_lease) = reader
        .acquire_retained_path(expiry_owner, 9, target.hash, &[genesis.hash], scope)
        .expect("the failed-read expiry cursor acquires")
    else {
        panic!("the failed-read expiry cursor should be retained");
    };
    tokio::time::advance(RETAINED_PATH_LEASE_IDLE.saturating_sub(Duration::from_secs(1))).await;
    let mut corrupt = DiskWriteBatch::new();
    corrupt.zs_delete(&hash_by_height, path[0].height);
    db.write(corrupt)
        .expect("the test removes the expiring cursor's next hash");
    assert!(reader
        .read_retained_path(
            expiry_owner,
            9,
            expiry_lease.lease_id,
            scope,
            genesis.hash,
            1,
        )
        .is_err());
    tokio::time::advance(Duration::from_secs(2)).await;
    let mut restore = DiskWriteBatch::new();
    restore.zs_insert(&hash_by_height, path[0].height, path[0].hash);
    db.write(restore)
        .expect("the test restores the expiring cursor's next hash");
    assert_eq!(
        reader
            .read_retained_path(
                expiry_owner,
                9,
                expiry_lease.lease_id,
                scope,
                genesis.hash,
                1,
            )
            .expect("an expired cursor is a normal unavailable outcome"),
        RetainedPathReadOutcome::Unavailable,
        "a failed page must not renew its cursor deadline",
    );
}

#[tokio::test(start_paused = true)]
async fn retained_path_leases_are_exact_bounded_session_scoped_and_expiring() {
    let db_config = Config::ephemeral();
    let (engine_config, anchor, metadata) = fixture();
    let anchor_frontier = Frontier::new(anchor.height, anchor.hash);
    let store = HeaderChainStore::new(open(&db_config, engine_config.network()));
    store
        .initialize(metadata, anchor.clone())
        .expect("the empty schema initializes");
    let mut child_header = *anchor.header;
    child_header.previous_block_hash = anchor.hash;
    child_header.time += chrono::Duration::seconds(1);
    let child_header = Arc::new(child_header);
    let child = VerifiedHeaderRef {
        height: anchor.height.next().expect("genesis has a successor"),
        hash: child_header.hash(),
        header: child_header,
    };
    let mut grandchild_header = *anchor.header;
    grandchild_header.previous_block_hash = child.hash;
    grandchild_header.time += chrono::Duration::seconds(2);
    let grandchild_header = Arc::new(grandchild_header);
    let grandchild = VerifiedHeaderRef {
        height: child.height.next().expect("the child has a successor"),
        hash: grandchild_header.hash(),
        header: grandchild_header,
    };
    let (runtime, _) = store
        .startup_reconciled(
            &engine_config,
            anchor_frontier,
            Vec::new(),
            vec![child.clone(), grandchild.clone()],
        )
        .expect("the selected two-header path reconciles");
    let reader = runtime.reader();
    let validation_lease = reader
        .validation_context(anchor.hash)
        .expect("the retained parent context is coherent")
        .expect("the retained anchor has validation context");
    assert_eq!(validation_lease.parent(), anchor_frontier);
    assert_eq!(
        validation_lease.trust_anchor_digest(),
        engine_config.trust_anchor_digest()
    );
    assert_eq!(
        reader
            .validation_context(block::Hash([0xff; 32]))
            .expect("an absent parent is a normal stale read"),
        None
    );
    let durable_window = reader
        .selected_auxiliary_window(child.height, child.hash)
        .expect("the exact selected auxiliary window is coherent")
        .expect("the selected child is retained");
    let window = runtime
        .selected_auxiliary_window(child.height, child.hash)
        .expect("the in-memory selected auxiliary window is coherent")
        .expect("the selected child is retained in the committed engine");
    assert_eq!(window, durable_window);
    let captured_projection = runtime
        .capture_selected_projection()
        .expect("the in-memory selected projection is coherent");
    let child_index = captured_projection
        .frontiers
        .binary_search_by_key(&child.height, |frontier| frontier.height)
        .expect("the selected projection contains the child");
    assert_eq!(
        runtime
            .selected_auxiliary_window_at_projection_index(
                child_index,
                Frontier::new(child.height, child.hash),
            )
            .expect("the captured projection index is coherent"),
        Some(window.clone())
    );
    assert_eq!(
        runtime
            .selected_auxiliary_window_at_projection_index(
                child_index + 1,
                Frontier::new(child.height, child.hash),
            )
            .expect("a stale projection index is a normal read outcome"),
        None
    );
    assert_eq!(
        window.engine_snapshot,
        runtime.publisher().snapshot(),
        "the auxiliary window carries the snapshot read under the same transition lock"
    );
    assert_eq!(window.delivery_header.header_node.hash, child.hash);
    assert!(window.delivery_header.auxiliary_deliveries.is_empty());
    let successor_header = window
        .successor_header
        .expect("the selected grandchild follows");
    assert_eq!(successor_header.header_node.hash, grandchild.hash);
    assert!(successor_header.auxiliary_deliveries.is_empty());
    assert_eq!(
        reader
            .selected_auxiliary_window(child.height, block::Hash([0xfe; 32]))
            .expect("a stale branch hash is a normal read outcome"),
        None
    );
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(7, NonZeroU64::new(8).expect("eight is nonzero"));
    let repair = reader
        .vct_repair_context(owner, child.height)
        .expect("the selected repair context is coherent")
        .expect("the current owner resolves its selected header");
    assert_eq!(repair.target, Frontier::new(child.height, child.hash));
    assert_eq!(repair.locator.entries(), &[anchor_frontier]);
    assert_eq!(repair.selected_header_count(), 2);
    assert_eq!(
        repair.request_target(),
        Frontier::new(grandchild.height, grandchild.hash)
    );
    let checkpoint_bounded = reader
        .vct_repair_context_bounded(owner, child.height, child.height)
        .expect("the checkpoint-bounded repair context is coherent")
        .expect("the checkpoint permits the blocking target");
    assert_eq!(checkpoint_bounded.selected_header_count(), 1);
    assert_eq!(checkpoint_bounded.request_target(), repair.target);
    assert_eq!(
        reader
            .vct_repair_context_bounded(owner, child.height, anchor.height)
            .expect("a repair above the checkpoint is a normal stale outcome"),
        None
    );

    let mut stale_owner = owner;
    stale_owner.authority.verified_generation = VerifiedGeneration::new(
        owner
            .verified_generation
            .get()
            .checked_add(1)
            .expect("the fixture state version can advance"),
    );
    assert_eq!(
        reader
            .vct_repair_context(stale_owner, child.height)
            .expect("a stale repair owner is a normal read outcome"),
        None
    );
    assert_eq!(
        reader
            .vct_repair_context(owner, anchor.height)
            .expect("a finalized repair height is a normal stale outcome"),
        None
    );

    let aux = zakura_header_chain::TreeAuxRecordV1 {
        height: child.height,
        sapling_root: Default::default(),
        orchard_root: Default::default(),
        ironwood_root: Default::default(),
        sapling_tx_count: 13,
        orchard_tx_count: 14,
        ironwood_tx_count: 15,
        auth_data_root: zakura_chain::block::merkle::AuthDataRoot::from([16; 32]),
    };
    let delivery = AuxDelivery::new(
        EvidenceId::from_digest([0x91; 32]),
        child.hash,
        SourceId::from_digest([0x92; 32]),
        owner.into(),
        zakura_header_chain::BodySizeHint::Unknown,
        Some(aux),
    );
    let mut child_node = runtime
        .store
        .header_node(child.hash)
        .expect("the selected child row decodes")
        .expect("the selected child is retained");
    child_node.aux_delivery_ids.push(delivery.delivery_id);
    let mut aux_batch = DiskWriteBatch::new();
    runtime
        .store
        .put_value(
            &mut aux_batch,
            HEADER_NODE_BY_HASH,
            child.hash.0,
            &HeaderNodeDisk::from_domain(&child_node),
        )
        .expect("the selected child with auxiliary evidence encodes");
    runtime
        .store
        .put_value(
            &mut aux_batch,
            HEADER_AUX_DELIVERY,
            HeaderAuxDeliveryKey {
                header: child.hash,
                delivery: delivery.delivery_id,
            }
            .as_bytes(),
            &delivery,
        )
        .expect("the selected auxiliary delivery encodes");
    runtime
        .store
        .db
        .write(aux_batch)
        .expect("the coherent selected auxiliary fixture commits");
    *runtime
        .transition_engine
        .lock()
        .expect("the transition engine mutex is not poisoned") =
        load_transition_engine(&runtime.store)
            .expect("the direct durable test fixture refreshes the runtime mirror");
    let evidence_constrained = reader
        .vct_repair_context(owner, child.height)
        .expect("the evidence-constrained repair context is coherent")
        .expect("the selected target remains repairable");
    assert_eq!(evidence_constrained.selected_header_count(), 1);
    assert_eq!(evidence_constrained.request_target(), repair.target);
    let roots = reader
        .selected_block_roots(child.height, 2)
        .expect("selected auxiliary roots are coherent");
    assert_eq!(roots.len(), 1, "the read stops at the first missing height");
    assert_eq!(roots[0].height, child.height);
    assert_eq!(roots[0].sapling_tx, aux.sapling_tx_count);
    assert_eq!(roots[0].orchard_tx, aux.orchard_tx_count);
    assert_eq!(roots[0].ironwood_tx, aux.ironwood_tx_count);
    assert_eq!(roots[0].auth_data_root, aux.auth_data_root);
    let crate::service::write::VctAuxiliaryWindowRead::Ready(window) =
        crate::service::write::HeaderChainWriter::new(runtime.clone(), engine_config.clone())
            .vct_auxiliary_window(child.height, child.hash)
            .expect("the selected auxiliary window is coherent")
    else {
        panic!("the current delivery remains usable without successor auxiliary data");
    };
    assert_eq!(window.successor_height, Some(grandchild.height));
    assert!(window.successor.is_none());

    let owner = SourceId::from_digest([1; 32]);
    let lease_scope = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        grandchild.hash,
    );
    let acquired = reader
        .acquire_retained_path(owner, 7, grandchild.hash, &[anchor.hash], lease_scope)
        .expect("the coherent target path is readable");
    let RetainedPathLeaseOutcome::Acquired(lease) = acquired else {
        panic!("the exact retained target should acquire a lease");
    };
    assert_eq!(
        lease.target,
        Frontier::new(grandchild.height, grandchild.hash)
    );
    assert_eq!(lease.common_ancestor, anchor_frontier);
    assert_eq!(lease.scope, lease_scope);
    let mut wrong_scope = lease_scope;
    wrong_scope.header_generation = wrong_scope
        .header_generation
        .checked_next()
        .expect("the fixture generation has a successor");
    assert_eq!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xee; 32]),
                7,
                grandchild.hash,
                &[anchor.hash],
                wrong_scope,
            )
            .expect("a stale acquisition scope is a normal refusal"),
        RetainedPathLeaseOutcome::Busy
    );
    assert!(matches!(
        reader
            .acquire_retained_path(owner, 7, grandchild.hash, &[anchor.hash], lease_scope,)
            .expect("the lease bound is a normal outcome"),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
    assert!(matches!(
        reader
            .acquire_retained_path(owner, 8, grandchild.hash, &[anchor.hash], lease_scope)
            .expect("a new session cannot replace a live lease"),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
    assert_eq!(
        reader
            .read_retained_path(owner, 8, lease.lease_id, lease_scope, anchor.hash, 1)
            .expect("a mismatched session is non-fatal"),
        RetainedPathReadOutcome::Unavailable
    );
    assert_eq!(
        reader
            .read_retained_path(owner, 7, lease.lease_id, wrong_scope, anchor.hash, 1)
            .expect("a mismatched branch scope is non-fatal"),
        RetainedPathReadOutcome::Unavailable
    );
    assert!(!reader
        .release_retained_path(owner, 7, lease.lease_id, wrong_scope)
        .expect("a mismatched release scope is non-fatal"));
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(owner, 7, lease.lease_id, lease_scope, anchor.hash, 1)
        .expect("a lease page read validates against the serialized publication gate")
    else {
        panic!("the current owner should read its lease");
    };
    assert_eq!(page.headers.len(), 1);
    assert_eq!(page.headers[0].hash(), child.hash);
    assert_eq!(page.common_ancestor, anchor_frontier);
    assert_eq!(page.scope, lease_scope);
    assert_eq!(page.aux_deliveries, vec![vec![delivery]]);
    assert!(!page.complete);
    assert_eq!(
        reader
            .read_retained_path(owner, 7, lease.lease_id, lease_scope, anchor.hash, 1)
            .expect("a replayed cursor position is a normal refusal"),
        RetainedPathReadOutcome::Unavailable,
        "the opaque cursor advances exactly once and cannot be rewound",
    );

    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(owner, 7, grandchild.hash, &[child.hash], lease_scope)
        .unwrap()
    else {
        panic!("the next page acquires its own lease");
    };
    let cursor = runtime
        .leases
        .lock()
        .expect("the lease registry is available")
        .get(owner, 7, lease.lease_id, Instant::now())
        .expect("the lease remains active");
    let captured_read = reader
        .capture_path_read(&cursor, 1)
        .expect("the page captures a coherent read view");
    assert!(
        reader.store.writer.try_lock().is_ok(),
        "page I/O does not hold the writer"
    );
    assert!(
        reader.transition_engine.try_lock().is_ok(),
        "page I/O does not hold the engine"
    );

    let before = runtime.publisher().snapshot();
    let evidence = EvidenceId::from_digest([3; 32]);
    let id = zakura_header_chain::OperatorInvalidationId::new([3; 16]);
    let mut hasher = sha2::Sha256::new();
    use sha2::Digest as _;
    hasher.update(b"zakura-operator-invalidation-v1");
    hasher.update(child.hash.0);
    hasher.update(id.bytes());
    let authority = Authority(evidence);
    runtime
        .apply(
            TransitionRequest {
                expected_version: before.state_version,
                event: TransitionEvent::OperatorInvalidate(
                    zakura_header_chain::OperatorInvalidate {
                        target: child.hash,
                        id,
                        operator_reason_digest: hasher.finalize().into(),
                        evidence,
                    },
                ),
            },
            &TransitionContext {
                config: &engine_config,
                clock: &SystemClock,
                full_state_authority: Some(&authority),
                retention_references: &[],
            },
        )
        .expect("the selected path can change while the lease is active");
    assert_eq!(
        runtime.publisher().snapshot().frontiers.header_best,
        anchor_frontier
    );

    let (captured_page, _, _) = captured_read
        .read_page(&cursor, 1)
        .expect("the old snapshot remains coherent after the branch changes")
        .expect("the captured path remains readable");
    assert_eq!(captured_page.headers[0].hash(), grandchild.hash);
    assert!(captured_page.complete);

    let stale_source = SourceId::from_digest([0xed; 32]);
    let RetainedPathLeaseOutcome::Acquired(stale_lease) = reader
        .acquire_retained_path(
            stale_source,
            7,
            grandchild.hash,
            &[anchor.hash],
            lease_scope,
        )
        .expect("a request queued before the head changed can still acquire its exact path")
    else {
        panic!("head changes do not invalidate an exact retained target");
    };
    assert_eq!(stale_lease.scope, lease_scope);
    assert!(reader
        .release_retained_path(stale_source, 7, stale_lease.lease_id, lease_scope)
        .unwrap());

    let RetainedPathReadOutcome::Page(continuation) = reader
        .read_retained_path(owner, 7, lease.lease_id, lease_scope, child.hash, 1)
        .expect("the immutable cursor continues after reselection")
    else {
        panic!("the current owner should read its continuation");
    };
    assert_eq!(
        continuation.common_ancestor,
        Frontier::new(child.height, child.hash)
    );
    assert_eq!(continuation.headers[0].hash(), grandchild.hash);
    assert!(continuation.complete);

    assert_eq!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([2; 32]),
                7,
                block::Hash([0xfe; 32]),
                &[anchor.hash],
                zakura_header_chain::HeaderWorkAuthority::for_target(
                    &runtime.publisher().snapshot(),
                    block::Hash([0xfe; 32]),
                ),
            )
            .expect("an absent target is a normal outcome"),
        RetainedPathLeaseOutcome::TargetNotRetained
    );
    assert_eq!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([2; 32]),
                7,
                child.hash,
                &[block::Hash([0xfd; 32])],
                zakura_header_chain::HeaderWorkAuthority::for_target(
                    &runtime.publisher().snapshot(),
                    child.hash,
                ),
            )
            .expect("a disjoint locator is a normal outcome"),
        RetainedPathLeaseOutcome::NoLocatorIntersection
    );
    let RetainedPathLeaseOutcome::Acquired(target_intersection) = reader
        .acquire_retained_path(
            SourceId::from_digest([2; 32]),
            7,
            child.hash,
            &[child.hash, anchor.hash],
            zakura_header_chain::HeaderWorkAuthority::for_target(
                &runtime.publisher().snapshot(),
                child.hash,
            ),
        )
        .expect("the nearest locator ancestor is selected")
    else {
        panic!("the target itself intersects the locator");
    };
    assert_eq!(target_intersection.common_ancestor.hash, child.hash);
    let RetainedPathReadOutcome::Page(completed) = reader
        .read_retained_path(
            SourceId::from_digest([2; 32]),
            7,
            target_intersection.lease_id,
            target_intersection.scope,
            child.hash,
            1,
        )
        .expect("a cursor acquired at its target is readable")
    else {
        panic!("the target-intersection cursor remains available");
    };
    assert!(completed.headers.is_empty());
    assert!(completed.complete);
    assert!(!reader
        .release_retained_path(
            SourceId::from_digest([2; 32]),
            7,
            target_intersection.lease_id,
            target_intersection.scope,
        )
        .expect("the target-intersection lease releases"));

    assert!(!reader
        .release_retained_path(owner, 7, lease.lease_id, lease_scope)
        .expect("the exact owner can release its lease"));
    // Ordinary leases fill the general slots, and the last short path uses the reserve.
    for marker in 1..=MAX_RETAINED_PATH_LEASES {
        let marker = u8::try_from(marker).expect("the lease cap fits in one byte");
        assert!(matches!(
            reader
                .acquire_retained_path(
                    SourceId::from_digest([marker; 32]),
                    9,
                    child.hash,
                    &[anchor.hash],
                    zakura_header_chain::HeaderWorkAuthority::for_target(
                        &runtime.publisher().snapshot(),
                        child.hash,
                    ),
                )
                .expect("bounded acquisition returns an outcome"),
            RetainedPathLeaseOutcome::Acquired(_)
        ));
    }
    assert!(matches!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xff; 32]),
                9,
                child.hash,
                &[anchor.hash],
                zakura_header_chain::HeaderWorkAuthority::for_target(
                    &runtime.publisher().snapshot(),
                    child.hash,
                ),
            )
            .expect("capacity refusal is a normal outcome"),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
    tokio::time::advance(RETAINED_PATH_LEASE_IDLE + Duration::from_secs(1)).await;
    assert!(matches!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xff; 32]),
                10,
                child.hash,
                &[anchor.hash],
                zakura_header_chain::HeaderWorkAuthority::for_target(
                    &runtime.publisher().snapshot(),
                    child.hash,
                ),
            )
            .expect("expired slots are reclaimed"),
        RetainedPathLeaseOutcome::Acquired(_)
    ));

    let snapshot = runtime.publisher().snapshot();
    let delivery = AuxDelivery::new(
        EvidenceId::from_digest([0xa1; 32]),
        anchor.hash,
        SourceId::from_digest([0xa2; 32]),
        body_owner(&snapshot, 11, 12).into(),
        zakura_header_chain::BodySizeHint::Unknown,
        None,
    );
    let mut corrupt = DiskWriteBatch::new();
    runtime
        .store
        .put_value(
            &mut corrupt,
            HEADER_AUX_DELIVERY,
            HeaderAuxDeliveryKey {
                header: anchor.hash,
                delivery: delivery.delivery_id,
            }
            .as_bytes(),
            &delivery,
        )
        .expect("the contradictory auxiliary row encodes");
    runtime
        .store
        .db
        .write(corrupt)
        .expect("the contradictory auxiliary row commits");
    assert!(matches!(
        reader.selected_auxiliary_window(anchor.height, anchor.hash),
        Err(HeaderChainStoreError::Store(StoreError::Incoherent(
            "retained node and auxiliary delivery index disagree"
        )))
    ));
}

#[tokio::test(start_paused = true)]
async fn retained_path_serves_a_bounded_finalized_range_below_the_header_frontier() {
    let (runtime, _db, genesis, path) = reconciled_store_with_finalized_prefix(4);
    let finalized = Frontier::new(path[2].height, path[2].hash);
    let reader = runtime.reader();

    // A VCT repair can ask for a selected range below the retained suffix. A supplier that has
    // finalized that range serves it from the finalized indexes.
    let target = Frontier::new(path[1].height, path[1].hash);
    assert!(target.height < finalized.height);
    let scope = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        target.hash,
    );
    // Transfers occupy every ordinary slot. The reserve still admits a bounded repair.
    let retained_target = Frontier::new(path[3].height, path[3].hash);
    let retained_scope = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        retained_target.hash,
    );
    for marker in 1..MAX_RETAINED_PATH_LEASES {
        let marker = u8::try_from(marker).expect("the lease cap fits in one byte");
        assert!(matches!(
            reader
                .acquire_retained_path(
                    SourceId::from_digest([marker; 32]),
                    10,
                    retained_target.hash,
                    &[genesis.hash],
                    retained_scope,
                )
                .expect("the general path acquisition is coherent"),
            RetainedPathLeaseOutcome::Acquired(_)
        ));
    }

    let owner = SourceId::from_digest([0x81; 32]);
    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(owner, 11, target.hash, &[path[0].hash], scope)
        .expect("the finalized target resolves through the finalized indexes")
    else {
        panic!("the finalized target should acquire a lease");
    };
    assert_eq!(
        lease.common_ancestor,
        Frontier::new(path[0].height, path[0].hash)
    );
    assert_eq!(lease.target, target);

    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(owner, 11, lease.lease_id, scope, path[0].hash, 4)
        .expect("the finalized target page is coherent")
    else {
        panic!("the finalized target lease should remain available");
    };
    assert_eq!(
        page.headers.as_slice(),
        std::slice::from_ref(&path[1].header)
    );
    assert_eq!(page.target, target);
    assert!(page.complete);
    assert!(!reader
        .release_retained_path(owner, 11, lease.lease_id, scope)
        .expect("the finalized target cursor releases"));

    // The same acquisition serves a range from an earlier canonical locator.
    let long_path_owner = SourceId::from_digest([0x84; 32]);
    let RetainedPathLeaseOutcome::Acquired(long_path_lease) = reader
        .acquire_retained_path(long_path_owner, 11, target.hash, &[genesis.hash], scope)
        .expect("the bounded finalized path lookup is coherent")
    else {
        panic!("the bounded finalized path should acquire a lease");
    };
    let RetainedPathReadOutcome::Page(long_path_page) = reader
        .read_retained_path(
            long_path_owner,
            11,
            long_path_lease.lease_id,
            scope,
            genesis.hash,
            4,
        )
        .expect("the bounded finalized path page is coherent")
    else {
        panic!("the bounded finalized path lease should remain available");
    };
    assert_eq!(
        long_path_page.headers,
        vec![path[0].header.clone(), path[1].header.clone()]
    );
    assert_eq!(long_path_page.target, target);
    assert!(long_path_page.complete);
    assert!(!reader
        .release_retained_path(long_path_owner, 11, long_path_lease.lease_id, scope,)
        .expect("the bounded finalized path cursor releases"));

    // The nearest canonical locator bounds the lease. Honouring list order instead would let a
    // requester place a distant ancestor first and lease a complete range it never needed.
    let nearest_owner = SourceId::from_digest([0x85; 32]);
    let RetainedPathLeaseOutcome::Acquired(nearest_lease) = reader
        .acquire_retained_path(
            nearest_owner,
            11,
            target.hash,
            &[genesis.hash, path[0].hash],
            scope,
        )
        .expect("the nearest canonical locator resolves")
    else {
        panic!("the nearest canonical locator should acquire a lease");
    };
    assert_eq!(
        nearest_lease.common_ancestor,
        Frontier::new(path[0].height, path[0].hash),
        "an ordered-first distant locator must not widen the leased range"
    );
    assert!(reader
        .release_retained_path(nearest_owner, 11, nearest_lease.lease_id, scope)
        .expect("the nearest canonical locator cursor releases"));

    // A locator above the target cannot intersect its ancestry.
    let above_owner = SourceId::from_digest([0x82; 32]);
    assert!(matches!(
        reader
            .acquire_retained_path(above_owner, 11, target.hash, &[path[2].hash], scope)
            .expect("the locator lookup is coherent"),
        RetainedPathLeaseOutcome::NoLocatorIntersection
    ));

    // An unknown target stays unservable.
    let unknown_owner = SourceId::from_digest([0x83; 32]);
    let unknown = zakura_chain::block::Hash([0x9c; 32]);
    let unknown_scope = zakura_header_chain::HeaderWorkAuthority::for_target(
        &runtime.publisher().snapshot(),
        unknown,
    );
    assert!(matches!(
        reader
            .acquire_retained_path(unknown_owner, 11, unknown, &[genesis.hash], unknown_scope)
            .expect("the unknown target lookup is coherent"),
        RetainedPathLeaseOutcome::TargetNotRetained
    ));
}

#[test]
fn body_size_hints_by_hash_read_known_sizes_from_retained_deliveries() {
    let (runtime, db, _genesis, path) = reconciled_store_with_finalized_prefix(5);
    let parent = Frontier::new(path[2].height, path[2].hash);
    let target = Frontier::new(path[3].height, path[3].hash);
    let successor = Frontier::new(path[4].height, path[4].hash);
    let snapshot = runtime.publisher().snapshot();
    let owner = zakura_header_chain::BodyWorkAuthority::for_snapshot(&snapshot)
        .bind(27, NonZeroU64::new(28).expect("twenty-eight is nonzero"));
    let range = runtime
        .reader()
        .vct_repair_context(owner, target.height)
        .expect("the range repair context is coherent")
        .expect("the selected empty range needs repair");
    let prefix = range
        .bounded_prefix(1)
        .expect("the one-header range prefix exists");
    let lease = runtime
        .reader()
        .validation_context(parent.hash)
        .expect("the repair parent validation context is coherent")
        .expect("the repair parent remains retained");
    let rules =
        HeaderRules::for_validation_lease(&lease).expect("the repair parent produces header rules");
    let batch = zakura_header_chain::prepare_headers(
        HeaderBatchInput::new(std::slice::from_ref(&path[3].header)),
        parent,
        &rules,
        &SystemClock,
    )
    .expect("the selected prefix passes deterministic preparation");
    let source = SourceId::from_digest([0xc1; 32]);
    let known_size = std::num::NonZeroU32::new(123_456).expect("the fixture size is nonzero");
    let request = TransitionRequest {
        expected_version: StateVersion::default(),
        event: TransitionEvent::InsertHeaders(Box::new(InsertHeaders {
            owner: owner.into(),
            source,
            parent_hash: parent.hash,
            target_tip_hash: target.hash,
            completion: TargetCompletion::SelectedAuxiliaryRepair {
                common_ancestor: parent,
                selected_target: target,
                episode: prefix.episode,
            },
            batch,
            aux: vec![AuxDelivery::new(
                EvidenceId::from_digest([0xc2; 32]),
                target.hash,
                source,
                owner.into(),
                zakura_header_chain::BodySizeHint::Unknown,
                Some(zakura_header_chain::TreeAuxRecordV1 {
                    height: target.height,
                    sapling_root: Default::default(),
                    orchard_root: Default::default(),
                    ironwood_root: Default::default(),
                    sapling_tx_count: 1,
                    orchard_tx_count: 0,
                    ironwood_tx_count: 0,
                    auth_data_root: [0xc3; 32].into(),
                }),
            )],
        })),
    };
    let original_request = request.clone();
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: None,
        retention_references: &[],
    };
    assert!(matches!(
        runtime
            .apply(request, &context)
            .expect("the one-header range prefix applies"),
        ApplyResult::Committed
    ));

    let hints_by_hash = || {
        runtime
            .reader()
            .body_size_hints_by_hash(&[parent.hash, target.hash, successor.hash])
            .expect("the delivery hints read")
    };
    assert_eq!(hints_by_hash(), vec![None, None, None]);
    assert!(runtime
        .store
        .scan_raw(HEADER_AUX_BODY_SIZE)
        .unwrap()
        .is_empty());
    let replay = |request_id, marker, size| {
        let view = runtime.publisher().view();
        let mut replay = original_request.clone();
        replay.expected_version = view.state_version;
        let TransitionEvent::InsertHeaders(insert) = &mut replay.event else {
            unreachable!()
        };
        let new_owner = HeaderWorkAuthority::for_target(&view.snapshot, target.hash)
            .bind(27, NonZeroU64::new(request_id).unwrap());
        insert.owner = new_owner.into();
        insert.completion = TargetCompletion::TargetPrefix {
            common_ancestor: parent,
        };
        insert.aux[0].owner = new_owner.into();
        insert.aux[0].delivery_id = EvidenceId::from_digest([marker; 32]);
        insert.aux[0].body_size = zakura_header_chain::BodySizeHint::new(size).unwrap();
        replay
    };
    let before = runtime.publisher().view();
    let filled = runtime
        .apply(replay(29, 0xc4, known_size.get()), &context)
        .unwrap();
    assert!(matches!(filled, ApplyResult::Committed), "{filled:?}");
    let after = runtime.publisher().view();
    assert_eq!(after.header_generation, before.header_generation);
    assert_eq!(after.body_work_epoch, before.body_work_epoch);
    assert_eq!(
        after.body_size_hint_revision,
        before.body_size_hint_revision + 1
    );
    assert_eq!(
        runtime.store.scan_raw(HEADER_AUX_DELIVERY).unwrap().len(),
        1
    );
    assert_eq!(
        runtime.store.scan_raw(HEADER_AUX_BODY_SIZE).unwrap().len(),
        1
    );
    let persisted = runtime.store.untrusted_aux_deliveries(target.hash).unwrap();
    assert_eq!(
        persisted[0].delivery().body_size,
        zakura_header_chain::BodySizeHint::Unknown
    );
    assert_eq!(hints_by_hash(), vec![None, Some(known_size), None]);

    // A differing known hint is false, so it cannot replace the filled size.
    let conflicting = runtime.apply(replay(30, 0xc5, 3_146), &context).unwrap();
    assert!(
        matches!(conflicting, ApplyResult::NoChange(_)),
        "{conflicting:?}"
    );
    assert_eq!(
        runtime.publisher().view().body_size_hint_revision,
        after.body_size_hint_revision
    );
    let config = runtime.config.clone();
    drop(runtime);
    let (reopened, _) = HeaderChainStore::new(db).startup(&config).unwrap();
    assert_eq!(
        reopened
            .reader()
            .body_size_hints_by_hash(&[target.hash])
            .unwrap(),
        vec![Some(known_size)]
    );
}

#[test]
fn retained_path_lookup_stops_at_the_locator_outside_commit_locks() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(64);
    let reader = runtime.reader();
    let target = path.last().unwrap();
    let parent = &path[path.len() - 2];
    let snapshot = runtime.publisher().snapshot();
    let scope = HeaderWorkAuthority::for_target(&snapshot, target.hash);

    // Make an older, unrequested row unreadable so a walk past the locator fails
    // deterministically. The target's requested suffix is still intact.
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .delete_raw(&mut batch, HEADER_NODE_BY_HASH, path[3].hash.0)
        .unwrap();
    db.write(batch).unwrap();
    let read = reader.store.audit_snapshot().unwrap();
    let node = read.retained_path_node(target.hash).unwrap().unwrap();
    {
        let _writer = reader.store.writer.lock().unwrap();
        let _engine = reader.transition_engine.lock().unwrap();
        let ancestors = read
            .retained_ancestry_to_nearest_locator(
                node,
                snapshot.frontiers.finalized,
                &HashSet::from([parent.hash]),
                None,
            )
            .unwrap();
        assert_eq!(
            ancestors,
            serving_snapshot::RetainedAncestry::Path(vec![
                Frontier::new(target.height, target.hash),
                Frontier::new(parent.height, parent.hash),
            ])
        );
    }

    let source = SourceId::from_digest([0xc1; 32]);
    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(source, 7, target.hash, &[parent.hash, path[2].hash], scope)
        .unwrap()
    else {
        panic!("a one-header request only needs the intact suffix");
    };
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, lease.lease_id, scope, parent.hash, 1)
        .unwrap()
    else {
        panic!("the requested suffix can be served");
    };
    assert_eq!(page.headers[0].hash(), target.hash);
    assert!(page.complete);
    // The nearest locator wins regardless of list order, so the walk never reaches the gap.
    let RetainedPathLeaseOutcome::Acquired(reordered) = reader
        .acquire_retained_path(
            SourceId::from_digest([0xc2; 32]),
            7,
            target.hash,
            &[path[2].hash, parent.hash],
            scope,
        )
        .unwrap()
    else {
        panic!("the nearest locator only needs the intact suffix");
    };
    assert_eq!(reordered.common_ancestor.hash, parent.hash);
    assert!(matches!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xc3; 32]),
                7,
                target.hash,
                &[path[2].hash],
                scope,
            )
            .unwrap(),
        RetainedPathLeaseOutcome::HistoryPruned
    ));
}

#[test]
fn retained_path_lookup_chooses_the_nearest_locator_and_skips_other_branches() {
    let (runtime, db, genesis, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let target = &path[4];
    let snapshot = runtime.publisher().snapshot();
    let scope = HeaderWorkAuthority::for_target(&snapshot, target.hash);
    let mut fork = runtime.store.header_node(path[3].hash).unwrap().unwrap();
    let mut header = *fork.header;
    header.nonce.0[0] = 0xff;
    fork.header = Arc::new(header);
    fork.hash = fork.header.hash();
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .put_value(
            &mut batch,
            HEADER_NODE_BY_HASH,
            fork.hash.0,
            &HeaderNodeDisk::from_domain(&fork),
        )
        .unwrap();
    db.write(batch).unwrap();
    for (index, (locators, ancestor)) in [
        (vec![path[2].hash, path[3].hash], &path[3]),
        (vec![path[3].hash, path[2].hash], &path[3]),
        (vec![genesis.hash, path[3].hash], &path[3]),
        (vec![path[3].hash, genesis.hash], &path[3]),
        (vec![path[5].hash, path[3].hash], &path[3]),
        (vec![fork.hash, target.hash], target),
        (vec![fork.hash, path[3].hash], &path[3]),
        (vec![fork.hash, genesis.hash], &genesis),
        (vec![target.hash, path[3].hash], target),
    ]
    .into_iter()
    .enumerate()
    {
        let source = SourceId::from_digest([u8::try_from(index).unwrap(); 32]);
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(source, 7, target.hash, &locators, scope)
            .unwrap()
        else {
            panic!("each locator list intersects the retained target's ancestry");
        };
        assert_eq!(lease.common_ancestor.hash, ancestor.hash);
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(source, 7, lease.lease_id, scope, ancestor.hash, 10)
            .unwrap()
        else {
            panic!("the path from the chosen locator remains contiguous");
        };
        assert_eq!(
            page.headers.len(),
            usize::try_from(target.height.0 - ancestor.height.0).unwrap()
        );
        assert_eq!(page.target.hash, target.hash);
        assert!(page.complete);
    }
}

#[test]
fn retained_path_survives_finalization_during_and_between_page_reads() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let target = Frontier::new(path[3].height, path[3].hash);
    let source = SourceId::from_digest([0xa1; 32]);
    let before = runtime.publisher().snapshot();
    let scope = HeaderWorkAuthority::for_target(&before, target.hash);
    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(source, 7, target.hash, &[path[2].hash], scope)
        .expect("the retained target can be leased")
    else {
        panic!("the retained target has capacity");
    };
    let cursor = runtime
        .leases
        .lock()
        .unwrap()
        .get(source, 7, lease.lease_id, Instant::now())
        .unwrap();
    let captured = reader.capture_path_read(&cursor, 1).unwrap();
    let ancestry_read = reader.store.audit_snapshot().unwrap();
    finalize_serving_test_path(&runtime, &db, &path[3..5]);
    assert!(runtime.publisher().snapshot().header_generation > before.header_generation);
    assert!(
        runtime.store.header_node(target.hash).unwrap().is_none(),
        "finality removes the old retained row"
    );
    let ancestors = ancestry_read
        .retained_ancestry_to_nearest_locator(
            ancestry_read
                .retained_path_node(target.hash)
                .unwrap()
                .unwrap(),
            before.frontiers.finalized,
            &HashSet::from([path[2].hash]),
            None,
        )
        .unwrap();
    assert_eq!(
        ancestors,
        serving_snapshot::RetainedAncestry::Path(vec![target, before.frontiers.finalized])
    );
    let (page, _, _) = captured.read_page(&cursor, 1).unwrap().unwrap();
    assert_eq!(page.headers[0].hash(), target.hash);
    assert!(page.complete);
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(source, 7, lease.lease_id, scope, path[2].hash, 1)
        .unwrap()
    else {
        panic!("a fresh page reads the same hash from finalized storage");
    };
    assert_eq!(page.headers[0].hash(), target.hash);
    assert!(page.complete);
    let RetainedPathLeaseOutcome::Acquired(fresh) = reader
        .acquire_retained_path(
            SourceId::from_digest([0xa2; 32]),
            7,
            target.hash,
            &[path[2].hash],
            scope,
        )
        .unwrap()
    else {
        panic!("an acquisition queued before finality can still serve the exact hash");
    };
    assert_eq!(fresh.target, target);
    assert_eq!(fresh.scope, scope);
}

#[test]
fn retained_path_rejects_a_target_pruned_before_lease_commit_or_page_capture() {
    let (runtime, db, _, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xb1; 32]);
    let target = Frontier::new(path[3].height, path[3].hash);
    let before = runtime.publisher().snapshot();
    let scope = HeaderWorkAuthority::for_target(&before, target.hash);
    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(source, 7, target.hash, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the original target is retained");
    };
    let cursor = runtime
        .leases
        .lock()
        .unwrap()
        .get(source, 7, lease.lease_id, Instant::now())
        .unwrap();
    let captured = reader.capture_path_read(&cursor, 1).unwrap();
    let ancestry_read = reader.store.audit_snapshot().unwrap();

    let cached_source = SourceId::from_digest([0xb4; 32]);
    let cached_target = path[4].hash;
    let cached_scope = HeaderWorkAuthority::for_target(&before, cached_target);
    let RetainedPathLeaseOutcome::Acquired(cached_lease) = reader
        .acquire_retained_path(
            cached_source,
            8,
            cached_target,
            &[path[2].hash],
            cached_scope,
        )
        .unwrap()
    else {
        panic!("the longer losing path can prepare a continuation");
    };
    let RetainedPathReadOutcome::Page(page) = reader
        .read_retained_path(
            cached_source,
            8,
            cached_lease.lease_id,
            cached_scope,
            path[2].hash,
            1,
        )
        .unwrap()
    else {
        panic!("the first losing-path page is available before finality");
    };
    assert!(!page.complete);

    let pending_source = SourceId::from_digest([0xb2; 32]);
    let (reservation_id, capacity) = runtime
        .leases
        .lock()
        .unwrap()
        .reserve(
            pending_source,
            Instant::now(),
            RetainedPathCapacity::General,
        )
        .unwrap();
    let reservation = RetainedPathReservation {
        leases: runtime.leases.clone(),
        peer: pending_source,
        reservation_id,
        active: true,
    };
    let pending = RetainedPathLeaseSpec {
        peer: pending_source,
        session_id: 8,
        target,
        common_ancestor: cursor.common_ancestor,
        scope,
        position: cursor.position,
        retained_path: cursor.retained_path.clone(),
        capacity,
    };

    let mut parent = path[2].clone();
    let mut fork = Vec::new();
    for _ in 0..3 {
        let mut header = *parent.header;
        header.previous_block_hash = parent.hash;
        header.time += chrono::Duration::seconds(10);
        let header = Arc::new(header);
        parent = VerifiedHeaderRef {
            height: parent.height.next().unwrap(),
            hash: header.hash(),
            header,
        };
        fork.push(parent.clone());
    }
    let evidence = EvidenceId::from_digest([0xb3; 32]);
    let authority = Authority(evidence);
    runtime
        .apply(
            TransitionRequest {
                expected_version: before.state_version,
                event: TransitionEvent::VerifiedChainChanged(VerifiedChainChanged {
                    full_state_transition_id: evidence,
                    old_tip: before.frontiers.verified_best,
                    new_path: fork.clone(),
                    cause: VerifiedChangeCause::Reset,
                }),
            },
            &TransitionContext {
                config: &runtime.config,
                clock: &SystemClock,
                full_state_authority: Some(&authority),
                retention_references: &[],
            },
        )
        .expect("full state can select the competing verified path");
    finalize_serving_test_path(&runtime, &db, &fork[..2]);
    assert_eq!(
        reader
            .acquire_retained_path(
                cached_source,
                8,
                cached_target,
                &[path[3].hash],
                cached_scope
            )
            .unwrap(),
        RetainedPathLeaseOutcome::TargetNotRetained,
        "a cached path must not resurrect a branch removed by finality"
    );
    assert!(runtime.store.header_node(target.hash).unwrap().is_none());
    assert!(reader
        .store
        .audit_snapshot()
        .unwrap()
        .finalized_frontier(target.hash)
        .unwrap()
        .is_none());

    let ancestors = ancestry_read
        .retained_ancestry_to_nearest_locator(
            ancestry_read
                .retained_path_node(target.hash)
                .unwrap()
                .unwrap(),
            before.frontiers.finalized,
            &HashSet::from([path[2].hash]),
            None,
        )
        .unwrap();
    assert_eq!(
        ancestors,
        serving_snapshot::RetainedAncestry::Path(vec![target, before.frontiers.finalized])
    );

    let (page, _, _) = captured.read_page(&cursor, 1).unwrap().unwrap();
    assert_eq!(page.headers[0].hash(), target.hash);
    assert!(page.complete);
    assert_eq!(
        reader
            .read_retained_path(source, 7, lease.lease_id, scope, path[2].hash, 1)
            .unwrap(),
        RetainedPathReadOutcome::Unavailable
    );
    assert!(matches!(
        reader.commit_path_lease(reservation, pending).unwrap(),
        RetainedPathLeaseOutcome::TargetNotRetained
    ));
    let leases = runtime.leases.lock().unwrap();
    assert!(!leases.reservations.contains_key(&pending_source));
    assert!(!leases.by_peer.contains_key(&pending_source));
}

fn finalize_serving_test_path(
    runtime: &HeaderChainRuntime,
    db: &DiskDb,
    rows: &[VerifiedHeaderRef],
) {
    let before = runtime.publisher().snapshot();
    let last = rows.last().expect("the test finalizes a nonempty range");
    let finalized = Frontier::new(last.height, last.hash);
    let proof: Vec<_> = runtime
        .verified_projection()
        .unwrap()
        .into_iter()
        .take_while(|frontier| frontier.height <= finalized.height)
        .map(|frontier| frontier.hash)
        .collect();
    let evidence =
        zakura_header_chain::full_state_finality_evidence(before.state_version, finalized, &proof);
    let authority = Authority(evidence);
    let mut batch = DiskWriteBatch::new();
    for header in rows {
        batch.zs_insert(
            &db.cf_handle("hash_by_height").unwrap(),
            header.height,
            header.hash,
        );
        batch.zs_insert(
            &db.cf_handle("height_by_hash").unwrap(),
            header.hash,
            header.height,
        );
        batch.zs_insert(
            &db.cf_handle("block_header_by_height").unwrap(),
            header.height,
            header.header.as_ref(),
        );
    }
    runtime
        .apply_combined(
            TransitionRequest {
                expected_version: before.state_version,
                event: TransitionEvent::FullStateFinalized(FullStateFinalized {
                    full_state_transition_id: evidence,
                    new_finalized: finalized,
                    verified_path_proof: proof,
                }),
            },
            &TransitionContext {
                config: &runtime.config,
                clock: &SystemClock,
                full_state_authority: Some(&authority),
                retention_references: &[],
            },
            batch,
            || {},
        )
        .expect("the authoritative test path finalizes");
}

#[test]
fn capacity_signals_follow_reservations_and_capacity_classes() {
    let mut leases = RetainedPathLeaseRegistry::default();
    let now = Instant::now();
    let first = SourceId::from_digest([0; 32]);
    let (first_id, _) = leases
        .reserve(first, now, RetainedPathCapacity::General)
        .unwrap();
    let Err(RetainedPathLeaseOutcome::CapacityBusy(peer_wait)) =
        leases.reserve(first, now, RetainedPathCapacity::General)
    else {
        panic!("the reservation occupies this peer's slot")
    };
    for marker in 1..MAX_RETAINED_PATH_LEASES - 1 {
        leases
            .reserve(
                SourceId::from_digest([u8::try_from(marker).unwrap(); 32]),
                now,
                RetainedPathCapacity::General,
            )
            .unwrap();
    }
    let waiting = SourceId::from_digest([0xfe; 32]);
    let Err(RetainedPathLeaseOutcome::CapacityBusy(general_wait)) =
        leases.reserve(waiting, now, RetainedPathCapacity::General)
    else {
        panic!("general capacity is full")
    };
    let Err(RetainedPathLeaseOutcome::CapacityBusy(other_wait)) = leases.reserve(
        SourceId::from_digest([0xfd; 32]),
        now,
        RetainedPathCapacity::General,
    ) else {
        panic!("another peer shares the same full capacity class")
    };
    assert_eq!(general_wait, other_wait);
    let fallback = SourceId::from_digest([0xff; 32]);
    let (fallback_id, _) = leases
        .reserve(fallback, now, RetainedPathCapacity::Bounded)
        .unwrap();
    let Err(RetainedPathLeaseOutcome::CapacityBusy(fallback_wait)) =
        leases.reserve(waiting, now, RetainedPathCapacity::Bounded)
    else {
        panic!("fallback capacity is full")
    };
    leases.release_reservation(fallback, fallback_id + 1);
    assert!(!fallback_wait.is_released());
    leases.release_reservation(fallback, fallback_id);
    assert!(fallback_wait.is_released());
    assert!(!general_wait.is_released());
    assert!(!peer_wait.is_released());
    leases.release_reservation(first, first_id);
    assert!(general_wait.is_released());
    assert!(other_wait.is_released());
    assert!(peer_wait.is_released());
    let (replacement, _) = leases
        .reserve(first, now, RetainedPathCapacity::General)
        .unwrap();
    let Err(RetainedPathLeaseOutcome::CapacityBusy(next_general_wait)) =
        leases.reserve(waiting, now, RetainedPathCapacity::General)
    else {
        panic!("another peer acquired the available general slot")
    };
    assert_ne!(general_wait, next_general_wait);
    let Err(RetainedPathLeaseOutcome::CapacityBusy(next_wait)) =
        leases.reserve(first, now, RetainedPathCapacity::General)
    else {
        panic!("the replacement occupies this peer's slot")
    };
    leases.release_reservation(first, first_id);
    assert!(!next_wait.is_released());
    assert!(!next_general_wait.is_released());
    leases.release_reservation(first, replacement);
    assert!(next_wait.is_released());
    assert!(next_general_wait.is_released());
}

#[test]
fn capacity_signal_survives_reservation_commit_and_page_release() {
    let (runtime, _db, _, path) = reconciled_store_with_finalized_prefix(6);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xd8; 32]);
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let RetainedPathLeaseOutcome::Acquired(lease) = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the target is retained")
    };
    let RetainedPathLeaseOutcome::CapacityBusy(signal) = reader
        .acquire_retained_path(source, 8, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the first session holds this peer's slot")
    };
    assert!(!reader
        .release_retained_path(source, 8, lease.lease_id, scope)
        .unwrap());
    assert!(!signal.is_released());
    assert!(matches!(
        reader
            .read_retained_path(source, 7, lease.lease_id, scope, path[2].hash, 1)
            .unwrap(),
        RetainedPathReadOutcome::Page(_)
    ));
    assert!(signal.is_released());
    assert!(!reader
        .release_retained_path(source, 7, lease.lease_id, scope)
        .unwrap());
}

#[test]
fn dropped_reservation_notifies_waiters() {
    let leases = Arc::new(Mutex::new(RetainedPathLeaseRegistry::default()));
    let peer = SourceId::from_digest([0xd9; 32]);
    let (id, _) = leases
        .lock()
        .unwrap()
        .reserve(peer, Instant::now(), RetainedPathCapacity::General)
        .unwrap();
    let reservation = RetainedPathReservation {
        leases: leases.clone(),
        peer,
        reservation_id: id,
        active: true,
    };
    let Err(RetainedPathLeaseOutcome::CapacityBusy(signal)) =
        leases
            .lock()
            .unwrap()
            .reserve(peer, Instant::now(), RetainedPathCapacity::General)
    else {
        panic!("the reservation occupies this peer's slot")
    };
    assert!(!signal.is_released());
    drop(reservation);
    assert!(signal.is_released());
}

#[test]
fn reservation_commit_keeps_the_waiter_until_exact_release_or_expiry() {
    for expire in [false, true] {
        let mut leases = RetainedPathLeaseRegistry::default();
        let peer = SourceId::from_digest([0xda; 32]);
        let now = Instant::now();
        let (reservation, capacity) = leases
            .reserve(peer, now, RetainedPathCapacity::General)
            .unwrap();
        let Err(RetainedPathLeaseOutcome::CapacityBusy(signal)) =
            leases.reserve(peer, now, RetainedPathCapacity::General)
        else {
            panic!("the reservation occupies this peer's slot")
        };
        let frontier = Frontier::new(block::Height(0), block::Hash([0; 32]));
        let scope = HeaderWorkAuthority {
            header_generation: zakura_header_chain::HeaderGeneration::new(1),
            branch: zakura_header_chain::BranchId::new(frontier.hash, frontier.hash),
        };
        let RetainedPathLeaseOutcome::Acquired(lease) = leases.commit_reservation(
            peer,
            reservation,
            RetainedPathLeaseSpec {
                peer,
                session_id: 7,
                target: frontier,
                common_ancestor: frontier,
                scope,
                position: CanonicalHeaderPathPosition::Complete,
                capacity,
                retained_path: Arc::from([]),
            },
            now,
        ) else {
            panic!("the reservation commits its lease")
        };
        assert!(!signal.is_released());
        assert!(!leases.release(peer, 8, lease.lease_id, scope));
        assert!(!signal.is_released());
        if expire {
            leases.expire(now + RETAINED_PATH_LEASE_IDLE);
        } else {
            assert!(leases.release(peer, 7, lease.lease_id, scope));
        }
        assert!(signal.is_released());
    }
}

#[tokio::test]
async fn abandoned_blocking_acquisition_releases_its_lease_and_notifies_waiters() {
    let (runtime, _db, _, path) = reconciled_store_with_finalized_prefix(7);
    let reader = runtime.reader();
    let source = SourceId::from_digest([0xe5; 32]);
    let target = path[5].hash;
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target);
    let outcome = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap();
    assert!(matches!(outcome, RetainedPathLeaseOutcome::Acquired(_)));
    let RetainedPathLeaseOutcome::CapacityBusy(signal) = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap()
    else {
        panic!("the first acquisition owns the peer slot");
    };
    let (resume, blocked) = std::sync::mpsc::channel();
    let task_reader = reader.clone();
    let task = tokio::task::spawn_blocking(move || {
        blocked.recv().unwrap();
        PendingRetainedPathAcquisition::new(task_reader, outcome)
    });
    drop(task);
    assert!(!signal.is_released());
    resume.send(()).unwrap();
    tokio::time::timeout(std::time::Duration::from_secs(5), signal.released())
        .await
        .unwrap();
    let outcome = reader
        .acquire_retained_path(source, 7, target, &[path[2].hash], scope)
        .unwrap();
    let pending = PendingRetainedPathAcquisition::new(reader.clone(), outcome);
    let RetainedPathLeaseOutcome::Acquired(lease) = pending.into_outcome() else {
        panic!("abandonment must return the peer slot");
    };
    // Receiving the result transfers ownership to the caller.
    assert!(reader
        .release_retained_path(source, 7, lease.lease_id, scope)
        .unwrap());
}

fn retained_checkpoint_fixture() -> (HeaderChainRuntime, DiskDb, Vec<VerifiedHeaderRef>) {
    let (runtime, db, _genesis, path) = reconciled_store_with_finalized_prefix(5);
    let before = runtime.publisher().snapshot();
    let evidence = EvidenceId::from_digest([0xc4; 32]);
    let authority = Authority(evidence);
    runtime
        .apply(
            TransitionRequest {
                expected_version: before.state_version,
                event: TransitionEvent::VerifiedChainChanged(VerifiedChainChanged {
                    full_state_transition_id: evidence,
                    old_tip: before.frontiers.verified_best,
                    new_path: Vec::new(),
                    cause: VerifiedChangeCause::Reset,
                }),
            },
            &TransitionContext {
                config: &runtime.config,
                clock: &SystemClock,
                full_state_authority: Some(&authority),
                retention_references: &[],
            },
        )
        .expect("the fixture resets the verified tip while retaining its headers");
    assert_eq!(
        runtime.publisher().snapshot().frontiers.verified_best,
        before.frontiers.finalized
    );
    (runtime, db, path)
}

#[test]
fn retained_checkpoint_omits_context_but_missing_headers_and_other_causes_keep_it() {
    let (runtime, _db, path) = retained_checkpoint_fixture();
    let before = runtime.publisher().snapshot();
    let make_request = |header: VerifiedHeaderRef, cause| TransitionRequest {
        expected_version: before.state_version,
        event: TransitionEvent::VerifiedChainChanged(VerifiedChainChanged {
            full_state_transition_id: zakura_header_chain::checkpoint_finality_evidence(
                before.state_version,
                Frontier::new(header.height, header.hash),
            ),
            old_tip: before.frontiers.verified_best,
            new_path: vec![header],
            cause,
        }),
    };
    let engine = runtime
        .transition_engine
        .lock()
        .expect("the fixture writer is unlocked");
    let retained = make_request(
        path[3].clone(),
        VerifiedChangeCause::CheckpointFinalizedGrow,
    );
    let input = runtime
        .build_transition_input(retained.clone(), &before, runtime.config.network(), &engine)
        .expect("retained checkpoint input needs no durable context");
    assert!(input
        .header_validation_facts()
        .expect("checkpoint facts exist")
        .validation_leases
        .is_empty());
    let grow = runtime
        .build_transition_input(
            make_request(path[3].clone(), VerifiedChangeCause::Grow),
            &before,
            runtime.config.network(),
            &engine,
        )
        .expect("ordinary growth keeps its context");
    assert_eq!(
        grow.header_validation_facts()
            .expect("growth facts exist")
            .validation_leases
            .len(),
        1
    );
    let mut missing = path[3].clone();
    Arc::make_mut(&mut missing.header).nonce.0[0] ^= 0x80;
    missing.hash = missing.header.hash();
    let input = runtime
        .build_transition_input(
            make_request(missing, VerifiedChangeCause::CheckpointFinalizedGrow),
            &before,
            runtime.config.network(),
            &engine,
        )
        .expect("a missing header receives durable context");
    assert_eq!(
        input
            .header_validation_facts()
            .expect("checkpoint facts exist")
            .validation_leases
            .len(),
        1
    );
    drop(engine);

    let TransitionEvent::VerifiedChainChanged(event) = &retained.event else {
        unreachable!()
    };
    let authority = Authority(event.full_state_transition_id);
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: Some(&authority),
        retention_references: &[],
    };
    let mut batch = DiskWriteBatch::new();
    let accepted = Frontier::new(path[3].height, path[3].hash);
    stage_full_state_canonical_hash(&runtime.store, &mut batch, accepted);
    assert!(matches!(
        runtime
            .apply_combined(retained, &context, batch, || {})
            .expect("retained checkpoint commits through the full adapter"),
        ApplyResult::Committed
    ));
    assert_eq!(runtime.publisher().snapshot().frontiers.finalized, accepted);
}

#[test]
fn retained_checkpoint_still_rejects_mismatched_header_identity() {
    let (runtime, _db, path) = retained_checkpoint_fixture();
    let before = runtime.publisher().snapshot();
    let accepted = Frontier::new(path[3].height, path[3].hash);
    let evidence =
        zakura_header_chain::checkpoint_finality_evidence(before.state_version, accepted);
    let authority = Authority(evidence);
    let context = TransitionContext {
        config: &runtime.config,
        clock: &SystemClock,
        full_state_authority: Some(&authority),
        retention_references: &[],
    };
    let mut tampered = path[3].clone();
    Arc::make_mut(&mut tampered.header).nonce.0[0] ^= 0x80;
    let request = TransitionRequest {
        expected_version: before.state_version,
        event: TransitionEvent::VerifiedChainChanged(VerifiedChainChanged {
            full_state_transition_id: evidence,
            old_tip: before.frontiers.verified_best,
            new_path: vec![tampered],
            cause: VerifiedChangeCause::CheckpointFinalizedGrow,
        }),
    };
    assert!(runtime
        .apply_combined(request, &context, DiskWriteBatch::new(), || {})
        .is_err());
    assert_eq!(runtime.publisher().snapshot(), before);
}

/// Read a complete path, reacquiring the target with a continuation locator after each page.
fn read_whole_retained_path(
    reader: &HeaderChainReader,
    owner: SourceId,
    target: block::Hash,
    locators: &[block::Hash],
    scope: HeaderWorkAuthority,
    page_count: u32,
) -> (Frontier, Vec<Arc<block::Header>>) {
    let mut locators = locators.to_vec();
    let mut first_ancestor = None;
    let mut headers = Vec::new();
    loop {
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(owner, 1, target, &locators, scope)
            .expect("the target resolves on either side of finality")
        else {
            panic!("the same locator must acquire every target");
        };
        first_ancestor.get_or_insert(lease.common_ancestor);
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(
                owner,
                1,
                lease.lease_id,
                scope,
                lease.common_ancestor.hash,
                page_count,
            )
            .expect("the cursor reads a coherent page")
        else {
            panic!("the path must remain available");
        };
        assert_eq!(page.target.hash, target);
        assert!(page.aux_deliveries.iter().all(Vec::is_empty));
        headers.extend(page.headers.iter().cloned());
        if page.complete {
            break;
        }
        locators = vec![page
            .headers
            .last()
            .expect("an incomplete page is nonempty")
            .hash()];
    }
    (
        first_ancestor.expect("the loop acquires at least once"),
        headers,
    )
}

#[tokio::test(start_paused = true)]
async fn retained_path_requests_have_identical_rules_across_finality() {
    for finalized_count in [1, 3, 5] {
        let (runtime, _db, genesis, path) = reconciled_store_with_finality(5, finalized_count);
        let reader = runtime.reader();
        let owner = SourceId::from_digest([0xc1; 32]);
        let target = Frontier::new(path[2].height, path[2].hash);
        let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target.hash);
        for page_count in [1, 4] {
            let (ancestor, headers) = read_whole_retained_path(
                &reader,
                owner,
                target.hash,
                &[
                    genesis.hash,
                    path[0].hash,
                    path[4].hash,
                    block::Hash([0xff; 32]),
                ],
                scope,
                page_count,
            );
            assert_eq!(ancestor.hash, path[0].hash);
            assert_eq!(
                headers,
                vec![path[1].header.clone(), path[2].header.clone()]
            );
        }
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(owner, 1, target.hash, &[genesis.hash, target.hash], scope)
            .unwrap()
        else {
            panic!("the target itself must intersect in every storage band");
        };
        assert_eq!(lease.common_ancestor, target);
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(owner, 1, lease.lease_id, scope, target.hash, 1)
            .unwrap()
        else {
            panic!("the empty path must be readable");
        };
        assert!(page.headers.is_empty());
        assert!(page.complete);
        assert_eq!(
            reader
                .acquire_retained_path(owner, 1, target.hash, &[path[4].hash], scope)
                .unwrap(),
            RetainedPathLeaseOutcome::NoLocatorIntersection
        );
    }
}

#[tokio::test(start_paused = true)]
async fn retained_path_reserves_bounded_repair_capacity_for_every_storage_band() {
    let (runtime, _db, genesis, path) =
        reconciled_store_with_finalized_prefix(crate::constants::MAX_HEADER_SYNC_HEIGHT_RANGE + 4);
    let reader = runtime.reader();
    let ordinary_target = path.last().unwrap();
    let ordinary_scope =
        HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), ordinary_target.hash);
    let mut ordinary_leases = Vec::new();
    for marker in 1..MAX_RETAINED_PATH_LEASES {
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(
                SourceId::from_digest([u8::try_from(marker).unwrap(); 32]),
                1,
                ordinary_target.hash,
                &[genesis.hash],
                ordinary_scope,
            )
            .unwrap()
        else {
            panic!("ordinary transfers must fill the general slots");
        };
        ordinary_leases.push(lease);
    }
    let owner = SourceId::from_digest([0xc2; 32]);
    let RetainedPathLeaseOutcome::CapacityBusy(long_wait) = reader
        .acquire_retained_path(
            owner,
            1,
            ordinary_target.hash,
            &[genesis.hash],
            ordinary_scope,
        )
        .unwrap()
    else {
        panic!("a long path rejected from the reserve waits for ordinary capacity");
    };
    assert!(!long_wait.is_released());
    let RetainedPathLeaseOutcome::CapacityBusy(missing_locator_wait) = reader
        .acquire_retained_path(
            owner,
            1,
            ordinary_target.hash,
            &[block::Hash([0xee; 32])],
            ordinary_scope,
        )
        .unwrap()
    else {
        panic!("reserve traversal stops at the range limit before resolving a missing locator");
    };
    assert_eq!(missing_locator_wait, long_wait);

    // Each two-header repair uses the reserve and stops at its admitted target.
    for (target, ancestor) in [
        (&path[1], &genesis),
        (&path[2], &path[0]),
        (&path[3], &path[1]),
    ] {
        let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target.hash);
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(owner, 1, target.hash, &[ancestor.hash], scope)
            .unwrap()
        else {
            panic!("bounded repair must acquire the reserved slot");
        };
        assert_eq!(
            runtime.leases.lock().unwrap().by_peer[&owner].capacity,
            RetainedPathCapacity::Bounded
        );
        let RetainedPathLeaseOutcome::CapacityBusy(capacity_signal) = reader
            .acquire_retained_path(
                SourceId::from_digest([0xc3; 32]),
                1,
                target.hash,
                &[ancestor.hash],
                scope,
            )
            .unwrap()
        else {
            panic!("one bounded lease fills the reserve and reports its release signal");
        };
        assert!(!capacity_signal.is_released());
        let RetainedPathReadOutcome::Page(page) = reader
            .read_retained_path(
                owner,
                1,
                lease.lease_id,
                scope,
                ancestor.hash,
                crate::constants::MAX_HEADER_SYNC_HEIGHT_RANGE,
            )
            .unwrap()
        else {
            panic!("bounded repair must read the reserved path");
        };
        assert_eq!(page.headers.len(), 2);
        assert_eq!(page.headers.last().unwrap().hash(), target.hash);
        assert!(page.complete);
        assert!(capacity_signal.is_released());
    }

    let target = &path[3];
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target.hash);
    assert!(
        matches!(
            reader
                .acquire_retained_path(owner, 1, target.hash, &[path[1].hash], scope)
                .unwrap(),
            RetainedPathLeaseOutcome::Acquired(_)
        ),
        "a completed page releases the reserve"
    );
    assert!(!long_wait.is_released());
    let released = ordinary_leases.pop().unwrap();
    assert!(reader
        .release_retained_path(released.peer, 1, released.lease_id, ordinary_scope)
        .unwrap());
    assert!(
        long_wait.is_released(),
        "a freed ordinary slot wakes long paths rejected from the reserve"
    );
    assert!(
        matches!(
            reader
                .acquire_retained_path(
                    released.peer,
                    2,
                    ordinary_target.hash,
                    &[genesis.hash],
                    ordinary_scope,
                )
                .unwrap(),
            RetainedPathLeaseOutcome::Acquired(_)
        ),
        "a reserve lease must not consume a released general slot"
    );
}

#[tokio::test(start_paused = true)]
async fn retained_path_long_transfers_use_ordinary_capacity_across_finality() {
    let range = crate::constants::MAX_HEADER_SYNC_HEIGHT_RANGE;
    let target_index = usize::try_from(range).unwrap();
    for finalized_count in [1, target_index + 2] {
        let (runtime, _db, genesis, path) =
            reconciled_store_with_finality(range + 2, finalized_count);
        let reader = runtime.reader();
        let target = &path[target_index];
        let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target.hash);
        let owner = SourceId::from_digest([0xc4; 32]);
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(owner, 1, target.hash, &[genesis.hash], scope)
            .unwrap()
        else {
            panic!("long paths must use ordinary capacity in either storage band");
        };
        assert_eq!(
            runtime.leases.lock().unwrap().by_peer[&owner].capacity,
            RetainedPathCapacity::General
        );
        let RetainedPathReadOutcome::Page(first) = reader
            .read_retained_path(owner, 1, lease.lease_id, scope, genesis.hash, range)
            .unwrap()
        else {
            panic!("the first protocol range must be readable");
        };
        assert_eq!(first.headers.len(), target_index);
        assert!(!first.complete);
        let continuation = path[target_index - 1].hash;
        let RetainedPathLeaseOutcome::Acquired(lease) = reader
            .acquire_retained_path(owner, 1, target.hash, &[continuation], scope)
            .unwrap()
        else {
            panic!("the continuation must reacquire the target");
        };
        let RetainedPathReadOutcome::Page(last) = reader
            .read_retained_path(owner, 1, lease.lease_id, scope, continuation, range)
            .unwrap()
        else {
            panic!("the final page must be readable");
        };
        assert_eq!(last.headers, vec![target.header.clone()]);
        assert!(last.complete);
        for marker in 1..MAX_RETAINED_PATH_LEASES {
            assert!(matches!(
                reader
                    .acquire_retained_path(
                        SourceId::from_digest([u8::try_from(marker).unwrap(); 32]),
                        1,
                        target.hash,
                        &[genesis.hash],
                        scope
                    )
                    .unwrap(),
                RetainedPathLeaseOutcome::Acquired(_)
            ));
        }
        let repair_owner = SourceId::from_digest([0xc5; 32]);
        let RetainedPathLeaseOutcome::CapacityBusy(long_wait) = reader
            .acquire_retained_path(repair_owner, 1, target.hash, &[genesis.hash], scope)
            .unwrap()
        else {
            panic!("a long path waits for ordinary capacity in either storage band");
        };
        assert!(!long_wait.is_released());
        assert!(
            matches!(
                reader
                    .acquire_retained_path(repair_owner, 1, target.hash, &[path[0].hash], scope)
                    .unwrap(),
                RetainedPathLeaseOutcome::Acquired(_)
            ),
            "a protocol-sized repair must still use the reserve in either storage band"
        );
    }
}

#[test]
fn retained_path_reservations_keep_capacity_classes_separate() {
    let mut registry = RetainedPathLeaseRegistry::default();
    let now = Instant::now();
    let peers: Vec<_> = (0..MAX_RETAINED_PATH_LEASES)
        .map(|marker| SourceId::from_digest([u8::try_from(marker).unwrap(); 32]))
        .collect();
    let mut reservations = Vec::new();
    for peer in &peers {
        reservations.push(
            registry
                .reserve(*peer, now, RetainedPathCapacity::Bounded)
                .unwrap(),
        );
    }
    assert_eq!(
        reservations.last().unwrap().1,
        RetainedPathCapacity::Bounded
    );
    let Err(RetainedPathLeaseOutcome::CapacityBusy(general_wait)) = registry.reserve(
        SourceId::from_digest([0xfe; 32]),
        now,
        RetainedPathCapacity::General,
    ) else {
        panic!("ordinary reservations fill the general class")
    };
    registry.release_reservation(peers[0], reservations[0].0);
    assert!(
        general_wait.is_released(),
        "the reserve must not hide a freed ordinary slot"
    );
    assert_eq!(
        registry
            .reserve(peers[0], now, RetainedPathCapacity::General)
            .unwrap()
            .1,
        RetainedPathCapacity::General
    );
    assert!(registry
        .reserve(peers[0], now, RetainedPathCapacity::Bounded)
        .is_err());
    assert!(registry
        .reserve(
            SourceId::from_digest([0xff; 32]),
            now,
            RetainedPathCapacity::Bounded
        )
        .is_err());
}

#[test]
fn reserve_rejection_reports_an_ordinary_slot_freed_after_admission() {
    let mut registry = RetainedPathLeaseRegistry::default();
    let now = Instant::now();
    let peers: Vec<_> = (0..MAX_RETAINED_PATH_LEASES)
        .map(|marker| SourceId::from_digest([u8::try_from(marker).unwrap(); 32]))
        .collect();
    let reservations: Vec<_> = peers
        .iter()
        .map(|peer| {
            registry
                .reserve(*peer, now, RetainedPathCapacity::Bounded)
                .unwrap()
        })
        .collect();
    let (reserve_id, class) = *reservations.last().unwrap();
    assert_eq!(class, RetainedPathCapacity::Bounded);
    let Err(RetainedPathLeaseOutcome::CapacityBusy(reserve_wait)) = registry.reserve(
        SourceId::from_digest([0xfe; 32]),
        now,
        RetainedPathCapacity::Bounded,
    ) else {
        panic!("the reserve is occupied");
    };

    // An ordinary slot frees while the reserve-admitted request walks its ancestry.
    registry.release_reservation(peers[0], reservations[0].0);
    let RetainedPathLeaseOutcome::CapacityBusy(ordinary_wait) =
        registry.reject_beyond_reserve(*peers.last().unwrap(), reserve_id)
    else {
        panic!("a reserve rejection returns the ordinary capacity signal");
    };
    assert!(
        ordinary_wait.is_released(),
        "the requester must not wait for a slot that is already free"
    );
    assert!(
        reserve_wait.is_released(),
        "freeing any slot wakes bounded waiters"
    );
    assert!(!registry.reservations.contains_key(peers.last().unwrap()));
}

#[test]
fn retained_path_busy_admission_does_not_lock_the_engine() {
    let (runtime, _db, genesis, path) = reconciled_store_with_finalized_prefix(4);
    let reader = runtime.reader();
    let target = path.last().unwrap();
    let scope = HeaderWorkAuthority::for_target(&runtime.publisher().snapshot(), target.hash);
    let owner = SourceId::from_digest([0xc6; 32]);
    assert!(matches!(
        reader
            .acquire_retained_path(owner, 1, target.hash, &[genesis.hash], scope)
            .unwrap(),
        RetainedPathLeaseOutcome::Acquired(_)
    ));
    let engine = reader.transition_engine.clone();
    let _ = std::thread::spawn(move || {
        let _guard = engine.lock().unwrap();
        panic!("poison the engine to detect any access after failed admission");
    })
    .join();
    assert!(matches!(
        reader
            .acquire_retained_path(owner, 2, target.hash, &[genesis.hash], scope)
            .unwrap(),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
    for marker in 0..MAX_RETAINED_PATH_LEASES - 1 {
        reader
            .leases
            .lock()
            .unwrap()
            .reserve(
                SourceId::from_digest([u8::try_from(marker).unwrap(); 32]),
                Instant::now(),
                RetainedPathCapacity::Bounded,
            )
            .unwrap();
    }
    assert!(matches!(
        reader
            .acquire_retained_path(
                SourceId::from_digest([0xff; 32]),
                1,
                target.hash,
                &[genesis.hash],
                scope
            )
            .unwrap(),
        RetainedPathLeaseOutcome::CapacityBusy(_)
    ));
}

#[test]
fn stored_validation_context_equals_the_lease_built_from_rehashed_headers() {
    let path_len = u8::try_from(zakura_header_chain::MAX_POW_PREDECESSOR_CONTEXT_SPAN + 6)
        .expect("the predecessor span fixture is shorter than 256");
    let (runtime, _, _, path) = reconciled_store_with_finalized_prefix(u32::from(path_len));
    let (engine_config, _, _) = fixture();
    let network = engine_config.network();
    let parent = path.last().expect("the fixture path is nonempty");

    let lease = runtime
        .store
        .validation_context(parent.hash, network)
        .expect("the retained parent has a coherent validation context");

    // Rebuild the lease the way it was built before hash reuse: hash every context header.
    let parent_node = runtime
        .store
        .header_node(parent.hash)
        .expect("the parent row decodes")
        .expect("the parent is retained");
    let mut facts = vec![zakura_header_chain::HeaderContextFact {
        frontier: Frontier::new(parent_node.height, parent.hash),
        header: parent_node.header.clone(),
    }];
    facts.extend(
        authenticated_context_headers(&runtime.store, parent.hash, None)
            .expect("the stored context authenticates")
            .into_iter()
            .rev()
            .map(|context| context.fact()),
    );
    assert_eq!(
        facts.len(),
        zakura_header_chain::MAX_POW_PREDECESSOR_CONTEXT_SPAN + 1
    );
    for fact in &facts {
        assert_eq!(fact.frontier.hash, fact.header.hash());
    }
    let expected = zakura_header_chain::ValidationLease::new(
        lease.parent(),
        facts,
        network.clone(),
        runtime
            .store
            .metadata()
            .expect("the metadata row exists")
            .anchor_manifest_digest,
    );
    assert_eq!(lease, expected);
}

#[test]
fn stored_validation_context_rejects_a_predecessor_row_with_altered_header_bytes() {
    let (runtime, _, _, path) = reconciled_store_with_finalized_prefix(8);
    let (engine_config, _, _) = fixture();
    let parent = &path[7];
    let altered = path[5].hash;
    runtime
        .store
        .validation_context(parent.hash, engine_config.network())
        .expect("the unaltered context is coherent");

    let cf = runtime
        .store
        .cf(HEADER_NODE_BY_HASH)
        .expect("the node column family exists");
    let mut row = runtime
        .store
        .db
        .raw_get_cf(&cf, &altered.0)
        .expect("the node row reads")
        .expect("the predecessor is retained");
    // The row starts with a four-byte header length, then the header: version (4), previous
    // hash (32), merkle root (32), and commitment (32) precede the four-byte time.
    row[4 + 100] ^= 0x01;
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .put_raw(&mut batch, HEADER_NODE_BY_HASH, altered.0, &row)
        .expect("the altered row is addressable");
    runtime
        .store
        .db
        .write(batch)
        .expect("the fixture corruption is durable");

    assert!(matches!(
        runtime
            .store
            .validation_context(parent.hash, engine_config.network()),
        Err(StoreError::Incoherent("durable header-chain read failed"))
    ));
}

/// Rewrites the stored node row of `hash` with `rewrite`, durably.
fn rewrite_node_row(
    runtime: &HeaderChainRuntime,
    hash: block::Hash,
    rewrite: impl FnOnce(&mut Vec<u8>),
) {
    let cf = runtime
        .store
        .cf(HEADER_NODE_BY_HASH)
        .expect("the node column family exists");
    let mut row = runtime
        .store
        .db
        .raw_get_cf(&cf, &hash.0)
        .expect("the node row reads")
        .expect("the node is retained");
    rewrite(&mut row);
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .put_raw(&mut batch, HEADER_NODE_BY_HASH, hash.0, &row)
        .expect("the row is addressable");
    runtime
        .store
        .db
        .write(batch)
        .expect("the fixture corruption is durable");
}

#[test]
fn validation_context_rejects_truncated_and_hash_flipped_predecessor_rows() {
    use zakura_chain::serialization::ZcashSerialize;

    for corruption in ["truncated", "stored hash flipped"] {
        let (runtime, path, network) = hashed_evidence_fixture();
        let parent = path.last().expect("the fixture path is nonempty").hash;
        let corrupted = path[path.len() - 5].hash;
        rewrite_node_row(&runtime, corrupted, |row| {
            let (node, _) = HeaderNodeDisk::decode_hashed(row).expect("the stored row decodes");
            let header_len = node
                .header
                .zcash_serialize_to_vec()
                .expect("a decoded header serializes")
                .len();
            match corruption {
                // Cut the row inside the stored hash that follows the header.
                "truncated" => row.truncate(4 + header_len + 16),
                // The row is a four-byte length, the header, then the redundant stored hash.
                _ => row[4 + header_len] ^= 0x01,
            }
        });

        assert!(
            matches!(
                runtime.store.validation_context(parent, &network),
                Err(StoreError::Incoherent("durable header-chain read failed"))
            ),
            "{corruption} row must fail the integrity-checking decode"
        );
    }
}

#[test]
fn validation_context_rejects_rows_with_tampered_parent_or_work_fields() {
    use crate::service::finalized_state::disk_format::FallibleDiskValue;

    for field in ["parent_hash", "block_work"] {
        let (runtime, path, network) = hashed_evidence_fixture();
        let parent = path.last().expect("the fixture path is nonempty").hash;
        let tampered = path[path.len() - 5].hash;
        // Re-encode a well-formed row: the header bytes and stored hash stay consistent, so
        // only the hashed-header node construction can notice the contradicted field.
        rewrite_node_row(&runtime, tampered, |row| {
            let (mut node, _) = HeaderNodeDisk::decode_hashed(row).expect("the stored row decodes");
            match field {
                "parent_hash" => node.parent_hash.0[0] ^= 0x01,
                // Valid headers have nonzero work, so doubling it changes the field.
                _ => node.block_work <<= 1,
            }
            *row = node.encode().expect("a tampered field still encodes");
        });

        assert!(
            matches!(
                runtime.store.validation_context(parent, &network),
                Err(StoreError::Incoherent("invalid durable node"))
            ),
            "a row with a tampered {field} must be rejected"
        );
    }
}

#[test]
fn validation_context_notices_corruption_written_between_two_builds() {
    let (runtime, path, network) = hashed_evidence_fixture();
    let parent = path.last().expect("the fixture path is nonempty").hash;
    runtime
        .store
        .validation_context(parent, &network)
        .expect("the uncorrupted context is coherent");

    // A later build must read the row again rather than reuse anything from the first build.
    rewrite_node_row(&runtime, path[path.len() - 5].hash, |row| {
        row[4 + 100] ^= 0x01;
    });
    assert!(matches!(
        runtime.store.validation_context(parent, &network),
        Err(StoreError::Incoherent("durable header-chain read failed"))
    ));
}

fn hashed_evidence_fixture() -> (HeaderChainRuntime, Vec<VerifiedHeaderRef>, Network) {
    let path_len = u8::try_from(zakura_header_chain::MAX_POW_PREDECESSOR_CONTEXT_SPAN + 6)
        .expect("the predecessor span fixture is shorter than 256");
    let (runtime, _, _, path) = reconciled_store_with_finalized_prefix(u32::from(path_len));
    let (engine_config, _, _) = fixture();
    (runtime, path, engine_config.network().clone())
}

#[test]
fn repeated_validation_contexts_reread_every_row_and_build_identical_leases() {
    let (runtime, path, network) = hashed_evidence_fixture();
    let parent = path.last().expect("the fixture path is nonempty").hash;

    HeaderChainStore::reset_header_node_disk_reads();
    let first = runtime
        .store
        .validation_context(parent, &network)
        .expect("coherent");
    let first_reads = HeaderChainStore::header_node_disk_reads();
    HeaderChainStore::reset_header_node_disk_reads();
    let second = runtime
        .store
        .validation_context(parent, &network)
        .expect("coherent");
    let second_reads = HeaderChainStore::header_node_disk_reads();

    assert_eq!(first, second);
    // The parent is read by the build and again by the context walk, then one read per
    // predecessor: no row is served from an earlier build.
    let expected = u64::try_from(zakura_header_chain::MAX_POW_PREDECESSOR_CONTEXT_SPAN + 2)
        .expect("the span fits in u64");
    assert_eq!(first_reads, expected);
    assert_eq!(second_reads, expected);
}

#[test]
fn validation_context_rejects_a_missing_predecessor_row() {
    let (runtime, path, network) = hashed_evidence_fixture();
    let parent = path.last().expect("the fixture path is nonempty").hash;
    let missing = path[path.len() - 5].hash;
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .delete_raw(&mut batch, HEADER_NODE_BY_HASH, missing.0)
        .expect("the node row is addressable");
    runtime
        .store
        .db
        .write(batch)
        .expect("the deletion is durable");

    assert!(matches!(
        runtime.store.validation_context(parent, &network),
        Err(StoreError::Incoherent("validation context has a gap"))
    ));
}

#[test]
fn validation_context_rejects_a_valid_row_stored_under_another_hash() {
    let (runtime, path, network) = hashed_evidence_fixture();
    let parent = path.last().expect("the fixture path is nonempty").hash;
    let replaced = path[path.len() - 5].hash;
    let other = path[path.len() - 6].hash;
    let cf = runtime
        .store
        .cf(HEADER_NODE_BY_HASH)
        .expect("the node column family exists");
    let other_row = runtime
        .store
        .db
        .raw_get_cf(&cf, &other.0)
        .expect("the node row reads")
        .expect("the other predecessor is retained");
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .put_raw(&mut batch, HEADER_NODE_BY_HASH, replaced.0, &other_row)
        .expect("the row is addressable");
    runtime
        .store
        .db
        .write(batch)
        .expect("the replacement is durable");

    assert!(matches!(
        runtime.store.validation_context(parent, &network),
        Err(StoreError::Incoherent("node key/hash mismatch"))
    ));
}

#[test]
fn header_evidence_from_another_row_is_not_used() {
    let (runtime, path, _) = hashed_evidence_fixture();
    let cf = runtime
        .store
        .cf(HEADER_NODE_BY_HASH)
        .expect("the node column family exists");
    let raw = |hash: block::Hash| {
        runtime
            .store
            .db
            .raw_get_cf(&cf, &hash.0)
            .expect("the node row reads")
            .expect("the node is retained")
    };
    let a = path[path.len() - 2].hash;
    let b = path[path.len() - 3].hash;
    let (row_a, evidence_a) = HeaderNodeDisk::decode_hashed(&raw(a)).expect("row a decodes");
    let (_, evidence_b) = HeaderNodeDisk::decode_hashed(&raw(b)).expect("row b decodes");
    assert_eq!(evidence_a.hash(), a);
    assert_eq!(evidence_b.hash(), b);

    let expected = row_a
        .clone()
        .into_domain(Vec::new())
        .expect("row a is coherent");
    let with_foreign = row_a
        .clone()
        .into_domain_hashed(evidence_b, Vec::new())
        .expect("foreign evidence is ignored and row a is re-hashed");
    let with_own = row_a
        .into_domain_hashed(evidence_a, Vec::new())
        .expect("row a is coherent");
    assert_eq!(with_foreign, expected);
    assert_eq!(with_own, expected);
    assert_eq!(expected.hash, a);

    // Evidence for an equal header in a different allocation is not used either.
    let (mut row_copy, evidence_copy) =
        HeaderNodeDisk::decode_hashed(&raw(a)).expect("row a decodes");
    row_copy.header = Arc::new(*row_copy.header);
    assert!(!Arc::ptr_eq(evidence_copy.header(), &row_copy.header));
    assert_eq!(
        row_copy
            .into_domain_hashed(evidence_copy, Vec::new())
            .expect("row a is coherent"),
        expected
    );
}

/// Replace one retained predecessor's node row with a `HEADER_VALIDATION_CONTEXT` row.
fn replace_node_with_context_row(
    runtime: &HeaderChainRuntime,
    target: &VerifiedHeaderRef,
    context: HeaderValidationContextDisk,
) {
    let mut batch = DiskWriteBatch::new();
    runtime
        .store
        .delete_raw(&mut batch, HEADER_NODE_BY_HASH, target.hash.0)
        .expect("the node row is addressable");
    runtime
        .store
        .put_value(
            &mut batch,
            HEADER_VALIDATION_CONTEXT,
            target.hash.0,
            &context,
        )
        .expect("the context row encodes");
    runtime
        .store
        .db
        .write(batch)
        .expect("the replacement is durable");
}

#[test]
fn validation_context_fallback_rows_build_the_same_lease_and_reject_tampering() {
    let (runtime, path, network) = hashed_evidence_fixture();
    let parent = path.last().expect("the fixture path is nonempty").hash;
    let target = path[path.len() - 5].clone();
    let original = runtime
        .store
        .validation_context(parent, &network)
        .expect("coherent");

    // A coherent fallback row builds exactly the same lease.
    replace_node_with_context_row(
        &runtime,
        &target,
        HeaderValidationContextDisk {
            header: target.header.clone(),
            height: target.height,
        },
    );
    assert_eq!(
        runtime
            .store
            .validation_context(parent, &network)
            .expect("coherent"),
        original
    );

    // A wrong height is rejected.
    replace_node_with_context_row(
        &runtime,
        &target,
        HeaderValidationContextDisk {
            header: target.header.clone(),
            height: target
                .height
                .next()
                .expect("the fixture height has a successor"),
        },
    );
    assert!(matches!(
        runtime.store.validation_context(parent, &network),
        Err(StoreError::Incoherent(
            "invalid immutable validation context"
        ))
    ));

    // Different header bytes under the same key are rejected.
    let mut altered = *target.header;
    altered.time += chrono::Duration::seconds(1);
    replace_node_with_context_row(
        &runtime,
        &target,
        HeaderValidationContextDisk {
            header: Arc::new(altered),
            height: target.height,
        },
    );
    assert!(matches!(
        runtime.store.validation_context(parent, &network),
        Err(StoreError::Incoherent(
            "invalid immutable validation context"
        ))
    ));
}