zakura-network 2.0.0

Networking code for the Zakura node. Internal crate, published to support cargo install zakura
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
use std::{collections::HashMap, future};

use proptest::{prop_assert, prop_assert_eq};

use super::*;
use super::{
    config::{
        BS_CHECKPOINT_RANGE_BYTE_FLOOR, BS_PER_BLOCK_WORST_CASE_BYTES,
        DEFAULT_BS_BBR_RELIABILITY_WEIGHT_PERCENT, DEFAULT_BS_FLOOR_PEER_AVOID_COOLDOWN,
        DEFAULT_BS_INITIAL_BLOCK_PROBE_REQUESTS, DEFAULT_BS_MAX_INFLIGHT_BLOCK_BYTES,
        DEFAULT_BS_MAX_REORDER_LOOKAHEAD_BYTES, DEFAULT_BS_MAX_REQUESTS_WITHOUT_BLOCK_PROGRESS,
        DEFAULT_BS_MAX_RESPONSE_BYTES, DEFAULT_BS_NO_PROGRESS_PEER_COOLDOWN,
        DEFAULT_BS_REQUEST_TIMEOUT, MAX_BS_INFLIGHT_REQUESTS, MAX_BS_RESPONSE_BYTES,
        MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES,
    },
    reactor::node_id_from_block_peer_id,
    reorder::*,
    request::*,
    sequencer::*,
    sequencer_task::{initial_view, SequencedBody, SequencerControlInput, SequencerTask},
    state::*,
    work_queue::WorkQueue,
};
use crate::zakura::{
    framed_channel,
    testkit::{TraceCapture, TraceValue},
    ChainFrontier, FramedRecv, FramedSend, Frontier, FrontierChange, FrontierUpdate, Peer, Service,
    ServicePeerSnapshot, ServiceRegistry, StreamMode, ZakuraBlockSyncCandidateState,
    ZakuraSyncExchange,
};
use zakura_chain::{
    fmt::HexDebug,
    serialization::{ZcashDeserializeInto, ZcashSerialize},
    transaction::Transaction,
    transparent,
};
use zakura_test::vectors::{BLOCK_MAINNET_1_BYTES, BLOCK_MAINNET_2_BYTES, BLOCK_MAINNET_3_BYTES};

fn peer(byte: u8) -> ZakuraPeerId {
    ZakuraPeerId::new(vec![byte; 32]).expect("test peer id is within bounds")
}

fn mainnet_block(bytes: &[u8]) -> Arc<block::Block> {
    Arc::new(bytes.zcash_deserialize_into().expect("block vector parses"))
}

fn mainnet_blocks_1_to_3() -> Vec<Arc<block::Block>> {
    vec![
        mainnet_block(&BLOCK_MAINNET_1_BYTES),
        mainnet_block(&BLOCK_MAINNET_2_BYTES),
        mainnet_block(&BLOCK_MAINNET_3_BYTES),
    ]
}

fn raw_block_payload(block: &Arc<block::Block>) -> Arc<[u8]> {
    let frame = BlockSyncMessage::Block(block.clone())
        .encode_frame()
        .expect("test block frame encodes");

    Arc::from(frame.payload.into_boxed_slice())
}

fn forked_block(block: &Arc<block::Block>, nonce_tag: u8) -> Arc<block::Block> {
    let mut fork = block.as_ref().clone();
    let mut header = *fork.header;
    header.nonce = HexDebug([nonce_tag; 32]);
    fork.header = Arc::new(header);
    Arc::new(fork)
}

fn block_with_bad_merkle_root(
    block: &Arc<block::Block>,
    extra_tx: &Arc<block::Block>,
) -> Arc<block::Block> {
    let mut bad_block = block.as_ref().clone();
    bad_block
        .transactions
        .push(extra_tx.transactions[0].clone());

    assert_eq!(bad_block.hash(), block.hash());
    assert_eq!(bad_block.coinbase_height(), block.coinbase_height());
    assert_ne!(
        bad_block
            .transactions
            .iter()
            .collect::<block::merkle::Root>(),
        bad_block.header.merkle_root
    );

    Arc::new(bad_block)
}

/// Build `count` internally-consistent blocks at the sequential heights
/// `1..=count`.
///
/// Each block is mainnet block 1 with its coinbase height rewritten and its
/// header merkle root recomputed, so it has a distinct hash and a header that
/// commits to its transactions. The real test vectors
/// only cover a handful of contiguous heights, which is too few to flood the
/// per-peer wire queue, so the body-flood test synthesizes its own chain.
fn fake_sequential_blocks(count: u32) -> Vec<Arc<block::Block>> {
    let template = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    (1..=count)
        .map(|height| fake_block_at_height(&template, block::Height(height)))
        .collect()
}

fn fake_blocks_in_range(start: u32, end: u32) -> Vec<Arc<block::Block>> {
    let template = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    (start..=end)
        .map(|height| fake_block_at_height(&template, block::Height(height)))
        .collect()
}

fn fake_block_at_height(template: &Arc<block::Block>, height: block::Height) -> Arc<block::Block> {
    let mut block = template.as_ref().clone();

    let mut coinbase = block.transactions[0].clone();
    let input = match Arc::make_mut(&mut coinbase) {
        Transaction::V1 { inputs, .. }
        | Transaction::V2 { inputs, .. }
        | Transaction::V3 { inputs, .. }
        | Transaction::V4 { inputs, .. }
        | Transaction::V5 { inputs, .. } => &mut inputs[0],
        Transaction::V6 { inputs, .. } => &mut inputs[0],
    };
    match input {
        transparent::Input::Coinbase {
            height: coinbase_height,
            ..
        } => *coinbase_height = height,
        _ => panic!("template block must start with a coinbase input"),
    }
    block.transactions[0] = coinbase;

    // Rewriting the coinbase changes the merkle root, so recompute it to keep the
    // synthesized block internally consistent (its header commits to its txs).
    let merkle_root = block.transactions.iter().collect::<block::merkle::Root>();
    let mut header = *block.header;
    header.merkle_root = merkle_root;
    block.header = Arc::new(header);

    Arc::new(block)
}

fn block_size(block: &block::Block) -> u32 {
    u32::try_from(
        block
            .zcash_serialize_to_vec()
            .expect("test block serializes")
            .len(),
    )
    .expect("test block size fits u32")
}

fn status() -> BlockSyncStatus {
    BlockSyncStatus {
        servable_low: block::Height(1),
        servable_high: block::Height(42),
        tip_hash: block::Hash([7; 32]),
        max_blocks_per_response: 16,
        max_inflight_requests: 4,
        max_response_bytes: MAX_BS_RESPONSE_BYTES,
    }
}

fn immediate_body_download_config() -> ZakuraBlockSyncConfig {
    ZakuraBlockSyncConfig {
        max_blocks_per_response: MAX_BS_BLOCKS_PER_REQUEST,
        ..ZakuraBlockSyncConfig::default()
    }
}

/// Config for tests that exercise fill-loop, budget-rotation and retry mechanics on
/// freshly-connected peers, where the one-probe cold start (`initial_block_probe_requests`)
/// is orthogonal noise: it would throttle a fresh peer to a single request before it has
/// delivered a body. Opening the probe cap to the proven budget lets these tests drive a
/// peer's full advertised window immediately. Probe-first behaviour has dedicated coverage.
fn fill_loop_mechanics_config() -> ZakuraBlockSyncConfig {
    ZakuraBlockSyncConfig {
        initial_block_probe_requests: DEFAULT_BS_MAX_REQUESTS_WITHOUT_BLOCK_PROGRESS,
        ..immediate_body_download_config()
    }
}

fn test_frontier(height: u32) -> Frontier {
    let hash_byte = u8::try_from(height % 251).expect("height modulo 251 fits in u8");
    Frontier::new(block::Height(height), block::Hash([hash_byte; 32]))
}

fn test_frontier_update(
    finalized: u32,
    verified_body: u32,
    best_header: u32,
    change: FrontierChange,
) -> FrontierUpdate {
    FrontierUpdate {
        frontier: ChainFrontier {
            finalized: test_frontier(finalized),
            verified_body: test_frontier(verified_body),
            best_header: test_frontier(best_header),
        },
        change,
    }
}

fn exchange_block_sync_startup(
    initial: FrontierUpdate,
    config: ZakuraBlockSyncConfig,
) -> (ZakuraSyncExchange, BlockSyncStartup) {
    let exchange = ZakuraSyncExchange::new(initial, ZakuraTrace::noop());
    let frontier = initial.frontier;
    let startup = BlockSyncStartup::new_with_exchange(
        BlockSyncFrontiers {
            finalized_height: frontier.finalized.height,
            verified_block_tip: frontier.verified_body.height,
            verified_block_hash: frontier.verified_body.hash,
        },
        (frontier.best_header.height, frontier.best_header.hash),
        exchange.subscribe_frontier(),
        config,
    );

    (exchange, startup)
}

fn round_trip(message: BlockSyncMessage) {
    let encoded = message.encode().expect("message encodes");
    let decoded = BlockSyncMessage::decode(&encoded).expect("message decodes");

    assert_eq!(decoded, message);
}

async fn next_event(events: &mut mpsc::Receiver<BlockSyncEvent>) -> BlockSyncEvent {
    tokio::time::timeout(Duration::from_secs(1), events.recv())
        .await
        .expect("block-sync event should arrive")
        .expect("block-sync event channel should stay open")
}

async fn next_action(actions: &mut mpsc::Receiver<BlockSyncAction>) -> BlockSyncAction {
    tokio::time::timeout(Duration::from_secs(1), actions.recv())
        .await
        .expect("block-sync action should arrive")
        .expect("block-sync action channel should stay open")
}

async fn wait_for_query_needed_blocks(
    actions: &mut mpsc::Receiver<BlockSyncAction>,
    verified_block_tip: block::Height,
    best_header_tip: block::Height,
) {
    let expected_from = verified_block_tip.next().unwrap_or(verified_block_tip);
    loop {
        match next_action(actions).await {
            BlockSyncAction::QueryNeededBlocks {
                from,
                best_header_tip: actual_best,
                ..
            } if from == expected_from && actual_best == best_header_tip => return,
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before target QueryNeededBlocks: {action:?}"),
        }
    }
}

/// Push one decoded stream-6 message to a peer's inbound stream as a real frame.
///
/// The inbound data flow is inverted: a peer's frames are decoded and dispatched
/// by its per-peer pipe-routine, not the reactor. Tests that previously injected a
/// `BlockSyncEvent::WireMessage{peer,msg}` shortcut now push the encoded frame onto
/// the peer's `inbound_tx` (the same `FramedSend` `connect_peer_with_status`
/// returns), exactly as the real transport would deliver it.
async fn send_inbound(inbound_tx: &FramedSend, msg: BlockSyncMessage) {
    inbound_tx
        .send(msg.encode_frame().expect("message encodes"))
        .await
        .expect("inbound frame queues onto the peer stream");
}

async fn next_outbound_message(outbound: &mut FramedRecv) -> BlockSyncMessage {
    let frame = tokio::time::timeout(Duration::from_secs(1), outbound.recv())
        .await
        .expect("outbound frame arrives")
        .expect("outbound channel is live");
    BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
}

async fn wait_for_outbound_block(outbound: &mut FramedRecv) -> Arc<block::Block> {
    loop {
        match next_outbound_message(outbound).await {
            BlockSyncMessage::Block(block) => return block,
            BlockSyncMessage::Status(_) | BlockSyncMessage::GetBlocks { .. } => {}
            msg => panic!("unexpected outbound message before block: {msg:?}"),
        }
    }
}

async fn wait_for_outbound_blocks_done(outbound: &mut FramedRecv) -> (block::Height, u32) {
    loop {
        match next_outbound_message(outbound).await {
            BlockSyncMessage::BlocksDone {
                start_height,
                returned,
            } => return (start_height, returned),
            BlockSyncMessage::Status(_) | BlockSyncMessage::GetBlocks { .. } => {}
            msg => panic!("unexpected outbound message before BlocksDone: {msg:?}"),
        }
    }
}

async fn wait_for_outbound_range_unavailable(outbound: &mut FramedRecv) -> (block::Height, u32) {
    loop {
        match next_outbound_message(outbound).await {
            BlockSyncMessage::RangeUnavailable {
                start_height,
                count,
            } => return (start_height, count),
            BlockSyncMessage::Status(_) | BlockSyncMessage::GetBlocks { .. } => {}
            msg => panic!("unexpected outbound message before RangeUnavailable: {msg:?}"),
        }
    }
}

/// Read this peer's real outbound until the node sends it a `GetBlocks`, returning
/// the requested range. The peer is implicit in `outbound` (the node→peer stream
/// the routine writes its real `try_send_get_blocks` to), so unlike the old
/// mirror-based `wait_for_getblocks` there is no `peer` to return: a test that
/// needs to assert *which* peer was asked reads that peer's own `outbound`. Skips
/// `Status` frames, which interleave with requests as status refreshes.
async fn wait_for_outbound_getblocks(outbound: &mut FramedRecv) -> (block::Height, u32) {
    loop {
        match next_outbound_message(outbound).await {
            BlockSyncMessage::GetBlocks {
                start_height,
                count,
            } => return (start_height, count),
            BlockSyncMessage::Status(_) => {}
            msg => panic!("unexpected outbound message before GetBlocks: {msg:?}"),
        }
    }
}

/// Wait for the node's `Status` advertisement on this peer's real outbound — the
/// connect status the reactor sends on `PeerConnected`, and later refreshes.
/// Replaces the mirror-based `wait_for_connect_status`; the peer is implicit in
/// `outbound`, and the advertised status is returned for tests that assert on it.
async fn wait_for_outbound_status(outbound: &mut FramedRecv) -> BlockSyncStatus {
    match next_outbound_message(outbound).await {
        BlockSyncMessage::Status(status) => status,
        msg => panic!("unexpected outbound message before Status: {msg:?}"),
    }
}

/// Multi-peer replacement for the old mirror-based `wait_for_getblocks` in tests
/// where work assignment between peers is nondeterministic. The previous mirror
/// serialized every peer's outbound on one global `actions` channel and returned
/// which peer was asked; now the only real signal is each peer's own outbound
/// `FramedRecv`, so we `select!` across all of them and return the `(peer, start,
/// count)` of whichever peer the routine actually sent a `GetBlocks` to. Skips
/// `Status` frames (status refreshes interleave with requests). `peers` pairs each
/// peer id with its own outbound; the returned peer is the one whose stream the
/// `GetBlocks` arrived on, so peer-targeting is still proven against the real wire.
async fn wait_for_getblocks_across(
    peers: &mut [(ZakuraPeerId, &mut FramedRecv)],
) -> (ZakuraPeerId, block::Height, u32) {
    use futures::stream::{FuturesUnordered, StreamExt};
    loop {
        let (peer_id, frame) = {
            let mut recvs: FuturesUnordered<_> = peers
                .iter_mut()
                .map(|(peer_id, outbound)| {
                    let peer_id = peer_id.clone();
                    async move {
                        let frame = outbound.recv().await.expect("outbound channel is live");
                        (peer_id, frame)
                    }
                })
                .collect();
            tokio::time::timeout(Duration::from_secs(1), recvs.next())
                .await
                .expect("an outbound frame arrives on some peer")
                .expect("at least one peer outbound is live")
        };
        match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
            BlockSyncMessage::GetBlocks {
                start_height,
                count,
            } => return (peer_id, start_height, count),
            BlockSyncMessage::Status(_) => {}
            msg => panic!("unexpected outbound message before GetBlocks: {msg:?}"),
        }
    }
}

async fn drain_parent_first_actions(
    actions: &mut mpsc::Receiver<BlockSyncAction>,
    verified_tip: &mut block::Height,
    expected_new_fork: Option<&[Arc<block::Block>]>,
) {
    while let Ok(Some(action)) =
        tokio::time::timeout(Duration::from_millis(25), actions.recv()).await
    {
        match action {
            BlockSyncAction::SubmitBlock { block, .. } => {
                let height = block
                    .coinbase_height()
                    .expect("submitted test block has height");
                assert_eq!(
                    Some(height),
                    next_height(*verified_tip),
                    "block sync must submit only the contiguous parent-first prefix"
                );
                if let Some(new_fork) = expected_new_fork {
                    let expected_hash = match height.0 {
                        2 => new_fork[1].hash(),
                        3 => new_fork[2].hash(),
                        _ => panic!("unexpected post-reset submitted height: {height:?}"),
                    };
                    assert_eq!(
                        block.hash(),
                        expected_hash,
                        "post-reset submissions must follow the re-derived fork"
                    );
                }
                *verified_tip = height;
            }
            BlockSyncAction::Misbehavior {
                reason: BlockSyncMisbehavior::InvalidBlock | BlockSyncMisbehavior::UnsolicitedBlock,
                ..
            } => {}
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action while draining body responses: {action:?}"),
        }
    }
}

/// Build a `DownloadWindow` (the per-peer adaptive outbound window that per-peer routines moved
/// off `PeerBlockState` into the spawned `PeerRoutine`). The window math is the
/// same the routine drives; these unit tests pin it in isolation.
fn download_window() -> DownloadWindow {
    DownloadWindow::new(&ZakuraBlockSyncConfig::default())
}

fn test_delivery_snapshot(now: Instant) -> DeliverySnapshot {
    DeliverySnapshot {
        delivered: 0,
        delivered_at: now,
    }
}

fn window_request(height: u32) -> OutstandingBlockRange {
    let byte = u8::try_from(height).expect("test heights fit in u8");
    let now = Instant::now();
    OutstandingBlockRange {
        request: BlockRangeRequest {
            start_height: block::Height(height),
            count: 1,
            anchor_hash: block::Hash([byte; 32]),
            estimated_bytes: 1,
            expected_blocks: vec![ExpectedBlock {
                height: block::Height(height),
                hash: block::Hash([byte; 32]),
                estimated_bytes: 1,
            }],
        },
        queued_at: now,
        deadline: now,
        delivery_snapshot: test_delivery_snapshot(now),
        delivered_bytes: 0,
        received: ReceivedBlockTracker::default(),
    }
}

fn window_request_range(start: u32, count: u32) -> OutstandingBlockRange {
    let byte = u8::try_from(start).expect("test heights fit in u8");
    let now = Instant::now();
    OutstandingBlockRange {
        request: BlockRangeRequest {
            start_height: block::Height(start),
            count,
            anchor_hash: block::Hash([byte; 32]),
            estimated_bytes: u64::from(count),
            expected_blocks: (start..start + count)
                .map(|height| ExpectedBlock {
                    height: block::Height(height),
                    hash: block::Hash([u8::try_from(height).expect("test heights fit in u8"); 32]),
                    estimated_bytes: 1,
                })
                .collect(),
        },
        queued_at: now,
        deadline: now,
        delivery_snapshot: test_delivery_snapshot(now),
        delivered_bytes: 0,
        received: ReceivedBlockTracker::default(),
    }
}

#[test]
fn block_liveness_disconnects_silent_active_peer_after_default_timeout() {
    let config = ZakuraBlockSyncConfig::default();
    let timeout = config.effective_liveness_timeout();
    assert_eq!(timeout, Duration::from_secs(32));

    let now = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);

    assert_eq!(
        window.check_liveness(now + timeout - Duration::from_millis(1)),
        LivenessOutcome::Ok
    );
    assert_eq!(
        window.check_liveness(now + timeout),
        LivenessOutcome::Disconnect
    );
}

/// The defensive `Disarm` arm in `check_liveness`: a block-liveness deadline that exists
/// with no recorded request (`last_request_at == None`) was never armed by `arm_liveness`,
/// so it is disarmed rather than treated as a disconnect. This state is unreachable in
/// production — every deadline setter runs after a request is sent — so the test sets the
/// deadline directly to exercise the arm.
#[test]
fn block_liveness_disarms_a_deadline_set_without_a_request() {
    let now = Instant::now();
    let mut window = download_window();

    assert_eq!(window.check_liveness(now), LivenessOutcome::Ok);

    window.block_liveness_deadline = Some(now);
    assert_eq!(window.check_liveness(now), LivenessOutcome::Disarm);
    window.clear_liveness_if_idle();
    assert_eq!(window.block_liveness_deadline, None);
    assert_eq!(window.check_liveness(now), LivenessOutcome::Ok);
}

/// The reliability EWMA is a per-request goodput fraction: a completed request credits one
/// success and a timed-out request charges one failure. A short response
/// (`BlocksDone`/`RangeUnavailable`) that leaves many heights unreceived must likewise be
/// ONE failure for the request — not one per missing height, which (once
/// `max_blocks_per_response > 1`) would near-seal a peer for a single protocol-legal short
/// answer. This asserts the charge is independent of the missing-height count.
#[test]
fn short_response_charges_one_reliability_failure_per_request_not_per_height() {
    let fresh = download_window().reliability_factor();

    let one_missing = {
        let mut window = download_window();
        window.penalize_short_response(1);
        window.reliability_factor()
    };
    let many_missing = {
        let mut window = download_window();
        window.penalize_short_response(64);
        window.reliability_factor()
    };

    assert!(
        one_missing < fresh,
        "a short response must lower reliability (one goodput failure)"
    );
    assert_eq!(
        one_missing, many_missing,
        "a short response is one failure per request, independent of the missing-height count"
    );
}

#[test]
fn block_liveness_progress_before_deadline_keeps_peer_alive() {
    let timeout = ZakuraBlockSyncConfig::default().effective_liveness_timeout();
    let mut now = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);

    for _ in 0..4 {
        now += timeout - Duration::from_millis(1);
        assert_eq!(window.check_liveness(now), LivenessOutcome::Ok);
        window.note_block_progress(now, timeout);
        assert_eq!(window.block_liveness_deadline, Some(now + timeout));
    }
}

#[test]
fn block_liveness_disconnects_silent_peer_after_outstanding_drains() {
    let timeout = ZakuraBlockSyncConfig::default().effective_liveness_timeout();
    let now = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);

    window.outstanding.clear();
    window.disarm_liveness_after_progress_if_idle();

    assert_eq!(window.block_liveness_deadline, Some(now + timeout));
    assert_eq!(
        window.check_liveness(now + timeout),
        LivenessOutcome::Disconnect
    );
}

#[test]
fn block_liveness_disarms_when_satisfied_request_drains() {
    let timeout = ZakuraBlockSyncConfig::default().effective_liveness_timeout();
    let now = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);
    window.note_block_progress(now + Duration::from_millis(1), timeout);
    window.outstanding.clear();
    window.disarm_liveness_after_progress_if_idle();

    assert_eq!(window.block_liveness_deadline, None);
    assert_eq!(window.check_liveness(now + timeout), LivenessOutcome::Ok);
}

#[test]
fn block_liveness_uses_probe_cap_until_first_accepted_body() {
    let config = ZakuraBlockSyncConfig {
        initial_block_probe_requests: 1,
        max_requests_without_block_progress: 8,
        ..ZakuraBlockSyncConfig::default()
    };
    let timeout = config.effective_liveness_timeout();
    let now = Instant::now();
    let mut window = DownloadWindow::new(&config);

    assert!(!window.has_block_progress());
    assert_eq!(window.no_progress_request_cap(), 1);

    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);

    assert_eq!(window.requests_without_block_progress, 1);
    assert_eq!(window.no_progress_request_cap(), 1);

    window.note_block_progress(now + Duration::from_millis(1), timeout);

    assert!(window.has_block_progress());
    assert_eq!(window.requests_without_block_progress, 0);
    assert_eq!(window.no_progress_request_cap(), 8);
}

#[test]
fn block_liveness_resuming_after_idle_gets_fresh_deadline() {
    let timeout = ZakuraBlockSyncConfig::default().effective_liveness_timeout();
    let now = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);
    window.note_block_progress(now + Duration::from_millis(1), timeout);
    window.outstanding.clear();
    window.disarm_liveness_after_progress_if_idle();

    let resumed = now + Duration::from_secs(60);
    window.outstanding.push(window_request(2));
    window.arm_liveness(resumed, timeout);

    assert_eq!(window.block_liveness_deadline, Some(resumed + timeout));
}

#[test]
fn block_liveness_multi_block_range_progress_resets_each_body() {
    let timeout = ZakuraBlockSyncConfig::default().effective_liveness_timeout();
    let start = Instant::now();
    let mut window = download_window();
    window.outstanding.push(window_request_range(1, 3));
    window.arm_liveness(start, timeout);

    let first = start + Duration::from_secs(4);
    window.note_block_progress(first, timeout);
    assert_eq!(window.block_liveness_deadline, Some(first + timeout));

    let second = first + Duration::from_secs(4);
    assert_eq!(window.check_liveness(second), LivenessOutcome::Ok);
    window.note_block_progress(second, timeout);
    assert_eq!(window.block_liveness_deadline, Some(second + timeout));

    let third = second + Duration::from_secs(4);
    assert_eq!(window.check_liveness(third), LivenessOutcome::Ok);
    window.note_block_progress(third, timeout);
    assert_eq!(window.block_liveness_deadline, Some(third + timeout));
}

#[test]
fn view_reset_reclears_probe_streak_so_unproven_peer_can_reprobe() {
    // Regression for the destructive-reset zombie: an unproven peer whose single
    // probe is in flight when a destructive view reset pulls its outstanding must
    // not stay pinned at the one-probe cap forever. Before the fix, `on_view_changed`
    // cleared the liveness deadline but left `requests_without_block_progress` at the
    // cap, so the peer could neither issue another request (want-work gated at
    // `streak >= cap`) nor ever be disconnected (deadline cleared) — a permanent
    // zombie holding a live connection.
    let config = ZakuraBlockSyncConfig {
        initial_block_probe_requests: 1,
        ..ZakuraBlockSyncConfig::default()
    };
    let timeout = config.effective_liveness_timeout();
    let now = Instant::now();
    let mut window = DownloadWindow::new(&config);

    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);
    assert_eq!(window.requests_without_block_progress, 1);
    assert_eq!(window.no_progress_request_cap(), 1);

    // A destructive reset returns the peer's outstanding to the queue on our
    // initiative, then runs the reset hook.
    window.outstanding.clear();
    window.note_view_reset();

    // The peer can probe again (streak below the cap) and is not left as a zombie
    // (liveness cleared, so `check_liveness` is `Ok`, and proof state is untouched).
    assert_eq!(window.requests_without_block_progress, 0);
    assert!(window.requests_without_block_progress < window.no_progress_request_cap());
    assert!(!window.has_block_progress());
    assert_eq!(
        window.check_liveness(now + timeout),
        LivenessOutcome::Ok,
        "a reset peer must not carry a phantom liveness deadline",
    );
}

#[test]
fn view_reset_preserves_proof_but_reclears_streak() {
    // A *proven* peer that is reset keeps its proof (cap stays at the proven value)
    // but its no-progress streak restarts, since the reset cancelled its in-flight
    // work on our side.
    let config = ZakuraBlockSyncConfig {
        initial_block_probe_requests: 1,
        max_requests_without_block_progress: 8,
        ..ZakuraBlockSyncConfig::default()
    };
    let timeout = config.effective_liveness_timeout();
    let now = Instant::now();
    let mut window = DownloadWindow::new(&config);

    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);
    window.note_block_progress(now + Duration::from_millis(1), timeout);
    // Prove, then issue further requests that go unanswered before the reset.
    window.outstanding.push(window_request(2));
    window.arm_liveness(now + Duration::from_millis(2), timeout);
    assert!(window.has_block_progress());
    assert_eq!(window.no_progress_request_cap(), 8);

    window.outstanding.clear();
    window.note_view_reset();

    assert_eq!(window.requests_without_block_progress, 0);
    assert!(
        window.has_block_progress(),
        "reset must not un-prove a peer"
    );
    assert_eq!(window.no_progress_request_cap(), 8);
}

#[test]
fn backpressure_extends_liveness_instead_of_disconnecting() {
    // Regression for the outbound-backpressure false disconnect: when the routine's
    // outbound queue is full it stops draining inbound, so a would-be liveness
    // disconnect is attributable to our own write-side congestion, not the peer.
    // The routine extends the deadline via `extend_liveness_deadline` in that case;
    // this pins the window mechanism that makes the extension turn a `Disconnect`
    // back into `Ok`, while still enforcing the cap once the congestion clears.
    let config = ZakuraBlockSyncConfig::default();
    let timeout = config.effective_liveness_timeout();
    let now = Instant::now();
    let mut window = download_window();

    window.outstanding.push(window_request(1));
    window.arm_liveness(now, timeout);
    assert_eq!(
        window.check_liveness(now + timeout),
        LivenessOutcome::Disconnect,
        "the deadline has expired: without backpressure this disconnects",
    );

    // Under local backpressure the routine extends instead of disconnecting.
    let extended_at = now + timeout;
    window.extend_liveness_deadline(extended_at, timeout);
    assert_eq!(window.check_liveness(extended_at), LivenessOutcome::Ok);

    // The extension is bounded: once it too expires (congestion did not clear and no
    // body arrived), the peer is still disconnected.
    assert_eq!(
        window.check_liveness(extended_at + timeout),
        LivenessOutcome::Disconnect,
    );
}

// The old `BlockRangeScheduler` single-pass timeout-retry bias
// (`scheduler_retry_after_timeout_*`) is removed: the WorkQueue has no
// per-peer assignment to bias, so a returned height is simply contestable by any
// servable peer. The peer-local timeout bias is re-introduced in per-peer routines. The
// reactor-level locality property is still covered by
// `reactor_timeout_recovery_is_local_and_healthy_peer_keeps_filling`.
#[test]
fn work_queue_returned_height_is_contestable_by_any_peer() {
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);

    // A peer takes the floor height (it leaves `pending` → `in_flight`).
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(queue.in_flight_contains(block::Height(1)));
    assert!(!queue.pending_contains(block::Height(1)));

    // Its request times out: the height returns to `pending`, where any servable
    // peer (not just the original holder) can take it again. No bias toward or
    // away from any particular peer exists in WorkQueue.
    queue.return_items([block::Height(1)]);
    assert!(queue.pending_contains(block::Height(1)));
    assert_eq!(
        queue
            .take_in_range(block::Height(1), block::Height(1), 1)
            .len(),
        1,
        "a returned height must be immediately re-takable"
    );
}

async fn connect_peer_with_status(
    service: &BlockSyncService,
    actions: &mut mpsc::Receiver<BlockSyncAction>,
    byte: u8,
    servable_high: block::Height,
    tip_hash: block::Hash,
    max_inflight_requests: u32,
    max_response_bytes: u32,
) -> (ZakuraPeerId, FramedSend, FramedRecv) {
    connect_peer_with_status_message(
        service,
        actions,
        byte,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high,
            tip_hash,
            max_blocks_per_response: 16,
            max_inflight_requests,
            max_response_bytes,
        },
    )
    .await
}

async fn connect_peer_with_status_message(
    service: &BlockSyncService,
    actions: &mut mpsc::Receiver<BlockSyncAction>,
    byte: u8,
    status: BlockSyncStatus,
) -> (ZakuraPeerId, FramedSend, FramedRecv) {
    let peer = peer(byte);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    // Read the connect-status the reactor sends on `PeerConnected` off this peer's
    // own real outbound (reading the peer's own stream proves targeting). The
    // `actions` channel is still passed through for callers that drain it.
    let _ = actions;
    wait_for_outbound_status(&mut outbound_rx).await;
    inbound_tx
        .send(
            BlockSyncMessage::Status(status)
                .encode_frame()
                .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    (peer, inbound_tx, outbound_rx)
}

fn needed(height: u32, size: BlockSizeEstimate) -> (block::Height, block::Hash, BlockSizeEstimate) {
    (block::Height(height), block::Hash([height as u8; 32]), size)
}

/// Build a fresh `WorkQueue` seeded above-floor with the given needed items, for
/// the WorkQueue unit tests that replaced the old `BlockRangeScheduler` tests.
fn work_queue_with(
    floor: u32,
    items: impl IntoIterator<Item = (block::Height, block::Hash, BlockSizeEstimate)>,
) -> super::work_queue::WorkQueue {
    let queue = super::work_queue::WorkQueue::new(block::Height(floor));
    queue.set_estimate_floor_for_tests(1);
    queue.extend(items);
    queue
}

fn block_meta(block: &Arc<block::Block>) -> BlockSyncBlockMeta {
    BlockSyncBlockMeta {
        height: block.coinbase_height().expect("test block has height"),
        hash: block.hash(),
        size: BlockSizeEstimate::Advertised(block_size(block)),
    }
}

#[test]
fn block_sync_config_defaults_and_round_trips() {
    let default = ZakuraBlockSyncConfig::default();
    assert_eq!(default.max_blocks_per_response, 1);
    assert_eq!(default.max_inflight_requests, 32000);
    assert_eq!(
        default.max_inflight_block_bytes,
        DEFAULT_BS_MAX_INFLIGHT_BLOCK_BYTES
    );
    assert_eq!(
        default.max_reorder_lookahead_bytes,
        DEFAULT_BS_MAX_REORDER_LOOKAHEAD_BYTES
    );
    assert_eq!(
        default.floor_peer_avoid_cooldown,
        DEFAULT_BS_FLOOR_PEER_AVOID_COOLDOWN
    );
    assert_eq!(
        default.no_progress_peer_cooldown,
        DEFAULT_BS_NO_PROGRESS_PEER_COOLDOWN
    );
    assert_eq!(
        default.initial_block_probe_requests,
        DEFAULT_BS_INITIAL_BLOCK_PROBE_REQUESTS,
    );
    assert_eq!(
        default.max_requests_without_block_progress,
        DEFAULT_BS_MAX_REQUESTS_WITHOUT_BLOCK_PROGRESS,
    );
    assert_eq!(
        default.bbr_reliability_weight_percent,
        DEFAULT_BS_BBR_RELIABILITY_WEIGHT_PERCENT,
    );
    assert_eq!(
        default.effective_max_reorder_lookahead_bytes(),
        DEFAULT_BS_MAX_REORDER_LOOKAHEAD_BYTES
    );
    assert_eq!(
        default.floor_request_byte_reservation(),
        u64::from(DEFAULT_BS_MAX_RESPONSE_BYTES)
    );
    assert_eq!(
        default.effective_floor_peer_avoid_cooldown(),
        DEFAULT_BS_FLOOR_PEER_AVOID_COOLDOWN
    );
    assert_eq!(
        default.effective_no_progress_peer_cooldown(),
        DEFAULT_BS_NO_PROGRESS_PEER_COOLDOWN
    );
    assert!(default.validate().is_ok());
    assert_eq!(
        default.max_submitted_block_applies,
        MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES
    );
    assert_eq!(
        default.submitted_apply_limit(),
        MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES
    );
    assert_eq!(default.request_timeout, DEFAULT_BS_REQUEST_TIMEOUT);

    let encoded = toml::to_string(&default).expect("block-sync config serializes");
    let decoded: ZakuraBlockSyncConfig =
        toml::from_str(&encoded).expect("block-sync config deserializes");
    assert_eq!(decoded, default);

    let config: crate::Config = toml::from_str(
        r#"
        [zakura.block_sync]
        max_submitted_block_applies = 9
        "#,
    )
    .expect("nested Zakura block-sync config deserializes");
    assert_eq!(config.zakura.block_sync.max_submitted_block_applies, 9);
    assert_eq!(
        config.zakura.block_sync.submitted_apply_limit(),
        MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES,
    );
}

#[test]
fn config_validate_rejects_degenerate_values() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 0,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());

    config = ZakuraBlockSyncConfig {
        max_reorder_lookahead_bytes: 0,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());

    // A request budget below the checkpoint-range floor is fine: submitted bodies
    // release their reservation at receipt, so the budget only has to exceed one
    // floor request (checked below the floor-request bound in `validate`).
    config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_CHECKPOINT_RANGE_BYTE_FLOOR - 1,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_ok());

    config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_CHECKPOINT_RANGE_BYTE_FLOOR,
        max_reorder_lookahead_bytes: BS_CHECKPOINT_RANGE_BYTE_FLOOR,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_ok());

    config = ZakuraBlockSyncConfig {
        request_timeout: Duration::ZERO,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());

    config = ZakuraBlockSyncConfig {
        initial_block_probe_requests: 0,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());

    config = ZakuraBlockSyncConfig {
        max_requests_without_block_progress: 0,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());

    config = ZakuraBlockSyncConfig {
        bbr_reliability_weight_percent: 101,
        ..ZakuraBlockSyncConfig::default()
    };
    assert!(config.validate().is_err());
}

#[test]
fn config_deserialize_keeps_below_range_floor_inflight_block_bytes() {
    // An older config with a small `max_inflight_block_bytes` (e.g. the stored
    // `v4.5.0-zakura-blocksync.toml` 256 MiB value) loads unchanged: the request
    // budget no longer bounds retention, so it needs no checkpoint-range clamp —
    // only `validate`'s one-floor-request lower bound applies.
    let config: crate::Config = toml::from_str(
        r#"
        [zakura.block_sync]
        max_inflight_block_bytes = 268435456
        "#,
    )
    .expect("a below-range-floor max_inflight_block_bytes config still loads");
    const {
        assert!(268435456u64 < BS_CHECKPOINT_RANGE_BYTE_FLOOR);
    }
    assert_eq!(config.zakura.block_sync.max_inflight_block_bytes, 268435456);
}

#[test]
fn config_deserialize_clamps_sub_floor_request_inflight_block_bytes() {
    // A stored config whose request budget cannot cover one floor request
    // (e.g. an old 16 MiB value) loads clamped to just above the floor instead
    // of failing `validate`'s one-floor-request lower bound, so older nodes
    // keep starting.
    let config: crate::Config = toml::from_str(
        r#"
        [zakura.block_sync]
        max_inflight_block_bytes = 16777216
        "#,
    )
    .expect("a sub-floor-request max_inflight_block_bytes config still loads");
    let request_floor = config.zakura.block_sync.floor_request_byte_reservation();
    assert!(
        16_777_216 <= request_floor,
        "test premise: the stored value is at or below one floor request"
    );
    assert_eq!(
        config.zakura.block_sync.max_inflight_block_bytes,
        request_floor + 1
    );
}

#[test]
fn codec_round_trips_every_message_variant() {
    round_trip(BlockSyncMessage::Status(status()));
    round_trip(BlockSyncMessage::GetBlocks {
        start_height: block::Height(10),
        count: 3,
    });
    round_trip(BlockSyncMessage::Block(mainnet_block(
        &BLOCK_MAINNET_1_BYTES,
    )));
    round_trip(BlockSyncMessage::BlocksDone {
        start_height: block::Height(10),
        returned: 3,
    });
    round_trip(BlockSyncMessage::RangeUnavailable {
        start_height: block::Height(10),
        count: 3,
    });
}

#[test]
fn codec_round_trips_block_near_max_block_bytes() {
    let block = Arc::new(zakura_chain::block::tests::generate::large_multi_transaction_block());
    let serialized_len = block
        .zcash_serialize_to_vec()
        .expect("large test block serializes")
        .len();
    let max_block_bytes =
        usize::try_from(block::MAX_BLOCK_BYTES).expect("max block size fits in usize");

    assert!(
        serialized_len <= max_block_bytes && serialized_len > max_block_bytes - 1000,
        "test block should be close to the consensus cap, got {serialized_len}"
    );
    round_trip(BlockSyncMessage::Block(block));
}

#[test]
fn codec_rejects_malformed_discriminator_and_truncated_payload() {
    assert!(matches!(
        BlockSyncMessage::decode(&[99]),
        Err(BlockSyncWireError::UnknownMessageType(99))
    ));

    assert!(matches!(
        BlockSyncMessage::decode(&[MSG_BS_GET_BLOCKS, 1, 0]),
        Err(BlockSyncWireError::Io(_))
    ));
}

#[test]
fn codec_classifies_payloads_above_old_raw_stream6_cap() {
    let old_max_bs_message_bytes =
        usize::try_from(block::MAX_BLOCK_BYTES).expect("max block bytes fits in usize") + 1;
    let payload = vec![99; old_max_bs_message_bytes + 1];

    assert!(payload.len() <= MAX_BS_MESSAGE_BYTES);
    assert!(matches!(
        BlockSyncMessage::decode(&payload),
        Err(BlockSyncWireError::UnknownMessageType(99))
    ));
}

#[test]
fn codec_rejects_oversized_frame_and_oversized_block() {
    let oversized_payload = vec![0; MAX_BS_MESSAGE_BYTES + 1];
    assert!(matches!(
        BlockSyncMessage::decode(&oversized_payload),
        Err(BlockSyncWireError::OversizedPayload { .. })
    ));

    let oversized_block =
        Arc::new(zakura_chain::block::tests::generate::oversized_multi_transaction_block());
    assert!(matches!(
        BlockSyncMessage::Block(oversized_block).encode(),
        Err(BlockSyncWireError::OversizedBlock { .. })
            | Err(BlockSyncWireError::OversizedPayload { .. })
    ));
}

#[test]
fn codec_rejects_count_and_returned_over_cap() {
    let over_cap = MAX_BS_BLOCKS_PER_REQUEST + 1;

    assert!(matches!(
        BlockSyncMessage::BlocksDone {
            start_height: block::Height(1),
            returned: 0,
        }
        .encode(),
        Err(BlockSyncWireError::ZeroBlockCount)
    ));

    let mut zero_count_get_blocks = vec![MSG_BS_GET_BLOCKS];
    zero_count_get_blocks.extend_from_slice(&1u32.to_le_bytes());
    zero_count_get_blocks.extend_from_slice(&0u32.to_le_bytes());
    assert!(matches!(
        BlockSyncMessage::decode(&zero_count_get_blocks),
        Err(BlockSyncWireError::ZeroBlockCount)
    ));

    let mut zero_count_range_unavailable = vec![MSG_BS_RANGE_UNAVAILABLE];
    zero_count_range_unavailable.extend_from_slice(&1u32.to_le_bytes());
    zero_count_range_unavailable.extend_from_slice(&0u32.to_le_bytes());
    assert!(matches!(
        BlockSyncMessage::decode(&zero_count_range_unavailable),
        Err(BlockSyncWireError::ZeroBlockCount)
    ));

    assert!(matches!(
        BlockSyncMessage::GetBlocks {
            start_height: block::Height(1),
            count: over_cap,
        }
        .encode(),
        Err(BlockSyncWireError::BlockCountLimit { .. })
    ));

    assert!(matches!(
        BlockSyncMessage::BlocksDone {
            start_height: block::Height(1),
            returned: over_cap,
        }
        .encode(),
        Err(BlockSyncWireError::BlockCountLimit { .. })
    ));

    assert!(matches!(
        BlockSyncMessage::RangeUnavailable {
            start_height: block::Height(1),
            count: over_cap,
        }
        .encode(),
        Err(BlockSyncWireError::BlockCountLimit { .. })
    ));
}

#[test]
fn frame_decode_rejects_mismatched_unknown_flags_and_trailing_payload() {
    let frame = Frame {
        message_type: u16::from(MSG_BS_GET_BLOCKS),
        flags: 1,
        payload: BlockSyncMessage::GetBlocks {
            start_height: block::Height(1),
            count: 1,
        }
        .encode()
        .expect("message encodes"),
    };
    assert!(matches!(
        BlockSyncMessage::decode_frame(frame),
        Err(BlockSyncWireError::UnsupportedFlags(1))
    ));

    let mut payload = BlockSyncMessage::Status(status())
        .encode()
        .expect("message encodes");
    payload.push(0);
    assert!(matches!(
        BlockSyncMessage::decode(&payload),
        Err(BlockSyncWireError::TrailingBytes)
    ));

    let frame = Frame {
        message_type: u16::from(MSG_BS_BLOCK),
        flags: 0,
        payload: BlockSyncMessage::Status(status())
            .encode()
            .expect("message encodes"),
    };
    assert!(matches!(
        BlockSyncMessage::decode_frame(frame),
        Err(BlockSyncWireError::MismatchedFrameMessageType { .. })
    ));
}

#[test]
fn status_decode_clamps_peer_capacity_advertisements() {
    let mut payload = Vec::new();
    payload.push(MSG_BS_STATUS);
    payload.extend_from_slice(&block::Height(1).0.to_le_bytes());
    payload.extend_from_slice(&block::Height(2).0.to_le_bytes());
    block::Hash([9; 32])
        .zcash_serialize(&mut payload)
        .expect("hash serializes");
    payload.extend_from_slice(&u32::MAX.to_le_bytes());
    payload.extend_from_slice(&u32::MAX.to_le_bytes());
    payload.extend_from_slice(&u32::MAX.to_le_bytes());

    let BlockSyncMessage::Status(status) =
        BlockSyncMessage::decode(&payload).expect("status decodes")
    else {
        panic!("expected status message");
    };

    assert_eq!(status.max_blocks_per_response, MAX_BS_BLOCKS_PER_REQUEST);
    assert_eq!(status.max_inflight_requests, MAX_BS_INFLIGHT_REQUESTS);
    assert_eq!(status.max_response_bytes, MAX_BS_RESPONSE_BYTES);
}

#[test]
fn aggregate_response_cap_is_not_the_per_frame_cap() {
    assert!(
        MAX_BS_RESPONSE_BYTES > u32::try_from(MAX_BS_MESSAGE_BYTES).expect("frame cap fits u32"),
        "range responses are multiple independently-capped block frames"
    );
    assert_eq!(
        ZakuraBlockSyncConfig::default().advertised_max_response_bytes(),
        MAX_BS_RESPONSE_BYTES
    );
}

// The byte-budget reservation and per-peer fairness logic moved from the old
// `BlockRangeScheduler::next_for_peer` into the reactor's `fill_peer` issuance
// path (commit-1 lossless worst-case reservation + commit-3 per-peer byte cap).
// Those are now exercised end-to-end by the reactor integration tests below
// (`reactor_fill_loop_*`, `reactor_keeps_issuing_*`); the WorkQueue itself only
// owns dedup / servable-range eligibility, asserted here.

#[test]
fn work_queue_take_dedups_a_height_across_peers() {
    // fanout = 1: a height taken by one peer leaves `pending`, so a second peer
    // querying the same range cannot also take it.
    let queue = work_queue_with(
        0,
        [
            needed(1, BlockSizeEstimate::Advertised(10_000)),
            needed(2, BlockSizeEstimate::Advertised(10_000)),
            needed(3, BlockSizeEstimate::Advertised(10_000)),
        ],
    );

    let first = queue.take_in_range(
        block::Height(1),
        block::Height(3),
        MAX_BS_BLOCKS_PER_REQUEST as usize,
    );
    assert_eq!(
        first.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![1, 2, 3]
    );
    assert_eq!(queue.in_flight_len(), 3);

    let second = queue.take_in_range(
        block::Height(1),
        block::Height(3),
        MAX_BS_BLOCKS_PER_REQUEST as usize,
    );
    assert!(
        second.is_empty(),
        "a height taken by one peer must not be re-takable by another (dedup)"
    );
}

#[test]
fn work_queue_extend_dedups_against_pending_in_flight_and_floor() {
    let queue = work_queue_with(
        5,
        [
            // At/below the floor: rejected.
            needed(3, BlockSizeEstimate::Advertised(100)),
            needed(5, BlockSizeEstimate::Advertised(100)),
            // Above the floor: accepted.
            needed(6, BlockSizeEstimate::Advertised(100)),
            needed(7, BlockSizeEstimate::Advertised(100)),
        ],
    );
    assert_eq!(queue.pending_len(), 2);
    assert!(!queue.pending_contains(block::Height(5)));

    // Take h6 into `in_flight`, then re-extend with h6 (in flight) and h7
    // (already pending): both are skipped, only a genuinely new height inserts.
    queue.take_in_range(block::Height(6), block::Height(6), 1);
    let inserted = queue.extend([
        needed(6, BlockSizeEstimate::Advertised(100)), // in flight
        needed(7, BlockSizeEstimate::Advertised(100)), // already pending
        needed(8, BlockSizeEstimate::Advertised(100)), // new
    ]);
    assert_eq!(inserted, 1, "only the genuinely new height is inserted");
    assert!(queue.pending_contains(block::Height(8)));
    assert!(!queue.pending_contains(block::Height(6)));
}

#[test]
fn work_queue_take_respects_servable_range_contiguity_and_max() {
    // Heights 10,11,12 then a gap then 20,21.
    let queue = work_queue_with(
        0,
        [
            needed(10, BlockSizeEstimate::Advertised(100)),
            needed(11, BlockSizeEstimate::Advertised(100)),
            needed(12, BlockSizeEstimate::Advertised(100)),
            needed(20, BlockSizeEstimate::Advertised(100)),
            needed(21, BlockSizeEstimate::Advertised(100)),
        ],
    );

    // `max` bounds the chunk.
    let chunk = queue.take_in_range(block::Height(10), block::Height(30), 2);
    assert_eq!(
        chunk.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![10, 11]
    );

    // The chunk stops at the gap (12 then nothing until 20): a take over the full
    // range returns only the contiguous run 12, not 12,20,21.
    let run = queue.take_in_range(
        block::Height(12),
        block::Height(30),
        MAX_BS_BLOCKS_PER_REQUEST as usize,
    );
    assert_eq!(
        run.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![12],
        "take must stop at the first gap so the chunk is one contiguous request"
    );

    // `low` excludes lower heights; the next contiguous run is 20,21.
    let high = queue.take_in_range(
        block::Height(20),
        block::Height(30),
        MAX_BS_BLOCKS_PER_REQUEST as usize,
    );
    assert_eq!(
        high.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![20, 21]
    );
}

#[test]
fn work_queue_budgeted_take_respects_count_cap() {
    let queue = work_queue_with(
        0,
        (1..=4).map(|height| needed(height, BlockSizeEstimate::Advertised(100))),
    );

    let taken = queue.take_in_range_budgeted(block::Height(1), block::Height(4), 2, u64::MAX);

    assert_eq!(
        taken.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![1, 2]
    );
}

#[test]
fn work_queue_budgeted_take_respects_estimated_byte_cap() {
    let queue = work_queue_with(
        0,
        [
            needed(1, BlockSizeEstimate::Advertised(100)),
            needed(2, BlockSizeEstimate::Advertised(150)),
            needed(3, BlockSizeEstimate::Advertised(1)),
        ],
    );

    let taken = queue.take_in_range_budgeted(block::Height(1), block::Height(3), 3, 250);

    assert_eq!(
        taken.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![1, 2]
    );
    assert!(queue.pending_contains(block::Height(3)));
}

#[test]
fn work_queue_budgeted_take_stops_at_gaps() {
    let queue = work_queue_with(
        0,
        [
            needed(10, BlockSizeEstimate::Advertised(100)),
            needed(11, BlockSizeEstimate::Advertised(100)),
            needed(13, BlockSizeEstimate::Advertised(100)),
        ],
    );

    let taken = queue.take_in_range_budgeted(block::Height(10), block::Height(13), 3, u64::MAX);

    assert_eq!(
        taken.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![10, 11]
    );
    assert!(queue.pending_contains(block::Height(13)));
}

#[test]
fn work_queue_budgeted_take_takes_one_oversized_first_item_for_progress() {
    let queue = work_queue_with(
        0,
        [
            needed(1, BlockSizeEstimate::Advertised(500)),
            needed(2, BlockSizeEstimate::Advertised(1)),
        ],
    );

    let taken = queue.take_in_range_budgeted(block::Height(1), block::Height(2), 2, 100);

    assert_eq!(
        taken.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![1]
    );
    assert_eq!(taken[0].1.estimated_bytes, 500);
    assert!(queue.pending_contains(block::Height(2)));
}

#[test]
fn work_queue_budgeted_take_preserves_estimates_through_take_and_return() {
    let queue = work_queue_with(0, [needed(10, BlockSizeEstimate::Advertised(12_345))]);

    let taken = queue.take_in_range_budgeted(block::Height(10), block::Height(10), 1, 1);
    assert_eq!(taken.len(), 1);
    assert_eq!(taken[0].1.estimated_bytes, 12_345);

    queue.return_items([block::Height(10)]);
    let retaken = queue.take_in_range_budgeted(block::Height(10), block::Height(10), 1, 1);
    assert_eq!(retaken.len(), 1);
    assert_eq!(retaken[0].1.estimated_bytes, 12_345);
}

/// Test shorthand: the grant for an admitted take, or `None` on any refusal.
fn admit_grant(
    config: &ZakuraBlockSyncConfig,
    snapshot: super::admission::AdmissionSnapshot,
    start: block::Height,
    servable_high: block::Height,
    response_byte_cap: u64,
) -> Option<super::admission::AdmissionGrant> {
    match super::admission::admit(config, snapshot, start, servable_high, response_byte_cap) {
        super::admission::AdmissionOutcome::Admit(grant) => Some(grant),
        super::admission::AdmissionOutcome::LookaheadAtCap
        | super::admission::AdmissionOutcome::InflightBudgetEmpty => None,
    }
}

#[test]
fn admission_blocks_above_floor_at_cap_but_keeps_floor_fundable() {
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 40_000_000,
        max_reorder_lookahead_bytes: 500,
        ..ZakuraBlockSyncConfig::default()
    };
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(10),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 500,
        reorder_buffered_blocks: 1,
        applying_buffered_bytes: 0,
        applying_buffered_blocks: 0,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 40_000_000,
    };

    let floor = admit_grant(
        &config,
        snapshot,
        block::Height(11),
        block::Height(11),
        1_000,
    )
    .expect("floor rescue remains admitted at the look-ahead cap");
    assert_eq!(floor.priority, super::admission::RequestPriority::Floor);
    assert_eq!(floor.max_request_bytes, 1_000);

    // Height 412 is the first height above the commit window (verified_tip 10 + 401).
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(412),
            block::Height(412),
            1_000
        ),
        None,
        "above-floor work stops at the look-ahead cap"
    );

    let under_cap = super::admission::AdmissionSnapshot {
        reorder_buffered_bytes: 100,
        budget_available: 40_000_000,
        ..snapshot
    };
    let above = admit_grant(
        &config,
        under_cap,
        block::Height(412),
        block::Height(412),
        u64::MAX,
    )
    .expect("above-floor work is admitted below the cap");
    assert_eq!(
        above.priority,
        super::admission::RequestPriority::AboveFloor
    );
    // Remaining headroom is wire-denominated: 500 - 100 = 400 wire bytes.
    assert_eq!(above.max_request_bytes, 400);
}

#[test]
fn admission_counts_inflight_to_sequencer_bytes() {
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(10),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 200,
        reorder_buffered_blocks: 1,
        applying_buffered_bytes: 200,
        applying_buffered_blocks: 1,
        sequencer_input_queued_bytes: 600,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 64_000_000,
    };

    // Probe above the commit window (verified_tip 10 + 401) so the gate applies.
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(412),
            block::Height(412),
            1_000
        ),
        None,
        "above-floor admission includes bytes already queued to the sequencer"
    );
}

#[test]
fn total_resident_plateaus_under_commit_stall() {
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(10),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 300,
        reorder_buffered_blocks: 1,
        applying_buffered_bytes: 700,
        applying_buffered_blocks: 1,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 64_000_000,
    };

    // Probe above the commit window (verified_tip 10 + 401) so the gate applies.
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(412),
            block::Height(412),
            1_000
        ),
        None,
        "above-floor admission includes applying bytes held during a commit stall"
    );
}

#[test]
fn floor_priority_request_does_not_buffer_above_floor_past_cap() {
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    let capped = super::admission::AdmissionSnapshot {
        download_floor: block::Height(10),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 1_000,
        reorder_buffered_blocks: 1,
        applying_buffered_bytes: 0,
        applying_buffered_blocks: 0,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 64_000_000,
    };

    // Probe above the commit window (verified_tip 10 + 401): the speculative tail of a
    // floor-starting request is refused at the cap once it leaves the window.
    assert_eq!(
        admit_grant(
            &config,
            capped,
            block::Height(412),
            block::Height(412),
            1_000
        ),
        None,
        "the above-floor tail of a floor-starting request is refused at the cap"
    );
    let floor = admit_grant(
        &config,
        capped,
        block::Height(11),
        block::Height(10_000),
        1_000,
    )
    .expect("floor height remains fundable");
    assert_eq!(floor.priority, super::admission::RequestPriority::Floor);
    // The exempt grant is clamped at the commit-window top: the take cannot carry
    // above-window heights past the full gate.
    assert_eq!(floor.take_high, block::Height(411));
}

#[test]
fn outstanding_reservations_are_charged_at_wire_size() {
    // Regression for the reserved-0× hole: outstanding above-floor reservations land as
    // retained wire bytes like every other serialized pool, so they must be pre-charged
    // at their wire size. Charging them nothing makes in-flight volume invisible to the
    // byte gate until it is already resident.
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(600),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 0,
        reorder_buffered_blocks: 0,
        applying_buffered_bytes: 0,
        applying_buffered_blocks: 0,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 1_100,
        reserved_above_floor_blocks: 1,
        budget_available: 64_000_000,
    };
    // Reservations alone fill the budget: 1_100 >= 1_000, so both the speculative
    // lane and an escalated floor block above the commit window are refused.
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(602),
            block::Height(602),
            u64::MAX
        ),
        None,
        "outstanding reservations must count against the resident budget",
    );
    assert!(
        matches!(
            super::admission::admit(
                &config,
                snapshot,
                block::Height(601),
                block::Height(601),
                u64::MAX
            ),
            super::admission::AdmissionOutcome::LookaheadAtCap
        ),
        "an escalated floor take above the commit window is refused on reserved bytes alone",
    );
    // The commit window stays exempt so the committer can always drain.
    let window = admit_grant(
        &config,
        snapshot,
        block::Height(411),
        block::Height(411),
        1_000,
    )
    .expect("the commit window is exempt from the reservation charge");
    assert_eq!(window.max_request_bytes, 1_000);
}

#[test]
fn floor_backpressures_when_download_floor_escalates_past_commit() {
    // Regression for the OOM. The download floor advances on every download, so a
    // floor exemption tied to it lets the applying queue escalate unboundedly ahead of
    // commit. With the exemption anchored to the *commit window* (one checkpoint range above
    // the verified tip), a floor-priority request far above the commit tip is backpressured
    // once the resident-memory look-ahead budget is full, while the commit window stays
    // fundable so a pinned checkpoint range can assemble and commit can drain.
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        // Large enough that the byte (memory) cap, not the block cap, is what bites here.
        ..ZakuraBlockSyncConfig::default()
    };
    // Commit stalled far below the download floor; applying holds a full budget of
    // serialized backlog bodies: 1_200 wire bytes >= 1_000 budget.
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(1_000),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 0,
        reorder_buffered_blocks: 0,
        applying_buffered_bytes: 1_200,
        applying_buffered_blocks: 990,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 64_000_000,
    };

    // The download-frontier request (floor+1) is still classified floor-priority, but is now
    // refused: it is above the commit window, so it no longer bypasses the memory cap.
    assert_eq!(
        super::admission::request_priority(snapshot.download_floor, block::Height(1_001)),
        super::admission::RequestPriority::Floor,
    );
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(1_001),
            block::Height(1_001),
            1_000
        ),
        None,
        "a floor request far ahead of commit is backpressured when the memory budget is full",
    );

    // The commit window (verified_tip + 1 ..= verified_tip + 401) stays fundable, so the
    // committer can advance and drain the pipeline — no deadlock. The boundary is exact:
    // 411 is the last exempt height, 412 the first gated one.
    let frontier = admit_grant(
        &config,
        snapshot,
        block::Height(11),
        block::Height(11),
        1_000,
    )
    .expect("the commit-frontier block is always fundable");
    assert_eq!(frontier.max_request_bytes, 1_000);
    let window_top = admit_grant(
        &config,
        snapshot,
        block::Height(411),
        block::Height(411),
        1_000,
    )
    .expect("the top of the commit window is still fundable");
    assert_eq!(window_top.max_request_bytes, 1_000);
    assert_eq!(
        admit_grant(
            &config,
            snapshot,
            block::Height(412),
            block::Height(412),
            1_000
        ),
        None,
        "the first height above the commit window is memory-gated",
    );
}

#[test]
fn exempt_take_never_spans_the_commit_window_boundary() {
    // Pin for the above-window take bypass: with multi-block responses, a take whose
    // admission-checked start sits inside the commit window must not extend above the
    // window top — otherwise above-window heights ride the exempt request past the
    // resident gate, sized only by the in-flight budget. The clamp is structural
    // (gate-independent), so it holds whether or not the gate is full.
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 64_000_000,
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    // Gate full: 1,000 serialized applying bytes fill the 1,000-byte budget.
    let full = super::admission::AdmissionSnapshot {
        download_floor: block::Height(10),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 0,
        reorder_buffered_blocks: 0,
        applying_buffered_bytes: 1_000,
        applying_buffered_blocks: 10,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        budget_available: 64_000_000,
    };
    let grant = admit_grant(
        &config,
        full,
        block::Height(11),
        block::Height(10_000),
        1_000,
    )
    .expect("an in-window start stays fundable at a full gate");
    assert_eq!(
        grant.take_high,
        block::Height(411),
        "the exempt take is clamped at the commit-window top",
    );
    assert_eq!(grant.max_request_bytes, 1_000);

    // Same clamp with the gate open: no exempt take ever spans the boundary.
    let open = super::admission::AdmissionSnapshot {
        applying_buffered_bytes: 0,
        applying_buffered_blocks: 0,
        ..full
    };
    let grant = admit_grant(
        &config,
        open,
        block::Height(11),
        block::Height(10_000),
        1_000,
    )
    .expect("an in-window start is fundable with the gate open");
    assert_eq!(grant.take_high, block::Height(411));

    // An above-window start with headroom extends to the servable ceiling, sized by the
    // remaining wire-denominated headroom: 1_000 - 0 = 1_000.
    let grant = admit_grant(
        &config,
        open,
        block::Height(412),
        block::Height(10_000),
        u64::MAX,
    )
    .expect("an above-window start is admitted below the cap");
    assert_eq!(grant.take_high, block::Height(10_000));
    assert_eq!(grant.max_request_bytes, 1_000);
}

#[test]
fn commit_window_stays_fundable_at_exact_floor() {
    // Regression for the exact-fit clamp deadlock: a config clamped to the checkpoint-range
    // floors used to leave zero margin, so one next-range reorder body or reservation pushed
    // the gate over budget and the range-completing block was refused — checkpoint sync
    // wedged. With the whole commit window exempt, the active range assembles regardless of
    // how full the gate is.
    use super::config::{
        BS_CHECKPOINT_RANGE_BYTE_FLOOR, MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES,
    };

    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_CHECKPOINT_RANGE_BYTE_FLOOR,
        max_reorder_lookahead_bytes: 1,
        ..ZakuraBlockSyncConfig::default()
    };
    config.clamp_reorder_lookahead_to_floor();
    let range_blocks = u32::try_from(MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES)
        .expect("checkpoint range block count fits in u32");

    // verified_tip pinned at 0; applying holds all but the last worst-case range block —
    // all submitted during checkpoint sync, so charged at the decoded multiple — plus
    // next-range contamination in reorder and outstanding reservations. The byte gate is
    // full: 8 MiB + 800 MB + 4 MB serialized + 800 MB * 4 decoded >= 3_208_000_000.
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(range_blocks - 1),
        verified_block_tip: block::Height(0),
        reorder_buffered_bytes: 8_388_608,
        reorder_buffered_blocks: 4,
        applying_buffered_bytes: 800_000_000,
        applying_buffered_blocks: u64::from(range_blocks) - 1,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 800_000_000,
        reserved_above_floor_bytes: 4_000_000,
        reserved_above_floor_blocks: 2,
        budget_available: 2_000_000,
    };

    // The range-completing block (inside the commit window) stays fundable on both lanes.
    assert_eq!(
        super::admission::request_priority(snapshot.download_floor, block::Height(range_blocks)),
        super::admission::RequestPriority::Floor,
    );
    let completing = admit_grant(
        &config,
        snapshot,
        block::Height(range_blocks),
        block::Height(range_blocks),
        u64::MAX,
    )
    .expect("the range-completing floor take must pass a full gate");
    assert_eq!(
        completing.priority,
        super::admission::RequestPriority::Floor
    );
    assert_eq!(completing.max_request_bytes, 2_000_000);

    // The first height above the window is refused while the gate is full — on both
    // lanes, since `admit` gates every above-window start regardless of priority.
    assert!(matches!(
        super::admission::admit(
            &config,
            snapshot,
            block::Height(range_blocks + 1),
            block::Height(range_blocks + 1),
            u64::MAX
        ),
        super::admission::AdmissionOutcome::LookaheadAtCap
    ));
}

#[test]
fn work_queue_force_cancel_and_owner_timeout_release_once() {
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(budget.try_reserve(100));
    assert_eq!(queue.mark_reserved([block::Height(1)]), 100);
    assert_eq!(budget.reserved(), 100);

    let watchdog_released = queue.release_and_return_items([block::Height(1)]);
    budget.release(watchdog_released);
    assert_eq!(watchdog_released, 100);
    assert_eq!(budget.reserved(), 0);
    assert!(queue.pending_contains(block::Height(1)));

    let late_owner_released = queue.release_and_return_items([block::Height(1)]);
    budget.release(late_owner_released);
    assert_eq!(late_owner_released, 0);
    assert_eq!(budget.reserved(), 0);
    assert!(queue.pending_contains(block::Height(1)));
}

#[test]
fn work_queue_reserved_bytes_counter_matches_scan_across_transitions() {
    // Exercise every ledger transition and assert the O(1) `reserved_bytes` counter
    // never drifts from the O(n) ground-truth scan.
    let queue = work_queue_with(
        0,
        (1..=6).map(|h| needed(h, BlockSizeEstimate::Advertised(100))),
    );
    let check = |label: &str| {
        assert_eq!(
            queue.reserved_bytes(),
            queue.reserved_bytes_scanned(),
            "reserved_bytes counter drifted from scan after {label}"
        );
    };
    // Nothing reserved yet: all pending items are `Released`.
    assert_eq!(queue.reserved_bytes(), 0);
    check("seed");

    // take + mark_reserved: Released -> Reserved.
    let taken = queue.take_in_range(block::Height(1), block::Height(6), 6);
    assert_eq!(taken.len(), 6);
    assert_eq!(queue.mark_reserved((1..=6).map(block::Height)), 600);
    assert_eq!(queue.reserved_bytes(), 600);
    check("mark_reserved");

    // receipt: Reserved -> Released drops the reservation for height 1.
    assert_eq!(
        queue.release_active_reserved_height(block::Height(1)),
        Some(100),
    );
    assert_eq!(queue.reserved_bytes(), 500);
    check("release_active_reserved_height");

    // claim_received: Reserved -> Released drops height 2's reservation.
    assert_eq!(queue.claim_received(block::Height(2)), 100);
    assert_eq!(queue.reserved_bytes(), 400);
    check("claim_received");

    // release_heights: Reserved -> Released for height 3.
    queue.release_reserved_heights([block::Height(3)]);
    assert_eq!(queue.reserved_bytes(), 300);
    check("release_heights");

    // release_reserved_and_return_items: only the still-reserved height 4 releases.
    let released = queue.release_reserved_and_return_items([block::Height(4)]);
    assert_eq!(released, 100);
    assert_eq!(queue.reserved_bytes(), 200);
    check("release_reserved_and_return_items");

    // advance_floor drops the committed `<= floor` prefix. Heights 1 and 2
    // (received) and 3 (released) contribute no reservation. Only heights 5 and 6
    // remain reserved above the new floor.
    let released = queue.advance_floor(block::Height(4));
    assert_eq!(released, 0, "heights <= 4 owned no live reservation");
    assert!(!queue.pending_contains(block::Height(1)));
    assert!(!queue.in_flight_contains(block::Height(2)));
    assert_eq!(queue.reserved_bytes(), 200);
    check("advance_floor");

    // reset_above drops the `> floor` suffix (heights 5 and 6), releasing their
    // reservations and zeroing the counter.
    let released = queue.reset_above(block::Height(4));
    assert_eq!(released, 200);
    assert_eq!(queue.reserved_bytes(), 0);
    assert!(!queue.in_flight_contains(block::Height(5)));
    assert!(!queue.in_flight_contains(block::Height(6)));
    check("reset_above");
}

#[test]
fn work_queue_advance_floor_drops_only_committed_prefix() {
    let queue = work_queue_with(
        0,
        (1..=10).map(|h| needed(h, BlockSizeEstimate::Advertised(100))),
    );
    // Reserve a contiguous run so we can see the reservation accounting on GC.
    let _ = queue.take_in_range(block::Height(1), block::Height(10), 10);
    assert_eq!(queue.mark_reserved((1..=10).map(block::Height)), 1000);

    // advance_floor to 4: drops heights 1..=4 (still reserved -> released), keeps 5..=10.
    let released = queue.advance_floor(block::Height(4));
    assert_eq!(released, 400, "reserved bytes for the dropped 1..=4 prefix");
    for h in 1..=4 {
        assert!(!queue.in_flight_contains(block::Height(h)));
    }
    for h in 5..=10 {
        assert!(queue.in_flight_contains(block::Height(h)));
    }
    assert_eq!(queue.reserved_bytes(), 600);
    assert_eq!(queue.reserved_bytes(), queue.reserved_bytes_scanned());

    // A lower floor is a no-op (floor only advances).
    assert_eq!(queue.advance_floor(block::Height(2)), 0);
    assert_eq!(queue.reserved_bytes(), 600);
}

#[test]
fn receipt_releases_wire_reservation_while_body_retained() {
    // Receipt ends the wire reservation: the estimate returns to the budget while
    // the caller still owns the body (the height stays claimed in `in_flight`).
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(budget.try_reserve(100));
    assert_eq!(queue.mark_reserved([block::Height(1)]), 100);
    assert_eq!(queue.reserved_bytes(), 100);

    let reserved_estimate = queue
        .release_active_reserved_height(block::Height(1))
        .expect("active reserved height releases at receipt");
    assert_eq!(reserved_estimate, 100);
    budget.release(reserved_estimate);
    assert_eq!(queue.reserved_bytes(), 0);
    assert_eq!(budget.reserved(), 0);
    assert!(
        queue.in_flight_contains(block::Height(1)),
        "the received height stays claimed; the body handoff owns it"
    );
}

#[test]
fn floor_watchdog_skips_received_heights() {
    // After receipt released the reservation, the watchdog must neither requeue
    // the height (the body handoff owns it) nor release a second time.
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(budget.try_reserve(100));
    assert_eq!(queue.mark_reserved([block::Height(1)]), 100);

    let reserved_estimate = queue
        .release_active_reserved_height(block::Height(1))
        .expect("active reserved height releases at receipt");
    budget.release(reserved_estimate);
    assert_eq!(budget.reserved(), 0);

    let outcome = queue.release_reserved_and_return_items_detailed([block::Height(1)]);
    let watchdog_released = outcome.released_bytes;
    budget.release(watchdog_released);
    assert_eq!(
        watchdog_released, 0,
        "watchdog must not release a received height owned by the sequencer handoff"
    );
    assert!(
        queue.in_flight_contains(block::Height(1)),
        "the received height must not be requeued for a re-fetch"
    );
    assert_eq!(outcome.released_count, 1);
    assert_eq!(outcome.returned_count, 0);
    assert_eq!(outcome.missing_count, 0);
    assert!(queue.in_flight_contains(block::Height(1)));
    assert_eq!(budget.reserved(), 0);
    assert_eq!(queue.advance_floor(block::Height(1)), 0);
}

#[test]
fn late_body_does_not_resurrect_charge() {
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(budget.try_reserve(100));
    assert_eq!(queue.mark_reserved([block::Height(1)]), 100);

    let outcome = queue.release_reserved_and_return_items_detailed([block::Height(1)]);
    let watchdog_released = outcome.released_bytes;
    budget.release(watchdog_released);
    assert_eq!(outcome.returned_count, 1);
    assert_eq!(outcome.released_count, 0);
    assert_eq!(outcome.missing_count, 0);
    assert_eq!(budget.reserved(), 0);
    assert!(queue.pending_contains(block::Height(1)));

    let duplicate =
        queue.release_reserved_and_return_items_detailed([block::Height(1), block::Height(2)]);
    assert_eq!(duplicate.already_pending_count, 1);
    assert_eq!(duplicate.missing_count, 1);
    assert_eq!(duplicate.min_height, Some(block::Height(1)));
    assert_eq!(duplicate.max_height, Some(block::Height(2)));

    assert_eq!(
        queue.release_active_reserved_height(block::Height(1)),
        None,
        "a late body cannot release a claim the watchdog already released"
    );
    assert_eq!(budget.reserved(), 0);
}

#[test]
fn claim_received_does_not_orphan_a_charge() {
    // An unmatched queued body claims its height without a new reservation, but
    // any stale request reservation it still owned is handed back exactly once.
    let queue = work_queue_with(0, [needed(1, BlockSizeEstimate::Advertised(100))]);
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(1), 1);
    assert_eq!(taken.len(), 1);
    assert!(budget.try_reserve(100));
    assert_eq!(queue.mark_reserved([block::Height(1)]), 100);

    let old_charge = queue.claim_received(block::Height(1));
    budget.release(old_charge);
    assert_eq!(old_charge, 100);
    assert_eq!(budget.reserved(), 0);

    let released = queue.release_reserved_heights([block::Height(1)]);
    budget.release(released);
    assert_eq!(released, 0, "a received height owns no further charge");
    assert_eq!(budget.reserved(), 0);
}

#[test]
fn release_reserved_mixed_received_and_reserved_conserves_budget() {
    let queue = work_queue_with(
        0,
        [
            needed(1, BlockSizeEstimate::Advertised(100)),
            needed(2, BlockSizeEstimate::Advertised(100)),
        ],
    );
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(2), 2);
    assert_eq!(taken.len(), 2);
    assert!(budget.try_reserve(200));
    assert_eq!(
        queue.mark_reserved([block::Height(1), block::Height(2)]),
        200
    );

    // Height 1 is received: its whole estimate returns to the budget.
    let reserved_estimate = queue
        .release_active_reserved_height(block::Height(1))
        .expect("active height releases at receipt");
    assert_eq!(reserved_estimate, 100);
    budget.release(reserved_estimate);
    assert_eq!(budget.reserved(), 100);

    // Floor GC releases only the still-reserved (unreceived) height 2.
    let released = queue.advance_floor(block::Height(2));
    budget.release(released);
    assert_eq!(
        released, 100,
        "WorkQueue releases only the still-reserved height; received bodies hold no charge"
    );
    assert_eq!(budget.reserved(), 0);
}

#[test]
fn release_reserved_heights_skips_received_body_owned_by_sequencer() {
    // The owner's routine GC / stale-trim cleanup (`gc_committed_outstanding`,
    // `stale_adjusted_disposition`, `finish_detached`) releases via
    // `release_reserved_heights`. When a competing peer delivered a height late,
    // its receipt ended that height's reservation in the shared queue; the owner
    // must release only the still-reserved estimates and leave the received body
    // to the winner (which releases the ended estimate after its forward) — never
    // double-releasing.
    let queue = work_queue_with(
        0,
        [
            needed(1, BlockSizeEstimate::Advertised(100)),
            needed(2, BlockSizeEstimate::Advertised(100)),
        ],
    );
    let mut budget = ByteBudget::new(1_000);
    let taken = queue.take_in_range(block::Height(1), block::Height(2), 2);
    assert_eq!(taken.len(), 2);
    assert!(budget.try_reserve(200));
    assert_eq!(
        queue.mark_reserved([block::Height(1), block::Height(2)]),
        200
    );

    // A competing peer's late body ends height 1's reservation; height 2 stays
    // reserved (never delivered). The winner releases the estimate after its
    // forward.
    let estimate = queue
        .release_active_reserved_height(block::Height(1))
        .expect("height 1 is reserved");
    assert_eq!(estimate, 100);
    budget.release(estimate);
    assert_eq!(budget.reserved(), 100);

    // GC both heights: only the still-reserved height 2 releases. The received
    // height 1 is skipped (its reservation already ended) and stays in `in_flight`.
    let released = queue.release_reserved_heights([block::Height(1), block::Height(2)]);
    budget.release(released);
    assert_eq!(
        released, 100,
        "release_reserved_heights frees only the still-reserved estimate, exactly once"
    );
    assert!(queue.in_flight_contains(block::Height(1)));
    assert_eq!(budget.reserved(), 0);

    // Floor GC clears the bookkeeping; nothing drifts.
    assert_eq!(queue.advance_floor(block::Height(2)), 0);
    assert_eq!(budget.reserved(), 0);
}

#[test]
fn work_queue_take_does_not_clamp_high_to_floor() {
    // The download floor is NOT an upper bound on a take: a peer fetches as far
    // above the floor as its servable range allows.
    let queue = work_queue_with(
        0,
        (100..=104)
            .map(|height| needed(height, BlockSizeEstimate::Advertised(100)))
            .collect::<Vec<_>>(),
    );
    // Floor stays at 0; heights are far above it.
    let taken = queue.take_in_range(
        block::Height(100),
        block::Height(104),
        MAX_BS_BLOCKS_PER_REQUEST as usize,
    );
    assert_eq!(
        taken.iter().map(|(height, _)| height.0).collect::<Vec<_>>(),
        vec![100, 101, 102, 103, 104],
        "heights far above the floor are takable; the floor never clamps the take"
    );
}

#[test]
fn work_queue_preserves_work_item_estimate_through_take_and_return() {
    // The size estimate (feeds the SizeMismatch tolerance check) is preserved as
    // a height moves pending → in_flight → pending. Estimator overridden so the
    // clamp is wide enough to keep the hinted size.
    let queue = work_queue_with(0, [needed(10, BlockSizeEstimate::Advertised(12_345))]);
    let taken = queue.take_in_range(block::Height(10), block::Height(10), 1);
    assert_eq!(taken.len(), 1);
    assert_eq!(taken[0].1.estimated_bytes, 12_345);
    assert_eq!(taken[0].1.hash, block::Hash([10; 32]));

    queue.return_items([block::Height(10)]);
    let retaken = queue.take_in_range(block::Height(10), block::Height(10), 1);
    assert_eq!(
        retaken[0].1.estimated_bytes, 12_345,
        "return_items must restore the stored WorkItem unchanged"
    );
}

#[test]
fn work_queue_advance_floor_and_reset_above_gc_both_maps() {
    let queue = work_queue_with(
        0,
        (1..=6)
            .map(|height| needed(height, BlockSizeEstimate::Advertised(100)))
            .collect::<Vec<_>>(),
    );
    // h1,h2 in flight; h3..h6 pending.
    queue.take_in_range(block::Height(1), block::Height(2), 2);
    assert_eq!(queue.in_flight_len(), 2);
    assert_eq!(queue.pending_len(), 4);

    // advance_floor GCs <= floor from both maps (committed → never re-fetch).
    queue.advance_floor(block::Height(3));
    assert!(!queue.in_flight_contains(block::Height(1)));
    assert!(!queue.pending_contains(block::Height(3)));
    assert!(queue.pending_contains(block::Height(4)));

    // reset_above drops > floor from both maps (reset dropped their buffers).
    queue.take_in_range(block::Height(4), block::Height(4), 1); // h4 → in flight
    queue.reset_above(block::Height(4));
    assert!(queue.in_flight_contains(block::Height(4)));
    assert!(!queue.pending_contains(block::Height(5)));
    assert!(!queue.pending_contains(block::Height(6)));
    assert_eq!(queue.pending_len(), 0);
}

#[test]
fn work_queue_height_is_in_exactly_one_set() {
    // : a height is in exactly one of {below-floor (gone), pending, in_flight}.
    let queue = work_queue_with(0, [needed(10, BlockSizeEstimate::Advertised(100))]);
    let in_one_set = |height: block::Height| -> usize {
        usize::from(queue.pending_contains(height)) + usize::from(queue.in_flight_contains(height))
    };
    let h = block::Height(10);

    assert_eq!(in_one_set(h), 1, "pending only after extend");
    queue.take_in_range(h, h, 1);
    assert_eq!(in_one_set(h), 1, "in_flight only after take");
    queue.return_items([h]);
    assert_eq!(in_one_set(h), 1, "pending only after return");
    queue.take_in_range(h, h, 1);
    queue.advance_floor(h);
    assert_eq!(in_one_set(h), 0, "gone after the floor commits past it");
}

#[tokio::test]
async fn reactor_fill_loop_saturates_multiple_slots_in_one_pass() {
    let config = fill_loop_mechanics_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Peer serves heights 1..=4 and accepts four concurrent single-block requests.
    let (_peer_id, _inbound, mut outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        41,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(4),
            tip_hash: block::Hash([4; 32]),
            max_blocks_per_response: 1,
            max_inflight_requests: 4,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    tip_tx
        .send((block::Height(4), block::Hash([4; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: block::Hash([1; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: block::Hash([2; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(3),
                hash: block::Hash([3; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(4),
                hash: block::Hash([4; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
        ]))
        .await
        .expect("needed metadata queues");

    // The fill-loop opens all four slots from the single NeededBlocks event.
    // Pre-fill-loop scheduling issued only one GetBlocks per scheduling event,
    // so this would time out on the second request.
    // Reading this peer's own outbound proves all four requests targeted it.
    let mut heights = Vec::new();
    for _ in 0..4 {
        let (start_height, count) = wait_for_outbound_getblocks(&mut outbound).await;
        assert_eq!(count, 1);
        heights.push(start_height.0);
    }
    heights.sort_unstable();
    assert_eq!(heights, vec![1, 2, 3, 4]);

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_suppresses_duplicate_needed_block_query_until_response() {
    let config = immediate_body_download_config();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config,
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let best_hash = block::Hash([4; 32]);

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(4),
            hash: best_hash,
        })
        .await
        .expect("header-tip event queues");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(4)).await;

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(4),
            hash: best_hash,
        })
        .await
        .expect("duplicate header-tip event queues");
    assert!(
        tokio::time::timeout(Duration::from_millis(100), actions.recv())
            .await
            .is_err(),
        "same pending needed-block query should not be dispatched twice",
    );

    handle
        .send(BlockSyncEvent::NeededBlocks(Vec::new()))
        .await
        .expect("needed-block response queues");
    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(4),
            hash: best_hash,
        })
        .await
        .expect("header-tip event after response queues");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(4)).await;

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_suppresses_needed_block_query_when_work_already_covers_tip() {
    let config = immediate_body_download_config();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config,
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let best_hash = block::Hash([4; 32]);

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(4),
            hash: best_hash,
        })
        .await
        .expect("header-tip event queues");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(4)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=4)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([u8::try_from(height).expect("test height fits u8"); 32]),
                    size: BlockSizeEstimate::Advertised(1_000),
                })
                .collect(),
        ))
        .await
        .expect("needed-block response queues");
    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(4),
            hash: best_hash,
        })
        .await
        .expect("covered header-tip event queues");

    assert!(
        tokio::time::timeout(Duration::from_millis(100), actions.recv())
            .await
            .is_err(),
        "producer should not re-query when pending/in-flight work already covers the header tip",
    );

    reactor_task.abort();
}

/// Every connected peer that advertises an in-flight window must have that
/// window filled in one scheduling pass when there is enough needed work to go
/// around — not just the first peer.
///
/// This is the multi-peer complement to
/// `reactor_fill_loop_saturates_multiple_slots_in_one_pass`: with three peers
/// each advertising four concurrent single-block slots and twelve needed
/// heights, the fill loop must fan out four requests to *each* peer rather than
/// pouring all twelve into the lowest-id peer (or stopping after one peer's
/// window). A regression here is what makes download budget collect on a single
/// peer while the rest sit idle with free slots.
#[tokio::test]
async fn reactor_fill_loop_saturates_every_peer_window_not_just_one() {
    let config = fill_loop_mechanics_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Three peers, each willing to serve heights 1..=12 and accept four
    // concurrent single-block requests. The budget is ample, so the fill order
    // (rotated per pass) does not matter here: every peer's window is saturated
    // in the single pass regardless of which peer the rotation starts at.
    let mut peer_ids = Vec::new();
    // Keep every peer's stream handles alive for the whole test: dropping them
    // closes the channels and tears the peer down before it can serve.
    let mut peer_streams = Vec::new();
    for byte in [41u8, 42, 43] {
        let (peer_id, inbound, outbound) = connect_peer_with_status_message(
            &service,
            &mut actions,
            byte,
            BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(12),
                tip_hash: block::Hash([12; 32]),
                max_blocks_per_response: 1,
                max_inflight_requests: 4,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            },
        )
        .await;
        peer_ids.push(peer_id);
        peer_streams.push((inbound, outbound));
    }

    tip_tx
        .send((block::Height(12), block::Hash([12; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=12)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([height as u8; 32]),
                    size: BlockSizeEstimate::Advertised(1_000),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    // Collect all twelve requests and tally them per peer. With fanout=1 each
    // height is assignable to exactly one peer, so a correct fill loop hands
    // four distinct heights to each of the three peers. Which peer receives which
    // height is nondeterministic (the routines race for shared work), so observe
    // every peer's real outbound and attribute each `GetBlocks` to the peer whose
    // stream it arrived on.
    let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> = peer_ids
        .iter()
        .cloned()
        .zip(peer_streams.iter_mut().map(|(_, outbound)| outbound))
        .collect();
    let mut per_peer: HashMap<ZakuraPeerId, Vec<u32>> = HashMap::new();
    for _ in 0..12 {
        let (peer, start_height, count) = wait_for_getblocks_across(&mut outbound_by_peer).await;
        assert_eq!(count, 1);
        per_peer.entry(peer).or_default().push(start_height.0);
    }

    assert_eq!(
        per_peer.len(),
        3,
        "all three peers must receive requests, not just the first; got {per_peer:?}"
    );
    for peer_id in &peer_ids {
        let issued = per_peer
            .get(peer_id)
            .unwrap_or_else(|| panic!("peer {peer_id:?} received no requests: {per_peer:?}"));
        assert_eq!(
            issued.len(),
            4,
            "peer {peer_id:?} window of 4 was not saturated: {per_peer:?}"
        );
    }

    let mut all_heights: Vec<u32> = per_peer.values().flatten().copied().collect();
    all_heights.sort_unstable();
    assert_eq!(
        all_heights,
        (1..=12).collect::<Vec<_>>(),
        "every needed height must be requested exactly once across peers"
    );

    reactor_task.abort();
}

/// Under a budget that only covers one in-flight request at a time, issuance
/// must rotate across the status-ready peers rather than always pouring the
/// single budgeted request into the lowest-node-id peer.
///
/// Per-peer routines replace the central full-pass `fill_rotation_cursor`: per-peer routines
/// race for the shared work, with the per-peer byte cap as the fairness mechanism
/// for multi-height work. For a single contested height with fanout=1 there is no
/// per-round rotation guarantee (whichever routine's `take_in_range` wins the race
/// gets it). The invariant this still pins is that the contested height stays
/// **contestable** and is re-offered every time a peer fails it — no wedge, no
/// stall — which is the property that actually matters for liveness. (The
/// honest-peer-eventually-offered property is also covered by
/// `reactor_does_not_wedge_honest_peer_under_range_unavailable_spam`.)
#[tokio::test]
async fn reactor_budget_constrained_issuance_rotates_across_peers() {
    let config = fill_loop_mechanics_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Three peers, each able to serve height 1 with a single in-flight slot.
    // Distinct ascending id bytes give the old sorted order a fixed lowest peer
    // (0x41) that a regression would always pick first.
    let mut peer_inbounds = HashMap::new();
    // Keep every peer's outbound handle alive too (dropping it closes the channel
    // and tears the peer down before it can be offered work), paired with the peer
    // id so the observed `GetBlocks` can be attributed to the peer whose stream it
    // arrived on.
    let mut peer_outbounds = Vec::new();
    for byte in [0x41u8, 0x42, 0x43] {
        let (peer_id, inbound, outbound) = connect_peer_with_status_message(
            &service,
            &mut actions,
            byte,
            BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 1,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            },
        )
        .await;
        peer_inbounds.insert(peer_id.clone(), inbound);
        peer_outbounds.push((peer_id, outbound));
    }

    tip_tx
        .send((block::Height(1), block::Hash([1; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block::Hash([1; 32]),
            size: BlockSizeEstimate::Advertised(1_000),
        }]))
        .await
        .expect("needed metadata queues");

    // A single contested height with fanout=1 can be assigned to exactly one
    // peer at a time. Each pass offers it to the rotation-start peer; that peer
    // answers `RangeUnavailable`, which re-queues the range and runs another full
    // pass. The rotating cursor advances once per pass, so over several passes
    // the offered peer rotates instead of pinning to the lowest-id peer (which is
    // what the old static sorted order did).
    let range_unavailable = BlockSyncMessage::RangeUnavailable {
        start_height: block::Height(1),
        count: 1,
    }
    .encode_frame()
    .expect("RangeUnavailable frame encodes");

    // Each round the contested height must be re-offered to *some* connected peer
    // (no wedge), and that peer answers `RangeUnavailable` to return it to the
    // shared queue for the next round. Observe every peer's real outbound and learn
    // which peer the routine actually asked.
    let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> = peer_outbounds
        .iter_mut()
        .map(|(peer_id, outbound)| (peer_id.clone(), outbound))
        .collect();
    for round in 0..6 {
        let (peer, start_height, count) = wait_for_getblocks_across(&mut outbound_by_peer).await;
        assert_eq!(start_height, block::Height(1));
        assert_eq!(count, 1, "fanout=1 yields single-block requests");
        let inbound = peer_inbounds.get(&peer).unwrap_or_else(|| {
            panic!("round {round}: served peer {peer:?} must be one of the connected peers")
        });
        inbound
            .send(range_unavailable.clone())
            .await
            .expect("RangeUnavailable frame queues");
    }

    reactor_task.abort();
}

/// One peer whose request times out enters local recovery and must not block the
/// other peers from being filled out of the same shared work.
///
/// This is the timeout-locality invariant: a slow peer's recovery is local to
/// that peer. The retry path re-queues the timed-out range to a *different*
/// servable peer, so the healthy peer keeps making progress while the slow peer
/// is in recovery rather than the whole download stalling behind one straggler.
#[tokio::test]
async fn reactor_timeout_recovery_is_local_and_healthy_peer_keeps_filling() {
    let mut config = fill_loop_mechanics_config();
    // A request timeout long enough that the opening pass fans both heights out
    // before anything expires, but short enough that the slow peer's unanswered
    // request still times out within the test window.
    config.request_timeout = Duration::from_millis(400);
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 64;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Two peers, both able to serve heights 1..=2 with a single in-flight slot.
    // One will be left holding an unanswered request (the slow peer); the other
    // answers and must keep being filled from the same shared work — including
    // the slow peer's range once it times out and re-queues.
    let status = || BlockSyncStatus {
        servable_low: block::Height(1),
        servable_high: block::Height(2),
        tip_hash: block::Hash([2; 32]),
        max_blocks_per_response: 1,
        max_inflight_requests: 1,
        max_response_bytes: MAX_BS_RESPONSE_BYTES,
    };
    let (peer_a, a_in, mut a_out) =
        connect_peer_with_status_message(&service, &mut actions, 0x41, status()).await;
    let (peer_b, b_in, mut b_out) =
        connect_peer_with_status_message(&service, &mut actions, 0x42, status()).await;
    let mut inbounds = HashMap::from([(peer_a.clone(), a_in), (peer_b.clone(), b_in)]);

    tip_tx
        .send((block::Height(2), block::Hash([2; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: block::Hash([1; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: block::Hash([2; 32]),
                size: BlockSizeEstimate::Advertised(1_000),
            },
        ]))
        .await
        .expect("needed metadata queues");

    // Observe both peers' real outbounds; which peer is offered which height is
    // nondeterministic, so attribute each `GetBlocks` to the peer whose stream it
    // arrived on.
    let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> =
        vec![(peer_a.clone(), &mut a_out), (peer_b.clone(), &mut b_out)];

    // Opening pass: with fanout=1 each peer is offered one of the two heights.
    let first = wait_for_getblocks_across(&mut outbound_by_peer).await;
    let second = wait_for_getblocks_across(&mut outbound_by_peer).await;
    let mut offered: HashMap<ZakuraPeerId, block::Height> = HashMap::new();
    offered.insert(first.0.clone(), first.1);
    offered.insert(second.0.clone(), second.1);
    assert_eq!(
        offered.len(),
        2,
        "both peers must be offered a height in the opening pass: {offered:?}"
    );

    // Pick one peer to be the straggler (it never answers) and the other to be
    // healthy. The healthy peer answers `RangeUnavailable` for its own range so
    // it frees its slot without committing anything; the straggler's range then
    // times out and re-queues. Because timeout recovery is local to the
    // straggler, the healthy peer must keep being offered the re-queued shared
    // work rather than the whole download stalling behind the straggler.
    let healthy = peer_b.clone();
    let healthy_in = inbounds.remove(&healthy).expect("healthy peer inbound");

    let healthy_offers = tokio::time::timeout(Duration::from_secs(3), async {
        let mut count = 0usize;
        loop {
            // Whenever the healthy peer is offered a range, free its slot with a
            // `RangeUnavailable` so it can be offered the next range; the slow
            // peer never answers and stays in timeout recovery.
            let (peer, start_height, count_blocks) =
                wait_for_getblocks_across(&mut outbound_by_peer).await;
            if peer == healthy {
                count += 1;
                if count >= 2 {
                    break count;
                }
                healthy_in
                    .send(
                        BlockSyncMessage::RangeUnavailable {
                            start_height,
                            count: count_blocks,
                        }
                        .encode_frame()
                        .expect("RangeUnavailable frame encodes"),
                    )
                    .await
                    .expect("RangeUnavailable frame queues");
            }
        }
    })
    .await
    .expect(
        "the healthy peer must keep being offered shared work while the slow peer \
         is in timeout recovery; a stall here means a straggler wedged the pass",
    );
    assert!(
        healthy_offers >= 2,
        "the healthy peer was filled repeatedly despite the slow peer's timeout recovery"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn block_liveness_disconnects_silent_peer_and_traces_reason() {
    let mut capture =
        TraceCapture::for_test("block_liveness_disconnects_silent_peer_and_traces_reason")
            .expect("trace capture initializes");
    let mut config = immediate_body_download_config();
    config.request_timeout = Duration::from_millis(400);
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 64;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let mut startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    startup.trace = ZakuraTrace::new(capture.tracer(), "01");
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let peer = peer(0x51);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    let connection_cancel = CancellationToken::new();
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        connection_cancel.clone(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 1,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(1), block::Hash([1; 32])))
        .expect("tip watch is live");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(1)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block::Hash([1; 32]),
            size: BlockSizeEstimate::Advertised(1_000),
        }]))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(count, 1);

    tokio::time::timeout(Duration::from_secs(3), connection_cancel.cancelled())
        .await
        .expect("silent active peer is disconnected by block-progress liveness");

    capture.flush().await;
    let reader = capture.reader().expect("trace rows load");
    reader.table("block_sync").assert_row(
        bs_trace::BLOCK_GET_BLOCKS_SENT,
        &[
            ("requests_without_block_progress", TraceValue::U64(1)),
            ("no_progress_request_cap", TraceValue::U64(1)),
            ("block_progress_proven", TraceValue::U64(0)),
        ],
    );
    reader.table("block_sync").assert_row(
        bs_trace::BLOCK_PEER_PROTOCOL_REJECT,
        &[(
            bs_trace::REASON,
            TraceValue::Str("block_sync_no_block_progress"),
        )],
    );

    reactor_task.abort();
}

#[tokio::test]
async fn block_liveness_credits_late_unmatched_body_and_keeps_peer() {
    // Regression: a peer whose probe times out but that then delivers the body late
    // — after its own outstanding request was already removed, so the body arrives
    // through the unmatched-queued path — must be credited with block progress and
    // kept. Before the fix, `accept_unmatched_queued_body` buffered the useful body
    // without resetting the no-progress streak or proving the peer, so the peer was
    // disconnected at the liveness deadline despite delivering the block we accepted.
    let mut config = immediate_body_download_config();
    // Short request/floor-rescue leash so the probe times out fast; the liveness
    // deadline (request_timeout * 4 = 1.2s) is what a false disconnect would trip.
    config.request_timeout = Duration::from_millis(300);
    config.floor_rescue_timeout = Duration::from_millis(120);
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 64;

    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let peer = peer(0x53);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    let connection_cancel = CancellationToken::new();
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        connection_cancel.clone(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: blocks[0].hash(),
                max_blocks_per_response: 1,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(1), blocks[0].hash()))
        .expect("tip watch is live");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(1)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[0])]))
        .await
        .expect("needed metadata queues");

    // The peer receives exactly one probe (the initial unproven budget), which arms
    // its liveness deadline.
    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(count, 1);

    // Let that probe time out on the floor-rescue leash: height 1 returns to the
    // queue and, being unproven, the peer is now gated at its one-probe cap.
    tokio::time::sleep(Duration::from_millis(200)).await;

    // The body arrives late, matching no outstanding request → the unmatched-queued
    // path buffers and forwards it.
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("late block frame queues");

    // Non-vacuous: the late body was accepted (forwarded for submission).
    let submitted = tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            match next_action(&mut actions).await {
                BlockSyncAction::SubmitBlock { block, .. } => break block.coinbase_height(),
                _ => continue,
            }
        }
    })
    .await
    .expect("the late unmatched body is accepted and submitted");
    assert_eq!(submitted, Some(block::Height(1)));

    // The credited progress must keep the peer alive past the liveness deadline
    // (1.2s from the probe). Before the fix the peer was disconnected here.
    assert!(
        tokio::time::timeout(Duration::from_millis(1500), connection_cancel.cancelled())
            .await
            .is_err(),
        "a peer that delivered an accepted (late) body must not be parked as silent",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn peer_emits_periodic_bbr_heartbeat_while_idle() {
    // The per-peer `block_peer_bbr` heartbeat fires on a fixed cadence even while the
    // peer is idle (its interval's first tick is immediate), so the controller state is
    // observable between deliveries. A freshly-connected, unproven, idle peer must emit
    // at least one heartbeat carrying the BBR fields, with reliability at the optimistic
    // full value and no proven progress yet.
    let mut capture = TraceCapture::for_test("peer_emits_periodic_bbr_heartbeat_while_idle")
        .expect("trace capture initializes");
    let config = immediate_body_download_config();

    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let mut startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    startup.trace = ZakuraTrace::new(capture.tracer(), "01");
    let (_handle, _actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, _handle.clone());

    let peer = peer(0x5b);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 1,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    // Let the routine reach its idle select loop and fire the immediate heartbeat tick.
    tokio::time::sleep(Duration::from_millis(100)).await;

    capture.flush().await;
    let reader = capture.reader().expect("trace rows load");
    reader.table("block_sync").assert_row(
        bs_trace::BLOCK_PEER_BBR,
        &[
            ("bbr_reliability_permille", TraceValue::U64(1000)),
            ("block_progress_proven", TraceValue::U64(0)),
            ("bbr_phase", TraceValue::U64(0)),
        ],
    );

    reactor_task.abort();
}

// The old covered-prefix / assigned-key / queued-retry-ordering scheduler tests
// (`scheduler_partial_*`, `scheduler_drops_*`, `scheduler_splits_*`,
// `scheduler_retries_only_uncovered_suffix`, `scheduler_keeps_queued_*`,
// `scheduler_releases_budget_*`) are removed: the WorkQueue replaces the
// covered/assigned bookkeeping with `in_flight`, the byte budget moves to the
// reactor's `fill_peer`, and a `BTreeMap` keeps ascending order by construction.
// The remaining WorkQueue-owned behaviors (dedup, range eligibility, GC, the
// size-estimate clamp, and ordering diagnostics) are asserted here; commit-1 /
// commit-3 byte behavior is covered by the reactor integration tests.

#[test]
fn work_queue_estimate_clamps_hint_between_floor_and_max_block_bytes() {
    use super::work_queue::DEFAULT_BS_SIZE_FLOOR_BYTES;

    // Default estimator: Unknown -> worst case; tiny hints clamp up to the floor;
    // huge hints clamp down to MAX_BLOCK_BYTES; ordinary hints pass through.
    let queue = super::work_queue::WorkQueue::new(block::Height(0));
    queue.extend([
        needed(1, BlockSizeEstimate::Unknown),
        needed(2, BlockSizeEstimate::Advertised(1)), // below the floor
        needed(3, BlockSizeEstimate::Advertised(12_345)),
        needed(4, BlockSizeEstimate::Confirmed(u32::MAX)), // above MAX_BLOCK_BYTES
    ]);
    let item = |height| {
        queue
            .take_in_range(block::Height(height), block::Height(height), 1)
            .pop()
            .expect("height present")
            .1
            .estimated_bytes
    };
    assert_eq!(item(1), block::MAX_BLOCK_BYTES);
    assert_eq!(item(2), DEFAULT_BS_SIZE_FLOOR_BYTES);
    assert_eq!(item(3), 12_345);
    assert_eq!(item(4), block::MAX_BLOCK_BYTES);

    // The test estimator override changes the floor clamp.
    let tuned = super::work_queue::WorkQueue::new(block::Height(0));
    tuned.set_estimate_floor_for_tests(100);
    tuned.extend([
        needed(10, BlockSizeEstimate::Unknown),
        needed(11, BlockSizeEstimate::Advertised(50)), // below the tuned floor
    ]);
    assert_eq!(
        tuned
            .take_in_range(block::Height(10), block::Height(10), 1)
            .pop()
            .unwrap()
            .1
            .estimated_bytes,
        block::MAX_BLOCK_BYTES
    );
    assert_eq!(
        tuned
            .take_in_range(block::Height(11), block::Height(11), 1)
            .pop()
            .unwrap()
            .1
            .estimated_bytes,
        100
    );
}

#[test]
fn work_queue_diagnostics_report_runs_min_and_max() {
    // Two contiguous runs (10..=12 and 20..=21) plus an in-flight height feed the
    // BLOCK_SYNC_STATE trace remaps (queue_len -> runs, queue_blocks -> pending,
    // queue_min_start -> min_pending, covered_max_end -> max_in_flight).
    let queue = work_queue_with(
        0,
        [
            needed(10, BlockSizeEstimate::Advertised(100)),
            needed(11, BlockSizeEstimate::Advertised(100)),
            needed(12, BlockSizeEstimate::Advertised(100)),
            needed(20, BlockSizeEstimate::Advertised(100)),
            needed(21, BlockSizeEstimate::Advertised(100)),
        ],
    );
    assert_eq!(queue.pending_run_count(), 2);
    assert_eq!(queue.pending_len(), 5);
    assert_eq!(queue.min_pending(), Some(block::Height(10)));
    assert_eq!(queue.max_in_flight(), None);

    queue.take_in_range(block::Height(20), block::Height(21), 2);
    assert_eq!(queue.pending_run_count(), 1, "the 20..=21 run was taken");
    assert_eq!(queue.min_pending(), Some(block::Height(10)));
    assert_eq!(queue.max_in_flight(), Some(block::Height(21)));
    assert_eq!(
        queue.hash_for_height(block::Height(21)),
        Some(block::Hash([21; 32]))
    );
    assert_eq!(
        queue.hash_for_height(block::Height(12)),
        Some(block::Hash([12; 32]))
    );
    assert_eq!(queue.hash_for_height(block::Height(99)), None);
}

#[test]
fn work_queue_keeps_pending_ordered_by_height() {
    // A BTreeMap keeps the lowest needed height first regardless of extend order,
    // so a newly-needed lower height never sits behind later queued work.
    let queue = super::work_queue::WorkQueue::new(block::Height(0));
    queue.extend([needed(20, BlockSizeEstimate::Advertised(100))]);
    queue.extend([needed(10, BlockSizeEstimate::Advertised(100))]);
    assert_eq!(queue.min_pending(), Some(block::Height(10)));
    let taken = queue.take_in_range(block::Height(1), block::Height(30), 1);
    assert_eq!(
        taken[0].0,
        block::Height(10),
        "lower work must be taken before higher work"
    );
}

#[test]
fn reorder_drains_only_contiguous_prefix_and_reports_dropped_bytes() {
    // The reorder buffer never touches the byte budget: it maintains only the
    // retained-size accounting (`buffered_bytes`) the resident gate reads, and
    // its drop paths report the freed bytes for that accounting.
    let mut reorder = ReorderBuffer::new();
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);

    assert_eq!(
        reorder.insert(block::Height(3), block.clone(), 300, peer(0)),
        ReorderInsertResult::Inserted
    );
    assert!(reorder.drain_contiguous_prefix(block::Height(0)).is_empty());
    assert_eq!(reorder.buffered_bytes(), 300);

    assert_eq!(
        reorder.insert(block::Height(1), block.clone(), 100, peer(0)),
        ReorderInsertResult::Inserted
    );
    let released = reorder.drain_contiguous_prefix(block::Height(0));
    assert_eq!(
        released
            .iter()
            .map(|drained| (drained.height, drained.bytes))
            .collect::<Vec<_>>(),
        vec![(block::Height(1), 100)]
    );
    // Draining the contiguous prefix hands bytes to the apply stage; height 3
    // stays buffered behind the gap at 2.
    assert_eq!(reorder.buffered_bytes(), 300);

    assert_eq!(
        reorder.insert(block::Height(2), block.clone(), 200, peer(0)),
        ReorderInsertResult::Inserted
    );
    let released = reorder.drain_contiguous_prefix(block::Height(1));
    assert_eq!(
        released
            .iter()
            .map(|drained| (drained.height, drained.bytes))
            .collect::<Vec<_>>(),
        vec![(block::Height(2), 200), (block::Height(3), 300)]
    );
    assert_eq!(reorder.buffered_bytes(), 0);

    assert_eq!(
        reorder.insert(block::Height(2), block.clone(), 200, peer(0)),
        ReorderInsertResult::Inserted
    );
    assert_eq!(
        reorder.insert(block::Height(3), block, 300, peer(0)),
        ReorderInsertResult::Inserted
    );
    // `drop_from`/`drop_through`/`clear` return the bytes their dropped bodies
    // held, keeping `buffered_bytes` consistent for the resident view.
    assert_eq!(reorder.drop_from(block::Height(3)), 300);
    assert_eq!(reorder.buffered_bytes(), 200);
    assert_eq!(
        reorder.decoded_attributed_memory_bytes(),
        reorder.decoded_attributed_memory_bytes_scanned()
    );
    assert_eq!(reorder.drop_through(block::Height(2)), 200);
    assert_eq!(reorder.buffered_bytes(), 0);
    assert_eq!(reorder.decoded_attributed_memory_bytes(), 0);
    assert_eq!(
        reorder.insert(
            block::Height(3),
            mainnet_block(&BLOCK_MAINNET_1_BYTES),
            300,
            peer(0)
        ),
        ReorderInsertResult::Inserted
    );
    assert_eq!(reorder.clear(), 300);
    assert_eq!(reorder.buffered_bytes(), 0);
    assert_eq!(reorder.decoded_attributed_memory_bytes(), 0);
}

// ---- Sequencer commit pipeline ----

fn test_sequencer(verified_tip: u32, submitted_apply_limit: usize) -> Sequencer {
    Sequencer::new(block::Height(verified_tip), submitted_apply_limit)
}

#[test]
fn sequencer_accept_body_buffers_then_reports_duplicate() {
    let mut seq = test_sequencer(0, 4);
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    let hash = block.hash();
    let decoded_attributed_memory_size_bytes = block.attributed_memory_size_bytes();
    // First arrival above the floor buffers the body and reports its covered
    // height; the reorder buffer takes ownership of the reservation.
    assert_eq!(
        seq.accept_body(block::Height(1), hash, block.clone(), 100, peer(0)),
        AcceptOutcome::Buffered {
            covered: block::Height(1)
        }
    );
    assert!(seq.reorder_contains(block::Height(1)));
    assert_eq!(
        seq.reorder_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_size_bytes
    );
    // A second arrival of the same buffered height is redundant; its bytes are
    // handed back for the reactor to release.
    assert_eq!(
        seq.accept_body(block::Height(1), hash, block, 100, peer(0)),
        AcceptOutcome::Redundant { release_bytes: 100 }
    );
    assert_eq!(
        seq.reorder_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_size_bytes
    );
    assert_eq!(
        seq.reorder_decoded_attributed_memory_bytes(),
        seq.reorder_decoded_attributed_memory_bytes_scanned()
    );
}

#[test]
fn sequencer_retains_raw_bytes_for_non_contiguous_backlog() {
    let mut seq = test_sequencer(0, 4);
    let blocks = mainnet_blocks_1_to_3();
    let block1 = blocks[0].clone();
    let block2 = blocks[1].clone();
    let distinguishable_decoded_block2 = forked_block(&block2, 99);

    assert_ne!(distinguishable_decoded_block2.hash(), block2.hash());
    assert_eq!(
        distinguishable_decoded_block2.coinbase_height(),
        block2.coinbase_height()
    );

    let block2_body = BufferedBlockBody::from_decoded_block(
        distinguishable_decoded_block2.clone(),
        Some(raw_block_payload(&block2)),
    );

    assert_eq!(
        seq.accept_buffered_body(
            block::Height(2),
            block2.hash(),
            block2.header.previous_block_hash,
            block2_body,
            200,
            peer(0)
        ),
        AcceptOutcome::Buffered {
            covered: block::Height(2)
        }
    );
    assert!(seq.drain_ready_into_applying().is_empty());
    assert!(seq.reorder_contains(block::Height(2)));
    assert_eq!(seq.reorder_decoded_attributed_memory_bytes(), 0);
    assert_eq!(
        seq.reorder_decoded_attributed_memory_bytes(),
        seq.reorder_decoded_attributed_memory_bytes_scanned()
    );

    assert_eq!(
        seq.accept_body(
            block::Height(1),
            block1.hash(),
            block1.clone(),
            100,
            peer(0),
        ),
        AcceptOutcome::Buffered {
            covered: block::Height(1)
        }
    );
    assert_eq!(
        seq.drain_ready_into_applying(),
        vec![block::Height(1), block::Height(2)]
    );
    assert_eq!(seq.applying_hash(block::Height(2)), Some(block2.hash()));
    // The backlogged body kept only its raw payload, so submission decodes the
    // raw bytes (block2), not the dropped decoded copy (the distinguishable fork).
    let submitted = seq
        .prepare_submit(block::Height(2))
        .expect("height 2 is applying");
    assert_eq!(submitted.block.hash(), block2.hash());
    assert_ne!(
        submitted.block.hash(),
        distinguishable_decoded_block2.hash()
    );
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        block1
            .attributed_memory_size_bytes()
            .saturating_add(block2.attributed_memory_size_bytes())
    );
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        seq.applying_decoded_attributed_memory_bytes_scanned()
    );
}

#[test]
fn sequencer_bounds_decoded_bodies_to_submission_window() {
    // A deep contiguous backlog must not hold decoded blocks beyond the
    // submission window: everything past the free submit slots stays as raw
    // bytes until `prepare_submit` decodes it.
    let limit = 2;
    let mut seq = test_sequencer(0, limit);
    let blocks = mainnet_blocks_1_to_3();

    for (index, block) in blocks.iter().enumerate() {
        let height = block::Height(index as u32 + 1);
        let body =
            BufferedBlockBody::from_decoded_block(block.clone(), Some(raw_block_payload(block)));
        assert_eq!(
            seq.accept_buffered_body(
                height,
                block.hash(),
                block.header.previous_block_hash,
                body,
                100,
                peer(0)
            ),
            AcceptOutcome::Buffered { covered: height }
        );
    }

    assert_eq!(
        seq.drain_ready_into_applying(),
        vec![block::Height(1), block::Height(2), block::Height(3)]
    );
    assert_eq!(seq.applying_len(), 3);
    assert!(
        seq.decoded_applying_count() <= limit,
        "decoded applying bodies ({}) exceed the submission window ({limit})",
        seq.decoded_applying_count(),
    );

    // Submission decodes exactly the window; the backlog tail stays raw.
    for height in seq.submittable_heights() {
        seq.prepare_submit(height).expect("height is applying");
    }
    assert_eq!(seq.in_flight_submission_count(), limit);
    assert_eq!(seq.decoded_applying_count(), limit);

    // Rolling a submission back also rolls its body out of the decode window.
    seq.unsubmit(block::Height(1), 1);
    assert_eq!(seq.decoded_applying_count(), limit - 1);
}

#[test]
fn sequencer_applying_counters_match_scan_across_transitions() {
    // Assert the O(1) applying and in-flight-submission counters never drift
    // from their ground truth across insert / submit / unsubmit / detach /
    // completion / commit-release / reset.
    let mut seq = test_sequencer(0, 8);
    let blocks = mainnet_blocks_1_to_3();
    let check = |seq: &Sequencer, label: &str| {
        assert_eq!(
            seq.applying_buffered_bytes(),
            seq.applying_buffered_bytes_scanned(),
            "applying_buffered_bytes drifted after {label}"
        );
        assert_eq!(
            seq.applying_decoded_attributed_memory_bytes(),
            seq.applying_decoded_attributed_memory_bytes_scanned(),
            "applying_decoded_attributed_memory_bytes drifted after {label}"
        );
        assert_eq!(
            seq.reorder_decoded_attributed_memory_bytes(),
            seq.reorder_decoded_attributed_memory_bytes_scanned(),
            "reorder_decoded_attributed_memory_bytes drifted after {label}"
        );
        assert_eq!(
            seq.in_flight_submission_count(),
            seq.in_flight_submission_count_scanned(),
            "in_flight_submission_count drifted after {label}"
        );
        assert_eq!(
            seq.in_flight_submission_bytes(),
            seq.in_flight_submission_bytes_scanned(),
            "in_flight_submission_bytes drifted after {label}"
        );
        assert_eq!(
            seq.unsubmitted_applying_count(),
            seq.applying_len() - seq.attached_submission_count_scanned(),
            "unsubmitted derivation wrong after {label}"
        );
    };

    // Buffer heights 1..=3 with distinct sizes and drain them into `applying`.
    for (i, block) in blocks.iter().enumerate() {
        let height = (i + 1) as u32;
        seq.accept_body(
            block::Height(height),
            block.hash(),
            block.clone(),
            100 * u64::from(height),
            peer(0),
        );
    }
    assert_eq!(
        seq.drain_ready_into_applying(),
        vec![block::Height(1), block::Height(2), block::Height(3)]
    );
    assert_eq!(seq.applying_buffered_bytes(), 600);
    assert_eq!(seq.in_flight_submission_count(), 0);
    check(&seq, "drain");

    // Submit heights 1 and 2.
    let item1 = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 applying");
    let item2 = seq
        .prepare_submit(block::Height(2))
        .expect("height 2 applying");
    assert_eq!(seq.in_flight_submission_count(), 2);
    assert_eq!(seq.in_flight_submission_bytes(), 300);
    assert_eq!(seq.unsubmitted_applying_count(), 1);
    check(&seq, "submit 1,2");

    // Roll back the submit for height 1.
    seq.unsubmit(block::Height(1), item1.token);
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(seq.in_flight_submission_bytes(), 200);
    check(&seq, "unsubmit 1");

    // Detaching the still-submitted height 2 does not release the driver-owned
    // decoded body or its submission-window charge.
    seq.remove_applying(block::Height(2));
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(seq.in_flight_submission_bytes(), 200);
    assert_eq!(seq.applying_buffered_bytes(), 400);
    check(&seq, "detach submitted 2");
    assert!(seq.finish_submission(item2.token, item2.height, item2.hash));
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(seq.in_flight_submission_bytes(), 0);
    check(&seq, "finish detached 2");

    // Commit through height 1: releases the applied body (height 1) from `applying`.
    seq.advance_verified_tip(block::Height(1), true);
    assert_eq!(seq.applying_buffered_bytes(), 300);
    check(&seq, "advance_verified_tip");

    // Reset drops all applying state; there are no in-flight submissions left.
    seq.reset_to(block::Height(0), false);
    assert_eq!(seq.applying_buffered_bytes(), 0);
    assert_eq!(seq.applying_decoded_attributed_memory_bytes(), 0);
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(seq.in_flight_submission_bytes(), 0);
    check(&seq, "reset");
}

#[tokio::test]
async fn sequencer_stale_checkpoint_completions_refill_full_submission_window() {
    const BLOCK_COUNT: u32 = 403;
    const CHANNEL_TIMEOUT: Duration = Duration::from_secs(2);
    const MISSING_SUBMISSION_TIMEOUT: Duration = Duration::from_millis(100);

    let submission_limit = MIN_BS_CHECKPOINT_SUBMITTED_BLOCK_APPLIES;
    let submission_limit_u64 =
        u64::try_from(submission_limit).expect("the checkpoint submission limit fits in u64");
    let body_channel_capacity = usize::try_from(BLOCK_COUNT).expect("403 test bodies fit in usize");
    assert_eq!(submission_limit, 401);

    let blocks = fake_sequential_blocks(BLOCK_COUNT);
    let frontiers = BlockSyncFrontiers {
        finalized_height: block::Height(0),
        verified_block_tip: block::Height(0),
        verified_block_hash: block::Hash([0; 32]),
    };
    let body_input_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let body_input_decoded_attributed_memory_bytes = Arc::new(std::sync::atomic::AtomicU64::new(0));
    let (body_tx, body_rx) = mpsc::channel(body_channel_capacity);
    let (control_tx, control_rx) = mpsc::unbounded_channel();
    let (actions_tx, mut actions_rx) = mpsc::channel(submission_limit + 128);
    let (view_tx, mut view_rx) = watch::channel(initial_view(frontiers));
    let task = SequencerTask::new(
        Sequencer::new(block::Height(0), submission_limit),
        ByteBudget::new(1),
        Arc::new(WorkQueue::new(block::Height(0))),
        actions_tx,
        ThroughputMeter::new(Instant::now()),
        frontiers,
        body_rx,
        control_rx,
        body_input_bytes.clone(),
        body_input_decoded_attributed_memory_bytes.clone(),
        view_tx,
        CHANNEL_TIMEOUT,
        ZakuraTrace::noop(),
    );
    let task = tokio::spawn(task.run());

    for (index, block) in blocks.iter().enumerate() {
        let height =
            block::Height(u32::try_from(index + 1).expect("403 test block indices fit in u32"));
        body_tx
            .send(SequencedBody::new_queued(
                height,
                block.hash(),
                block.header.previous_block_hash,
                BufferedBlockBody::from_decoded_block(
                    block.clone(),
                    Some(raw_block_payload(block)),
                ),
                u64::from(block_size(block)),
                peer(1),
                Instant::now(),
                body_input_bytes.clone(),
                body_input_decoded_attributed_memory_bytes.clone(),
            ))
            .await
            .expect("sequencer body channel remains live");
    }

    time::timeout(CHANNEL_TIMEOUT, async {
        loop {
            let view = *view_rx.borrow_and_update();
            if view.applying_len == u64::from(BLOCK_COUNT)
                && view.in_flight_submission_count == submission_limit_u64
                && view.unsubmitted_applying_count == 2
            {
                break;
            }
            view_rx
                .changed()
                .await
                .expect("sequencer view remains live");
        }
    })
    .await
    .expect("all bodies reach applying and fill the initial submission window");

    let mut initial_submissions = Vec::with_capacity(submission_limit);
    while initial_submissions.len() < submission_limit {
        let action = time::timeout(CHANNEL_TIMEOUT, actions_rx.recv())
            .await
            .expect("initial submission action arrives")
            .expect("sequencer action channel remains live");
        match action {
            BlockSyncAction::SubmitBlock { token, block } => {
                initial_submissions.push((token, block));
            }
            action => panic!("unexpected action before initial submissions complete: {action:?}"),
        }
    }
    for (index, (_, block)) in initial_submissions.iter().enumerate() {
        assert_eq!(
            block.coinbase_height(),
            Some(block::Height(
                u32::try_from(index + 1).expect("401 submission indices fit in u32")
            )),
            "initial submissions must be ordered through the full checkpoint window",
        );
    }

    let (token_1, block_1) = &initial_submissions[0];
    control_tx
        .send(SequencerControlInput::ApplyFinished {
            token: *token_1,
            height: block::Height(1),
            hash: block_1.hash(),
            result: BlockApplyResult::Committed,
            local_frontier: Some(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(3),
                verified_block_hash: blocks[2].hash(),
            }),
        })
        .expect("height 1 completion queues");

    let block_402 = match time::timeout(CHANNEL_TIMEOUT, actions_rx.recv())
        .await
        .expect("height 402 submission arrives")
        .expect("sequencer action channel remains live")
    {
        BlockSyncAction::SubmitBlock { block, .. } => block,
        action => panic!("unexpected action before height 402 submission: {action:?}"),
    };
    assert_eq!(block_402.coinbase_height(), Some(block::Height(402)));

    for (height, (token, block)) in [
        (block::Height(2), &initial_submissions[1]),
        (block::Height(3), &initial_submissions[2]),
    ] {
        control_tx
            .send(SequencerControlInput::ApplyFinished {
                token: *token,
                height,
                hash: block.hash(),
                result: BlockApplyResult::Committed,
                local_frontier: Some(BlockSyncFrontiers {
                    finalized_height: block::Height(0),
                    verified_block_tip: block::Height(3),
                    verified_block_hash: blocks[2].hash(),
                }),
            })
            .expect("stale checkpoint completion queues");
    }

    let submit_403 = time::timeout(MISSING_SUBMISSION_TIMEOUT, async {
        loop {
            let action = actions_rx
                .recv()
                .await
                .expect("sequencer action channel remains live");
            if let BlockSyncAction::SubmitBlock { block, .. } = action {
                assert_eq!(block.coinbase_height(), Some(block::Height(403)));
                break;
            }
        }
    })
    .await;
    let diagnostic = *view_rx.borrow();
    assert!(
        submit_403.is_ok(),
        "height 403 must refill the checkpoint submission window; \
         in_flight_submission_count = {}, unsubmitted_applying_count = {}",
        diagnostic.in_flight_submission_count,
        diagnostic.unsubmitted_applying_count,
    );

    time::timeout(CHANNEL_TIMEOUT, async {
        loop {
            let view = *view_rx.borrow_and_update();
            if view.in_flight_submission_count == 400 && view.unsubmitted_applying_count == 0 {
                break;
            }
            view_rx
                .changed()
                .await
                .expect("sequencer view remains live");
        }
    })
    .await
    .expect("stale completions settle with a refilled checkpoint submission window");

    task.abort();
}

#[test]
fn sequencer_accept_body_rejects_at_or_below_floor() {
    let mut seq = test_sequencer(5, 4);
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    assert_eq!(
        seq.accept_body(block::Height(5), block.hash(), block.clone(), 100, peer(0)),
        AcceptOutcome::Redundant { release_bytes: 100 }
    );
    assert!(!seq.reorder_contains(block::Height(5)));
}

#[test]
fn sequencer_drains_contiguous_prefix_into_applying_and_advances_floor() {
    let mut seq = test_sequencer(0, 8);
    let blocks = mainnet_blocks_1_to_3();
    // Buffer heights 1 and 3, leaving a gap at 2.
    seq.accept_body(
        block::Height(1),
        blocks[0].hash(),
        blocks[0].clone(),
        100,
        peer(0),
    );
    seq.accept_body(
        block::Height(3),
        blocks[2].hash(),
        blocks[2].clone(),
        300,
        peer(0),
    );
    // Only the contiguous prefix above the floor (height 1) drains.
    assert_eq!(seq.drain_ready_into_applying(), vec![block::Height(1)]);
    assert_eq!(seq.floor(), block::Height(1));
    assert!(seq.applying_contains(block::Height(1)));
    assert_eq!(seq.applying_len(), 1);
    // Filling the gap lets 2 and 3 drain together and advances the floor to 3.
    seq.accept_body(
        block::Height(2),
        blocks[1].hash(),
        blocks[1].clone(),
        200,
        peer(0),
    );
    assert_eq!(
        seq.drain_ready_into_applying(),
        vec![block::Height(2), block::Height(3)]
    );
    assert_eq!(seq.floor(), block::Height(3));
    assert_eq!(seq.reorder_len(), 0);
}

#[test]
fn sequencer_submits_within_window_and_rolls_back_on_unsubmit() {
    let mut seq = test_sequencer(0, 2);
    let blocks = mainnet_blocks_1_to_3();
    for (index, block) in blocks.iter().enumerate() {
        let height = block::Height(index as u32 + 1);
        seq.accept_body(height, block.hash(), block.clone(), 100, peer(0));
    }
    assert_eq!(seq.drain_ready_into_applying().len(), 3);
    // The submission window of 2 caps the eligible heights.
    assert_eq!(
        seq.submittable_heights(),
        vec![block::Height(1), block::Height(2)]
    );
    let item1 = seq.prepare_submit(block::Height(1)).expect("applying at 1");
    let item2 = seq.prepare_submit(block::Height(2)).expect("applying at 2");
    assert_eq!((item1.token, item2.token), (1, 2));
    assert_eq!(seq.in_flight_submission_count(), 2);
    // The window is now full, so nothing else is submittable.
    assert!(seq.submittable_heights().is_empty());
    // Rolling back a failed dispatch frees the slot and re-offers the height.
    seq.unsubmit(block::Height(2), item2.token);
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(seq.submittable_heights(), vec![block::Height(2)]);
}

#[test]
fn sequencer_completed_duplicate_releases_attached_decode_window_slot() {
    let mut seq = test_sequencer(0, 1);
    let blocks = mainnet_blocks_1_to_3();
    for (index, block) in blocks.iter().take(2).enumerate() {
        let height = block::Height(index as u32 + 1);
        let body =
            BufferedBlockBody::from_decoded_block(block.clone(), Some(raw_block_payload(block)));
        seq.accept_buffered_body(
            height,
            block.hash(),
            block.header.previous_block_hash,
            body,
            100,
            peer(0),
        );
    }
    seq.drain_ready_into_applying();

    let item = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 is applying");
    seq.record_submitted_apply(item.height, item.hash);
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert!(seq.submittable_heights().is_empty());

    // A duplicate completion can arrive before the frontier proving that block
    // advances. Keep its applying entry attached, but drop the decoded copy and
    // free the global submission slot because the driver released its Arc.
    assert!(seq.finish_attached_submission(item.token, item.height, item.hash));
    assert!(seq.applying_contains(block::Height(1)));
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(seq.decoded_applying_count(), 0);
    assert_eq!(seq.submittable_heights(), vec![block::Height(2)]);
}

#[test]
fn sequencer_records_and_decrements_submitted_applies() {
    let mut seq = test_sequencer(0, 4);
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    let hash = block.hash();
    assert!(!seq.has_submitted_apply(block::Height(1), hash));
    seq.accept_body(block::Height(1), hash, block, 100, peer(0));
    seq.drain_ready_into_applying();
    let item = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 is applying");
    seq.record_submitted_apply(item.height, item.hash);
    assert!(seq.has_submitted_apply(block::Height(1), hash));
    assert!(seq.submitted_contains(block::Height(1)));
    seq.remove_applying(item.height);
    assert!(seq.finish_submission(item.token, item.height, item.hash));
    assert!(!seq.has_submitted_apply(block::Height(1), hash));
    assert!(!seq.submitted_contains(block::Height(1)));
}

#[test]
fn sequencer_frontier_release_keeps_in_flight_submission_charged_until_completion() {
    let mut seq = test_sequencer(0, 1);
    let blocks = mainnet_blocks_1_to_3();
    let decoded_attributed_memory_bytes = blocks
        .iter()
        .map(|block| block.attributed_memory_size_bytes())
        .fold(0u64, u64::saturating_add);
    let remaining_decoded_attributed_memory_bytes = blocks
        .iter()
        .skip(1)
        .map(|block| block.attributed_memory_size_bytes())
        .fold(0u64, u64::saturating_add);
    for (index, block) in blocks.iter().enumerate() {
        let height = block::Height(index as u32 + 1);
        seq.accept_body(height, block.hash(), block.clone(), 100, peer(0));
    }
    seq.drain_ready_into_applying();

    let item = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 is applying");
    seq.record_submitted_apply(item.height, item.hash);
    assert!(seq.submitted_contains(block::Height(1)));
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes
    );
    assert!(
        seq.submittable_heights().is_empty(),
        "submitted-apply window is full"
    );

    assert_eq!(seq.release_applied_through(block::Height(1)), 100);
    assert!(!seq.submitted_contains(block::Height(1)));
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes,
        "detached driver-owned decoded memory remains charged"
    );
    assert!(
        seq.submittable_heights().is_empty(),
        "detached driver submission still occupies the decode window"
    );

    assert!(!seq.finish_submission(item.token, item.height, block::Hash([99; 32])));
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes
    );
    assert!(seq.finish_submission(item.token, item.height, item.hash));
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        remaining_decoded_attributed_memory_bytes
    );
    assert_eq!(seq.submittable_heights(), vec![block::Height(2)]);
}

#[test]
fn sequencer_advance_verified_tip_releases_bytes_and_reports_change() {
    let mut seq = test_sequencer(0, 8);
    let blocks = mainnet_blocks_1_to_3();
    seq.accept_body(
        block::Height(1),
        blocks[0].hash(),
        blocks[0].clone(),
        100,
        peer(0),
    );
    seq.accept_body(
        block::Height(2),
        blocks[1].hash(),
        blocks[1].clone(),
        200,
        peer(0),
    );
    // Advancing the verified tip drops buffered bodies at or below it and reports
    // their bytes for the reactor to release.
    let advance = seq.advance_verified_tip(block::Height(2), false);
    assert!(advance.changed);
    assert_eq!(advance.release_bytes, 300);
    assert_eq!(seq.verified_tip(), block::Height(2));
    assert!(seq.floor() >= block::Height(2));
    // A no-op advance to the same tip frees nothing and reports unchanged.
    let advance = seq.advance_verified_tip(block::Height(2), false);
    assert!(!advance.changed);
    assert_eq!(advance.release_bytes, 0);
}

#[test]
fn sequencer_reset_clears_buffers_and_pins_floor_and_tip() {
    let mut seq = test_sequencer(0, 8);
    let blocks = mainnet_blocks_1_to_3();
    seq.accept_body(
        block::Height(1),
        blocks[0].hash(),
        blocks[0].clone(),
        100,
        peer(0),
    );
    seq.drain_ready_into_applying();
    seq.accept_body(
        block::Height(2),
        blocks[1].hash(),
        blocks[1].clone(),
        200,
        peer(0),
    );
    // Reset drops everything (one applying@100 + one reorder@200) and pins the
    // floor/tip to the reset target.
    let released = seq.reset_to(block::Height(0), false);
    assert_eq!(released, 300);
    assert_eq!(seq.floor(), block::Height(0));
    assert_eq!(seq.verified_tip(), block::Height(0));
    assert_eq!(seq.applying_len(), 0);
    assert_eq!(seq.reorder_len(), 0);
}

#[test]
fn sequencer_reset_keeps_detached_submissions_charged_until_matching_completions() {
    let mut seq = test_sequencer(0, 2);
    let blocks = mainnet_blocks_1_to_3();
    let decoded_attributed_memory_bytes = blocks
        .iter()
        .take(2)
        .map(|block| block.attributed_memory_size_bytes())
        .fold(0u64, u64::saturating_add);
    for (index, block) in blocks.iter().take(2).enumerate() {
        let height = block::Height(index as u32 + 1);
        seq.accept_body(height, block.hash(), block.clone(), 100, peer(0));
    }
    seq.drain_ready_into_applying();

    let old_items: Vec<_> = seq
        .submittable_heights()
        .into_iter()
        .map(|height| {
            let item = seq.prepare_submit(height).expect("height is applying");
            seq.record_submitted_apply(item.height, item.hash);
            item
        })
        .collect();
    assert_eq!(old_items.len(), 2);
    assert_eq!(seq.in_flight_submission_count(), 2);

    // Keep `old_items` alive to model the driver's pending/in-flight Arc<Block>s.
    seq.reset_to(block::Height(0), false);
    assert_eq!(seq.applying_len(), 0);
    assert_eq!(seq.in_flight_submission_count(), 2);
    assert_eq!(seq.in_flight_submission_bytes(), 200);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes,
        "reset must retain detached driver-owned decoded memory charges"
    );

    for (index, block) in blocks.iter().take(2).enumerate() {
        let replacement = forked_block(block, 100 + index as u8);
        let height = block::Height(index as u32 + 1);
        seq.accept_body(height, replacement.hash(), replacement, 100, peer(1));
    }
    seq.drain_ready_into_applying();
    assert!(
        seq.submittable_heights().is_empty(),
        "replacement bodies must not exceed the live decode window"
    );
    let decoded_attributed_memory_bytes_before_completion =
        seq.applying_decoded_attributed_memory_bytes();

    let first = &old_items[0];
    assert!(
        !seq.finish_submission(first.token, first.height, block::Hash([99; 32])),
        "a mismatched completion must not release a detached charge"
    );
    assert_eq!(seq.in_flight_submission_count(), 2);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes_before_completion
    );
    assert!(seq.finish_submission(first.token, first.height, first.hash));
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes_before_completion
            .saturating_sub(blocks[0].attributed_memory_size_bytes())
    );
    assert_eq!(seq.submittable_heights().len(), 1);

    let second = &old_items[1];
    assert!(seq.finish_submission(second.token, second.height, second.hash));
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        decoded_attributed_memory_bytes_before_completion
            .saturating_sub(decoded_attributed_memory_bytes)
    );
    assert_eq!(seq.submittable_heights().len(), 2);
}

#[test]
fn sequencer_reject_drops_successors_and_rolls_floor_back() {
    let mut seq = test_sequencer(0, 8);
    let blocks = mainnet_blocks_1_to_3();
    for (index, block) in blocks.iter().enumerate() {
        let height = block::Height(index as u32 + 1);
        seq.accept_body(height, block.hash(), block.clone(), 100, peer(0));
    }
    seq.drain_ready_into_applying();
    assert_eq!(seq.floor(), block::Height(3));
    // A reject at height 2 drops applying >= 2 (200 bytes) and rolls the floor
    // back below 2, never below the verified tip.
    let released = seq.release_applying_blocks_from(block::Height(2));
    assert_eq!(released, 200);
    assert!(seq.applying_contains(block::Height(1)));
    assert!(!seq.applying_contains(block::Height(2)));
    seq.reset_floor_below(block::Height(2));
    assert_eq!(seq.floor(), block::Height(1));
    // The committed prefix at or below height 1 is releasable.
    assert_eq!(seq.release_applied_through(block::Height(1)), 100);
    assert_eq!(seq.applying_len(), 0);
}

#[test]
fn sequencer_rejection_release_keeps_detached_submissions_charged() {
    let mut seq = test_sequencer(0, 2);
    let blocks = mainnet_blocks_1_to_3();
    for (index, block) in blocks.iter().enumerate() {
        let height = block::Height(index as u32 + 1);
        seq.accept_body(
            height,
            block.hash(),
            block.clone(),
            100 * (index as u64 + 1),
            peer(0),
        );
    }
    seq.drain_ready_into_applying();
    // Submit heights 2 and 3 so the released prefix (>= 2) is all submitted work.
    let item2 = seq
        .prepare_submit(block::Height(2))
        .expect("height 2 applying");
    let item3 = seq
        .prepare_submit(block::Height(3))
        .expect("height 3 applying");
    assert_eq!(seq.in_flight_submission_count(), 2);
    assert_eq!(seq.in_flight_submission_bytes(), 200 + 300);

    let released = seq.release_applying_blocks_from(block::Height(2));
    assert_eq!(released, 500);
    assert_eq!(seq.applying_len(), 1);
    // Only unsubmitted height 1 survives in `applying`, but both decoded
    // submissions remain retained by the driver and occupy the whole window.
    assert_eq!(seq.applying_buffered_bytes(), 100);
    assert_eq!(seq.in_flight_submission_count(), 2);
    assert_eq!(seq.in_flight_submission_bytes(), 500);
    assert!(seq.submittable_heights().is_empty());
    assert_eq!(
        seq.applying_buffered_bytes(),
        seq.applying_buffered_bytes_scanned()
    );
    assert_eq!(
        seq.in_flight_submission_count(),
        seq.in_flight_submission_count_scanned()
    );
    assert_eq!(
        seq.in_flight_submission_bytes(),
        seq.in_flight_submission_bytes_scanned()
    );

    assert!(seq.finish_submission(item2.token, item2.height, item2.hash));
    assert_eq!(seq.submittable_heights(), vec![block::Height(1)]);
    assert!(seq.finish_submission(item3.token, item3.height, item3.hash));
    assert_eq!(seq.in_flight_submission_count(), 0);
}

#[test]
fn sequencer_unsubmit_ignores_stale_or_mismatched_token() {
    // `unsubmit` only rolls back (and decrements the submitted counters) when the
    // token still matches the in-flight submission, so a stale rollback cannot
    // clobber a newer one or double-decrement the O(1) counters.
    let mut seq = test_sequencer(0, 4);
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    seq.accept_body(block::Height(1), block.hash(), block.clone(), 100, peer(0));
    seq.drain_ready_into_applying();
    let item = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 applying");
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(seq.in_flight_submission_bytes(), 100);

    // A rollback carrying a non-matching token is ignored: the submission and the
    // counters are untouched.
    seq.unsubmit(block::Height(1), item.token + 1);
    assert_eq!(seq.in_flight_submission_count(), 1);
    assert_eq!(seq.in_flight_submission_bytes(), 100);
    assert_eq!(
        seq.in_flight_submission_count(),
        seq.in_flight_submission_count_scanned()
    );
    assert_eq!(
        seq.in_flight_submission_bytes(),
        seq.in_flight_submission_bytes_scanned()
    );

    // The matching rollback frees the slot exactly once.
    seq.unsubmit(block::Height(1), item.token);
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(seq.in_flight_submission_bytes(), 0);

    // Replaying the now-stale token must not decrement a second time.
    seq.unsubmit(block::Height(1), item.token);
    assert_eq!(seq.in_flight_submission_count(), 0);
    assert_eq!(seq.in_flight_submission_bytes(), 0);
    assert_eq!(
        seq.in_flight_submission_count(),
        seq.in_flight_submission_count_scanned()
    );
    assert_eq!(
        seq.in_flight_submission_bytes(),
        seq.in_flight_submission_bytes_scanned()
    );
}

#[test]
fn sequencer_keeps_whole_body_for_contiguous_height() {
    // The retain-for-backlog trim only applies to *non-contiguous* bodies. A body
    // arriving at the next contiguous height above the floor is kept whole, so its
    // decoded block — not a re-decode of the raw payload — drains into `applying`.
    // This is the mirror of `sequencer_retains_raw_bytes_for_non_contiguous_backlog`.
    let mut seq = test_sequencer(0, 4);
    let block1 = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    // A decoded block distinguishable from its own raw payload lets us observe which
    // half of `DecodedWithRawFramePayload` survived acceptance.
    let distinguishable_decoded_block1 = forked_block(&block1, 99);
    assert_ne!(distinguishable_decoded_block1.hash(), block1.hash());

    let body = BufferedBlockBody::from_decoded_block(
        distinguishable_decoded_block1.clone(),
        Some(raw_block_payload(&block1)),
    );
    // Height 1 is the next contiguous height above the floor (0).
    assert_eq!(
        seq.accept_buffered_body(
            block::Height(1),
            block1.hash(),
            block1.header.previous_block_hash,
            body,
            100,
            peer(0)
        ),
        AcceptOutcome::Buffered {
            covered: block::Height(1)
        }
    );
    assert_eq!(seq.drain_ready_into_applying(), vec![block::Height(1)]);
    // The drained body is inside the submission window, so the kept decoded
    // block is submitted directly, not a re-decode of the raw payload.
    let submitted = seq
        .prepare_submit(block::Height(1))
        .expect("height 1 is applying");
    assert_eq!(
        submitted.block.hash(),
        distinguishable_decoded_block1.hash()
    );
    assert_eq!(
        seq.applying_decoded_attributed_memory_bytes(),
        distinguishable_decoded_block1.attributed_memory_size_bytes()
    );
}

#[test]
fn reorder_fuzzes_arrival_order_as_parent_first() {
    let orders = [
        [1, 2, 3, 4],
        [4, 3, 2, 1],
        [2, 4, 1, 3],
        [3, 1, 4, 2],
        [2, 1, 4, 3],
    ];

    for order in orders {
        let mut reorder = ReorderBuffer::new();
        let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
        let mut tip = block::Height(0);
        let mut released_all = Vec::new();

        for height in order {
            assert_eq!(
                reorder.insert(block::Height(height), block.clone(), 100, peer(0)),
                ReorderInsertResult::Inserted
            );
            for drained in reorder.drain_contiguous_prefix(tip) {
                assert_eq!(drained.height, block::Height(tip.0 + 1));
                tip = drained.height;
                released_all.push(drained.height);
            }
        }

        assert_eq!(
            released_all,
            vec![
                block::Height(1),
                block::Height(2),
                block::Height(3),
                block::Height(4)
            ]
        );
        assert_eq!(reorder.buffered_bytes(), 0);
    }
}

/// Build an outstanding three-block range whose summed size-estimate reservation
/// is already held against `budget`, mirroring what the fill loop does at send
/// time. Per-height size-estimate reservation used by the budget-accounting tests.
const THREE_BLOCK_ESTIMATE: u64 = 1_000;

fn outstanding_three_block_range(budget: &mut ByteBudget) -> OutstandingBlockRange {
    let request = BlockRangeRequest {
        start_height: block::Height(1),
        count: 3,
        anchor_hash: block::Hash([1; 32]),
        // Size-estimate reservation: each block reserves its size hint, so the
        // request reserves the sum of the per-height estimates below.
        estimated_bytes: THREE_BLOCK_ESTIMATE * 3,
        expected_blocks: vec![
            ExpectedBlock {
                height: block::Height(1),
                hash: block::Hash([1; 32]),
                estimated_bytes: 1_000,
            },
            ExpectedBlock {
                height: block::Height(2),
                hash: block::Hash([2; 32]),
                estimated_bytes: 1_000,
            },
            ExpectedBlock {
                height: block::Height(3),
                hash: block::Hash([3; 32]),
                estimated_bytes: 1_000,
            },
        ],
    };
    assert!(budget.try_reserve(request.estimated_bytes));
    let now = Instant::now();
    OutstandingBlockRange {
        request,
        queued_at: now,
        deadline: now,
        delivery_snapshot: test_delivery_snapshot(now),
        delivered_bytes: 0,
        received: ReceivedBlockTracker::default(),
    }
}

#[test]
fn outstanding_range_accumulates_delivered_bytes_for_bbr_sample() {
    let mut budget = ByteBudget::new(THREE_BLOCK_ESTIMATE * 3);
    let mut outstanding = outstanding_three_block_range(&mut budget);

    for (height, bytes) in [
        (block::Height(1), 700),
        (block::Height(2), 800),
        (block::Height(3), 900),
    ] {
        outstanding.record_body_bytes(bytes);
        outstanding.mark_received(height);
    }

    assert!(outstanding.is_complete());
    assert_eq!(outstanding.delivered_bytes, 700 + 800 + 900);
}

#[test]
fn block_budget_ledger_releases_reserved_exactly_once() {
    let mut ledger = BlockBudgetLedger::reserved(1_000);
    assert!(ledger.is_reserved());
    assert_eq!(ledger.reserved_charge(), 1_000);
    assert_eq!(ledger.release_reserved(), 1_000);
    assert!(!ledger.is_reserved());
    assert_eq!(ledger.reserved_charge(), 0);
    // Releasing twice yields nothing: the reservation lifecycle is one-shot.
    assert_eq!(ledger.release_reserved(), 0);

    let mut released = BlockBudgetLedger::Released;
    assert!(!released.is_reserved());
    assert_eq!(released.release_reserved(), 0);
}

#[test]
fn budget_audit_catches_injected_drift() {
    let mut budget = ByteBudget::new(1_000);
    assert!(budget.try_reserve(400));
    assert!(budget.audit(400, "test matching audit"));
    // A budget excess is expected receipt-handoff skew (paired call sites drain
    // the source ledger before releasing the budget), never drift.
    assert!(budget.audit(300, "test transient handoff excess"));
    // A budget shortfall cannot be produced by any healthy interleaving
    // (a double release or lost charge): drift.
    assert!(
        !budget.audit(500, "test injected drift"),
        "audit reports a budget shortfall as drift"
    );
    budget.release(400);
    assert!(budget.audit(0, "test released audit"));
}

#[test]
fn received_body_admission_ignores_request_budget() {
    // A received body consumes no request budget, so a wire budget saturated by
    // outstanding requests must not cause it to be dropped and re-downloaded:
    // only the commit-window exemption and the resident gate apply.
    let config = ZakuraBlockSyncConfig {
        max_reorder_lookahead_bytes: 1_000,
        ..ZakuraBlockSyncConfig::default()
    };
    let snapshot = super::admission::AdmissionSnapshot {
        download_floor: block::Height(600),
        verified_block_tip: block::Height(10),
        reorder_buffered_bytes: 0,
        reorder_buffered_blocks: 0,
        applying_buffered_bytes: 0,
        applying_buffered_blocks: 0,
        sequencer_input_queued_bytes: 0,
        in_flight_submission_bytes: 0,
        reserved_above_floor_bytes: 0,
        reserved_above_floor_blocks: 0,
        // Outstanding requests have spent the entire in-flight budget.
        budget_available: 0,
    };
    // In-window heights (<= verified_tip 10 + 401 = 411) stay exempt.
    assert!(super::admission::admit_received_body(
        &config,
        &snapshot,
        block::Height(411),
        2_000_000,
    ));
    // Above the window the resident gate is the sole authority. The body is
    // retained serialized, so one wire byte consumes one byte of headroom.
    assert!(super::admission::admit_received_body(
        &config,
        &snapshot,
        block::Height(602),
        1_000,
    ));
    // A body larger than the remaining serialized headroom is refused.
    assert!(!super::admission::admit_received_body(
        &config,
        &snapshot,
        block::Height(602),
        1_001,
    ));
}

proptest::proptest! {
    #![proptest_config(proptest::test_runner::Config::with_cases(256))]

    #[test]
    fn admit_respects_lookahead_bounds(
        reorder_bytes in 0u64..2_000,
        applying_bytes in 0u64..2_000,
        input_bytes in 0u64..2_000,
        reserved_bytes in 0u64..2_000,
        // Occasionally saturate the hard block cap so the count-gate arm below
        // stays non-vacuous (ordinary counts never approach 262,144).
        reorder_blocks in proptest::prop_oneof![
            0u64..20,
            proptest::strategy::Just(super::admission::LOOKAHEAD_BLOCK_HARD_CAP),
        ],
        applying_blocks in 0u64..20,
        reserved_blocks in 0u64..20,
    ) {
        let config = ZakuraBlockSyncConfig {
            max_inflight_block_bytes: 64_000_000,
            max_reorder_lookahead_bytes: 1_000,
            ..ZakuraBlockSyncConfig::default()
        };
        // The download floor sits far above the commit window (verified_tip 10 + 401 = 411),
        // so the gated probe below is genuinely memory-gated, not window-exempt.
        let snapshot = super::admission::AdmissionSnapshot {
            download_floor: block::Height(600),
            verified_block_tip: block::Height(10),
            reorder_buffered_bytes: reorder_bytes,
            reorder_buffered_blocks: reorder_blocks,
            applying_buffered_bytes: applying_bytes,
            applying_buffered_blocks: applying_blocks,
            sequencer_input_queued_bytes: input_bytes,
            in_flight_submission_bytes: 0,
            reserved_above_floor_bytes: reserved_bytes,
            reserved_above_floor_blocks: reserved_blocks,
            budget_available: 64_000_000,
        };
        // Serialized pools are charged at wire size. The sequencer input also
        // carries a decoded copy, so it pays the decoded multiple in addition.
        let factor = super::admission::DESERIALIZED_MEM_FACTOR;
        let estimated_resident = reorder_bytes
            .saturating_add(applying_bytes)
            .saturating_add(input_bytes)
            .saturating_add(reserved_bytes)
            .saturating_add(input_bytes.saturating_mul(factor));
        let held_blocks = reorder_blocks
            .saturating_add(applying_blocks)
            .saturating_add(reserved_blocks);
        let effective = config.effective_max_reorder_lookahead_bytes();
        let above = super::admission::admit(
            &config,
            snapshot,
            block::Height(602),
            block::Height(100_000),
            1_000,
        );
        if estimated_resident >= effective
            || held_blocks >= super::admission::LOOKAHEAD_BLOCK_HARD_CAP
            || effective - estimated_resident == 0
        {
            prop_assert_eq!(above, super::admission::AdmissionOutcome::LookaheadAtCap);
        } else {
            // A gated request funds min(budget, remaining wire headroom,
            // response cap); admitted backlog bodies remain serialized.
            let remaining_wire = effective - estimated_resident;
            let expected = snapshot.budget_available.min(remaining_wire).min(1_000);
            match above {
                super::admission::AdmissionOutcome::Admit(grant) => {
                    prop_assert_eq!(grant.max_request_bytes, expected);
                    // Gated grants pass the servable ceiling through unchanged.
                    prop_assert_eq!(grant.take_high, block::Height(100_000));
                    // The new reservation is charged at wire size, so one grant
                    // cannot push the resident estimate past the budget.
                    prop_assert!(
                        estimated_resident
                            .saturating_add(grant.max_request_bytes)
                            <= effective
                    );
                }
                other => prop_assert!(false, "expected a gated grant, got {:?}", other),
            }
        }

        // The commit window (heights <= 411) stays fundable regardless of pool fill,
        // and the exempt grant never spans the window boundary.
        match super::admission::admit(
            &config,
            snapshot,
            block::Height(11),
            block::Height(100_000),
            1_000,
        ) {
            super::admission::AdmissionOutcome::Admit(grant) => {
                prop_assert_eq!(grant.max_request_bytes, 1_000);
                prop_assert_eq!(grant.take_high, block::Height(411));
            }
            other => prop_assert!(
                false,
                "the commit window remains admitted while budget is available, got {:?}",
                other
            ),
        }
    }
}

proptest::proptest! {
    #![proptest_config(proptest::test_runner::Config::with_cases(256))]

    #[test]
    fn block_budget_ledger_mirrors_byte_budget(
        estimate in 1u64..1_000_000,
        release_before_receipt in proptest::bool::ANY,
    ) {
        // Whichever terminal path runs first (receipt, or a timeout/watchdog
        // release) drains the mirrored budget to zero; any later path is a no-op.
        let mut ledger = BlockBudgetLedger::reserved(estimate);
        let mut budget = ByteBudget::new(u64::MAX);
        prop_assert!(budget.try_reserve(estimate));

        if release_before_receipt {
            budget.release(ledger.release_reserved());
            prop_assert_eq!(budget.reserved(), 0);
            prop_assert!(!ledger.is_reserved());
        }
        budget.release(ledger.release_reserved());
        prop_assert_eq!(budget.reserved(), 0);
        prop_assert_eq!(ledger.reserved_charge(), 0);
        // A third release still yields nothing.
        budget.release(ledger.release_reserved());
        prop_assert_eq!(budget.reserved(), 0);
    }
}

/// The global reservation tracks only unreceived request estimates: each height
/// releases its whole estimate exactly once (receipt or timeout), retained bodies
/// charge nothing, and the counter never exceeds the max.
#[test]
fn budget_reservation_tracks_only_unreceived_estimates() {
    let estimate = THREE_BLOCK_ESTIMATE;
    let max = estimate * 3;

    // Happy path: download -> release-on-receipt -> buffer (uncharged) -> commit.
    {
        let mut budget = ByteBudget::new(max);
        let mut reorder = ReorderBuffer::new();
        let mut outstanding = outstanding_three_block_range(&mut budget);
        assert_eq!(budget.reserved(), max);
        assert!(budget.reserved() <= budget.max_bytes_for_test());

        let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
        // Receive each height: release its whole estimate and hand the body's
        // actual size to the reorder buffer without any budget charge.
        let actuals = [700u64, 800, 900];
        for (index, height) in [block::Height(1), block::Height(2), block::Height(3)]
            .into_iter()
            .enumerate()
        {
            budget.release(estimate);
            outstanding.mark_received(height);
            assert_eq!(
                reorder.insert(height, block.clone(), actuals[index], peer(0)),
                ReorderInsertResult::Inserted
            );
            // The budget mirrors the unreceived estimates exactly.
            assert_eq!(budget.reserved(), outstanding.reserved_bytes());
        }
        assert!(outstanding.is_complete());
        assert_eq!(outstanding.reserved_bytes(), 0);
        assert_eq!(
            budget.reserved(),
            0,
            "retained bodies charge nothing; the wire budget is fully free"
        );
        assert_eq!(reorder.buffered_bytes(), 700 + 800 + 900);

        // Commit: draining to apply carries the actual bytes for the retained
        // view; no request-budget release is owed downstream.
        let applied_bytes: u64 = reorder
            .drain_contiguous_prefix(block::Height(0))
            .into_iter()
            .map(|drained| drained.bytes)
            .sum();
        assert_eq!(applied_bytes, 700 + 800 + 900);
        assert_eq!(budget.reserved(), 0);
    }

    // Timeout / short-response path: the received height released its estimate at
    // receipt; the unreceived heights release theirs exactly once on timeout.
    {
        let mut budget = ByteBudget::new(max);
        let mut outstanding = outstanding_three_block_range(&mut budget);
        assert_eq!(budget.reserved(), estimate * 3);
        // A short response delivers only height 1; its estimate is released.
        budget.release(estimate);
        outstanding.mark_received(block::Height(1));
        // The remaining two unreceived heights still reserve their estimate each.
        assert_eq!(outstanding.reserved_bytes(), estimate * 2);
        assert_eq!(budget.reserved(), estimate * 2);
        // On timeout the outstanding range releases its still-reserved estimates.
        budget.release(outstanding.reserved_bytes());
        assert_eq!(budget.reserved(), 0);
    }

    // Duplicate path: neither the first body nor a dropped duplicate touches the
    // budget; only the retained-size accounting sees them.
    {
        let budget = ByteBudget::new(max);
        let mut reorder = ReorderBuffer::new();
        let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
        assert_eq!(
            reorder.insert(block::Height(1), block.clone(), 1_000, peer(0)),
            ReorderInsertResult::Inserted
        );
        assert_eq!(
            reorder.insert(block::Height(1), block, 1_000, peer(0)),
            ReorderInsertResult::Duplicate
        );
        assert_eq!(reorder.buffered_bytes(), 1_000);
        assert_eq!(budget.reserved(), 0);
        assert!(budget.reserved() <= budget.max_bytes_for_test());
    }
}

/// A request range at the maximum advertised block count (128) fills the
/// `ReceivedBlockTracker`'s `u128` bitset exactly (offsets `0..=127`): every height —
/// including the top-bit height 128 — must be markable, complete, and fully released,
/// so no height silently falls off the end of the bitset. Guards the boundary that the
/// `MAX_BS_BLOCKS_PER_REQUEST <= u128::BITS` const assertion in `state.rs` protects.
#[test]
fn received_tracker_handles_a_full_range_at_the_bitset_boundary() {
    let count = MAX_BS_BLOCKS_PER_REQUEST;
    assert_eq!(count, u128::BITS, "the cap is sized to the bitset width");
    // Heights `1..=128`, offsets `0..=127`; the helper keeps heights within `u8`.
    let mut outstanding = window_request_range(1, count);
    assert_eq!(outstanding.reserved_bytes(), u64::from(count));

    for height in 1..=count {
        assert!(
            !outstanding.has_received(block::Height(height)),
            "height {height} should start unreceived",
        );
        outstanding.mark_received(block::Height(height));
        assert!(
            outstanding.has_received(block::Height(height)),
            "height {height} (offset {}) must be markable — the bitset must cover the \
             whole range",
            height - 1,
        );
    }

    assert!(
        outstanding.is_complete(),
        "a fully-received {count}-block range must report complete",
    );
    assert_eq!(
        outstanding.reserved_bytes(),
        0,
        "every height received ⇒ no reserved bytes remain (no offset fell off the bitset)",
    );
}

/// A body whose actual serialized size exceeds its advertised size hint is still
/// accepted and buffered, and receipt releases exactly the reserved hint — never
/// more — so an oversized body cannot underflow or leak the request budget.
#[test]
fn underestimated_body_is_buffered_and_releases_only_its_estimate() {
    let hint = 1_000u64;
    // Budget holds several hint-sized shares: enough to reserve this body's hint.
    let mut budget = ByteBudget::new(hint * 4);
    let mut reorder = ReorderBuffer::new();

    let request = BlockRangeRequest {
        start_height: block::Height(1),
        count: 1,
        anchor_hash: block::Hash([1; 32]),
        // Size-estimate reservation: the per-height hint, not worst case.
        estimated_bytes: hint,
        expected_blocks: vec![ExpectedBlock {
            height: block::Height(1),
            hash: block::Hash([1; 32]),
            estimated_bytes: hint,
        }],
    };
    assert!(budget.try_reserve(request.estimated_bytes));
    let now = Instant::now();
    let mut outstanding = OutstandingBlockRange {
        request,
        queued_at: now,
        deadline: now,
        delivery_snapshot: test_delivery_snapshot(now),
        delivered_bytes: 0,
        received: ReceivedBlockTracker::default(),
    };
    assert_eq!(budget.reserved(), hint);

    // The body's actual serialized size is far larger than the hint (but still
    // <= MAX_BLOCK_BYTES).
    let actual = hint * 50;
    assert!(actual < BS_PER_BLOCK_WORST_CASE_BYTES);
    assert!(actual > hint);

    // Receipt: release the reserved hint. The oversized body is retained at its
    // actual size by the reorder buffer, invisible to the request budget (the
    // resident look-ahead gate accounts for it instead).
    budget.release(hint);
    outstanding.mark_received(block::Height(1));
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    assert_eq!(
        reorder.insert(block::Height(1), block, actual, peer(0)),
        ReorderInsertResult::Inserted,
        "an underestimated body must still buffer; a received body is never dropped"
    );
    assert_eq!(reorder.buffered_bytes(), actual);
    assert_eq!(budget.reserved(), 0);
    assert_eq!(outstanding.reserved_bytes(), 0);
    assert!(
        budget.try_reserve(hint),
        "the freed reservation funds the next request immediately"
    );
    let dropped = reorder.drop_through(block::Height(1));
    assert_eq!(dropped, actual);
    assert_eq!(reorder.buffered_bytes(), 0);
}

#[test]
fn block_sync_stream_declares_kind_capability_version_and_frame_cap() {
    let stream = block_sync_streams()
        .first()
        .copied()
        .expect("block sync declares one stream");

    assert_eq!(stream.kind, ZAKURA_STREAM_BLOCK_SYNC);
    assert_eq!(stream.version, ZAKURA_BLOCK_SYNC_STREAM_VERSION);
    assert_eq!(stream.capability, ZAKURA_CAP_BLOCK_SYNC);
    assert_eq!(stream.mode, StreamMode::Ordered);
    assert_eq!(stream.frame_cap, MAX_BS_FRAME_BYTES);
}

#[tokio::test]
async fn service_registry_routes_block_sync_by_exact_capability_and_version() {
    let service = Arc::new(BlockSyncService::new(ZakuraBlockSyncConfig::default()));
    let registry =
        ServiceRegistry::new(vec![service]).expect("block-sync service declares unique kind");
    let peer = peer(1);

    assert_eq!(
        registry.capability_for_stream(ZAKURA_STREAM_BLOCK_SYNC, ZAKURA_BLOCK_SYNC_STREAM_VERSION),
        Some(ZAKURA_CAP_BLOCK_SYNC)
    );
    assert!(registry
        .capability_for_stream(
            ZAKURA_STREAM_BLOCK_SYNC,
            ZAKURA_BLOCK_SYNC_STREAM_VERSION + 1
        )
        .is_none());
    assert_eq!(
        registry
            .ordered_streams_for_negotiated(ZAKURA_CAP_BLOCK_SYNC)
            .iter()
            .map(|stream| stream.kind)
            .collect::<Vec<_>>(),
        vec![ZAKURA_STREAM_BLOCK_SYNC]
    );
    assert!(registry.ordered_streams_for_negotiated(0).is_empty());
    assert!(registry.wants_ordered_stream(
        ZAKURA_STREAM_BLOCK_SYNC,
        ZAKURA_CAP_BLOCK_SYNC,
        &peer,
        ServicePeerDirection::Inbound,
    ));
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn inert_reactor_parks_after_header_tip_watch_closes() {
    let _service = BlockSyncService::new(ZakuraBlockSyncConfig::default());

    let elapsed = tokio::time::timeout(Duration::from_secs(1), future::pending::<()>()).await;

    assert!(
        elapsed.is_err(),
        "paused-time timeout only elapses if the inert reactor has no always-ready branch"
    );
}

#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "state-backed block sync must have exactly one frontier source")]
fn state_backed_reactor_panics_with_two_frontier_sources() {
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let (_frontier_tx, frontier_rx) =
        watch::channel(test_frontier_update(0, 0, 0, FrontierChange::Snapshot));
    let mut startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        ZakuraBlockSyncConfig::default(),
    );
    startup.frontier_updates = Some(frontier_rx);

    let (_handle, _actions, _task) = spawn_block_sync_reactor(startup);
}

#[tokio::test]
async fn add_peer_emits_events_and_round_trips_status_over_framed_path() {
    let (service, mut events) = BlockSyncService::new_for_test(ZakuraBlockSyncConfig::default());
    let peer = peer(2);
    let cancel_token = CancellationToken::new();
    let (inbound_tx, inbound_rx) = framed_channel(4);
    let (outbound_tx, outbound_rx) = framed_channel(4);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        streams,
        cancel_token,
    ));

    let session = match next_event(&mut events).await {
        BlockSyncEvent::PeerConnected(session) => session,
        event => panic!("expected PeerConnected, got {event:?}"),
    };
    assert_eq!(session.peer_id(), &peer);
    assert_eq!(service.peer_count(), 1);
    let _outbound_rx = outbound_rx;

    // The inbound data flow is inverted: with no reactor wiring (`new_for_test`),
    // `add_peer` drains inbound frames rather than emitting a `WireMessage` event
    // (the production inbound path is the per-peer pipe-routine, exercised by the
    // reactor tests with real wiring). The frame still queues onto the framed
    // stream; this asserts the framed inbound path is live and consumed.
    inbound_tx
        .send(
            BlockSyncMessage::Status(status())
                .encode_frame()
                .expect("status frame encodes"),
        )
        .await
        .expect("inbound status queues");

    service.remove_peer(&peer, 0);
    assert_eq!(service.peer_count(), 0);
    assert!(session.cancel_token().is_cancelled());
}

#[tokio::test]
async fn stale_block_sync_teardown_keeps_replacement_session() {
    let (service, mut events) = BlockSyncService::new_for_test(ZakuraBlockSyncConfig::default());
    let peer = peer(92);
    let old_conn_id = 1;
    let new_conn_id = 2;

    let (old_inbound_tx, old_inbound_rx) = framed_channel(4);
    let (old_outbound_tx, _old_outbound_rx) = framed_channel(4);
    service.add_peer(Peer::new_with_conn_id_and_direction(
        old_conn_id,
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (old_inbound_rx, old_outbound_tx))]),
        CancellationToken::new(),
    ));
    assert!(matches!(
        next_event(&mut events).await,
        BlockSyncEvent::PeerConnected(session) if session.peer_id() == &peer
    ));

    let (new_inbound_tx, new_inbound_rx) = framed_channel(4);
    let (new_outbound_tx, _new_outbound_rx) = framed_channel(4);
    service.add_peer(Peer::new_with_conn_id_and_direction(
        new_conn_id,
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (new_inbound_rx, new_outbound_tx))]),
        CancellationToken::new(),
    ));
    assert!(matches!(
        next_event(&mut events).await,
        BlockSyncEvent::PeerConnected(session) if session.peer_id() == &peer
    ));
    assert_eq!(service.peer_count(), 1);

    let (_stale_inbound_tx, stale_inbound_rx) = framed_channel(4);
    let (stale_outbound_tx, _stale_outbound_rx) = framed_channel(4);
    service.add_peer(Peer::new_with_conn_id_and_direction(
        old_conn_id,
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        HashMap::from([(
            ZAKURA_STREAM_BLOCK_SYNC,
            (stale_inbound_rx, stale_outbound_tx),
        )]),
        CancellationToken::new(),
    ));
    assert_eq!(
        service.peer_count(),
        1,
        "stale add must not overwrite the replacement block-sync session",
    );

    service.remove_peer(&peer, old_conn_id);
    assert_eq!(service.peer_count(), 1);

    drop(old_inbound_tx);
    tokio::time::sleep(Duration::from_millis(50)).await;

    if let Ok(Some(BlockSyncEvent::PeerDisconnected(disconnected))) =
        tokio::time::timeout(Duration::from_millis(50), events.recv()).await
    {
        panic!("stale teardown disconnected replacement session for {disconnected:?}");
    }
    // The replacement session remains installed (the stale teardown did not
    // disconnect it): `peer_count` stays 1 and the live replacement record was
    // never removed by the old session's teardown. (The previous check that routed a
    // `send_action(SendMessage)` through the record only exercised the removed
    // test-only source-pump scaffolding.)
    assert_eq!(service.peer_count(), 1);

    drop(new_inbound_tx);
}

#[tokio::test]
async fn lifecycle_events_bypass_full_bounded_wire_queue() {
    let mut config = ZakuraBlockSyncConfig::default();
    config.peer_limits.inbound_queue_depth = 1;
    let (events, _event_rx) = mpsc::channel(config.peer_limits.inbound_queue_depth);
    // Fill the bounded wire-event queue (per-peer routines deleted `WireMessage`; any event that
    // rides the bounded `events` channel proves lifecycle bypass — use a header-tip
    // change).
    events
        .try_send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(1),
            hash: block::Hash([1; 32]),
        })
        .expect("test fills bounded wire queue");
    let (lifecycle, mut lifecycle_rx) = mpsc::unbounded_channel();
    let (_peers_tx, peers) = watch::channel(ServicePeerSnapshot::new(0, 0, config.peer_limits));
    let (_status_tx, status) = watch::channel(config.initial_status());
    let (_candidates_tx, candidates) = watch::channel(ZakuraBlockSyncCandidateState::default());
    let handle = BlockSyncHandle {
        events,
        lifecycle,
        peers,
        status,
        candidates,
        // No reactor wiring: `add_peer` drains inbound (no routine), and this test
        // only checks the lifecycle-bypass plumbing.
        routine_wiring: None,
    };
    let service = BlockSyncService::new_with_handle_for_test(config, handle);
    let peer = peer(91);
    let (inbound_tx, inbound_rx) = framed_channel(4);
    let (outbound_tx, _outbound_rx) = framed_channel(4);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    let _inbound_tx = inbound_tx;

    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), lifecycle_rx.recv())
            .await
            .expect("lifecycle event arrives")
            .expect("lifecycle channel stays open"),
        BlockSyncEvent::PeerConnected(session) if session.peer_id() == &peer
    ));

    service.remove_peer(&peer, 0);
    assert!(matches!(
        tokio::time::timeout(Duration::from_secs(1), lifecycle_rx.recv())
            .await
            .expect("lifecycle event arrives")
            .expect("lifecycle channel stays open"),
        BlockSyncEvent::PeerDisconnected(disconnected) if disconnected == peer
    ));
}

#[tokio::test]
async fn add_peer_decode_failure_reports_malformed_and_cancels_connection() {
    // inverted inbound flow: the per-peer pipe-routine decodes inbound frames in its own
    // task. A malformed frame is `MalformedMessage` misbehavior AND a fatal protocol
    // reject for the whole connection (the routine returns `Err(SinkReject::protocol)`,
    // which `handle_pipe_exit` turns into a connection cancel). With real reactor
    // wiring the routine runs; we observe the `Misbehavior(MalformedMessage)` action
    // and the connection-cancel.
    let config = ZakuraBlockSyncConfig::default();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, _reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let peer = peer(3);
    let (inbound_tx, inbound_rx) = framed_channel(4);
    let (outbound_tx, _outbound_rx) = framed_channel(4);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    let connection_cancel = CancellationToken::new();

    service.add_peer(Peer::new(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        streams,
        connection_cancel.clone(),
    ));

    inbound_tx
        .send(Frame {
            message_type: u16::from(MSG_BS_STATUS),
            flags: 0,
            payload: Vec::new(),
        })
        .await
        .expect("malformed inbound frame queues");

    // The routine reports `MalformedMessage` (skip the connect Status mirror).
    let reported = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::Misbehavior { peer: got, reason } => break (got, reason),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before malformed-message report: {action:?}"),
        }
    };
    assert_eq!(
        reported,
        (peer.clone(), BlockSyncMisbehavior::MalformedMessage)
    );

    // The malformed frame is a fatal protocol reject for the whole connection.
    tokio::time::timeout(Duration::from_secs(1), connection_cancel.cancelled())
        .await
        .expect("malformed frame cancels the connection");
}

#[tokio::test]
async fn registry_add_peer_requires_negotiated_block_sync_capability() {
    let (service, mut events) = BlockSyncService::new_for_test(ZakuraBlockSyncConfig::default());
    let registry = ServiceRegistry::new(vec![Arc::new(service)])
        .expect("block-sync service declares unique kind");
    let peer = peer(4);
    let (inbound_tx, inbound_rx) = framed_channel(4);
    let (outbound_tx, _outbound_rx) = framed_channel(4);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    registry.add_peer(Peer::new(peer, None, 0, streams, CancellationToken::new()));
    drop(inbound_tx);

    assert!(
        tokio::time::timeout(Duration::from_millis(100), events.recv())
            .await
            .is_err(),
        "without cap 1<<3 the registry must not deliver kind-6 streams"
    );
}

#[tokio::test]
async fn wants_peer_rejects_when_configured_slot_cap_is_reached() {
    let config = ZakuraBlockSyncConfig {
        peer_limits: ServicePeerLimits {
            max_inbound_peers: 0,
            max_outbound_peers: 2,
            ..ServicePeerLimits::default()
        },
        ..ZakuraBlockSyncConfig::default()
    };
    let (service, mut events) = BlockSyncService::new_for_test(config);
    let inbound_peer = peer(5);

    assert!(!service.wants_peer(
        &inbound_peer,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Inbound
    ));
    assert!(service.wants_peer(
        &inbound_peer,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound
    ));

    let mut inbound_senders = Vec::new();
    for byte in 6..=7 {
        let peer_id = peer(byte);
        let (inbound_tx, inbound_rx) = framed_channel(4);
        let (outbound_tx, _outbound_rx) = framed_channel(4);
        let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

        service.add_peer(Peer::new_with_direction(
            peer_id.clone(),
            None,
            ZAKURA_CAP_BLOCK_SYNC,
            ServicePeerDirection::Outbound,
            streams,
            CancellationToken::new(),
        ));

        assert!(matches!(
            next_event(&mut events).await,
            BlockSyncEvent::PeerConnected(session) if session.peer_id() == &peer_id
        ));
        inbound_senders.push(inbound_tx);
    }

    assert_eq!(service.peer_count(), 2);
    assert!(!service.wants_peer(
        &peer(8),
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound
    ));

    let (_inbound_tx, inbound_rx) = framed_channel(4);
    let (outbound_tx, _outbound_rx) = framed_channel(4);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer(8),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    assert_eq!(service.peer_count(), 2);
}

#[tokio::test]
async fn reactor_drives_tip_to_getblocks_to_submit_over_framed_path() {
    let config = immediate_body_download_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer = peer(40);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    let block_hash = block.hash();
    let block_size = u32::try_from(
        block
            .zcash_serialize_to_vec()
            .expect("block serializes")
            .len(),
    )
    .expect("test block size fits u32");
    tip_tx
        .send((block::Height(1), block_hash))
        .expect("tip watch is live");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::QueryNeededBlocks {
                from,
                best_header_tip,
                ..
            } => {
                assert_eq!(from, block::Height(1));
                // The startup query carries best_header_tip 0; wait for the
                // tip-1 query (there is no near-tip pause to suppress either).
                if best_header_tip == block::Height(1) {
                    break;
                }
            }
            action => panic!("unexpected action before query: {action:?}"),
        }
    }

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block_hash,
            size: BlockSizeEstimate::Advertised(block_size),
        }]))
        .await
        .expect("needed metadata queues");

    // Reading this peer's own real outbound proves the GetBlocks targeted it.
    loop {
        let frame = tokio::time::timeout(Duration::from_secs(1), outbound_rx.recv())
            .await
            .expect("outbound frame arrives")
            .expect("outbound channel is live");
        if let BlockSyncMessage::GetBlocks {
            start_height,
            count,
        } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
        {
            assert_eq!(start_height, block::Height(1));
            assert_eq!(count, 1);
            break;
        }
    }

    inbound_tx
        .send(
            BlockSyncMessage::Block(block.clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock {
                block: submitted, ..
            } => {
                assert_eq!(submitted.hash(), block_hash);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_releases_request_budget_at_receipt_not_apply() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let mut config = immediate_body_download_config();
    // One block's size hint of budget: size-based reservation now means one
    // advertised body fills the budget, throttling to one in-flight request.
    config.max_inflight_block_bytes = u64::from(block1_size);

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(41);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(2),
                tip_hash: blocks[1].hash(),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
        ]))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(count, 1);

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");

    let submit_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    };
    assert_eq!(handle.local_status().servable_high, block::Height(0));

    // Receipt — not apply-finish — released the request reservation, so with the
    // one-block-hint budget and the one-slot window both freed by the delivery,
    // the height-2 GetBlocks must go out while height 1 is still
    // submitted-but-unapplied (retention is bounded by the resident gate, not
    // the request budget).
    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(2));
    assert_eq!(count, 1);

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submit_token,
            height: block::Height(1),
            hash: blocks[0].hash(),
            result: BlockApplyResult::Committed,
            local_frontier: Some(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(1),
                verified_block_hash: blocks[0].hash(),
            }),
        })
        .await
        .expect("apply-finished event queues");
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if handle.local_status().servable_high == block::Height(1) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("apply completion frontier advances advertised status");

    reactor_task.abort();
}

/// Pins the Sequencer task producer-filter substitution `height > request_floor &&
/// !work.in_flight_contains(height)`. A height that has been received and is held
/// in the commit pipeline (buffered / applying / submitted) was taken into the
/// WorkQueue's `in_flight` at issuance and stays there until it commits, so a
/// later `NeededBlocks` snapshot that still lists it must NOT cause the reactor to
/// re-issue a `GetBlocks` for it. This is the `in_flight ⟺ held` invariant the
/// reactor relies on now that it can no longer read the Sequencer's
/// reorder/applying/submitted membership directly.
#[tokio::test]
async fn reactor_does_not_requeue_held_height_reported_still_needed() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let block2_size = block_size(&blocks[1]);
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 4;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(73);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    // Peer can serve heights 1..=2; the body for height 1 has a missing parent
    // (height 1 needs height 0's tip), so once received it is held in the commit
    // pipeline (reorder/applying) rather than immediately committing.
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(2),
                tip_hash: blocks[1].hash(),
                max_blocks_per_response: 1,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block2_size),
            },
        ]))
        .await
        .expect("needed metadata queues");

    // The peer's count cap is 1, so it requests height 1 first.
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    // Deliver height 1's body. It is taken from `pending` into `in_flight`, then
    // received and held (buffered then drained to applying, then submitted). It
    // never returns to `pending` while held.
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("body frame queues");
    // Wait for the held body to be submitted, confirming it is now in the commit
    // pipeline (and still claimed in `in_flight`).
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    }

    // State re-reports both heights as still needed (its snapshot has no
    // visibility into our in-memory commit pipeline). The producer must NOT
    // re-issue a GetBlocks for the held height 1; only the genuinely-missing
    // height 2 may be requested.
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block2_size),
            },
        ]))
        .await
        .expect("re-reported needed metadata queues");

    // A re-request of the held height would land on this peer's own real
    // outbound, so watch the wire for any GetBlocks of height 1.
    let saw_requeue_of_held_height = tokio::time::timeout(Duration::from_millis(300), async {
        loop {
            match outbound_rx.recv().await {
                Some(frame) => {
                    if let BlockSyncMessage::GetBlocks {
                        start_height: block::Height(1),
                        ..
                    } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
                    {
                        return true;
                    }
                }
                None => return false,
            }
        }
    })
    .await;
    assert!(
        saw_requeue_of_held_height.is_err(),
        "a held (in_flight) height reported still needed must not be re-requested",
    );

    reactor_task.abort();
}

/// A real body whose serialized size dwarfs its advertised size hint is still
/// accepted, buffered, and submitted: a received body never touches the budget
/// gate (its reservation is simply released at receipt), so it cannot be dropped
/// for lack of budget.
///
/// A/B: under the old release-then-reserve scheme the request reserved only the
/// hint-sized estimate, so a body larger than the hint re-reserved more than was
/// released and, against a tight budget, hit `BudgetFull` and dropped a valid
/// body. That path is unreachable now.
#[tokio::test]
async fn reactor_buffers_body_larger_than_its_size_hint() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    // Budget holds exactly one worst-case share, so a hint-sized re-reservation
    // would have left no headroom for an underestimated body.
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        41,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(1), blocks[0].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    // Advertise a 1-byte size hint, far below the real body size, with a
    // tolerance that admits the deviation without misbehavior scoring.
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: blocks[0].hash(),
            size: BlockSizeEstimate::Advertised(1),
        }]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("body queues");

    let submitted = tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            match next_action(&mut actions).await {
                BlockSyncAction::SubmitBlock { block, .. } => break block.hash(),
                // The preserved size-deviation check reports the hint mismatch but
                // must not drop the body.
                BlockSyncAction::Misbehavior {
                    reason: BlockSyncMisbehavior::SizeMismatch,
                    ..
                }
                | BlockSyncAction::QueryNeededBlocks { .. } => {}
                action => panic!("unexpected action before submit: {action:?}"),
            }
        }
    })
    .await
    .expect("underestimated body must still be buffered and submitted, not dropped");
    assert_eq!(submitted, blocks[0].hash());

    reactor_task.abort();
}

/// A stalled commit must not pace downloads. The refill low-water mark counts
/// only the download pipeline (`queued` + `outstanding`), never the commit
/// pipeline (`reorder` + `applying`), so a block stuck in `applying` (submitted
/// but never apply-finished) does not stop the reactor from re-querying and
/// downloading higher heights — downloads run ahead of commit, bounded only by
/// the in-flight byte budget.
///
/// A/B: before the decoupling, block 1 held in `applying` satisfies the
/// low-water mark (sized to one block here), so the reactor never issues the
/// second `QueryNeededBlocks` and this test times out waiting for it.
#[tokio::test]
async fn reactor_downloads_run_ahead_of_stalled_commit() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    // Low-water mark = 1 status peer * advertised inflight (1) * advertised
    // blocks-per-response (1) = 1 block, so a single block held in the commit
    // pipeline is enough to (before the fix) satisfy it. The default 4 GiB byte
    // budget stays far from binding for these tiny blocks.
    config.max_inflight_requests = 1;
    config.max_blocks_per_response = 1;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status_message(
        &service,
        &mut actions,
        41,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(3),
            tip_hash: blocks[2].hash(),
            max_blocks_per_response: 1,
            max_inflight_requests: 4,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    // A header tip above the verified tip opens the download window.
    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(3)).await;

    // Supply only height 1, download it, and submit it — then leave it stuck in
    // `applying` by never sending BlockApplyFinished (a stalled commit).
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[0])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");
    let _submit_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    };

    // The commit is now stalled: block 1 sits in `applying` (awaiting an
    // apply-finished that never comes), holding its byte reservation. The
    // download floor advanced to 1 on submit, but `queued` and `outstanding`
    // are both empty. A header-tip bump must still make the reactor re-query
    // and download height 2 — the download pipeline is empty even though the
    // commit pipeline is not.
    tip_tx
        .send((block::Height(4), block::Hash([4; 32])))
        .expect("tip watch is live");
    wait_for_query_needed_blocks(&mut actions, block::Height(1), block::Height(4)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[1])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 1),
        "the reactor must download height 2 ahead of the stalled commit of height 1",
    );

    reactor_task.abort();
}

fn add_outbound_block_sync_peer(
    service: &BlockSyncService,
    byte: u8,
    held: &mut Vec<(FramedSend, FramedRecv)>,
) -> ZakuraPeerId {
    let peer_id = peer(byte);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    held.push((inbound_tx, outbound_rx));
    peer_id
}

/// A connection-symmetry collision resolves by the loser re-registering an
/// already-present peer (adopting the winner's incoming stream). That
/// replacement must succeed even when the per-direction cap is full — the peer
/// is already counted — while a genuinely new peer at the cap is still rejected.
#[tokio::test]
async fn block_sync_add_peer_replaces_same_peer_even_at_full_cap() {
    let mut config = immediate_body_download_config();
    config.peer_limits.max_outbound_peers = 1;
    config.peer_limits.max_inbound_peers = 0;
    let (service, mut events) = BlockSyncService::new_for_test(config);

    // Keep every stream handle alive so the per-peer pipes are not torn down.
    let mut held = Vec::new();

    // Peer A fills the only outbound slot.
    let peer_a = add_outbound_block_sync_peer(&service, 41, &mut held);
    match next_event(&mut events).await {
        BlockSyncEvent::PeerConnected(session) => assert_eq!(session.peer_id(), &peer_a),
        event => panic!("expected PeerConnected for peer A, got {event:?}"),
    }
    assert_eq!(service.peer_count(), 1);

    // A distinct, new peer at the full cap is rejected: no session is created.
    let _peer_b = add_outbound_block_sync_peer(&service, 42, &mut held);
    let quiet = tokio::time::timeout(Duration::from_millis(100), events.recv()).await;
    assert!(
        quiet.is_err(),
        "a new peer at a full per-direction cap must be rejected",
    );
    assert_eq!(service.peer_count(), 1);

    // Re-registering peer A (the collision adoption) replaces its session even
    // though the cap is full, because A is already counted. The stale-session
    // teardown keys on the session id, so only a fresh PeerConnected is emitted.
    let peer_a_again = add_outbound_block_sync_peer(&service, 41, &mut held);
    assert_eq!(peer_a_again, peer_a);
    match next_event(&mut events).await {
        BlockSyncEvent::PeerConnected(session) => assert_eq!(session.peer_id(), &peer_a),
        event => panic!("expected PeerConnected for replaced peer A, got {event:?}"),
    }
    assert_eq!(
        service.peer_count(),
        1,
        "the replacement must not leave two sessions for the same peer",
    );
}

#[tokio::test]
async fn reactor_keeps_applying_body_after_non_advancing_duplicate_result() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let mut config = immediate_body_download_config();
    // One block's size hint of budget: size-based reservation now means one
    // advertised body fills the budget, throttling to one in-flight request.
    config.max_inflight_block_bytes = u64::from(block1_size);

    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        42,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
        ]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    send_inbound(&inbound_tx, BlockSyncMessage::Block(blocks[0].clone())).await;
    let submit_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    };

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submit_token,
            height: block::Height(1),
            hash: blocks[0].hash(),
            result: BlockApplyResult::Duplicate,
            local_frontier: Some(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(0),
                verified_block_hash: block::Hash([0; 32]),
            }),
        })
        .await
        .expect("non-advancing duplicate completion queues");

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
        ]))
        .await
        .expect("needed metadata after duplicate queues");

    // A re-request would land on this peer's own real outbound, so watch the wire.
    // Height 2 may legitimately be requested (receipt already freed height 1's
    // request reservation); only a height-1 re-request would be the regression.
    let no_duplicate_request = tokio::time::timeout(Duration::from_millis(100), async {
        while let Some(frame) = outbound_rx.recv().await {
            if let BlockSyncMessage::GetBlocks {
                start_height,
                count,
            } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
            {
                if start_height == block::Height(1) {
                    panic!("non-advancing duplicate result re-requested {start_height:?}/{count}");
                }
            }
        }
    })
    .await;
    assert!(
        no_duplicate_request.is_err(),
        "reactor should keep waiting after a duplicate result that did not advance the frontier",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_keeps_active_response_when_needed_snapshot_omits_inflight_height() {
    let blocks = fake_sequential_blocks(3);
    let config = immediate_body_download_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(42);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(3),
                tip_hash: blocks[2].hash(),
                max_blocks_per_response: 16,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("first block queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } if block.hash() == blocks[0].hash() => break,
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before first submit: {action:?}"),
        }
    }

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[2])]))
        .await
        .expect("newer needed metadata queues");

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("second block queues");

    let mut submitted_second = false;
    while let Ok(Some(action)) = tokio::time::timeout(Duration::from_secs(1), actions.recv()).await
    {
        match action {
            BlockSyncAction::SubmitBlock { block, .. } if block.hash() == blocks[1].hash() => {
                submitted_second = true;
                break;
            }
            BlockSyncAction::Misbehavior {
                peer,
                reason: BlockSyncMisbehavior::UnsolicitedBlock,
            } if peer == peer_id => panic!("in-flight body was misclassified as unsolicited"),
            BlockSyncAction::QueryNeededBlocks { .. } | BlockSyncAction::SubmitBlock { .. } => {}
            action => panic!("unexpected action after second block: {action:?}"),
        }
    }

    assert!(
        submitted_second,
        "second body from the original active response should remain correlated",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_unmatched_body_for_currently_needed_height() {
    let blocks = mainnet_blocks_1_to_3();
    let config = immediate_body_download_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(142);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(2),
                servable_high: block::Height(3),
                tip_hash: blocks[2].hash(),
                max_blocks_per_response: 16,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(1), blocks[0].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    // inverted inbound flow: the body is decoded by the peer's pipe-routine in its own
    // task, racing the reactor's producer `work.extend`. The reactor extends the
    // WorkQueue BEFORE publishing the candidate set, so waiting for height 1 to
    // appear in the candidate watch deterministically confirms the work is in
    // `pending` before we deliver the (unmatched-but-needed) body — without this
    // the routine could decode the body before `extend` runs and wrongly score it.
    let mut candidates = handle.subscribe_candidate_state();
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[0])]))
        .await
        .expect("needed metadata queues");
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if candidates
                .borrow_and_update()
                .missing_block_bodies
                .contains(&block::Height(1))
            {
                return;
            }
            candidates.changed().await.expect("candidate watch is live");
        }
    })
    .await
    .expect("producer extends the needed height into the WorkQueue");

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("unmatched needed block queues");

    let quiet = tokio::time::timeout(Duration::from_millis(200), async {
        loop {
            if let BlockSyncAction::Misbehavior { reason, .. } = next_action(&mut actions).await {
                return reason;
            }
        }
    })
    .await;
    assert!(
        quiet.is_err(),
        "unmatched body for a currently needed height should not be hard misbehavior",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_accepts_unmatched_body_for_queued_height() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let block2_size = block_size(&blocks[1]);
    let config = immediate_body_download_config();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    // One request slot and a response byte cap of one block-1 hint, so the single
    // GetBlocks below covers only height 1 and height 2 stays queued without an
    // outstanding request — the gap the unmatched-queued acceptance path fills.
    // (The old setup starved the request on the byte budget with an oversized
    // hint; the floor overdraft now funds a floor request regardless, so the gap
    // is created on slots/response bytes instead.)
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        143,
        block::Height(2),
        blocks[1].hash(),
        1,
        block1_size,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block2_size),
            },
        ]))
        .await
        .expect("needed metadata queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1),
        "the byte-capped request must cover only height 1",
    );

    // Height 2's body arrives without a matching outstanding request. It is a
    // queued (pending) height in the peer's servable range, so the routine must
    // claim and buffer it — no request reservation is consumed for it.
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("unmatched queued block queues");

    // Deliver height 1 on its live request; both bodies must submit in order,
    // proving the unmatched height-2 body was accepted and buffered.
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("matched block queues");

    let mut submitted = Vec::new();
    tokio::time::timeout(Duration::from_secs(1), async {
        while submitted.len() < 2 {
            if let BlockSyncAction::SubmitBlock { block, .. } = next_action(&mut actions).await {
                submitted.push(block.hash());
            }
        }
    })
    .await
    .expect("both bodies are submitted");
    assert_eq!(submitted, vec![blocks[0].hash(), blocks[1].hash()]);

    reactor_task.abort();
}

// Removed by the per-peer routine design: `reactor_accepts_queued_body_from_
// recently_disconnected_peer` exercised the reactor's "late body" path — a body
// arriving for a peer with no live routine, demuxed by the reactor's
// `handle_late_body`/`accept_unmatched_queued_body`. The inverted data flow removes
// that path entirely: a peer's frames are decoded by its own per-peer pipe-routine,
// so once the peer disconnects its stream is closed and the routine has exited —
// there is no transport over which a late body could arrive, and no reactor inbound
// demux to accept one. The live-peer unmatched-queued-body acceptance is still
// covered by `reactor_accepts_unmatched_body_for_queued_height` (the routine's
// `accept_unmatched_queued_body`, driven by a real inbound frame just above).

#[tokio::test]
async fn reactor_queries_needed_blocks_above_submitted_floor() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let block2_size = block_size(&blocks[1]);
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 2;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(43);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(3),
                tip_hash: blocks[2].hash(),
                max_blocks_per_response: 2,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: blocks[0].hash(),
                size: BlockSizeEstimate::Advertised(block1_size),
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block2_size),
            },
        ]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 2)
    );

    for block in blocks.iter().take(2) {
        inbound_tx
            .send(
                BlockSyncMessage::Block(block.clone())
                    .encode_frame()
                    .expect("block encodes"),
            )
            .await
            .expect("block queues");
    }

    let mut submitted = Vec::new();
    let mut saw_refill_query = false;
    while submitted.len() < 2 {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                submitted.push((
                    block.coinbase_height().expect("test block has height"),
                    token,
                ));
            }
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(3),
                best_header_tip,
                ..
            } => {
                assert_eq!(
                    best_header_tip,
                    block::Height(3),
                    "missing-body query must skip already claimed contiguous bodies",
                );
                saw_refill_query = true;
            }
            BlockSyncAction::QueryNeededBlocks { from, .. } => {
                panic!("missing-body query should skip claimed bodies, got from {from:?}")
            }
            action => panic!("unexpected action before checkpoint submissions: {action:?}"),
        }
    }
    assert_eq!(
        submitted
            .iter()
            .map(|(height, _token)| *height)
            .collect::<Vec<_>>(),
        vec![block::Height(1), block::Height(2)]
    );

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submitted[0].1,
            height: block::Height(1),
            hash: blocks[0].hash(),
            result: BlockApplyResult::Committed,
            local_frontier: Some(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(1),
                verified_block_hash: blocks[0].hash(),
            }),
        })
        .await
        .expect("apply-finished event queues");

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submitted[1].1,
            height: block::Height(2),
            hash: blocks[1].hash(),
            result: BlockApplyResult::Committed,
            local_frontier: Some(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(2),
                verified_block_hash: blocks[1].hash(),
            }),
        })
        .await
        .expect("apply-finished event queues");

    // The low-water ping can dispatch the refill as soon as heights 1 and 2 are
    // claimed, before this test has observed both `SubmitBlock` actions. If that
    // happened, the duplicate-pending guard intentionally suppresses another
    // identical query after apply-finished advances the state frontier.
    if !saw_refill_query {
        let action = tokio::time::timeout(Duration::from_secs(5), actions.recv())
            .await
            .expect(
                "bounded needed-block query should arrive after apply-finished advances the floor",
            )
            .expect("block-sync action channel should stay open");
        match action {
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(3),
                best_header_tip,
                ..
            } => {
                assert_eq!(
                    best_header_tip,
                    block::Height(3),
                    "missing-body query must skip already submitted contiguous bodies",
                );
            }
            BlockSyncAction::QueryNeededBlocks { from, .. } => {
                panic!("missing-body query should skip submitted bodies, got from {from:?}")
            }
            action => panic!("unexpected action before needed-block query: {action:?}"),
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_retries_submitted_body_after_apply_rejection() {
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    let block_bytes = block_size(&block);
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES;

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(42);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block.hash(),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(1), block.hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block.hash(),
            size: BlockSizeEstimate::Advertised(block_bytes),
        }]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(block.clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");
    let submit_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock {
                token,
                block: submitted,
            } => {
                assert_eq!(submitted.hash(), block.hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    };

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submit_token,
            height: block::Height(1),
            hash: block.hash(),
            result: BlockApplyResult::Rejected,
            local_frontier: None,
        })
        .await
        .expect("apply-finished event queues");
    // the rejection rollback (`reset_above` + floor reset) runs on the
    // Sequencer task while routines independently re-query, so re-supply the needed
    // metadata on every `QueryNeededBlocks` (idempotent — filtered while the height
    // is still in flight, re-extended once the rollback clears it) and wait for the
    // re-request that proves capacity/coverage were released.
    let retry_meta = vec![BlockSyncBlockMeta {
        height: block::Height(1),
        hash: block.hash(),
        size: BlockSizeEstimate::Advertised(block_bytes),
    }];
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks {
                        start_height: block::Height(1),
                        count,
                    } => {
                        assert_eq!(
                            count, 1,
                            "apply rejection must release capacity and clear submitted coverage"
                        );
                        break;
                    }
                    BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message before retry request: {msg:?}"),
                }
            }
            action = actions.recv() => {
                match action.expect("action channel is live") {
                    BlockSyncAction::QueryNeededBlocks { .. } => {
                        handle
                            .send(BlockSyncEvent::NeededBlocks(retry_meta.clone()))
                            .await
                            .expect("needed metadata queues after rejection");
                    }
                    BlockSyncAction::Misbehavior { .. } => {}
                    action => panic!("unexpected action before retry request: {action:?}"),
                }
            }
        }
    }

    reactor_task.abort();
}

/// footgun regression: downloads gate ONLY on byte budget + per-peer slots,
/// never on floor-distance / near-tip lag. With the verified floor at 0 and
/// needed heights far above it (1..=4 with the header tip near 1000), a peer with
/// free slots and ample budget MUST keep issuing GetBlocks — there is no
/// near-tip pause. The deleted `reactor_pauses_new_body_downloads_near_tip_by_default`
/// asserted the opposite; reintroducing any lag/near-tip gate fails this test
/// (the GetBlocks would never arrive).
#[tokio::test]
async fn reactor_keeps_issuing_far_above_floor_with_no_near_tip_pause() {
    // The *default* config previously paused within 2 blocks of the header tip;
    // here the needed heights sit far below a high header tip, but the point is
    // that issuance proceeds regardless of how close to (or far from) the tip we
    // are — only budget + slots gate it.
    let config = ZakuraBlockSyncConfig {
        // Open the one-probe cold start; this test exercises sustained issuance, not
        // the probe gate (which has dedicated coverage).
        initial_block_probe_requests: DEFAULT_BS_MAX_REQUESTS_WITHOUT_BLOCK_PROGRESS,
        ..ZakuraBlockSyncConfig::default()
    };
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Peer serves heights 1..=4 with four concurrent single-block slots.
    let (_peer_id, _inbound, mut outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        41,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(4),
            tip_hash: block::Hash([4; 32]),
            max_blocks_per_response: 1,
            max_inflight_requests: 4,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    // Header tip far above the floor (lag is huge — would have *not* paused) and
    // also exercises that being far from the tip does not gate either.
    tip_tx
        .send((block::Height(1_000), block::Hash([9; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=4)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([height as u8; 32]),
                    size: BlockSizeEstimate::Advertised(1_000),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    // All four slots fill: no near-tip pause exists to gate issuance.
    let mut heights = Vec::new();
    for _ in 0..4 {
        let (start_height, count) = wait_for_outbound_getblocks(&mut outbound).await;
        assert_eq!(count, 1);
        heights.push(start_height.0);
    }
    heights.sort_unstable();
    assert_eq!(
        heights,
        vec![1, 2, 3, 4],
        "a peer with free slots and budget must keep issuing regardless of floor distance"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn routine_refills_after_budget_release_no_missed_wake() {
    // missed-wake guard at the routine level: a routine blocked on an
    // exhausted byte budget must re-fill when budget is freed. The budget holds
    // exactly one worst-case block, so the first GetBlocks exhausts it; receipt
    // of that body releases the whole reservation and the routine must issue the
    // next GetBlocks without any external nudge.
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES;
    config.max_blocks_per_response = 1;
    config.request_timeout = Duration::from_secs(300);
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status_message(
        &service,
        &mut actions,
        70,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(2),
            tip_hash: blocks[1].hash(),
            max_blocks_per_response: 1,
            max_inflight_requests: 4,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[0]),
            block_meta(&blocks[1]),
        ]))
        .await
        .expect("needed metadata queues");

    // Only one worst-case block fits the budget, so exactly one GetBlocks is
    // issued first; the routine then parks blocked on the exhausted byte budget.
    let (first_start, _count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(first_start, block::Height(1));

    // Deliver height 1's body. Receipt releases its whole worst-case reservation
    // (retention charges nothing), so the routine can issue height 2 as soon as
    // its next fill pass runs.
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    // Drive height 1 through submit and apply so the pipeline finishes cleanly;
    // the height-2 GetBlocks below must arrive regardless (the receipt-time
    // release must wake the budget-blocked fill — a release between the
    // routine's fill-check and its await must not be lost).
    let token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.coinbase_height(), Some(block::Height(1)));
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before SubmitBlock: {action:?}"),
        }
    };
    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token,
            height: block::Height(1),
            hash: blocks[0].hash(),
            result: BlockApplyResult::Committed,
            local_frontier: None,
        })
        .await
        .expect("apply-finished event queues");

    let (second_start, _count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(
        second_start,
        block::Height(2),
        "freeing the request budget must wake the routine to issue the next request (no missed wake)"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn routine_disconnect_returns_outstanding_and_releases_budget() {
    // disconnect-mid-fetch guard: cancelling a routine with unreceived
    // outstanding must return those heights to `work.pending` and release their
    // budget, so a fresh peer is offered the same height. Driven black-box: the
    // first peer takes the height, then disconnects mid-fetch; a second peer must
    // be offered it.
    let mut config = immediate_body_download_config();
    config.request_timeout = Duration::from_secs(300);
    config.peer_limits.max_outbound_peers = 4;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_a, _a_in, mut a_out) = connect_peer_with_status(
        &service,
        &mut actions,
        0x71,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(1), blocks[0].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[0])]))
        .await
        .expect("needed metadata queues");

    let (start, _count) = wait_for_outbound_getblocks(&mut a_out).await;
    assert_eq!(start, block::Height(1));

    // Disconnect peer A mid-fetch (it never answers). Its routine's `Drop` guard
    // must return height 1 to `pending` and release its reservation.
    service.remove_peer(&peer_a, 0);
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if service.peer_count() == 0 {
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("disconnect releases the block-sync peer slot");

    // A fresh peer that can serve height 1 must be offered it again — proving the
    // height returned to `pending` (and its budget was released so the new request
    // can reserve).
    let (_peer_b, _b_in, mut b_out) = connect_peer_with_status(
        &service,
        &mut actions,
        0x72,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    let offered = tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            let (start, _count) = wait_for_outbound_getblocks(&mut b_out).await;
            if start == block::Height(1) {
                return true;
            }
        }
    })
    .await
    .expect("a fresh peer must be offered the re-queued height after a disconnect mid-fetch");
    assert!(offered);

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_reserves_size_hint_per_block_not_worst_case() {
    // The issuance path (`try_fill`) reserves the advertised size hint per block,
    // NOT `BS_PER_BLOCK_WORST_CASE_BYTES`. The global byte budget = 3 worst-case
    // blocks; the peer advertises a generous slot/response/block-count budget and
    // tiny 1 KiB size hints. Under the old worst-case reservation the budget would
    // bound the request to 3 blocks; because the reservation now honors the 1 KiB
    // hints, the full 16-block range fits under the budget and the request is the
    // whole 16-block range.
    let budget_blocks = 3u32;
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: u64::from(budget_blocks) * BS_PER_BLOCK_WORST_CASE_BYTES,
        // Generous per-request block count (the default is 1) so the count cap is
        // not the binding constraint — the byte budget is.
        max_blocks_per_response: 16,
        ..ZakuraBlockSyncConfig::default()
    };

    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // One slot, a generous response-byte and per-request block count, so neither
    // the slot count, the peer's response-byte cap, nor the block-count cap is the
    // binding constraint — only the per-peer byte cap is.
    let (_peer_id, _inbound, mut outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        51,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(16),
            tip_hash: block::Hash([16; 32]),
            max_blocks_per_response: 16,
            max_inflight_requests: 1,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=16)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([height as u8; 32]),
                    // Tiny hint: if the reservation honored this instead of the
                    // worst case, the whole 16-block range would fit under the cap.
                    size: BlockSizeEstimate::Advertised(1_000),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    let (_start_height, count) = wait_for_outbound_getblocks(&mut outbound).await;
    assert_eq!(
        count, 16,
        "the request must cover the full 16-block range: the 1 KiB size hints (not a \
         worst-case-per-block reservation) drive the budget, so all 16 fit under a \
         {budget_blocks}-worst-case-block budget",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_packs_small_estimates_under_peer_response_byte_cap() {
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: 4 * BS_PER_BLOCK_WORST_CASE_BYTES,
        max_blocks_per_response: 4,
        ..ZakuraBlockSyncConfig::default()
    };

    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let one_worst_case_response =
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES).expect("worst-case block size fits u32");
    let (_peer_id, _inbound, mut outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        52,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(4),
            tip_hash: block::Hash([4; 32]),
            max_blocks_per_response: 4,
            max_inflight_requests: 1,
            max_response_bytes: one_worst_case_response,
        },
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=4)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([height as u8; 32]),
                    size: BlockSizeEstimate::Advertised(1_000),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(
        count, 4,
        "small advertised estimates should pack more than the one worst-case block \
         allowed by the peer response byte cap",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_tiny_estimates_pack_into_one_worst_case_budget_block() {
    // A global budget of one worst-case block (2 MB) now holds many tiny-hint
    // bodies, because each reserves its size hint (clamped to the 1 KiB floor),
    // not a worst-case share. All 4 advertised heights fit in one request.
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES,
        max_blocks_per_response: 4,
        ..ZakuraBlockSyncConfig::default()
    };

    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let (_peer_id, _inbound, mut outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        53,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(4),
            tip_hash: block::Hash([4; 32]),
            max_blocks_per_response: 4,
            max_inflight_requests: 1,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            (1..=4)
                .map(|height| BlockSyncBlockMeta {
                    height: block::Height(height),
                    hash: block::Hash([u8::try_from(height).expect("test height fits u8"); 32]),
                    size: BlockSizeEstimate::Advertised(1),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(
        count, 4,
        "all 4 tiny-hint heights pack into one worst-case-block budget, because each \
         reserves its 1 KiB-floored size hint rather than a worst-case share",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_zero_pause_threshold_preserves_lag_one_downloads() {
    let config = immediate_body_download_config();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config,
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(1),
            hash: block::Hash([1; 32]),
        })
        .await
        .expect("header-tip event queues");

    // A lag of 1 above the floor must still query needed blocks: there is no
    // near-tip pause. (The startup query carries best_header_tip 0; the tip-1
    // event carries best_header_tip 1.)
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(1),
            best_header_tip: block::Height(1),
            ..
        }
    ) {}

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_keeps_block_sync_peer_after_catch_up_and_reuses_later() {
    // Block-sync streams stay open even when this node is locally caught up: a
    // synced node can still be the server a fresh peer needs for historical
    // bodies, so closing the stream after every local catch-up would starve fresh
    // Zakura-only nodes between checkpoint windows.
    let mut config = fill_loop_mechanics_config();
    config.peer_limits.max_outbound_peers = 1;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(4), block::Hash([4; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(4), block::Hash([4; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        71,
        block::Height(6),
        block::Hash([6; 32]),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(3),
            hash: block::Hash([3; 32]),
        })
        .await
        .expect("header-tip event queues");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: block::Hash([1; 32]),
                size: BlockSizeEstimate::Unknown,
            },
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: block::Hash([2; 32]),
                size: BlockSizeEstimate::Unknown,
            },
            BlockSyncBlockMeta {
                height: block::Height(3),
                hash: block::Hash([3; 32]),
                size: BlockSizeEstimate::Unknown,
            },
        ]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3)
    );

    for height in [block::Height(1), block::Height(2)] {
        let hash_byte = u8::try_from(height.0).expect("test height fits in u8");
        handle
            .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: height,
                verified_block_hash: block::Hash([hash_byte; 32]),
            }))
            .await
            .expect("frontier event queues");
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert_eq!(handle.peer_snapshot().outbound_peers, 1);
        assert_eq!(service.peer_count(), 1);
    }

    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(1),
                returned: 3,
            }
            .encode_frame()
            .expect("BlocksDone encodes"),
        )
        .await
        .expect("BlocksDone queues");

    handle
        .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(3),
            verified_block_hash: block::Hash([3; 32]),
        }))
        .await
        .expect("caught-up frontier event queues");
    tokio::time::sleep(Duration::from_millis(100)).await;
    assert_eq!(
        handle.peer_snapshot().outbound_peers,
        1,
        "caught-up nodes must keep block-sync peers so they can serve fresh nodes",
    );
    assert_eq!(service.peer_count(), 1);

    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(6),
            hash: block::Hash([6; 32]),
        })
        .await
        .expect("later header-tip event queues");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(4),
            best_header_tip: block::Height(6),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(4),
                hash: block::Hash([4; 32]),
                size: BlockSizeEstimate::Unknown,
            },
            BlockSyncBlockMeta {
                height: block::Height(5),
                hash: block::Hash([5; 32]),
                size: BlockSizeEstimate::Unknown,
            },
            BlockSyncBlockMeta {
                height: block::Height(6),
                hash: block::Hash([6; 32]),
                size: BlockSizeEstimate::Unknown,
            },
        ]))
        .await
        .expect("new needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(4), 3),
        "the retained block-sync peer should be reused after later header growth",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_accepts_multi_block_range_and_submits_parent_first() {
    let config = ZakuraBlockSyncConfig {
        max_blocks_per_response: 4,
        ..ZakuraBlockSyncConfig::default()
    };
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer = peer(43);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(3),
                tip_hash: blocks[2].hash(),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");
    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks
                .iter()
                .map(|block| BlockSyncBlockMeta {
                    height: block.coinbase_height().expect("test block has height"),
                    hash: block.hash(),
                    size: BlockSizeEstimate::Advertised(block_size(block)),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(count, 3);

    for index in [1usize, 2, 0] {
        inbound_tx
            .send(
                BlockSyncMessage::Block(blocks[index].clone())
                    .encode_frame()
                    .expect("block encodes"),
            )
            .await
            .expect("block queues");
    }

    let mut submitted = Vec::new();
    while submitted.len() < 3 {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => submitted.push(
                block
                    .coinbase_height()
                    .expect("submitted test block has height"),
            ),
            BlockSyncAction::Misbehavior { reason, .. } => {
                panic!("honest multi-block response was misclassified: {reason:?}")
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before all submits: {action:?}"),
        }
    }
    assert_eq!(
        submitted,
        vec![block::Height(1), block::Height(2), block::Height(3)]
    );

    reactor_task.abort();
}

/// Every solicited body in a burst must reach the apply stage — the inbound
/// peer->reactor path must never silently drop a block body under load.
///
/// This is the regression guard for the production "drop-through" stall. The
/// per-peer wire queue is bounded; the old inbound pump forwarded decoded
/// messages with a non-blocking `try_send` and dropped solicited block bodies
/// once that queue filled during a body flood. A single dropped body wedges
/// `body_download_floor`, and because checkpoint-range commits wait
/// indefinitely for a contiguous range, the wedge never clears — every block
/// above it sits in `applying` forever and sync stalls at a checkpoint. The fix
/// makes the pump backpressure instead of dropping, so the flood always drains.
///
/// The harness makes a drop *fatal* rather than self-healing, which is what our
/// earlier tests missed: a one-slot wire queue forces the drop, a single
/// in-flight request stops the reactor from working around the gap, and a very
/// long request timeout means a dropped body is never re-requested within the
/// deadline. So a regression hangs here (outer timeout) instead of slowly
/// recovering and passing.
#[tokio::test]
async fn reactor_backpressures_inbound_body_flood_without_dropping_bodies() {
    const FLOOD: u32 = 64;
    let blocks = fake_sequential_blocks(FLOOD);
    let tip = blocks.last().expect("flood is non-empty").clone();
    let tip_height = tip.coinbase_height().expect("tip has height");

    let mut config = immediate_body_download_config();
    // One-slot wire queue: a pump that outruns the reactor by more than one
    // frame must backpressure, never drop.
    config.peer_limits.inbound_queue_depth = 1;
    // Hold the whole flood in flight at once so nothing pauses on the byte
    // budget; the inbound flood, not the budget, is what this test exercises.
    config.max_inflight_block_bytes = u64::MAX;
    // A dropped body must not be quietly re-requested and healed before the
    // deadline — that would hide the very regression this test guards.
    config.request_timeout = Duration::from_secs(300);

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer = peer(64);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: tip_height,
                tip_hash: tip.hash(),
                max_blocks_per_response: FLOOD,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");
    tip_tx
        .send((tip_height, tip.hash()))
        .expect("tip watch is live");

    // Feed solicited bodies from a dedicated task so the drive loop never blocks
    // on inbound backpressure while it still needs to drain reactor actions.
    let feed_blocks = blocks.clone();
    let (feed_tx, mut feed_rx) = mpsc::unbounded_channel::<u32>();
    let feeder = tokio::spawn(async move {
        while let Some(height) = feed_rx.recv().await {
            let frame = BlockSyncMessage::Block(feed_blocks[(height - 1) as usize].clone())
                .encode_frame()
                .expect("block frame encodes");
            if inbound_tx.send(frame).await.is_err() {
                break;
            }
        }
    });

    let metas: Vec<_> = blocks
        .iter()
        .map(|block| BlockSyncBlockMeta {
            height: block.coinbase_height().expect("test block has height"),
            hash: block.hash(),
            size: BlockSizeEstimate::Advertised(block_size(block)),
        })
        .collect();

    let drive = async {
        let mut submitted = std::collections::HashSet::new();
        while submitted.len() < FLOOD as usize {
            // Multiplex the node's real outbound (the `GetBlocks` requests that
            // tell us which heights to feed) with the action channel (needed-blocks
            // queries and submissions). No per-source timeout: if a regression
            // drops a body the reactor simply stops, and the outer deadline below
            // reports the failure.
            tokio::select! {
                biased;
                frame = outbound_rx.recv() => {
                    let Some(frame) = frame else { break };
                    if let BlockSyncMessage::GetBlocks {
                        start_height,
                        count,
                    } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
                    {
                        for height in start_height.0..start_height.0 + count {
                            feed_tx.send(height).expect("feeder task stays open");
                        }
                    }
                }
                action = actions.recv() => {
                    let Some(action) = action else { break };
                    match action {
                        BlockSyncAction::QueryNeededBlocks { .. } => {
                            handle
                                .send(BlockSyncEvent::NeededBlocks(metas.clone()))
                                .await
                                .expect("needed metadata queues");
                        }
                        BlockSyncAction::SubmitBlock { block, .. } => {
                            submitted.insert(
                                block.coinbase_height().expect("submitted block has height"),
                            );
                        }
                        _ => {}
                    }
                }
            }
        }
        submitted
    };

    let submitted = tokio::time::timeout(Duration::from_secs(20), drive)
        .await
        .expect(
        "flooded bodies must all reach the apply stage; a dropped inbound body wedges block sync",
    );

    let expected: std::collections::HashSet<_> = (1..=FLOOD).map(block::Height).collect();
    assert_eq!(
        submitted, expected,
        "every solicited body in the flood must be submitted exactly once, with no drops"
    );

    feeder.abort();
    reactor_task.abort();
}

#[tokio::test]
async fn reactor_restarted_at_genesis_queries_and_schedules_without_tip_change() {
    let config = immediate_body_download_config();
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(3), blocks[2].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(3), blocks[2].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    match next_action(&mut actions).await {
        BlockSyncAction::QueryNeededBlocks {
            from,
            best_header_tip,
            ..
        } => {
            assert_eq!(from, block::Height(1));
            assert_eq!(best_header_tip, block::Height(3));
        }
        action => panic!("restart from genesis must query missing bodies, got {action:?}"),
    }

    let (_peer, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        67,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3),
        "restart from genesis must schedule scratch body sync from height 1"
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[0].hash());
                assert_eq!(block.coinbase_height(), Some(block::Height(1)));
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before first scratch submit: {action:?}"),
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_accepts_blocks_done_after_completed_range() {
    let config = immediate_body_download_config();
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        68,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[0])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    }

    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(1),
                returned: 1,
            }
            .encode_frame()
            .expect("BlocksDone encodes"),
        )
        .await
        .expect("BlocksDone queues");

    while let Ok(Some(action)) =
        tokio::time::timeout(Duration::from_millis(200), actions.recv()).await
    {
        if let BlockSyncAction::Misbehavior {
            peer: action_peer,
            reason,
        } = action
        {
            assert_ne!(
                (action_peer, reason),
                (peer.clone(), BlockSyncMisbehavior::UnsolicitedDone),
                "a valid terminator after a completed block response must not be scored"
            );
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_retries_missing_heights_after_partial_blocks_done() {
    let config = immediate_body_download_config();
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        69,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[0].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before first submit: {action:?}"),
        }
    }

    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(1),
                returned: 1,
            }
            .encode_frame()
            .expect("BlocksDone encodes"),
        )
        .await
        .expect("BlocksDone queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2),
        "partial responses must retry the contiguous missing suffix"
    );

    reactor_task.abort();
}

// `reactor_does_not_retry_missing_height_already_in_flight` was a fanout=2 test:
// it required the same range to be assigned to two peers and asserted that a
// partial response from one did not re-request heights the *other* still held.
// Fanout > 1 is removed in WorkQueue (a height is taken by exactly one peer), so the
// "in flight on another peer" scenario no longer exists. The structural property
// — a taken (in_flight) height is not re-takable — is now covered by the
// WorkQueue unit test `work_queue_take_dedups_a_height_across_peers`.

#[tokio::test]
async fn checkpoint_hole_disconnect_retries_first_missing_height_with_fresh_peer() {
    // Worst-case reservation caps a request at ~16 blocks (down from 128), so the
    // priming prefix is kept short enough to submit within the priming window
    // while still placing the hole behind several scheduled requests.
    const FIRST_NEEDED: u32 = 801;
    const PREFIX_END: u32 = 864;
    const HOLE_START: u32 = 865;
    const HOLE_END: u32 = 872;
    const LAST_METADATA: u32 = 933;
    const BEST_HEADER_TIP: u32 = 10_400;

    let blocks = fake_blocks_in_range(FIRST_NEEDED, LAST_METADATA);
    let block_at = |height: u32| -> Arc<block::Block> {
        let index =
            usize::try_from(height - FIRST_NEEDED).expect("test height is inside block vector");
        blocks[index].clone()
    };
    let metas: Vec<_> = blocks.iter().map(block_meta).collect();
    let prefix: std::collections::HashSet<_> =
        (FIRST_NEEDED..=PREFIX_END).map(block::Height).collect();
    let sparse_above_hole: std::collections::HashSet<_> = [873, 888, 905, 920]
        .into_iter()
        .map(block::Height)
        .collect();

    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = u64::MAX;
    config.request_timeout = Duration::from_secs(300);
    config.peer_limits.max_outbound_peers = 1;
    config.peer_limits.inbound_queue_depth = 128;
    // Worst-case reservation caps a request at ~16 blocks, so the prefix needs
    // more concurrent requests; keep the outbound queue wide enough that a fill
    // pass never overflows it and cancels the peer.
    config.peer_limits.outbound_queue_depth = 128;

    let (_tip_tx, tip_rx) = watch::channel((block::Height(BEST_HEADER_TIP), block::Hash([10; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(800),
            verified_block_tip: block::Height(800),
            verified_block_hash: block::Hash([8; 32]),
        },
        (block::Height(BEST_HEADER_TIP), block::Hash([10; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let (old_peer, old_inbound, mut old_outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        70,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(LAST_METADATA),
            tip_hash: block_at(LAST_METADATA).hash(),
            max_blocks_per_response: MAX_BS_BLOCKS_PER_REQUEST,
            // Worst-case reservation caps a request at `max_response_bytes /
            // MAX_BLOCK_BYTES` (~16) blocks, so allow more concurrent requests to
            // cover the checkpoint prefix within the priming window.
            max_inflight_requests: 8,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;
    handle
        .send(BlockSyncEvent::NeededBlocks(metas.clone()))
        .await
        .expect("checkpoint metadata queues after peer connection");

    let (feed_tx, mut feed_rx) = mpsc::unbounded_channel::<u32>();
    let blocks_for_feeder = blocks.clone();
    let feeder = tokio::spawn(async move {
        while let Some(height) = feed_rx.recv().await {
            let index = usize::try_from(height - FIRST_NEEDED)
                .expect("fed test height is inside block vector");
            let frame = BlockSyncMessage::Block(blocks_for_feeder[index].clone())
                .encode_frame()
                .expect("block frame encodes");
            if old_inbound.send(frame).await.is_err() {
                break;
            }
        }
    });

    let mut requests: Vec<(block::Height, u32)> = Vec::new();
    let mut submitted = std::collections::HashSet::new();
    let primed = tokio::time::timeout(Duration::from_secs(40), async {
        while !prefix.is_subset(&submitted)
            || !requests.iter().any(|(start, count)| {
                *start <= block::Height(HOLE_START) && start.0.saturating_add(*count) > HOLE_END
            })
        {
            // The old peer's `GetBlocks` arrive on its own real outbound (reading
            // that stream proves they targeted it); needed-block queries and
            // submissions come over the action channel.
            tokio::select! {
                biased;
                frame = old_outbound.recv() => {
                    let frame = frame.expect("old peer outbound is live");
                    if let BlockSyncMessage::GetBlocks {
                        start_height,
                        count,
                    } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
                    {
                        requests.push((start_height, count));
                        let end_height = start_height
                            .0
                            .checked_add(count)
                            .expect("test request height range fits u32");
                        for height in start_height.0..end_height {
                            let height = block::Height(height);
                            if height.0 <= PREFIX_END || sparse_above_hole.contains(&height) {
                                feed_tx.send(height.0).expect("feeder task stays open");
                            }
                        }
                    }
                }
                action = actions.recv() => {
                    match action.expect("block-sync action channel should stay open") {
                        BlockSyncAction::QueryNeededBlocks {
                            from,
                            best_header_tip,
                            ..
                        } => {
                            // queries fire at various floor states as commits
                            // advance the floor (it starts at 800 and climbs as the
                            // prefix commits), so the lower bound is `>= 800`, not
                            // exactly 800.
                            assert!(from >= block::Height(801));
                            assert_eq!(best_header_tip, block::Height(BEST_HEADER_TIP));
                            handle
                                .send(BlockSyncEvent::NeededBlocks(metas.clone()))
                                .await
                                .expect("checkpoint metadata queues");
                        }
                        BlockSyncAction::SubmitBlock { block, .. } => {
                            let height =
                                block.coinbase_height().expect("submitted block has height");
                            assert!(
                                submitted.insert(height),
                                "height {height:?} was submitted more than once before the hole retry"
                            );
                        }
                        action => {
                            panic!("unexpected action while priming checkpoint hole: {action:?}")
                        }
                    }
                }
            }
        }
    })
    .await;
    assert!(
        primed.is_ok(),
        "checkpoint-hole priming timed out: requests={requests:?}, submitted={} of {}",
        submitted.len(),
        prefix.len()
    );

    assert!(
        requests
            .iter()
            .any(|(start, count)| *start <= block::Height(HOLE_START)
                && start.0.saturating_add(*count) > HOLE_END),
        "the initial in-flight requests must cover the missing checkpoint hole"
    );

    service.remove_peer(&old_peer, 0);
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if handle.peer_snapshot().outbound_peers == 0 && service.peer_count() == 0 {
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("disconnect releases the old block-sync peer slot");

    let (_new_peer, _new_inbound, mut new_outbound) = connect_peer_with_status_message(
        &service,
        &mut actions,
        71,
        BlockSyncStatus {
            servable_low: block::Height(1),
            servable_high: block::Height(LAST_METADATA),
            tip_hash: block_at(LAST_METADATA).hash(),
            max_blocks_per_response: MAX_BS_BLOCKS_PER_REQUEST,
            max_inflight_requests: 8,
            max_response_bytes: MAX_BS_RESPONSE_BYTES,
        },
    )
    .await;

    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            // The fresh peer's `GetBlocks` arrive on its own real outbound (reading
            // that stream proves the request targeted it).
            tokio::select! {
                biased;
                frame = new_outbound.recv() => {
                    let frame = frame.expect("new peer outbound is live");
                    if let BlockSyncMessage::GetBlocks {
                        start_height,
                        count,
                    } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
                    {
                        assert_eq!(
                            start_height,
                            block::Height(HOLE_START),
                            "after a partial response disconnect, the first fresh request must fill \
                             the checkpoint hole instead of jumping above it or reusing a stale \
                             assignment"
                        );
                        assert!(count >= 1);
                        break;
                    }
                }
                action = actions.recv() => {
                    match action.expect("block-sync action channel should stay open") {
                        BlockSyncAction::QueryNeededBlocks { .. } => {
                            handle
                                .send(BlockSyncEvent::NeededBlocks(metas.clone()))
                                .await
                                .expect("post-disconnect metadata queues");
                        }
                        BlockSyncAction::SubmitBlock { block, .. } => {
                            let height =
                                block.coinbase_height().expect("submitted block has height");
                            assert!(
                                submitted.insert(height),
                                "height {height:?} was resubmitted before the checkpoint hole was retried"
                            );
                        }
                        action => {
                            panic!(
                                "unexpected action while waiting for checkpoint-hole retry: {action:?}"
                            )
                        }
                    }
                }
            }
        }
    })
    .await
    .expect("fresh peer should request the checkpoint hole after disconnect");

    feeder.abort();
    reactor_task.abort();
}

#[tokio::test]
async fn reactor_reset_mid_download_drops_stale_anchors_and_releases_budget() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        47,
        block::Height(3),
        blocks[2].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(3),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(10_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(3),
                hash: blocks[2].hash(),
                size: BlockSizeEstimate::Advertised(10_000),
            },
        ]))
        .await
        .expect("old-fork needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("out-of-order old-fork block queues");

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        }))
        .await
        .expect("reset event queues");
    // the reset (FrontierReset) and the producer are decoupled across tasks,
    // and routines re-query on a low-water ping, so several `QueryNeededBlocks`
    // can race the in-flight reset clear. Re-supply the new-fork metadata on every
    // query (idempotent: it is filtered while the stale height is still in flight,
    // and re-extended once the Sequencer's `reset_above` clears it) and wait for
    // the height-2 request that proves stale bytes were released.
    let new_fork_meta = vec![BlockSyncBlockMeta {
        height: block::Height(2),
        hash: block::Hash([92; 32]),
        size: BlockSizeEstimate::Advertised(20_000),
    }];
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks {
                        start_height: block::Height(2),
                        count,
                    } => {
                        assert_eq!(
                            count, 1,
                            "a full-budget new fork request can only be scheduled if stale bytes were released"
                        );
                        break;
                    }
                    BlockSyncMessage::GetBlocks { .. } | BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message before new fork request: {msg:?}"),
                }
            }
            action = actions.recv() => {
                match action.expect("action channel is live") {
                    BlockSyncAction::QueryNeededBlocks { .. } => {
                        handle
                            .send(BlockSyncEvent::NeededBlocks(new_fork_meta.clone()))
                            .await
                            .expect("new-fork needed metadata queues");
                    }
                    // The honest in-flight height-3 body (within the peer's advertised
                    // servable range) that races the in-place reset must NOT be scored
                    // `UnsolicitedBlock` — `ignore_servable_range_response` drops it
                    // quietly so a reorg does not churn honest peers. Any misbehavior
                    // here is a regression and falls through to the panic below.
                    action => panic!("unexpected action before new fork request: {action:?}"),
                }
            }
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_forward_reset_preserves_submitted_successor_body() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        49,
        block::Height(3),
        blocks[2].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(3),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[1]),
            block_meta(&blocks[2]),
        ]))
        .await
        .expect("initial needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("contiguous body queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[1].hash());
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before first submit: {action:?}"),
        }
    }

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("successor body queues");
    let successor_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), blocks[2].hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before successor submit: {action:?}"),
        }
    };

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(2),
            verified_block_hash: blocks[1].hash(),
        }))
        .await
        .expect("forward reset event queues");
    assert!(
        tokio::time::timeout(Duration::from_millis(100), actions.recv())
            .await
            .is_err(),
        "forward reset must not re-query or re-submit the preserved successor body",
    );

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: successor_token,
            height: block::Height(3),
            hash: blocks[2].hash(),
            result: BlockApplyResult::Committed,
            local_frontier: None,
        })
        .await
        .expect("successor apply result queues");
    assert!(
        tokio::time::timeout(Duration::from_millis(100), actions.recv())
            .await
            .is_err(),
        "at-tip successor apply must not trigger a redundant needed-block query",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_forward_reset_preserves_future_outstanding_body() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        72,
        block::Height(3),
        blocks[2].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(3),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[1]),
            block_meta(&blocks[2]),
        ]))
        .await
        .expect("initial needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(2),
            verified_block_hash: blocks[1].hash(),
        }))
        .await
        .expect("forward reset event queues");

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("successor body queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(block.hash(), blocks[2].hash());
                break;
            }
            BlockSyncAction::Misbehavior { peer, reason } => {
                assert_ne!(
                    (peer, reason),
                    (peer_id.clone(), BlockSyncMisbehavior::UnsolicitedBlock),
                    "forward reset must not drop a still-active successor request"
                );
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            BlockSyncAction::QueryBlocksByHeightRange { .. } => {}
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_forward_reset_preserves_buffered_successor_body() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        73,
        block::Height(3),
        blocks[2].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(3),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[1]),
            block_meta(&blocks[2]),
        ]))
        .await
        .expect("initial needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("successor body queues");
    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(2),
                returned: 2,
            }
            .encode_frame()
            .expect("BlocksDone encodes"),
        )
        .await
        .expect("BlocksDone queues");

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(2),
            verified_block_hash: blocks[1].hash(),
        }))
        .await
        .expect("forward reset event queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => {
                assert_eq!(
                    block.hash(),
                    blocks[2].hash(),
                    "buffered successor must submit without a duplicate download"
                );
                break;
            }
            BlockSyncAction::Misbehavior { peer, reason } => {
                assert_ne!(
                    (peer, reason),
                    (peer_id.clone(), BlockSyncMisbehavior::UnsolicitedBlock),
                    "forward reset must not drop a buffered successor body"
                );
            }
            BlockSyncAction::QueryNeededBlocks { .. }
            | BlockSyncAction::QueryBlocksByHeightRange { .. } => {}
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_destructive_forward_reset_does_not_rerequest_same_hash_in_flight_apply() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        68,
        block::Height(2),
        blocks[1].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[0]),
            block_meta(&blocks[1]),
        ]))
        .await
        .expect("initial needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 2)
    );

    for block in blocks.iter().take(2) {
        inbound_tx
            .send(
                BlockSyncMessage::Block(block.clone())
                    .encode_frame()
                    .expect("block encodes"),
            )
            .await
            .expect("block queues");
    }

    let mut submitted = Vec::new();
    while submitted.len() < 2 {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => submitted.push((
                block.coinbase_height().expect("test block has height"),
                token,
            )),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submitted bodies: {action:?}"),
        }
    }
    assert_eq!(
        submitted
            .iter()
            .map(|(height, _)| *height)
            .collect::<Vec<_>>(),
        vec![block::Height(1), block::Height(2)]
    );

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: block::Hash([99; 32]),
        }))
        .await
        .expect("destructive forward reset queues");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(2),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[1])]))
        .await
        .expect("same-hash needed metadata queues");

    // Sequencer task: the destructive reset preserves the submitted-apply record for height 2
    // (`remember_released_applies`) but `reset_above` drops its WorkQueue
    // `in_flight` claim, and the reactor's producer filter is now the hash-blind
    // `in_flight_contains` structural check (it can no longer read the Sequencer's
    // per-hash `has_submitted_apply`). So the same-hash height MAY now be
    // re-requested. The safety invariant the original test pinned still holds and
    // is what we verify: a re-delivered same-hash body whose apply is still
    // pending is dropped as redundant by the Sequencer and is NOT re-submitted
    // (no double apply), because the preserved submitted-apply record makes
    // `accept_body` report it `Redundant`.
    if let Ok((re_start, re_count)) = tokio::time::timeout(
        Duration::from_millis(200),
        wait_for_outbound_getblocks(&mut outbound_rx),
    )
    .await
    {
        assert_eq!(
            (re_start, re_count),
            (block::Height(2), 1),
            "any same-hash re-request must target exactly the released height"
        );
        // Deliver the same-hash body for the re-request and assert it is dropped
        // as redundant (no SubmitBlock) — the no-double-apply guarantee.
        inbound_tx
            .send(
                BlockSyncMessage::Block(blocks[1].clone())
                    .encode_frame()
                    .expect("block encodes"),
            )
            .await
            .expect("same-hash body queues");
        let no_resubmit = tokio::time::timeout(Duration::from_millis(200), async {
            loop {
                match actions.recv().await {
                    Some(BlockSyncAction::SubmitBlock { block, .. })
                        if block.hash() == blocks[1].hash() =>
                    {
                        panic!("same-hash body with a pending apply must not be re-submitted")
                    }
                    Some(_) => {}
                    None => break,
                }
            }
        })
        .await;
        assert!(
            no_resubmit.is_err(),
            "a redundant same-hash body must be dropped, not re-submitted",
        );
    }

    // A genuine fork to a different hash at height 2 reaches block sync as a reset
    // (reanchor), which `reset_above`s the WorkQueue and clears any stale
    // `in_flight` claim for height 2 before the producer re-fills — the path the
    // reset path relies on to install a new per-height hash (a bare
    // `NeededBlocks` never hash-corrects an in-flight height). After that reset the
    // different hash at the same height must schedule.
    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: block::Hash([99; 32]),
        }))
        .await
        .expect("fork reanchor reset queues");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            ..
        }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(2),
            hash: block::Hash([42; 32]),
            size: BlockSizeEstimate::Advertised(block_size(&blocks[1])),
        }]))
        .await
        .expect("new-fork needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 1),
        "different hash at the same height must still schedule after a fork reset"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_stale_apply_completion_after_resubmit() {
    let config = immediate_body_download_config();
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    let block_hash = block.hash();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(61);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block_hash,
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(1), block_hash))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block_hash,
            size: BlockSizeEstimate::Advertised(block_size(&block)),
        }]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(block.clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("first body frame queues");
    let stale_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), block_hash);
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before first submit: {action:?}"),
        }
    };

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        }))
        .await
        .expect("reset event queues");
    // the reset's `reset_above` runs on the Sequencer task while routines
    // re-query, so re-supply the needed metadata on every query (idempotent until
    // the reset clears the stale in-flight) and wait for the re-fetch.
    let reset_meta = vec![BlockSyncBlockMeta {
        height: block::Height(1),
        hash: block_hash,
        size: BlockSizeEstimate::Advertised(block_size(&block)),
    }];
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks {
                        start_height: block::Height(1),
                        count,
                    } => {
                        assert_eq!(count, 1);
                        break;
                    }
                    BlockSyncMessage::GetBlocks { .. } | BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message before reset re-fetch: {msg:?}"),
                }
            }
            action = actions.recv() => {
                match action.expect("action channel is live") {
                    BlockSyncAction::QueryNeededBlocks { .. } => {
                        handle
                            .send(BlockSyncEvent::NeededBlocks(reset_meta.clone()))
                            .await
                            .expect("needed metadata queues after reset");
                    }
                    BlockSyncAction::Misbehavior { .. } => {}
                    action => panic!("unexpected action before reset re-fetch: {action:?}"),
                }
            }
        }
    }
    inbound_tx
        .send(
            BlockSyncMessage::Block(block.clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("second body frame queues");
    let current_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), block_hash);
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before second submit: {action:?}"),
        }
    };
    assert_ne!(stale_token, current_token);

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: stale_token,
            height: block::Height(1),
            hash: block_hash,
            result: BlockApplyResult::Duplicate,
            local_frontier: None,
        })
        .await
        .expect("stale apply-finished event queues");
    // The stale completion must not release the current submission: it produces no
    // new `SubmitBlock` (no re-submission). Routines ping the producer on a
    // low-water timer, so a benign `QueryNeededBlocks` is allowed and skipped; the
    // releasing signal we guard against is a fresh `SubmitBlock`.
    while let Ok(Some(action)) =
        tokio::time::timeout(Duration::from_millis(100), actions.recv()).await
    {
        if let BlockSyncAction::SubmitBlock { .. } = action {
            panic!(
                "stale apply completion released/re-submitted the current submission: {action:?}"
            );
        }
    }

    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: current_token,
            height: block::Height(1),
            hash: block_hash,
            result: BlockApplyResult::Committed,
            local_frontier: None,
        })
        .await
        .expect("current apply-finished event queues");
    assert!(
        tokio::time::timeout(Duration::from_millis(100), actions.recv())
            .await
            .is_err(),
        "at-tip apply completion must not trigger a redundant needed-block query",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_fast_forward_reset_clears_buffered_bodies_and_releases_budget() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        50,
        block::Height(4),
        block::Hash([4; 32]),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 2).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(3),
            ..
        }
    ) {}

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(10_000),
            },
            BlockSyncBlockMeta {
                height: block::Height(3),
                hash: blocks[2].hash(),
                size: BlockSizeEstimate::Advertised(10_000),
            },
        ]))
        .await
        .expect("initial needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("out-of-order body queues");

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(3),
            verified_block_hash: blocks[2].hash(),
        }))
        .await
        .expect("fast-forward reset event queues");

    tip_tx
        .send((block::Height(4), block::Hash([4; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(4),
            best_header_tip: block::Height(4),
            ..
        }
    ) {}
    tokio::time::sleep(Duration::from_millis(100)).await;
    assert_eq!(
        handle.peer_snapshot().outbound_peers,
        1,
        "caught-up reset keeps the previous block-sync peer available for serving",
    );
    assert_eq!(service.peer_count(), 1);

    // the fast-forward commit + budget release run on the Sequencer task while
    // routines re-query, so re-supply the needed metadata on every query and wait
    // for the height-4 request that proves the buffered bytes were released.
    let post_reset_meta = vec![BlockSyncBlockMeta {
        height: block::Height(4),
        hash: block::Hash([4; 32]),
        size: BlockSizeEstimate::Advertised(20_000),
    }];
    handle
        .send(BlockSyncEvent::NeededBlocks(post_reset_meta.clone()))
        .await
        .expect("post-reset needed metadata queues");
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks {
                        start_height: block::Height(4),
                        count,
                    } => {
                        assert_eq!(
                            count, 1,
                            "a full-budget request after fast-forward Reset requires releasing buffered bytes"
                        );
                        break;
                    }
                    BlockSyncMessage::GetBlocks { .. } | BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message before fast-forward re-fetch: {msg:?}"),
                }
            }
            action = actions.recv() => {
                match action.expect("action channel is live") {
                    BlockSyncAction::QueryNeededBlocks { .. } => {
                        handle
                            .send(BlockSyncEvent::NeededBlocks(post_reset_meta.clone()))
                            .await
                            .expect("post-reset needed metadata queues");
                    }
                    BlockSyncAction::Misbehavior { .. } => {}
                    action => panic!("unexpected action before fast-forward re-fetch: {action:?}"),
                }
            }
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_fuzzes_arrival_order_across_fork_parent_first() {
    #[derive(Copy, Clone)]
    enum ForkBody {
        Old(usize),
        New(usize),
    }

    let cases = vec![
        (
            "stale-high-before-reset",
            vec![3],
            vec![],
            vec![ForkBody::Old(2), ForkBody::New(3), ForkBody::New(2)],
        ),
        (
            "old-prefix-before-reset",
            vec![2, 1],
            vec![],
            vec![ForkBody::Old(3), ForkBody::New(2), ForkBody::New(3)],
        ),
        (
            "stale-before-new-needed",
            vec![2],
            vec![3],
            vec![ForkBody::New(2), ForkBody::Old(2), ForkBody::New(3)],
        ),
        (
            "new-out-of-order-with-stale-tail",
            vec![],
            vec![2],
            vec![ForkBody::New(3), ForkBody::Old(3), ForkBody::New(2)],
        ),
    ];

    for (case, old_before_reset, old_before_new_needed, after_new_needed) in cases {
        let mut config = ZakuraBlockSyncConfig {
            max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 3,
            ..fill_loop_mechanics_config()
        };
        config.peer_limits.outbound_queue_depth = 16;
        let old_blocks = mainnet_blocks_1_to_3();
        let new_blocks = vec![
            forked_block(&old_blocks[0], 101),
            forked_block(&old_blocks[1], 102),
            forked_block(&old_blocks[2], 103),
        ];
        let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
        let startup = BlockSyncStartup::new(
            BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(0),
                verified_block_hash: block::Hash([0; 32]),
            },
            (block::Height(0), block::Hash([0; 32])),
            tip_rx,
            config.clone(),
        );
        let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
        let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
        let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
            &service,
            &mut actions,
            51,
            block::Height(4),
            old_blocks[2].hash(),
            1,
            u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES * 3).unwrap_or(u32::MAX),
        )
        .await;

        tip_tx
            .send((block::Height(3), old_blocks[2].hash()))
            .expect("tip watch is live");
        while !matches!(
            next_action(&mut actions).await,
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(1),
                best_header_tip: block::Height(3),
                ..
            }
        ) {}
        handle
            .send(BlockSyncEvent::NeededBlocks(
                old_blocks
                    .iter()
                    .map(|block| BlockSyncBlockMeta {
                        height: block.coinbase_height().expect("test block has height"),
                        hash: block.hash(),
                        size: BlockSizeEstimate::Advertised(block_size(block)),
                    })
                    .collect(),
            ))
            .await
            .expect("old-fork needed metadata queues");
        assert_eq!(
            wait_for_outbound_getblocks(&mut outbound_rx).await,
            (block::Height(1), 3),
            "{case}: old fork request schedules"
        );

        let mut submitted_tip = block::Height(0);
        for height in old_before_reset {
            inbound_tx
                .send(
                    BlockSyncMessage::Block(old_blocks[height - 1].clone())
                        .encode_frame()
                        .expect("old-fork block encodes"),
                )
                .await
                .expect("old-fork block queues");
            drain_parent_first_actions(&mut actions, &mut submitted_tip, None).await;
        }

        handle
            .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(1),
                verified_block_hash: new_blocks[0].hash(),
            }))
            .await
            .expect("reset event queues");
        while !matches!(
            next_action(&mut actions).await,
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(2),
                best_header_tip: block::Height(3),
                ..
            }
        ) {}
        submitted_tip = block::Height(1);

        tip_tx
            .send((block::Height(3), new_blocks[2].hash()))
            .expect("tip watch is live");
        while !matches!(
            next_action(&mut actions).await,
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(2),
                best_header_tip: block::Height(3),
                ..
            }
        ) {}

        for height in old_before_new_needed {
            inbound_tx
                .send(
                    BlockSyncMessage::Block(old_blocks[height - 1].clone())
                        .encode_frame()
                        .expect("stale old-fork block encodes"),
                )
                .await
                .expect("stale old-fork block queues");
            drain_parent_first_actions(&mut actions, &mut submitted_tip, Some(&new_blocks)).await;
        }

        // reset and the producer are decoupled across tasks, so re-supply the
        // new-fork metadata on every query until the height-2 re-fetch appears.
        let new_fork_meta = vec![
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: new_blocks[1].hash(),
                size: BlockSizeEstimate::Advertised(block_size(&new_blocks[1])),
            },
            BlockSyncBlockMeta {
                height: block::Height(3),
                hash: new_blocks[2].hash(),
                size: BlockSizeEstimate::Advertised(block_size(&new_blocks[2])),
            },
        ];
        handle
            .send(BlockSyncEvent::NeededBlocks(new_fork_meta.clone()))
            .await
            .expect("new-fork needed metadata queues");
        loop {
            tokio::select! {
                biased;
                frame = outbound_rx.recv() => {
                    let frame = frame.expect("outbound channel is live");
                    match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                        BlockSyncMessage::GetBlocks {
                            start_height: block::Height(2),
                            count,
                        } => {
                            assert_eq!(
                                count, 2,
                                "{case}: new fork request schedules after reset"
                            );
                            break;
                        }
                        BlockSyncMessage::GetBlocks { .. } | BlockSyncMessage::Status(_) => {}
                        msg => panic!("{case}: unexpected outbound message before new fork re-fetch: {msg:?}"),
                    }
                }
                action = actions.recv() => {
                    match action.expect("action channel is live") {
                        BlockSyncAction::QueryNeededBlocks { .. } => {
                            handle
                                .send(BlockSyncEvent::NeededBlocks(new_fork_meta.clone()))
                                .await
                                .expect("new-fork needed metadata queues");
                        }
                        BlockSyncAction::Misbehavior { .. } => {}
                        action => panic!("{case}: unexpected action before new fork re-fetch: {action:?}"),
                    }
                }
            }
        }

        for body in after_new_needed {
            let block = match body {
                ForkBody::Old(height) => old_blocks[height - 1].clone(),
                ForkBody::New(height) => new_blocks[height - 1].clone(),
            };
            inbound_tx
                .send(
                    BlockSyncMessage::Block(block)
                        .encode_frame()
                        .expect("fork body encodes"),
                )
                .await
                .expect("fork body queues");
            drain_parent_first_actions(&mut actions, &mut submitted_tip, Some(&new_blocks)).await;
        }
        assert_eq!(
            submitted_tip,
            block::Height(3),
            "{case}: new fork bodies submit parent-first through height 3"
        );

        handle
            .send(BlockSyncEvent::ChainTipGrow(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(3),
                verified_block_hash: new_blocks[2].hash(),
            }))
            .await
            .expect("post-submit grow event queues");
        tip_tx
            .send((block::Height(4), block::Hash([4; 32])))
            .expect("tip watch is live");
        while !matches!(
            next_action(&mut actions).await,
            BlockSyncAction::QueryNeededBlocks {
                from: block::Height(4),
                best_header_tip: block::Height(4),
                ..
            }
        ) {}
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert_eq!(
            handle.peer_snapshot().outbound_peers,
            1,
            "{case}: caught-up fork handling keeps the old block-sync peer available for serving",
        );
        assert_eq!(service.peer_count(), 1);
        handle
            .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
                height: block::Height(4),
                hash: block::Hash([4; 32]),
                size: BlockSizeEstimate::Advertised(60_000),
            }]))
            .await
            .expect("post-fuzz needed metadata queues");
        assert_eq!(
            wait_for_outbound_getblocks(&mut outbound_rx).await,
            (block::Height(4), 1),
            "{case}: byte budget returns to baseline after reset and submissions"
        );

        reactor_task.abort();
    }
}

#[tokio::test]
async fn reactor_competing_fork_download_switches_to_current_header_hashes() {
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        immediate_body_download_config(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(
        immediate_body_download_config(),
        handle.clone(),
    );
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        48,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(3), blocks[2].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[1]),
            block_meta(&blocks[2]),
        ]))
        .await
        .expect("old fork metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 2)
    );

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        }))
        .await
        .expect("reset event queues");
    // reset (`reset_above`) and the producer are decoupled, so re-supply the
    // new-fork metadata on every query until the height-2 re-fetch appears.
    let new_fork_meta = vec![BlockSyncBlockMeta {
        height: block::Height(2),
        hash: block::Hash([222; 32]),
        size: BlockSizeEstimate::Advertised(block_size(&blocks[1])),
    }];
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks {
                        start_height: block::Height(2),
                        count,
                    } => {
                        assert_eq!(count, 1);
                        break;
                    }
                    BlockSyncMessage::GetBlocks { .. } | BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message before new fork re-fetch: {msg:?}"),
                }
            }
            action = actions.recv() => {
                match action.expect("action channel is live") {
                    BlockSyncAction::QueryNeededBlocks { .. } => {
                        handle
                            .send(BlockSyncEvent::NeededBlocks(new_fork_meta.clone()))
                            .await
                            .expect("new fork metadata queues");
                    }
                    BlockSyncAction::Misbehavior { .. } => {}
                    action => panic!("unexpected action before new fork re-fetch: {action:?}"),
                }
            }
        }
    }

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("old-fork body encodes"),
        )
        .await
        .expect("old-fork body queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::Misbehavior { peer, reason } => {
                assert_eq!(peer, peer_id);
                assert_eq!(reason, BlockSyncMisbehavior::InvalidBlock);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before stale body rejection: {action:?}"),
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_legacy_commit_dedups_inflight_request_and_reuses_budget() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES,
        ..fill_loop_mechanics_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, _inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        49,
        block::Height(2),
        blocks[1].hash(),
        1,
        u32::try_from(BS_PER_BLOCK_WORST_CASE_BYTES).unwrap_or(u32::MAX),
    )
    .await;

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: blocks[0].hash(),
            size: BlockSizeEstimate::Advertised(10_000),
        }]))
        .await
        .expect("first needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 1)
    );

    handle
        .send(BlockSyncEvent::ChainTipGrow(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        }))
        .await
        .expect("legacy commit grow event queues");

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(2),
            best_header_tip: block::Height(2),
            ..
        }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(2),
            hash: blocks[1].hash(),
            size: BlockSizeEstimate::Advertised(10_000),
        }]))
        .await
        .expect("second needed metadata queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 1),
        "legacy commit must release the duplicate in-flight reservation"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_treats_duplicate_buffered_blocks_as_benign() {
    let config = immediate_body_download_config();
    let blocks = [
        mainnet_block(&BLOCK_MAINNET_1_BYTES),
        mainnet_block(&BLOCK_MAINNET_2_BYTES),
    ];
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(44);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(2),
                tip_hash: blocks[1].hash(),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    tip_tx
        .send((block::Height(2), blocks[1].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks
                .iter()
                .map(|block| BlockSyncBlockMeta {
                    height: block.coinbase_height().expect("test block has height"),
                    hash: block.hash(),
                    size: BlockSizeEstimate::Advertised(block_size(block)),
                })
                .collect(),
        ))
        .await
        .expect("needed metadata queues");

    let (start_height, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(start_height, block::Height(1));
    assert_eq!(count, 2);

    for block in [&blocks[1], &blocks[1], &blocks[0]] {
        inbound_tx
            .send(
                BlockSyncMessage::Block(block.clone())
                    .encode_frame()
                    .expect("block encodes"),
            )
            .await
            .expect("block queues");
    }

    let mut submitted = Vec::new();
    while submitted.len() < 2 {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => submitted.push(
                block
                    .coinbase_height()
                    .expect("submitted test block has height"),
            ),
            BlockSyncAction::Misbehavior { reason, .. } => {
                panic!("duplicate buffered body was misclassified: {reason:?}")
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before submit: {action:?}"),
        }
    }
    assert_eq!(submitted, vec![block::Height(1), block::Height(2)]);

    let quiet = tokio::time::timeout(Duration::from_millis(100), async {
        while let Some(action) = actions.recv().await {
            if let BlockSyncAction::Misbehavior { reason, .. } = action {
                panic!("duplicate buffered body was misclassified after submit: {reason:?}");
            }
        }
    })
    .await;
    assert!(quiet.is_err());

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_accepts_rapid_status_growth_without_spam_score() {
    let config = ZakuraBlockSyncConfig::default();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    drop(tip_tx);
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle);
    let peer_id = peer(46);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    for servable_high in [block::Height(1), block::Height(2)] {
        let hash_byte = u8::try_from(servable_high.0).expect("test height fits in u8");
        inbound_tx
            .send(
                BlockSyncMessage::Status(BlockSyncStatus {
                    servable_low: block::Height(1),
                    servable_high,
                    tip_hash: block::Hash([hash_byte; 32]),
                    max_blocks_per_response: 4,
                    max_inflight_requests: 1,
                    max_response_bytes: MAX_BS_RESPONSE_BYTES,
                })
                .encode_frame()
                .expect("status encodes"),
            )
            .await
            .expect("status frame queues");
    }

    let quiet = tokio::time::timeout(Duration::from_millis(100), async {
        while let Some(action) = actions.recv().await {
            if let BlockSyncAction::Misbehavior { reason, .. } = action {
                panic!("rapid status growth was misclassified: {reason:?}");
            }
        }
    })
    .await;
    assert!(quiet.is_err());

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_redundant_status_burst_without_spam_score() {
    let config = ZakuraBlockSyncConfig::default();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    drop(tip_tx);
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle);
    let peer_id = peer(47);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    let status = BlockSyncMessage::Status(BlockSyncStatus {
        servable_low: block::Height(1),
        servable_high: block::Height(1),
        tip_hash: block::Hash([1; 32]),
        max_blocks_per_response: 4,
        max_inflight_requests: 1,
        max_response_bytes: MAX_BS_RESPONSE_BYTES,
    })
    .encode_frame()
    .expect("status encodes");
    for _ in 0..3 {
        inbound_tx
            .send(status.clone())
            .await
            .expect("redundant status queues");
    }

    let quiet = tokio::time::timeout(Duration::from_millis(100), async {
        while let Some(action) = actions.recv().await {
            if let BlockSyncAction::Misbehavior { reason, .. } = action {
                panic!("redundant status burst was misclassified: {reason:?}");
            }
        }
    })
    .await;
    assert!(quiet.is_err());

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_rejects_block_hash_mismatch_without_hard_drop_for_size_mismatch() {
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        immediate_body_download_config(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(
        immediate_body_download_config(),
        handle.clone(),
    );
    let peer = peer(41);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status queues");
    tip_tx
        .send((block::Height(1), block::Hash([9; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block::Hash([9; 32]),
            size: BlockSizeEstimate::Advertised(1),
        }]))
        .await
        .expect("needed metadata queues");
    // The node's GetBlocks lands on this peer's real outbound.
    while !matches!(
        BlockSyncMessage::decode_frame(
            tokio::time::timeout(Duration::from_secs(1), outbound_rx.recv())
                .await
                .expect("outbound frame arrives")
                .expect("outbound channel is live")
        )
        .expect("frame decodes"),
        BlockSyncMessage::GetBlocks { .. }
    ) {}

    inbound_tx
        .send(
            BlockSyncMessage::Block(mainnet_block(&BLOCK_MAINNET_1_BYTES))
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::Misbehavior { reason, .. } => {
                assert_eq!(reason, BlockSyncMisbehavior::InvalidBlock);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before invalid-block report: {action:?}"),
        }
    }

    reactor_task.abort();
}

// Anti-drift guard for the outbound block-sync send path.
//
// Production (and now all) block-sync scheduling sends outbound `GetBlocks`
// *directly* through `BlockSyncPeerSession` (the per-peer routine's
// `try_send_get_blocks`). There is no per-peer action-pump "source" mirroring the
// send onto a second path, so a single scheduled request can never produce more
// than one outbound frame.
//
// This production-shaped scheduling test locks in that single-sourced outbound
// contract: one scheduled request yields EXACTLY ONE outbound `GetBlocks` frame
// (the authoritative direct session send), and guards against a future
// double-send regression if any mirroring path were ever reintroduced.
#[tokio::test]
async fn scheduled_get_blocks_is_sent_once_via_session() {
    let config = immediate_body_download_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Admit a peer through the production `add_peer` path with an observable
    // outbound transport channel.
    let peer = peer(57);
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    // The peer can serve exactly one block above our tip; publish the header tip
    // and the needed metadata so the reactor schedules exactly one request.
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([9; 32]),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status queues");
    tip_tx
        .send((block::Height(1), block::Hash([9; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block::Hash([9; 32]),
            size: BlockSizeEstimate::Advertised(1),
        }]))
        .await
        .expect("needed metadata queues");

    // Drain the outbound stream for a bounded idle window and count `GetBlocks`
    // frames. A single scheduled request must produce exactly one outbound
    // `GetBlocks`: the authoritative direct send through `BlockSyncPeerSession`
    // (the per-peer routine's `try_send_get_blocks`). There is no longer any
    // per-peer source action pump that could (double-)send a second copy.
    let mut get_blocks = 0usize;
    let mut frames = 0usize;
    while frames < 16 {
        match tokio::time::timeout(Duration::from_millis(300), outbound_rx.recv()).await {
            Ok(Some(frame)) => {
                frames += 1;
                if matches!(
                    BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes"),
                    BlockSyncMessage::GetBlocks { .. }
                ) {
                    get_blocks += 1;
                }
            }
            _ => break,
        }
    }
    assert_eq!(
        get_blocks, 1,
        "one scheduled request must produce exactly one outbound GetBlocks via \
         BlockSyncPeerSession; a different count would mean a mirroring path is \
         (double-)sending in addition to the authoritative direct path",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_scores_peer_whose_invalid_body_is_rejected_by_consensus() {
    let request_bytes: u32 = 10_000;
    let config = ZakuraBlockSyncConfig {
        max_inflight_block_bytes: BS_PER_BLOCK_WORST_CASE_BYTES * 2,
        ..immediate_body_download_config()
    };

    let blocks = mainnet_blocks_1_to_3();
    // A body that keeps block 1's header (so it passes the reactor's hash and
    // height gates) but carries an extra transaction, so its merkle root no
    // longer matches the header. The reactor no longer recomputes the merkle
    // root at ingress, so this body reaches consensus, which rejects it.
    let bad_body = block_with_bad_merkle_root(&blocks[0], &blocks[1]);
    assert_eq!(bad_body.hash(), blocks[0].hash());

    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (bad_peer, bad_inbound, mut bad_outbound) = connect_peer_with_status(
        &service,
        &mut actions,
        40,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    tip_tx
        .send((block::Height(1), blocks[0].hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: blocks[0].hash(),
            size: BlockSizeEstimate::Advertised(request_bytes),
        }]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut bad_outbound).await,
        (block::Height(1), 1)
    );

    bad_inbound
        .send(
            BlockSyncMessage::Block(bad_body)
                .encode_frame()
                .expect("bad block frame encodes"),
        )
        .await
        .expect("bad block frame queues");

    // The merkle-invalid body is no longer filtered at ingress: it is buffered
    // and submitted to consensus.
    let submit_token = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => {
                assert_eq!(block.hash(), blocks[0].hash());
                break token;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before invalid body submit: {action:?}"),
        }
    };

    // Consensus rejects the invalid body. The reactor must attribute the
    // rejection to the peer that delivered it and score the peer as misbehavior,
    // rather than silently rolling back scheduling state and letting the peer
    // keep feeding invalid bodies for needed heights.
    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token: submit_token,
            height: block::Height(1),
            hash: blocks[0].hash(),
            result: BlockApplyResult::Rejected,
            local_frontier: None,
        })
        .await
        .expect("apply-finished event queues");

    // the apply-rejection `Misbehavior` is emitted by the Sequencer task while
    // the routines independently ping `RequeryNeeded`, so one or more
    // `QueryNeededBlocks` can race ahead of the misbehavior report. Skip queries
    // and wait for the misbehavior; if it never arrives the `next_action` timeout
    // fails the test (the peer was not scored).
    let scored = loop {
        if let BlockSyncAction::Misbehavior { peer, reason } = next_action(&mut actions).await {
            assert_eq!(peer, bad_peer);
            assert_eq!(reason, BlockSyncMisbehavior::InvalidBlock);
            break true;
        }
    };
    assert!(
        scored,
        "a consensus apply rejection must score the peer that delivered the body",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_serves_committed_blocks_with_count_and_byte_clamps() {
    let blocks = mainnet_blocks_1_to_3();
    let block1_size = block_size(&blocks[0]);
    let mut config = ZakuraBlockSyncConfig {
        max_blocks_per_response: 2,
        max_response_bytes: block1_size,
        ..ZakuraBlockSyncConfig::default()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(4), block::Hash([4; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(3),
            verified_block_hash: blocks[2].hash(),
        },
        (block::Height(4), block::Hash([4; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        60,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    inbound_tx
        .send(
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(1),
                count: 10,
            }
            .encode_frame()
            .expect("GetBlocks frame encodes"),
        )
        .await
        .expect("GetBlocks frame queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::QueryBlocksByHeightRange { peer, start, count } => {
                assert_eq!(peer, peer_id);
                assert_eq!(start, block::Height(1));
                assert_eq!(count, 2);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before block range query: {action:?}"),
        }
    }

    handle
        .send(BlockSyncEvent::BlockRangeResponseReady {
            peer: peer_id.clone(),
            start_height: block::Height(1),
            requested_count: 2,
            blocks: vec![
                (
                    block::Height(1),
                    blocks[0].clone(),
                    usize::try_from(block1_size).expect("block size fits usize"),
                ),
                (
                    block::Height(2),
                    blocks[1].clone(),
                    usize::try_from(block_size(&blocks[1])).expect("block size fits usize"),
                ),
            ],
        })
        .await
        .expect("served block response queues");

    assert_eq!(
        wait_for_outbound_block(&mut outbound_rx).await.hash(),
        blocks[0].hash()
    );
    assert_eq!(
        wait_for_outbound_blocks_done(&mut outbound_rx).await,
        (block::Height(1), 1),
        "max_response_bytes clamps the served response to one body"
    );

    inbound_tx
        .send(
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(4),
                count: 1,
            }
            .encode_frame()
            .expect("GetBlocks frame encodes"),
        )
        .await
        .expect("above-tip GetBlocks frame queues");

    assert_eq!(
        wait_for_outbound_range_unavailable(&mut outbound_rx).await,
        (block::Height(4), 1)
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_never_serves_reorder_buffer_bodies() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(3), blocks[2].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(3), blocks[2].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        61,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[2])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(3), 1)
    );
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    let quiet = tokio::time::timeout(Duration::from_millis(50), async {
        while let Some(action) = actions.recv().await {
            if matches!(action, BlockSyncAction::SubmitBlock { .. }) {
                panic!("height 3 must stay buffered behind the height 2 gap");
            }
        }
    })
    .await;
    assert!(quiet.is_err());

    inbound_tx
        .send(
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(3),
                count: 1,
            }
            .encode_frame()
            .expect("GetBlocks frame encodes"),
        )
        .await
        .expect("GetBlocks frame queues");

    assert_eq!(
        wait_for_outbound_range_unavailable(&mut outbound_rx).await,
        (block::Height(3), 1),
        "uncommitted reorder-buffer body must not be served"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_schedules_gap_below_buffered_reorder_run() {
    // Regression for the mainnet stuck-at-0 deadlock: a body run received above
    // an open gap must not starve the gap below it. The state reports every
    // header-known, body-missing height (it cannot see our in-memory reorder
    // buffer), so a re-query returns already-buffered heights too. With
    // multi-peer fanout the held range lingers in the scheduler queue. Because
    // `refresh_needed` builds one maximal contiguous range and `ensure` rejects
    // any range overlapping a queued one, the gap below the held run would never
    // be scheduled and `body_download_floor` would freeze forever while we
    // re-requested the already-held blocks. The reactor must drop already-held
    // heights from the needed set so the gap gets scheduled.
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(3), blocks[2].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(3), blocks[2].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        63,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    // Height 2 is momentarily not offered, so we fetch and buffer height 3 in
    // the reorder buffer above the open height-2 gap.
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[2])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(3), 1)
    );
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    // Height 3 is now buffered in the reorder buffer and marked covered. Drain
    // to quiescence: this both lets the reactor finish processing the body and
    // asserts the core fix — a buffered (covered) height is NEVER re-requested.
    // The production deadlock re-requested the held run thousands of times via
    // the retry path (which bypasses the `needed`-set filter), pinning the queue
    // and every peer slot so the gap below the run never got a request. A
    // re-request would land on this peer's own outbound, so watch the real wire.
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks { start_height, .. } => {
                        panic!("buffered (covered) height {start_height:?} must not be re-requested")
                    }
                    BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message after buffering block: {msg:?}"),
                }
            }
            action = tokio::time::timeout(Duration::from_millis(50), actions.recv()) => {
                match action {
                    Ok(Some(BlockSyncAction::QueryNeededBlocks { .. })) => {}
                    Ok(Some(other)) => panic!("unexpected action after buffering block: {other:?}"),
                    Ok(None) | Err(_) => break,
                }
            }
        }
    }

    // The state still reports both 2 and 3 as body-missing because the reorder
    // buffer is invisible to it. With height 3 covered, the reactor must schedule
    // the gap at height 2 rather than staying trapped on the buffered run.
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[1]),
            block_meta(&blocks[2]),
        ]))
        .await
        .expect("needed metadata queues");

    let (got_start, _count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(
        got_start,
        block::Height(2),
        "reactor must schedule the gap at height 2 below the buffered reorder run",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_debounces_status_advertisements_on_serving_tip_change() {
    let mut config = ZakuraBlockSyncConfig {
        status_refresh_interval: Duration::from_secs(60),
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(4), block::Hash([4; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(4), block::Hash([4; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, _inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        62,
        block::Height(4),
        block::Hash([4; 32]),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    // `connect_peer_with_status` already read the connect-time `Status`; the
    // peer's first inbound `Status` now gets a reply as well.
    wait_for_outbound_status(&mut outbound_rx).await;

    handle
        .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        }))
        .await
        .expect("unchanged frontier queues");
    assert!(
        tokio::time::timeout(Duration::from_millis(50), outbound_rx.recv())
            .await
            .is_err(),
        "unchanged serving range must not advertise"
    );

    handle
        .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: block::Hash([1; 32]),
        }))
        .await
        .expect("changed frontier queues");
    match next_outbound_message(&mut outbound_rx).await {
        BlockSyncMessage::Status(status) => {
            assert_eq!(status.servable_high, block::Height(1));
            assert_eq!(handle.local_status().servable_high, block::Height(1));
        }
        msg => panic!("expected debounced Status after serving tip change, got {msg:?}"),
    }

    for height in [2, 3] {
        let hash_byte = u8::try_from(height).expect("test height fits in u8");
        handle
            .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
                finalized_height: block::Height(0),
                verified_block_tip: block::Height(height),
                verified_block_hash: block::Hash([hash_byte; 32]),
            }))
            .await
            .expect("burst frontier queues");
    }
    assert!(
        tokio::time::timeout(Duration::from_millis(50), outbound_rx.recv())
            .await
            .is_err(),
        "rapid serving-tip changes must be debounced to one Status per window"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_retries_status_to_peer_without_status_when_local_status_unchanged() {
    let mut config = ZakuraBlockSyncConfig {
        status_refresh_interval: Duration::from_millis(50),
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, _actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle);
    let peer = peer(63);
    let (_inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer,
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    assert!(matches!(
        next_outbound_message(&mut outbound_rx).await,
        BlockSyncMessage::Status(_)
    ));
    assert!(
        tokio::time::timeout(Duration::from_millis(25), outbound_rx.recv())
            .await
            .is_err(),
        "initial Status send must consume the peer refresh allowance"
    );
    assert!(matches!(
        next_outbound_message(&mut outbound_rx).await,
        BlockSyncMessage::Status(_)
    ));

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_replies_to_first_status_when_connect_status_queue_was_full() {
    let mut config = ZakuraBlockSyncConfig {
        status_refresh_interval: Duration::from_millis(50),
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 1;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, _actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer = peer(64);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(1);
    outbound_tx
        .try_send(
            BlockSyncMessage::Status(status())
                .encode_frame()
                .expect("filler status frame encodes"),
        )
        .expect("outbound queue starts full");
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer,
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if handle.peer_snapshot().outbound_peers == 1 {
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("peer is admitted while outbound queue is full");

    let _ = outbound_rx.recv().await.expect("filler frame drains");
    send_inbound(&inbound_tx, BlockSyncMessage::Status(status())).await;

    assert!(matches!(
        next_outbound_message(&mut outbound_rx).await,
        BlockSyncMessage::Status(_)
    ));

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_does_not_ping_pong_rapid_repeated_status() {
    let mut config = ZakuraBlockSyncConfig {
        status_refresh_interval: Duration::from_millis(50),
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, _actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle);
    let peer = peer(65);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(16);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);

    service.add_peer(Peer::new_with_direction(
        peer,
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    wait_for_outbound_status(&mut outbound_rx).await;
    send_inbound(&inbound_tx, BlockSyncMessage::Status(status())).await;
    wait_for_outbound_status(&mut outbound_rx).await;

    send_inbound(&inbound_tx, BlockSyncMessage::Status(status())).await;
    assert!(
        tokio::time::timeout(Duration::from_millis(25), outbound_rx.recv())
            .await
            .is_err(),
        "a rapid second inbound Status must not trigger another Status reply"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_watch_converges_to_latest_valid_frontier() {
    let initial = test_frontier_update(0, 0, 0, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());

    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );
    exchange.publish_frontier(
        test_frontier_update(0, 0, 2, FrontierChange::HeaderAdvanced),
        "test",
    );
    exchange.publish_frontier(
        test_frontier_update(0, 0, 5, FrontierChange::HeaderAdvanced),
        "test",
    );
    exchange.publish_frontier(
        test_frontier_update(0, 0, 5, FrontierChange::HeaderAdvanced),
        "test",
    );

    let (_handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(5)).await;
    assert_eq!(
        exchange.current_frontier().frontier.best_header,
        test_frontier(5)
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_progress_retries_after_empty_needed_blocks() {
    let initial = test_frontier_update(0, 0, 0, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(3)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(Vec::new()))
        .await
        .expect("empty needed-blocks event queues");

    exchange.publish_frontier(
        test_frontier_update(0, 0, 4, FrontierChange::HeaderAdvanced),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(4)).await;

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_body_progress_retries_after_header_tip_stops() {
    let initial = test_frontier_update(0, 0, 0, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());
    let (_handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(3)).await;

    exchange.publish_frontier(
        test_frontier_update(0, 1, 0, FrontierChange::VerifiedGrow),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(1), block::Height(3)).await;

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_coalesced_header_advance_catches_body_frontier_up() {
    let initial = test_frontier_update(0, 0, 0, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());

    exchange.publish_frontier(
        test_frontier_update(0, 3, 0, FrontierChange::VerifiedGrow),
        "test",
    );
    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );

    let (handle, _actions, reactor_task) = spawn_block_sync_reactor(startup);

    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            let status = handle.local_status();
            if status.servable_high == block::Height(3) {
                assert_eq!(status.tip_hash, test_frontier(3).hash);
                break;
            }
            tokio::task::yield_now().await;
        }
    })
    .await
    .expect("coalesced header update catches the body frontier up");

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_ignores_stale_grow_but_accepts_reset() {
    let initial = test_frontier_update(0, 5, 10, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    wait_for_query_needed_blocks(&mut actions, block::Height(5), block::Height(10)).await;

    exchange.publish_frontier(
        test_frontier_update(0, 4, 10, FrontierChange::VerifiedGrow),
        "test",
    );
    assert!(
        tokio::time::timeout(Duration::from_millis(50), actions.recv())
            .await
            .is_err(),
        "stale lower VerifiedGrow must not trigger a lower body query"
    );
    assert_eq!(handle.local_status().servable_high, block::Height(5));

    exchange.publish_frontier(
        test_frontier_update(0, 4, 0, FrontierChange::VerifiedReset),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(4), block::Height(10)).await;
    assert_eq!(handle.local_status().servable_high, block::Height(4));

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_preserves_successor_work_across_stale_finalized_reset() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    config.peer_limits.outbound_queue_depth = 16;
    config.request_timeout = Duration::from_secs(300);

    let (_tip_tx, tip_rx) = watch::channel((block::Height(3), blocks[2].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(2),
            verified_block_tip: block::Height(2),
            verified_block_hash: blocks[1].hash(),
        },
        (block::Height(3), blocks[2].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        72,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[2])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(3), 1)
    );

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[2].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::SubmitBlock { .. }
    ) {}

    handle
        .send(BlockSyncEvent::ChainTipReset(BlockSyncFrontiers {
            finalized_height: block::Height(2),
            verified_block_tip: block::Height(2),
            verified_block_hash: blocks[1].hash(),
        }))
        .await
        .expect("stale finalized reset queues");
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[2])]))
        .await
        .expect("duplicate needed metadata queues");

    // A re-request of the already-submitted successor would land on this peer's
    // own outbound, so watch the real wire for any GetBlocks of height 3.
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                if let BlockSyncMessage::GetBlocks {
                    start_height: block::Height(3),
                    ..
                } = BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes")
                {
                    panic!("stale finalized reset made an already-submitted successor requestable again");
                }
            }
            action = tokio::time::timeout(Duration::from_millis(100), actions.recv()) => {
                match action {
                    Ok(Some(_)) => {}
                    Ok(None) | Err(_) => break,
                }
            }
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_reanchor_lowers_only_best_header_target() {
    let initial = test_frontier_update(0, 5, 10, FrontierChange::Snapshot);
    let (exchange, startup) =
        exchange_block_sync_startup(initial, immediate_body_download_config());
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    wait_for_query_needed_blocks(&mut actions, block::Height(5), block::Height(10)).await;

    exchange.publish_frontier(
        test_frontier_update(0, 1, 7, FrontierChange::HeaderReanchored),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(5), block::Height(7)).await;
    assert_eq!(handle.local_status().servable_high, block::Height(5));

    reactor_task.abort();
}

/// A header reanchor that lands while downloads are in flight must still re-query
/// after the destructive `reset_above`. Regression for the CI stall in
/// `fuzz_large_to_small`: the post-reset producer used to skip refill when the
/// registry still mirrored pre-reset outstanding, leaving an empty work queue.
#[tokio::test]
async fn reactor_exchange_reanchor_requeries_while_downloads_in_flight() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes =
        BS_PER_BLOCK_WORST_CASE_BYTES * u64::try_from(blocks.len()).expect("block count fits u64");
    config.request_timeout = Duration::from_secs(300);

    let initial = test_frontier_update(0, 0, 3, FrontierChange::Snapshot);
    let (exchange, startup) = exchange_block_sync_startup(initial, config.clone());
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, _inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        67,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3)
    );

    // Reanchor the header tip below the in-flight range while the GetBlocks is
    // still outstanding. The forced post-reset producer query must fire even if
    // the registry still briefly counts those outstanding heights.
    exchange.publish_frontier(
        test_frontier_update(0, 0, 1, FrontierChange::HeaderReanchored),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(1)).await;

    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(3)).await;

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_exchange_reanchor_releases_stale_submitted_bodies() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    // Worst-case reservation: budget for exactly the three in-flight bodies.
    config.max_inflight_block_bytes =
        BS_PER_BLOCK_WORST_CASE_BYTES * u64::try_from(blocks.len()).expect("block count fits u64");
    config.request_timeout = Duration::from_secs(300);

    let initial = test_frontier_update(0, 0, 3, FrontierChange::Snapshot);
    let (exchange, startup) = exchange_block_sync_startup(initial, config.clone());
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        66,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 3)
    );

    for block in &blocks {
        inbound_tx
            .send(
                BlockSyncMessage::Block(block.clone())
                    .encode_frame()
                    .expect("block frame encodes"),
            )
            .await
            .expect("block frame queues");
    }

    let mut submitted = Vec::new();
    while submitted.len() < blocks.len() {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => submitted.push(
                block
                    .coinbase_height()
                    .expect("submitted test block has height"),
            ),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before all submitted bodies: {action:?}"),
        }
    }
    assert_eq!(
        submitted,
        vec![block::Height(1), block::Height(2), block::Height(3)]
    );

    exchange.publish_frontier(
        test_frontier_update(0, 0, 1, FrontierChange::HeaderReanchored),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(1)).await;

    exchange.publish_frontier(
        test_frontier_update(0, 0, 3, FrontierChange::HeaderAdvanced),
        "test",
    );
    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(3)).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata after reanchor queues");
    let (got_start, got_count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(got_start, block::Height(1));
    assert_eq!(
        got_count, 3,
        "reanchored headers must release old submitted bodies and request them again",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_clamps_tiny_submitted_apply_config_above_checkpoint_range() {
    let blocks = fake_sequential_blocks(4);
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = u64::MAX;
    config.max_submitted_block_applies = 2;
    config.request_timeout = Duration::from_secs(300);

    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(4), blocks[3].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    wait_for_query_needed_blocks(&mut actions, block::Height(0), block::Height(4)).await;
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        67,
        block::Height(4),
        blocks[3].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(
            blocks.iter().map(block_meta).collect(),
        ))
        .await
        .expect("needed metadata queues");
    let (_start, count) = wait_for_outbound_getblocks(&mut outbound_rx).await;
    assert_eq!(count, 4);

    for block in &blocks {
        inbound_tx
            .send(
                BlockSyncMessage::Block(block.clone())
                    .encode_frame()
                    .expect("block frame encodes"),
            )
            .await
            .expect("block frame queues");
    }

    let mut submitted = Vec::new();
    while submitted.len() < 4 {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { block, .. } => submitted.push(
                block
                    .coinbase_height()
                    .expect("submitted test block has height"),
            ),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action while collecting submissions: {action:?}"),
        }
    }
    assert_eq!(
        submitted,
        vec![
            block::Height(1),
            block::Height(2),
            block::Height(3),
            block::Height(4),
        ],
        "tiny configured submit caps are raised to the checkpoint-safe floor"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_far_ahead_header_tip_queries_only_next_refill_window() {
    let best_header_tip = block::Height(50_000);
    let (_tip_tx, tip_rx) = watch::channel((best_header_tip, block::Hash([50; 32])));
    let config = ZakuraBlockSyncConfig {
        max_blocks_per_response: 1,
        max_inflight_requests: 1,
        ..ZakuraBlockSyncConfig::default()
    };
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (best_header_tip, block::Hash([50; 32])),
        tip_rx,
        config,
    );
    let (_handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    assert!(matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(1),
            limit: 2,
            best_header_tip: block::Height(50_000),
        }
    ));

    reactor_task.abort();
}

/// The bounded-refill window must advance past the already-claimed heights rather
/// than re-scanning from the download floor every time.
///
/// This is the memory-and-throughput guard for the work-queue bound: with a far
/// ahead header tip the refill `from` is `max_claimed + 1`, not `request_floor +
/// 1`. A regression to the floor would keep re-querying the same low window
/// (silently re-scanning heights already in flight), collapsing the download
/// pipeline to a couple of blocks and re-inflating the work queue — while still
/// completing sync, so the fuzz completion checks would not catch it. Every
/// existing `from`-assertion runs with `max_claimed == request_floor`, so this is
/// the only test that pins the advance itself.
#[tokio::test]
async fn reactor_refill_window_advances_past_claimed_heights() {
    let best_header_tip = block::Height(50_000);
    let (_tip_tx, tip_rx) = watch::channel((best_header_tip, block::Hash([50; 32])));
    // low-water = peers(1) * max_inflight(4) * max_blocks(1) = 4, fanout = 8. Three
    // claimed heights sit below low-water, so the next refill fires immediately.
    let config = ZakuraBlockSyncConfig {
        max_blocks_per_response: 1,
        max_inflight_requests: 4,
        ..ZakuraBlockSyncConfig::default()
    };
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (best_header_tip, block::Hash([50; 32])),
        tip_rx,
        config,
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    // Startup refill scans from the floor (queue empty → `max_claimed` is None).
    assert!(matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(1),
            limit: 8,
            best_header_tip: block::Height(50_000),
        }
    ));

    // Populate the work queue with heights 1..=3 (max_claimed = 3), then nudge the
    // producer. `NeededBlocks` and `HeaderTipChanged` share one FIFO event channel,
    // so the queue is populated before the re-query runs (no watch race).
    let metas: Vec<_> = (1..=3)
        .map(|height| BlockSyncBlockMeta {
            height: block::Height(height),
            hash: block::Hash([u8::try_from(height).expect("height fits u8"); 32]),
            size: BlockSizeEstimate::Advertised(1_000),
        })
        .collect();
    handle
        .send(BlockSyncEvent::NeededBlocks(metas))
        .await
        .expect("needed-blocks event queues");
    handle
        .send(BlockSyncEvent::HeaderTipChanged {
            height: block::Height(50_001),
            hash: block::Hash([51; 32]),
        })
        .await
        .expect("header-tip event queues");

    // The refill now starts at max_claimed + 1 (= 4), never back at the floor (1).
    match next_action(&mut actions).await {
        BlockSyncAction::QueryNeededBlocks {
            from,
            limit,
            best_header_tip,
        } => {
            assert_eq!(
                from,
                block::Height(4),
                "refill must advance past the claimed heights, not rescan from the floor",
            );
            assert_eq!(limit, 8);
            assert_eq!(best_header_tip, block::Height(50_001));
        }
        action => panic!("expected the advanced refill query, got {action:?}"),
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_stale_non_reset_frontier_updates() {
    let (_tip_tx, tip_rx) = watch::channel((block::Height(3600), block::Hash([36; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(3200),
            verified_block_tip: block::Height(3200),
            verified_block_hash: block::Hash([32; 32]),
        },
        (block::Height(3600), block::Hash([36; 32])),
        tip_rx,
        immediate_body_download_config(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);

    assert!(matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks {
            from: block::Height(3201),
            best_header_tip: block::Height(3600),
            ..
        }
    ));

    handle
        .send(BlockSyncEvent::ChainTipGrow(BlockSyncFrontiers {
            finalized_height: block::Height(3200),
            verified_block_tip: block::Height(2913),
            verified_block_hash: block::Hash([29; 32]),
        }))
        .await
        .expect("stale grow event queues");

    assert!(
        tokio::time::timeout(Duration::from_millis(50), actions.recv())
            .await
            .is_err(),
        "stale lower grow frontier must not query from the lower height"
    );
    assert_eq!(handle.local_status().servable_high, block::Height(3200));

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_retries_matched_range_unavailable_without_scoring_peer() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = fill_loop_mechanics_config();
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        63,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[0]),
            block_meta(&blocks[1]),
        ]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 2)
    );

    inbound_tx
        .send(
            BlockSyncMessage::RangeUnavailable {
                start_height: block::Height(1),
                count: 2,
            }
            .encode_frame()
            .expect("RangeUnavailable frame encodes"),
        )
        .await
        .expect("RangeUnavailable frame queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 2),
        "matched RangeUnavailable should retry the original range without scoring the serving peer",
    );
    assert_eq!(handle.peer_snapshot().outbound_peers, 1);

    inbound_tx
        .send(
            BlockSyncMessage::RangeUnavailable {
                start_height: block::Height(2),
                count: 1,
            }
            .encode_frame()
            .expect("RangeUnavailable frame encodes"),
        )
        .await
        .expect("unmatched RangeUnavailable frame queues");

    // routines re-query on a low-water ping, so a benign `QueryNeededBlocks`
    // may appear; the unmatched RangeUnavailable must NOT score the peer or trigger
    // a fresh GetBlocks for the already-in-flight range. A fresh request would land
    // on this peer's own outbound, so watch the real wire while draining advisory
    // queries / misbehavior off the action channel.
    loop {
        tokio::select! {
            biased;
            frame = outbound_rx.recv() => {
                let frame = frame.expect("outbound channel is live");
                match BlockSyncMessage::decode_frame(frame).expect("outbound frame decodes") {
                    BlockSyncMessage::GetBlocks { .. } => {
                        panic!("unmatched RangeUnavailable must not trigger a fresh request")
                    }
                    BlockSyncMessage::Status(_) => {}
                    msg => panic!("unexpected outbound message after unmatched RangeUnavailable: {msg:?}"),
                }
            }
            action = tokio::time::timeout(Duration::from_millis(50), actions.recv()) => {
                match action {
                    Ok(Some(BlockSyncAction::Misbehavior { .. })) => {
                        panic!("unmatched RangeUnavailable must not score the serving peer")
                    }
                    Ok(Some(_)) => {}
                    Ok(None) | Err(_) => break,
                }
            }
        }
    }
    assert_eq!(handle.peer_snapshot().outbound_peers, 1);

    reactor_task.abort();
}

/// Regression guard for F-88604: two misbehaving peers that sort ahead of an honest
/// peer and spam `RangeUnavailable` for a contested range do **not** wedge body sync
/// — the honest peer is still offered the range and makes progress.
///
/// The audit flagged the unpenalized retry path as a possible wedge (two peers
/// re-occupying the whole fanout). Verified here that it is not: `handle_range_unavailable`
/// reschedules immediately after each response, and with one in-flight request per
/// peer the other misbehaving peer is still busy holding its stale request when the
/// first frees its slot, so the honest peer claims the freed companion slot. The
/// behavior is bounded churn, not a liveness wedge, so no peer-scoring guard is added.
/// This test fails if a future change ever lets the fanout peers lock the honest peer
/// out.
#[tokio::test]
async fn reactor_does_not_wedge_honest_peer_under_range_unavailable_spam() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = immediate_body_download_config();
    // A long request timeout ensures the timeout-driven retry self-heal cannot mask
    // the wedge within the test window.
    config.request_timeout = Duration::from_secs(300);
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Two misbehaving peers (ids 0x01, 0x02 sort first) and one honest peer (0x03).
    let (m1, m1_in, mut m1_out) = connect_peer_with_status(
        &service,
        &mut actions,
        0x01,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    let (m2, m2_in, mut m2_out) = connect_peer_with_status(
        &service,
        &mut actions,
        0x02,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    let (h, _h_in, mut h_out) = connect_peer_with_status(
        &service,
        &mut actions,
        0x03,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[0]),
            block_meta(&blocks[1]),
        ]))
        .await
        .expect("needed metadata queues");

    // Every time a misbehaving peer is offered the range it answers RangeUnavailable.
    // The honest peer must eventually be offered the range. Which peer the routine
    // races to offer is nondeterministic, so observe every peer's real outbound and
    // attribute each `GetBlocks` to the peer whose stream it arrived on.
    let range_unavailable = || {
        BlockSyncMessage::RangeUnavailable {
            start_height: block::Height(1),
            count: 2,
        }
        .encode_frame()
        .expect("RangeUnavailable frame encodes")
    };
    let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> = vec![
        (m1.clone(), &mut m1_out),
        (m2.clone(), &mut m2_out),
        (h.clone(), &mut h_out),
    ];
    let mut honest_offered = false;
    for _ in 0..16 {
        let (peer, _start, _count) = wait_for_getblocks_across(&mut outbound_by_peer).await;
        if peer == h {
            honest_offered = true;
            break;
        } else if peer == m1 {
            m1_in
                .send(range_unavailable())
                .await
                .expect("m1 RangeUnavailable queues");
        } else if peer == m2 {
            m2_in
                .send(range_unavailable())
                .await
                .expect("m2 RangeUnavailable queues");
        }
    }

    assert!(
        honest_offered,
        "honest peer must be offered the contested range after both fanout peers fail it"
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_range_unavailable_retries_only_unverified_suffix() {
    let blocks = mainnet_blocks_1_to_3();
    let mut config = fill_loop_mechanics_config();
    config.peer_limits.outbound_queue_depth = 16;
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (_peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        64,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[0]),
            block_meta(&blocks[1]),
        ]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(1), 2)
    );

    handle
        .send(BlockSyncEvent::ChainTipGrow(BlockSyncFrontiers {
            finalized_height: block::Height(1),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        }))
        .await
        .expect("frontier grow queues");

    inbound_tx
        .send(
            BlockSyncMessage::RangeUnavailable {
                start_height: block::Height(1),
                count: 2,
            }
            .encode_frame()
            .expect("RangeUnavailable frame encodes"),
        )
        .await
        .expect("RangeUnavailable frame queues");

    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 1),
        "late RangeUnavailable must not retry the already verified prefix",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_backpressures_serving_slots_without_scoring_peer() {
    let mut config = ZakuraBlockSyncConfig {
        max_inflight_requests: 1,
        ..ZakuraBlockSyncConfig::default()
    };
    config.peer_limits.outbound_queue_depth = 16;
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        63,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    tokio::time::sleep(Duration::from_millis(10)).await;

    for _ in 0..2 {
        inbound_tx
            .send(
                BlockSyncMessage::GetBlocks {
                    start_height: block::Height(1),
                    count: 1,
                }
                .encode_frame()
                .expect("GetBlocks frame encodes"),
            )
            .await
            .expect("GetBlocks frame queues");
    }
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryBlocksByHeightRange { .. }
    ) {}

    assert_eq!(
        wait_for_outbound_range_unavailable(&mut outbound_rx).await,
        (block::Height(1), 1),
        "serving-slot saturation should backpressure the requester, not score it as spam",
    );
    assert_eq!(handle.peer_snapshot().outbound_peers, 1);

    handle
        .send(BlockSyncEvent::BlockRangeResponseFinished {
            peer: peer_id.clone(),
            start_height: block::Height(1),
            requested_count: 1,
            returned_count: 1,
        })
        .await
        .expect("serving slot release queues");

    reactor_task.abort();
}

/// A full per-peer serving queue must drop the serving send, never disconnect
/// the peer.
///
/// The reactor serves `Status`/`Block`/`BlocksDone`/`RangeUnavailable` with
/// non-blocking `try_send_*`. On `Full` it drops the frame and bumps a
/// `*.serve_queue_full` metric; only a genuine send *error* cancels the peer.
/// A regression that collapsed those two arms (cancelling on `Full`) would
/// disconnect honest-but-slow peers under serving load — a self-inflicted DoS.
/// This guards the distinction: a saturated serving queue leaves the peer
/// connected, and serving resumes once the queue drains.
#[tokio::test]
async fn reactor_full_serving_queue_drops_without_disconnecting_peer() {
    let blocks = mainnet_blocks_1_to_3();
    let config = ZakuraBlockSyncConfig {
        max_blocks_per_response: 16,
        max_response_bytes: MAX_BS_RESPONSE_BYTES,
        ..ZakuraBlockSyncConfig::default()
    };
    // Tip == verified tip: the reactor is caught up, so it only *serves* and
    // never issues its own downloads into the tiny outbound queue below.
    let (_tip_tx, tip_rx) = watch::channel((block::Height(3), blocks[2].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(3),
            verified_block_hash: blocks[2].hash(),
        },
        (block::Height(3), blocks[2].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // A two-slot outbound queue, wired by hand so we keep the peer's
    // cancellation token: serving three bodies plus a terminator is four sends
    // through two slots, so `try_send` is guaranteed to hit `Full`.
    let peer_id = peer(66);
    let cancel = CancellationToken::new();
    let (inbound_tx, inbound_rx) = framed_channel(16);
    let (outbound_tx, mut outbound_rx) = framed_channel(2);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        cancel.clone(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;
    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(3),
                tip_hash: blocks[2].hash(),
                max_blocks_per_response: 16,
                max_inflight_requests: 8,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status frame queues");

    // The peer asks for the whole committed range; answer it so the reactor
    // serves all three bodies into the saturated queue.
    inbound_tx
        .send(
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(1),
                count: 3,
            }
            .encode_frame()
            .expect("GetBlocks frame encodes"),
        )
        .await
        .expect("GetBlocks frame queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::QueryBlocksByHeightRange { peer, start, count } => {
                assert_eq!(peer, peer_id);
                assert_eq!(start, block::Height(1));
                assert_eq!(count, 3);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before block range query: {action:?}"),
        }
    }
    let served: Vec<_> = blocks
        .iter()
        .map(|block| {
            (
                block.coinbase_height().expect("test block has height"),
                block.clone(),
                usize::try_from(block_size(block)).expect("block size fits usize"),
            )
        })
        .collect();
    handle
        .send(BlockSyncEvent::BlockRangeResponseReady {
            peer: peer_id.clone(),
            start_height: block::Height(1),
            requested_count: 3,
            blocks: served,
        })
        .await
        .expect("served block response queues");

    // Let the reactor finish the serve, including the sends that hit `Full`.
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(
        !cancel.is_cancelled(),
        "a full serving queue must drop sends, not cancel the peer",
    );
    assert_eq!(handle.peer_snapshot().outbound_peers, 1);

    // Self-heal: drain the queue, release the serving slot, and re-request. The
    // earlier drop neither wedged nor scored the peer, so a fresh serve lands.
    while tokio::time::timeout(
        Duration::from_millis(100),
        next_outbound_message(&mut outbound_rx),
    )
    .await
    .is_ok()
    {}
    handle
        .send(BlockSyncEvent::BlockRangeResponseFinished {
            peer: peer_id.clone(),
            start_height: block::Height(1),
            requested_count: 3,
            returned_count: 3,
        })
        .await
        .expect("serving slot release queues");
    inbound_tx
        .send(
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(1),
                count: 1,
            }
            .encode_frame()
            .expect("GetBlocks frame encodes"),
        )
        .await
        .expect("re-request GetBlocks frame queues");
    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::QueryBlocksByHeightRange { start, count, .. } => {
                assert_eq!(start, block::Height(1));
                assert_eq!(count, 1);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action before re-request query: {action:?}"),
        }
    }
    handle
        .send(BlockSyncEvent::BlockRangeResponseReady {
            peer: peer_id.clone(),
            start_height: block::Height(1),
            requested_count: 1,
            blocks: vec![(
                block::Height(1),
                blocks[0].clone(),
                usize::try_from(block_size(&blocks[0])).expect("block size fits usize"),
            )],
        })
        .await
        .expect("re-served block response queues");
    assert_eq!(
        wait_for_outbound_block(&mut outbound_rx).await.hash(),
        blocks[0].hash(),
        "serving resumes once the queue drains",
    );
    assert!(!cancel.is_cancelled());

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_publishes_block_sync_candidate_gap() {
    let config = immediate_body_download_config();
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer_id = peer(77);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer_id.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));
    wait_for_outbound_status(&mut outbound_rx).await;

    tip_tx
        .send((block::Height(2), block::Hash([2; 32])))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            BlockSyncBlockMeta {
                height: block::Height(2),
                hash: block::Hash([2; 32]),
                size: BlockSizeEstimate::Unknown,
            },
            BlockSyncBlockMeta {
                height: block::Height(1),
                hash: block::Hash([1; 32]),
                size: BlockSizeEstimate::Unknown,
            },
        ]))
        .await
        .expect("needed blocks event queues");

    let mut candidates = handle.subscribe_candidate_state();
    let observed = tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            candidates
                .changed()
                .await
                .expect("candidate watch remains open");
            let state = candidates.borrow().clone();
            if state.missing_block_bodies == vec![block::Height(1), block::Height(2)] {
                return state;
            }
        }
    })
    .await
    .unwrap_or_else(|_| handle.candidate_state());
    assert_eq!(
        observed.missing_block_bodies,
        vec![block::Height(1), block::Height(2)]
    );
    assert!(
        observed.admitted_node_ids.is_empty(),
        "a peer without block-sync status must not satisfy body-sync demand"
    );

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(2),
                tip_hash: block::Hash([2; 32]),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status queues");

    let peer_node_id =
        node_id_from_block_peer_id(&peer_id).expect("test peer id is a valid node id");
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            candidates
                .changed()
                .await
                .expect("candidate watch remains open");
            if candidates.borrow().admitted_node_ids == vec![peer_node_id] {
                return;
            }
        }
    })
    .await
    .expect("status-bearing peer is published as an admitted candidate");

    handle
        .send(BlockSyncEvent::StateFrontiersChanged(BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(2),
            verified_block_hash: block::Hash([2; 32]),
        }))
        .await
        .expect("frontier event queues");
    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if handle.candidate_state().missing_block_bodies.is_empty() {
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("candidate state clears after the gap is gone");

    reactor_task.abort();
}

#[tokio::test]
async fn oversize_body_policy_reports_size_mismatch_and_retries_without_buffering() {
    let mut config = ZakuraBlockSyncConfig {
        size_deviation_tolerance: 100,
        ..immediate_body_download_config()
    };
    config.peer_limits.outbound_queue_depth = 8;
    let (tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let peer = peer(42);
    let (inbound_tx, inbound_rx) = framed_channel(8);
    let (outbound_tx, mut outbound_rx) = framed_channel(8);
    let streams = HashMap::from([(ZAKURA_STREAM_BLOCK_SYNC, (inbound_rx, outbound_tx))]);
    service.add_peer(Peer::new_with_direction(
        peer,
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        streams,
        CancellationToken::new(),
    ));

    inbound_tx
        .send(
            BlockSyncMessage::Status(BlockSyncStatus {
                servable_low: block::Height(1),
                servable_high: block::Height(1),
                tip_hash: block::Hash([1; 32]),
                max_blocks_per_response: 4,
                max_inflight_requests: 1,
                max_response_bytes: MAX_BS_RESPONSE_BYTES,
            })
            .encode_frame()
            .expect("status encodes"),
        )
        .await
        .expect("status queues");
    let block = mainnet_block(&BLOCK_MAINNET_1_BYTES);
    tip_tx
        .send((block::Height(1), block.hash()))
        .expect("tip watch is live");
    while !matches!(
        next_action(&mut actions).await,
        BlockSyncAction::QueryNeededBlocks { .. }
    ) {}
    handle
        .send(BlockSyncEvent::NeededBlocks(vec![BlockSyncBlockMeta {
            height: block::Height(1),
            hash: block.hash(),
            size: BlockSizeEstimate::Advertised(1),
        }]))
        .await
        .expect("needed metadata queues");
    // The node's GetBlocks lands on this peer's real outbound.
    while !matches!(
        BlockSyncMessage::decode_frame(
            tokio::time::timeout(Duration::from_secs(1), outbound_rx.recv())
                .await
                .expect("outbound frame arrives")
                .expect("outbound channel is live")
        )
        .expect("frame decodes"),
        BlockSyncMessage::GetBlocks { .. }
    ) {}

    inbound_tx
        .send(
            BlockSyncMessage::Block(block.clone())
                .encode_frame()
                .expect("block encodes"),
        )
        .await
        .expect("block queues");

    loop {
        match next_action(&mut actions).await {
            BlockSyncAction::Misbehavior { reason, .. } => {
                assert_eq!(reason, BlockSyncMisbehavior::SizeMismatch);
                break;
            }
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action during size mismatch test: {action:?}"),
        }
    }

    let no_submit = tokio::time::timeout(Duration::from_millis(200), async {
        while let Some(action) = actions.recv().await {
            if matches!(action, BlockSyncAction::SubmitBlock { .. }) {
                return false;
            }
        }
        true
    })
    .await
    .unwrap_or(true);
    assert!(
        no_submit,
        "oversize body is not submitted after SizeMismatch"
    );

    reactor_task.abort();
}

// SECURITY AUDIT (candidate claude-block-sync-unsolicited-blocksdone-not-rejected /
// codex-blocksync-unsolicited-blocksdone-not-rejected): SR-6/SR-7 response
// correlation + fail-closed.
//
// `handle_blocks_done` reports `UnsolicitedDone` only when the peer is *unknown*.
// For a known, active peer that sends a valid `BlocksDone` with no matching
// outstanding request, the `if let Some(index)` body is skipped and the reactor
// falls through to `schedule()` with no `else` reporting `UnsolicitedDone`.
// `UnsolicitedDone` is a *hard* block-sync misbehavior (`block_sync_misbehavior_is_hard`
// in zakurad start.rs), so the production driver `drive_block_sync_actions`
// disconnects on the first offense -- but this branch never emits it, so an
// admitted peer can stream uncorrelated response terminators forever and stay
// connected.
//
// This test asserts the SAFE behavior (the reactor must report `UnsolicitedDone`).
// It currently FAILS, which is the reproduction. Do not weaken it to pass; the
// fix is to add the missing `else` branch in `handle_blocks_done`.
#[tokio::test]
async fn reactor_known_peer_unsolicited_blocks_done_is_reported_as_misbehavior() {
    let config = ZakuraBlockSyncConfig::default();
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Connect a peer that advertises no downloadable work (servable_high == our
    // verified tip), so the reactor never schedules a GetBlocks and the peer has
    // zero outstanding requests. The peer is known/active (received_status=true).
    let (peer_id, inbound_tx, _outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        63,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    // Surprising/hostile input: a valid `BlocksDone` terminator with a start
    // height that matches no outstanding request (there are none).
    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(7),
                returned: 1,
            }
            .encode_frame()
            .expect("BlocksDone frame encodes"),
        )
        .await
        .expect("BlocksDone frame queues");

    // Expected safe behavior: the reactor reports `UnsolicitedDone` for this peer
    // (which the production driver maps to a hard disconnect). Collect actions for
    // a bounded window and assert it appears.
    let mut saw_unsolicited_done = false;
    while let Ok(Some(action)) = tokio::time::timeout(Duration::from_secs(1), actions.recv()).await
    {
        if let BlockSyncAction::Misbehavior { peer, reason } = action {
            if peer == peer_id && reason == BlockSyncMisbehavior::UnsolicitedDone {
                saw_unsolicited_done = true;
                break;
            }
        }
    }

    assert!(
        saw_unsolicited_done,
        "a known peer's unsolicited BlocksDone with no matching outstanding request \
         must be reported as Misbehavior::UnsolicitedDone (SR-6/SR-7), but the reactor \
         silently tolerated it and kept the peer connected",
    );

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_accepts_unmatched_body_for_height_active_on_another_request() {
    let config = immediate_body_download_config();
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    let (peer1, inbound1, mut outbound1) = connect_peer_with_status(
        &service,
        &mut actions,
        65,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    let (peer2, inbound2, mut outbound2) = connect_peer_with_status(
        &service,
        &mut actions,
        66,
        block::Height(3),
        blocks[2].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[1])]))
        .await
        .expect("needed metadata queues");
    // Which peer the routine offers the request to is nondeterministic, so observe
    // both peers' real outbounds and learn which one was asked.
    let (requested_peer, start_height, _count) = {
        let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> = vec![
            (peer1.clone(), &mut outbound1),
            (peer2.clone(), &mut outbound2),
        ];
        wait_for_getblocks_across(&mut outbound_by_peer).await
    };
    assert_eq!(start_height, block::Height(2));

    // Simulate a later state snapshot that omits the active in-flight height.
    // The scheduler retains the outstanding request for correlation, but
    // `needed_heights` no longer contains the height, matching the production
    // late-response race after retries/reconnects.
    handle
        .send(BlockSyncEvent::NeededBlocks(Vec::new()))
        .await
        .expect("empty needed metadata queues");

    // The peer that did NOT get the request sends the body+terminator as real
    // inbound frames. First valid completion wins: the body is accepted even
    // though another peer currently owns the request slot, and the later
    // duplicate from the original owner will be dropped by the sequencer.
    let (late_peer, late_inbound) = if requested_peer == peer1 {
        (peer2, inbound2)
    } else {
        (peer1, inbound1)
    };
    send_inbound(&late_inbound, BlockSyncMessage::Block(blocks[1].clone())).await;
    let submitted = tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            match next_action(&mut actions).await {
                BlockSyncAction::SubmitBlock { block, .. } => return block.hash(),
                BlockSyncAction::QueryNeededBlocks { .. } => {}
                BlockSyncAction::Misbehavior { peer, reason } => {
                    assert_ne!(
                        peer, late_peer,
                        "late active body was reported as {reason:?}"
                    );
                }
                action => {
                    panic!("unexpected action while waiting for late body submit: {action:?}")
                }
            }
        }
    })
    .await
    .expect("late active body is accepted and submitted");
    assert_eq!(submitted, blocks[1].hash());

    send_inbound(
        &late_inbound,
        BlockSyncMessage::BlocksDone {
            start_height: block::Height(2),
            returned: 1,
        },
    )
    .await;

    while let Ok(Some(action)) =
        tokio::time::timeout(Duration::from_millis(200), actions.recv()).await
    {
        if let BlockSyncAction::Misbehavior { peer, reason } = action {
            assert_ne!(
                peer, late_peer,
                "late response for an active request was reported as {reason:?}"
            );
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_duplicate_response_at_body_download_floor() {
    let config = immediate_body_download_config();
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(2), blocks[1].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(2), blocks[1].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_id, inbound_tx, mut outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        65,
        block::Height(2),
        blocks[1].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[1])]))
        .await
        .expect("needed metadata queues");
    assert_eq!(
        wait_for_outbound_getblocks(&mut outbound_rx).await,
        (block::Height(2), 1)
    );
    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("block frame encodes"),
        )
        .await
        .expect("block frame queues");

    let (token, hash) = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => break (token, block.hash()),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action while waiting for submit: {action:?}"),
        }
    };

    // Simulate the verifier reporting success before the frontier mirror has
    // delivered the matching verified-tip update. The applying entry is gone,
    // but `body_download_floor` still proves this height was already accepted.
    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token,
            height: block::Height(2),
            hash,
            result: BlockApplyResult::Committed,
            local_frontier: None,
        })
        .await
        .expect("apply result queues");

    inbound_tx
        .send(
            BlockSyncMessage::Block(blocks[1].clone())
                .encode_frame()
                .expect("duplicate block frame encodes"),
        )
        .await
        .expect("duplicate block frame queues");
    inbound_tx
        .send(
            BlockSyncMessage::BlocksDone {
                start_height: block::Height(2),
                returned: 1,
            }
            .encode_frame()
            .expect("duplicate terminator frame encodes"),
        )
        .await
        .expect("duplicate terminator frame queues");

    while let Ok(Some(action)) =
        tokio::time::timeout(Duration::from_millis(200), actions.recv()).await
    {
        if let BlockSyncAction::Misbehavior { peer, reason } = action {
            assert_ne!(
                peer, peer_id,
                "duplicate response at body_download_floor was reported as {reason:?}"
            );
        }
    }

    reactor_task.abort();
}

#[tokio::test]
async fn reactor_ignores_matched_duplicate_response_at_body_download_floor() {
    // fanout = 1: a height is requested from exactly one peer. The duplicate body
    // that must be ignored at the floor instead arrives unsolicited from the
    // *other* connected peer after the height has committed.
    let blocks = mainnet_blocks_1_to_3();
    let block2_size = block_size(&blocks[1]);
    let mut config = immediate_body_download_config();
    config.max_inflight_block_bytes = BS_PER_BLOCK_WORST_CASE_BYTES * 2;

    let (_tip_tx, tip_rx) = watch::channel((block::Height(4), block::Hash([4; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(4), block::Hash([4; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());
    let (peer_a, inbound_a, mut outbound_a) = connect_peer_with_status(
        &service,
        &mut actions,
        66,
        block::Height(4),
        block::Hash([4; 32]),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    let (peer_b, inbound_b, mut outbound_b) = connect_peer_with_status(
        &service,
        &mut actions,
        67,
        block::Height(4),
        block::Hash([4; 32]),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![block_meta(&blocks[1])]))
        .await
        .expect("needed metadata queues");
    // Which peer the routine offers the request to is nondeterministic (the routines
    // race for the shared work), so observe both peers' real outbounds and learn
    // which one was asked.
    let mut outbound_by_peer: Vec<(ZakuraPeerId, &mut FramedRecv)> = vec![
        (peer_a.clone(), &mut outbound_a),
        (peer_b.clone(), &mut outbound_b),
    ];
    let first_request = wait_for_getblocks_across(&mut outbound_by_peer).await;
    assert_eq!((first_request.1, first_request.2), (block::Height(2), 1));
    // The other peer is the one that will deliver the ignored duplicate.
    let (other_peer, requested_inbound, other_inbound) = if first_request.0 == peer_a {
        (peer_b.clone(), &inbound_a, &inbound_b)
    } else {
        (peer_a.clone(), &inbound_b, &inbound_a)
    };

    send_inbound(
        requested_inbound,
        BlockSyncMessage::Block(blocks[1].clone()),
    )
    .await;

    let (token, hash) = loop {
        match next_action(&mut actions).await {
            BlockSyncAction::SubmitBlock { token, block } => break (token, block.hash()),
            BlockSyncAction::QueryNeededBlocks { .. } => {}
            action => panic!("unexpected action while waiting for submit: {action:?}"),
        }
    };
    handle
        .send(BlockSyncEvent::BlockApplyFinished {
            token,
            height: block::Height(2),
            hash,
            result: BlockApplyResult::Committed,
            local_frontier: None,
        })
        .await
        .expect("apply result queues");

    // A late duplicate body for the now-committed height arrives from the other
    // peer as a real inbound frame; it sits at/below the body-download floor and
    // must be ignored without permanently consuming reorder budget.
    let _ = &other_peer;
    send_inbound(other_inbound, BlockSyncMessage::Block(blocks[1].clone())).await;

    handle
        .send(BlockSyncEvent::NeededBlocks(vec![
            block_meta(&blocks[2]),
            BlockSyncBlockMeta {
                height: block::Height(4),
                hash: block::Hash([4; 32]),
                size: BlockSizeEstimate::Advertised(block2_size),
            },
        ]))
        .await
        .expect("next needed metadata queues");

    // The commit pipeline now runs on its own task and reports the committed
    // floor back asynchronously, so the late duplicate can momentarily reach the
    // unmatched-queued path and transiently reserve before the Sequencer reports
    // it `Redundant` and releases. The invariant that still must hold is that the
    // duplicate consumes no budget *permanently*: both remaining heights (3 and 4)
    // must still get requested, each exactly once, within the two-block budget.
    // Collect GetBlocks until 3 and 4 are both covered and assert no double-fetch.
    let mut requested: Vec<block::Height> = Vec::new();
    tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            let (peer, start, count) = wait_for_getblocks_across(&mut outbound_by_peer).await;
            assert!(
                peer == peer_a || peer == peer_b,
                "request should target one of the connected peers"
            );
            for offset in 0..count {
                if let Some(height) = height_after_count(start, offset) {
                    requested.push(height);
                }
            }
            if requested.contains(&block::Height(3)) && requested.contains(&block::Height(4)) {
                break;
            }
        }
    })
    .await
    .expect("both remaining heights are requested within the unchanged budget");
    requested.sort_unstable();
    let mut deduped = requested.clone();
    deduped.dedup();
    assert_eq!(
        requested, deduped,
        "a matched duplicate response at the body floor must not consume reorder budget \
         (no height should be fetched twice)"
    );
    assert!(
        requested.contains(&block::Height(3)) && requested.contains(&block::Height(4)),
        "both needed heights must be fetched once the duplicate releases its transient reservation"
    );

    reactor_task.abort();
}

// Per-peer routines removed the reactor "late response after disconnect"
// path that the original first half of this test exercised: a disconnected peer's
// `FramedRecv` is closed and its routine has exited, so there is no transport for a
// late frame and no reactor inbound demux to ignore one. The surviving, still-
// meaningful guarantee — a connected peer's routine hard-scores an unsolicited
// `BlocksDone` correlating to no outstanding request — is kept and exercised over a
// real inbound frame.
#[tokio::test]
async fn reactor_scores_unsolicited_terminator_from_connected_peer() {
    let config = ZakuraBlockSyncConfig::default();
    let blocks = mainnet_blocks_1_to_3();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(1), blocks[0].hash()));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(1),
            verified_block_hash: blocks[0].hash(),
        },
        (block::Height(1), blocks[0].hash()),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config.clone(), handle.clone());

    let (peer_id, inbound_tx, _outbound_rx) = connect_peer_with_status(
        &service,
        &mut actions,
        64,
        block::Height(1),
        blocks[0].hash(),
        1,
        MAX_BS_RESPONSE_BYTES,
    )
    .await;
    send_inbound(
        &inbound_tx,
        BlockSyncMessage::BlocksDone {
            start_height: block::Height(7),
            returned: 1,
        },
    )
    .await;

    let mut saw_unsolicited_done = false;
    while let Ok(Some(action)) = tokio::time::timeout(Duration::from_secs(1), actions.recv()).await
    {
        if let BlockSyncAction::Misbehavior { peer, reason } = action {
            if peer == peer_id && reason == BlockSyncMisbehavior::UnsolicitedDone {
                saw_unsolicited_done = true;
                break;
            }
        }
    }
    assert!(
        saw_unsolicited_done,
        "an unsolicited terminator from a connected peer is hard-scored UnsolicitedDone"
    );

    reactor_task.abort();
}

/// Misbehavior is record-only: a repeatedly-misbehaving peer is still *observed*
/// (the reactor emits a `Misbehavior` action as a record) but is **not**
/// disconnected. Peer scoring no longer drives disconnects, so what used to be a
/// "soft" offense crossing the threshold-of-3 now leaves the peer connected.
#[tokio::test]
async fn repeated_misbehavior_is_recorded_without_disconnecting_the_peer() {
    let config = ZakuraBlockSyncConfig::default();
    let (_tip_tx, tip_rx) = watch::channel((block::Height(0), block::Hash([0; 32])));
    let startup = BlockSyncStartup::new(
        BlockSyncFrontiers {
            finalized_height: block::Height(0),
            verified_block_tip: block::Height(0),
            verified_block_hash: block::Hash([0; 32]),
        },
        (block::Height(0), block::Hash([0; 32])),
        tip_rx,
        config.clone(),
    );
    let (handle, mut actions, reactor_task) = spawn_block_sync_reactor(startup);
    let service = BlockSyncService::new_with_handle_for_test(config, handle.clone());

    // Connect the probe peer with a real pipe-routine (per-peer routines) so its inbound frames
    // are decoded and dispatched.
    let probe = peer(7);
    let (probe_inbound_tx, probe_inbound_rx) = framed_channel(8);
    let (probe_outbound_tx, _probe_outbound_rx) = framed_channel(8);
    service.add_peer(Peer::new_with_direction(
        probe.clone(),
        None,
        ZAKURA_CAP_BLOCK_SYNC,
        ServicePeerDirection::Outbound,
        HashMap::from([(
            ZAKURA_STREAM_BLOCK_SYNC,
            (probe_inbound_rx, probe_outbound_tx),
        )]),
        CancellationToken::new(),
    ));
    tokio::time::timeout(Duration::from_secs(1), async {
        while service.peer_count() == 0 {
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("probe peer connects");

    // Each `GetBlocks` from a peer that has not sent a Status is `GetBlocksSpam`
    // (formerly a "soft" offense that disconnected at a threshold of 3). Send well
    // past the old threshold.
    for _ in 0..8 {
        send_inbound(
            &probe_inbound_tx,
            BlockSyncMessage::GetBlocks {
                start_height: block::Height(1),
                count: 1,
            },
        )
        .await;
    }

    // The violation is still recorded: the reactor emits a best-effort
    // `Misbehavior` action for the spamming peer.
    tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            if let BlockSyncAction::Misbehavior { peer, reason } = next_action(&mut actions).await {
                if peer == probe && reason == BlockSyncMisbehavior::GetBlocksSpam {
                    break;
                }
            }
        }
    })
    .await
    .expect("a misbehavior action is recorded for the spamming peer");

    // But the peer is never torn down: misbehavior no longer cancels the session.
    // Give the reactor ample time to (not) act, then confirm the peer remains.
    tokio::time::sleep(Duration::from_millis(100)).await;
    assert_eq!(
        service.peer_count(),
        1,
        "misbehavior is record-only: a repeatedly-misbehaving peer must NOT be disconnected",
    );

    reactor_task.abort();
}