ethl 0.1.44

Tools for capturing, processing, archiving, and replaying Ethereum events
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
use std::collections::VecDeque;
use std::future::Future;
use std::sync::Once;
use std::time::Duration;

use alloy::{
    network::Ethereum,
    primitives::B256,
    providers::{DynProvider, Provider},
    rpc::types::{BlockNumberOrTag, Filter, Header, Log},
};
use async_stream::stream;
use futures_util::{StreamExt, TryStreamExt, pin_mut, stream::Stream};
use tokio::time::{Instant, sleep, sleep_until};
use tracing::{debug, info, warn};

use crate::rpc::cursor::{TipGate, TipWaitOutcome, next_cursor_after_batch, wait_for_tip};
use crate::rpc::error_tracking::{
    ErrorCategory, ProviderErrorTracker, find_active_provider, truncate_error, truncate_error_short,
};
use crate::rpc::{
    LogRange, RpcError,
    config::{CaptureTarget, ProviderSettings},
    progress::ScanProgress,
};

/// Maximum block range per WS request to prevent "max results" errors
const MAX_BLOCKS_PER_WS_REQUEST: u64 = 300;

/// Bound on the head await when no flush deadline is pending, so a provider
/// that accepts the WS subscription and then goes silent — half-open socket,
/// dead subscription that never closes the stream — can't park the session
/// forever. Not a staleness or liveness signal: it makes no claim about
/// whether the chain is progressing, only that this one subscription has
/// gone quiet long enough to be worth abandoning. Expiry rotates to the next
/// provider; it never records a provider error. A consecutive expiry on
/// EVERY configured provider — a full quiet rotation with no header seen in
/// between — surfaces `RpcError::AllProvidersIdle` instead of rotating
/// again; see `IdleRotationCounter`.
///
/// 120s so rotation is attempted before booda's per-chain lag CRITICAL pages
/// the operator (288s on ethereum, 500s on base): the alarm should report
/// exhaustion, not a condition nothing has tried yet to fix.
/// `IdleRotationCounter::expire` thresholds on the configured provider
/// count, so a two-provider chain reaches `AllProvidersIdle` at 240s.
/// Robinhood configures a single provider, so 120s is its entire budget
/// rather than half of one — accepted 2026-09-04 as the correct asymmetry,
/// not a bug to route around.
const IDLE_HEAD_AWAIT_SECS: u64 = 120;

/// Steps the reorg-ring top-up walks per flush (`flush_window_range`,
/// `HeadLinkage::extend_downward`). Bounded, not a config knob: the walk is a
/// sequential hash chain (one RPC per step) running inside
/// `flush_window_range`'s own `bound_flush_time` budget — 4 s on BSC — which
/// exists to keep this loop under alloy's 16-slot WS head buffer (~7.2 s to
/// overflow at ~0.45 s/block, `bsc.rs:83`). A one-shot walk to the full 96
/// depth is ~95 sequential round trips, ~42 ms each against public BSC RPC —
/// it would blow the 4 s bound on its own. `LIVE_ROUTER_COALESCE_WINDOW_MS`
/// is 0 in CDK, so a flush runs on essentially every head (~0.45–0.75 s
/// apart); at 8 steps/flush that consumes roughly 500 ms of headroom out of
/// the 4 s budget against the wall-clock realities the budget is sized for —
/// and the ring reaches full depth in ~12 blocks (5–9 s), about 8× faster
/// than the forward-observation rate it replaces.
///
/// Happy-path cost only. The walk shares the flush's aggregate bound, not a
/// per-step one, and each step can itself fan out over every configured HTTP
/// provider on a miss (`get_block_by_hash_with_http_fallback`) — worst case
/// `8 × N` RPCs, not 8, and per-call timeouts are configured larger than this
/// aggregate bound, so one hung call can individually exceed the whole
/// budget on its own. Accepted (settled decision 7): the top-up shares the
/// flush's bound rather than getting its own, and a timed-out top-up is
/// fail-closed like any other stalled flush (see `flush_window_range`'s
/// placement comment on `top_up_reorg_ring`).
const REORG_RING_TOP_UP_STEPS: u64 = 8;

/// Length bound on `flush_window_range`'s self-heal walk, in blocks.
///
/// That walk is sequential and fail-closed — one `get_block_by_hash` per block,
/// no by-number fallback — so its cost is linear in how far the flush cursor
/// trails the ring's floor, and nothing else caps it. `flush_max_total_secs`
/// defaults to `0` (disabled), so on any chain that has not opted in this is the
/// walk's only bound, and `MAX_BLOCKS_PER_WS_REQUEST` caps a single fetch batch
/// rather than this cursor-to-tip span.
///
/// Sized about an order of magnitude above the deepest recovery window in
/// service (96 on BSC and mainnet), because the trigger that fires at roughly
/// `recovery_window_depth + 1` blocks — a flush failing repeatedly while heads
/// keep arriving — needs room to accumulate several such cycles before the bound
/// closes on it; a bound at or under the window would fail closed on that
/// trigger's very first attempt, during ordinary degraded operation. At BSC's
/// ~0.45 s blocks, 1,024 blocks is ~7.5 minutes of missed flushing, and ~43 s of
/// walking at the ~42 ms per sequential step measured for
/// `REORG_RING_TOP_UP_STEPS`: far enough out that only a genuinely stuck stream
/// reaches it, near enough that reaching it does not itself become the outage.
/// Added to the configured window rather than maximized against it, so the bound
/// always carries this constant's full headroom above the backlog it must cover
/// — never merely equal to it, whatever depth a chain configures.
const SELF_HEAL_WALK_MAX_BLOCKS: u64 = 1_024;

#[derive(Debug, Clone)]
struct HeadCoalescer {
    block_cursor: Option<u64>,
    latest_seen_head: Option<u64>,
    flush_deadline: Option<Instant>,
    /// Coalesce rapid head updates into a bounded polling cadence.
    window: Duration,
    /// Optional scan-progress handle. `None` for every internal test/call site that doesn't
    /// opt in — `advance_cursor` and `record_tip` are no-ops without it.
    progress: Option<ScanProgress>,
}

impl HeadCoalescer {
    fn new(block_cursor: Option<u64>, window: Duration) -> Self {
        Self {
            block_cursor,
            latest_seen_head: None,
            flush_deadline: None,
            window,
            progress: None,
        }
    }

    fn with_progress(mut self, progress: Option<ScanProgress>) -> Self {
        self.progress = progress;
        self
    }

    /// Record a newly observed chain tip on the attached progress handle, if any. Called from
    /// `handle_empty_flush` when its `get_tip` closure resolves `Ok` — the only place in the
    /// live loop that fetches a tip, and only opportunistically (span-capped empty flushes).
    fn record_tip(&self, tip: u64) {
        if let Some(p) = &self.progress {
            p.record_observed_tip(tip);
        }
    }

    fn block_cursor(&self) -> Option<u64> {
        self.block_cursor
    }

    fn observe_head(&mut self, head_number: u64, now: Instant) -> bool {
        let from_block = self.block_cursor.unwrap_or(head_number);
        if head_number < from_block {
            return false;
        }

        self.latest_seen_head = Some(
            self.latest_seen_head
                .map_or(head_number, |latest| latest.max(head_number)),
        );

        if self.flush_deadline.is_none() {
            self.flush_deadline = Some(now + self.window);
        }

        true
    }

    fn pending_range(&self) -> Option<(u64, u64)> {
        let to_block = self.latest_seen_head?;
        let from_block = self.block_cursor.unwrap_or(to_block);
        (to_block >= from_block).then_some((from_block, to_block))
    }

    fn flush_deadline(&self) -> Option<Instant> {
        self.pending_range()?;
        self.flush_deadline
    }

    fn should_flush(&self, now: Instant) -> bool {
        let Some((from_block, to_block)) = self.pending_range() else {
            return false;
        };

        if to_block - from_block + 1 >= MAX_BLOCKS_PER_WS_REQUEST {
            return true;
        }

        self.flush_deadline.is_some_and(|deadline| now >= deadline)
    }

    fn advance_cursor(&mut self, next_block: u64) {
        self.block_cursor = Some(next_block);

        // Every call site passes the *next* block to fetch, never the last-scanned one
        // (`last_block + 1`, `watermark + 1`, `to_block + 1`) — translate back to the
        // highest block actually scanned before recording.
        if let Some(p) = &self.progress {
            p.record_scanned_to(next_block.saturating_sub(1));
        }

        if self
            .latest_seen_head
            .is_some_and(|latest| next_block > latest)
        {
            self.latest_seen_head = None;
            self.flush_deadline = None;
        }
    }

    /// Called after an empty, non-capped flush so the stream waits for the next
    /// head instead of busy-looping the same range. Clears `flush_deadline`
    /// only — the cursor and `latest_seen_head` are untouched, so the next
    /// `observe_head` re-arms the deadline while the span-cap arm of
    /// `should_flush` still fires deadline-free.
    fn defer_flush(&mut self) {
        self.flush_deadline = None;
    }
}

/// Outcome of feeding one head into the live reorg linkage check.
#[derive(Debug, Clone, PartialEq, Eq)]
enum LinkOutcome {
    /// The head extends (or bootstraps) the canonical chain — no reorg.
    Linked,
    /// A reorg whose common ancestor was resolved within the ring.
    Reorg { common_ancestor: u64 },
    /// The head's parent is not the recorded canonical block and the ancestor
    /// could not be resolved from the ring alone (the provider skipped the
    /// intermediate new-chain heads). The caller must fetch the parent block by
    /// hash and walk the new chain back — bounded RPC, reorg branch only — feeding
    /// the fetched `(number, hash)` back through `matches`.
    Detached {
        parent_hash: B256,
        child_number: u64,
    },
    /// Heads were skipped: the arriving head sits above `ring_tip + 1`, so the
    /// ring cannot assert linkage over the missing blocks. Missed observation,
    /// not a fork — the caller reports the break in our own view and hands
    /// recovery to the consumer. Kept distinct from `NoRecordedParent` so the
    /// caller can log the ring tip and the gap it left.
    Gap { ring_tip: u64 },
    /// Nothing is recorded at the head's parent height — the parent sits below
    /// the ring floor, the ring never reached there, or the head is block 0 and
    /// has no parent at all. Absence of a record is not a claim about the
    /// chain: there was nothing here to disagree with.
    NoRecordedParent,
}

/// A ring of canonical `(number, hash)` taken from the head stream, as deep as
/// the configured recovery window, plus a `parent_hash` linkage check. Pure and
/// synchronous — the network is thin glue around it, mirroring
/// `HeadCoalescer`. `depth == 0` disables it: `observe` is then inert and
/// returns `Linked` for every head (zero overhead, the L2 / snapshot default).
#[derive(Debug, Clone)]
struct HeadLinkage {
    ring: VecDeque<(u64, B256)>,
    depth: u64,
}

impl HeadLinkage {
    fn new(depth: u64) -> Self {
        Self {
            ring: VecDeque::new(),
            depth,
        }
    }

    fn enabled(&self) -> bool {
        self.depth > 0
    }

    /// Lowest block number still recorded in the ring (the resolution floor).
    fn floor(&self) -> Option<u64> {
        self.ring.front().map(|&(number, _)| number)
    }

    /// Lowest block number the ring may hold while honoring `depth`, given
    /// the current tip. `None` on an empty ring, mirroring `latest()`. Kept
    /// as a method rather than exposing `depth` itself (a private field) to
    /// callers that need to know how far the ring should reach — the
    /// top-up's stop condition: once `floor()` reaches this, the ring
    /// already spans `depth` and there is nothing left to walk.
    fn lowest_worth_recording(&self) -> Option<u64> {
        let (latest, _) = self.latest()?;
        Some(latest.saturating_sub(self.depth.saturating_sub(1)))
    }

    /// The recovery window this ring is configured to retain, in blocks.
    /// Distinct from `lowest_worth_recording`, which answers where the ring
    /// should reach given its current tip; this is the configured span itself,
    /// which the self-heal walk's length bound must clear.
    fn recovery_window_depth(&self) -> u64 {
        self.depth
    }

    /// Recorded canonical hash at `number`, if it is within the ring.
    fn hash_at(&self, number: u64) -> Option<B256> {
        let &(front, _) = self.ring.front()?;
        let offset = number.checked_sub(front)? as usize;
        self.ring.get(offset).map(|&(_, hash)| hash)
    }

    /// True if the ring records `hash` as canonical at `number`.
    fn matches(&self, number: u64, hash: B256) -> bool {
        self.hash_at(number) == Some(hash)
    }

    /// Append `(number, hash)` as the new tip, evicting the oldest beyond `depth`.
    fn push(&mut self, number: u64, hash: B256) {
        self.ring.push_back((number, hash));
        while self.ring.len() as u64 > self.depth {
            self.ring.pop_front();
        }
    }

    /// Extend the ring downward with `pairs` in ascending `(number, hash)`
    /// order — the shape a backward hash-chain walk yields once reversed.
    /// Not a `push`: these sit below the ring's current front, so appending
    /// would corrupt the ring's ordering and its floor.
    ///
    /// Pairs at or above the current floor are already recorded and are
    /// skipped — the normal case for a walk's own anchor pair. The kept
    /// pairs must be contiguous with the front and with each other: `hash_at`
    /// indexes by offset from the front, so a gap would silently return the
    /// wrong hash for every entry above it. Never carries the floor below
    /// `lowest_worth_recording`, so the ring never exceeds `depth`. A batch
    /// that fails either check records nothing. Inert when `!enabled()`.
    fn extend_downward(&mut self, pairs: &[(u64, B256)]) {
        if !self.enabled() {
            return;
        }
        let Some(front) = self.floor() else {
            return; // nothing to anchor a downward extension against
        };
        let deepest = self.lowest_worth_recording().unwrap_or(front);
        let below: Vec<(u64, B256)> = pairs
            .iter()
            .copied()
            .filter(|&(n, _)| (deepest..front).contains(&n))
            .collect();
        let Some(&(top, _)) = below.last() else {
            return; // nothing below the floor, or nothing within depth
        };
        let contiguous =
            top + 1 == front && below.windows(2).all(|pair| pair[1].0 == pair[0].0 + 1);
        if !contiguous {
            return;
        }
        for &(number, hash) in below.iter().rev() {
            self.ring.push_front((number, hash));
        }
    }

    /// The most recently recorded `(number, hash)` entry (the ring's canonical tip).
    ///
    /// Returns `None` only when the ring is completely empty (before the first
    /// `observe`). When `linkage.enabled()` and a flush fires, this is always `Some`
    /// because `observe` bootstraps or re-anchors the ring at the newest head before
    /// `should_flush` can return true.
    fn latest(&self) -> Option<(u64, B256)> {
        self.ring.back().copied()
    }

    /// Re-anchor the ring at `ancestor` (drop everything above it), then record
    /// the new-chain head `(number, hash)`.
    fn reanchor(&mut self, ancestor: u64, number: u64, hash: B256) {
        while self.ring.back().is_some_and(|&(n, _)| n > ancestor) {
            self.ring.pop_back();
        }
        self.push(number, hash);
    }

    /// Observe one head's `(number, hash, parent_hash)` against the recorded
    /// chain. See `LinkOutcome`. Disabled (`depth == 0`) ⇒ always `Linked`.
    fn observe(&mut self, number: u64, hash: B256, parent_hash: B256) -> LinkOutcome {
        if !self.enabled() {
            return LinkOutcome::Linked;
        }

        let Some(&(tip_number, tip_hash)) = self.ring.back() else {
            // Bootstrap: the first head seeds the ring.
            self.push(number, hash);
            return LinkOutcome::Linked;
        };

        // The common case: a clean forward extension of the tip.
        if number == tip_number + 1 && parent_hash == tip_hash {
            self.push(number, hash);
            return LinkOutcome::Linked;
        }

        // A head the ring already records at this exact height is not new
        // information, wherever in the ring it sits. Tested before the ring is
        // consulted for the parent: a re-observed head whose parent has since
        // been evicted would otherwise read as an absent record and end the
        // stream over a block we already hold.
        if self.hash_at(number) == Some(hash) {
            return LinkOutcome::Linked;
        }

        // A forward gap (heads skipped ahead — e.g. across a reconnect) is
        // missed observation, not a fork. Its length is outage duration times
        // block rate and bears no relation to how deep two chains part, so a
        // backward walk sized from the ring's fork window would spend a
        // fork-sized budget on a question it was never asked and then report a
        // divergence it never observed. Report the break in our own view and
        // let the consumer re-anchor.
        if number > tip_number + 1 {
            return LinkOutcome::Gap {
                ring_tip: tip_number,
            };
        }

        // `number <= tip_number + 1`, not a duplicate, and the parent did not
        // extend the tip: a reorg, or a detachment that needs an RPC walk.
        let Some(parent_number) = number.checked_sub(1) else {
            return LinkOutcome::NoRecordedParent;
        };
        match self.hash_at(parent_number) {
            // Parent links to a known canonical block, and `number` is not the
            // block we recorded there: it was replaced on a chain sharing
            // canonical `parent_number` → that is the common ancestor.
            Some(canonical_parent) if canonical_parent == parent_hash => {
                self.reanchor(parent_number, number, hash);
                LinkOutcome::Reorg {
                    common_ancestor: parent_number,
                }
            }
            // Parent is within the ring but differs → diverges deeper; the caller
            // must walk the new chain back to find the ancestor.
            Some(_) => LinkOutcome::Detached {
                parent_hash,
                child_number: number,
            },
            // Nothing recorded at the parent's height. `hash_at` returned
            // `None`, so no comparison happened here at all — a parent below
            // the floor and a ring that never reached there are the same
            // absence, and neither disagrees with anything.
            None => LinkOutcome::NoRecordedParent,
        }
    }
}

/// Sequentially asks the configured HTTP providers for `hash`, starting at
/// `start_index` and rotating exactly as `get_logs_with_http_fallback_retry`
/// does — never a concurrent fan-out. We trust our providers: a response
/// whose own header satisfies `is_match` IS the requested block, no second
/// source needed, no corroboration. Null, a transport error, and an identity
/// mismatch (wrong hash, or for `collect_window_hashes` also wrong number)
/// are the same thing — "this provider did not answer" — and simply advance
/// to the next one. `skip_first` excludes `start_index` itself from the
/// rotation, for callers that already queried it directly through their own
/// already-connected client.
///
/// Returns the answering provider's index alongside the header — the same
/// shape `get_logs_with_http_fallback_retry` returns — so a caller that steps
/// repeatedly can start its next call where this one left off, instead of
/// paying a full rotation from `start_index` again.
///
/// Exhausting every attempt without a match is a claim about our OWN view —
/// no provider answered — never about the chain; the caller decides what
/// that means. The returned error mirrors `fallback_http_exhausted_error`'s
/// shape: the hash and the hosts tried.
async fn get_block_by_hash_with_http_fallback(
    caller: &str,
    providers: &ProviderSettings,
    reused: Option<&[DynProvider<Ethereum>]>,
    start_index: usize,
    skip_first: bool,
    hash: B256,
    is_match: impl Fn(&Header) -> bool,
) -> Result<(usize, Box<Header>), RpcError> {
    let n = providers.http_providers.len();
    let mut attempted_hosts: Vec<String> = Vec::new();
    let mut last_err = String::new();

    for step in usize::from(skip_first)..n {
        let idx = fallback_http_index(start_index, step, n);
        let host = providers.http_settings(idx).host();
        let http_provider = resolve_http_provider(providers, reused, idx);
        let outcome = match http_provider.get_block_by_hash(hash).await {
            Ok(Some(block)) if is_match(&block.header) => return Ok((idx, Box::new(block.header))),
            Ok(Some(_)) => "answered a non-matching block".to_string(),
            Ok(None) => "has no block".to_string(),
            Err(e) => truncate_error_short(e, 100),
        };
        warn!("{caller}: provider {host} did not answer for block {hash}: {outcome}");
        last_err = outcome;
        attempted_hosts.push(host);
    }

    Err(RpcError::ConnectionError(if attempted_hosts.is_empty() {
        format!("{caller}: no provider left to try for block {hash}")
    } else {
        format!(
            "{caller}: no provider answered for block {hash} after trying [{}]: {}",
            attempted_hosts.join(", "),
            last_err
        )
    }))
}

/// `N ≥ 1`, and when a reused-client slice is supplied its length matches `N` —
/// the shared precondition both walk entry points enforce before any HTTP
/// resolution, the same fail-closed posture `flush_window_range`'s own
/// empty-set guard already uses. Production upholds `reused.len() == N` via
/// `build_reused_http_clients`; a mismatch, like `N == 0`, is a configuration
/// fault, not a walk outcome to keep walking past.
fn provider_set_preconditions(
    n: usize,
    reused: Option<&[DynProvider<Ethereum>]>,
) -> Option<RpcError> {
    if n == 0 {
        return Some(RpcError::ConnectionError(
            "no HTTP providers configured to resolve reorg-walk steps".to_string(),
        ));
    }
    if let Some(set) = reused
        && set.len() != n
    {
        return Some(RpcError::ConnectionError(format!(
            "reused HTTP client count {} does not match configured provider count {n}",
            set.len(),
        )));
    }
    None
}

/// Walk backward from `tip_hash` at `tip_number` down to `from_block`, collecting
/// canonical `(number, hash)` pairs in descending order (tip → from_block).
///
/// Used by the backfill boot path to resolve hashes for the reorg-exposed window
/// before handing off to `stream_heads_with_logs`. Does not touch any ring.
///
/// Trust rule: a response whose hash AND number match what was asked is the
/// requested block, verified outright — no second source. Null, a transport
/// error, a wrong hash, or a wrong number are all "this provider did not
/// answer"; the primary's own miss is retried against the other configured
/// HTTP providers in sequence, and exhausting them yields `ConnectionError`
/// (a claim about our view, never the chain).
pub(crate) async fn collect_window_hashes(
    provider: &DynProvider<Ethereum>,
    providers: &ProviderSettings,
    reused: Option<&[DynProvider<Ethereum>]>,
    primary_index: usize,
    tip_hash: B256,
    tip_number: u64,
    from_block: u64,
) -> Result<Vec<(u64, B256)>, RpcError> {
    let n = providers.http_providers.len();
    if let Some(err) = provider_set_preconditions(n, reused) {
        return Err(err);
    }
    if tip_number < from_block {
        return Ok(Vec::new());
    }
    let primary_index = primary_index % n;
    let mut collected: Vec<(u64, B256)> = Vec::new();
    let mut current_hash = tip_hash;
    let mut current_number = tip_number;

    loop {
        collected.push((current_number, current_hash));
        if current_number == from_block {
            break;
        }
        let hash = current_hash;
        let header = match provider.get_block_by_hash(hash).await {
            // Matching hash and number: trusted outright, no fallback, no
            // extra RPC.
            Ok(Some(block))
                if block.header.hash == hash && block.header.number == current_number =>
            {
                Box::new(block.header)
            }
            // Null, wrong hash, wrong number, or a transport error: the
            // primary did not answer — try the other configured providers.
            _ => {
                let (_, header) = get_block_by_hash_with_http_fallback(
                    "collect_window_hashes",
                    providers,
                    reused,
                    primary_index,
                    true,
                    hash,
                    |h| h.hash == hash && h.number == current_number,
                )
                .await?;
                header
            }
        };
        let parent_hash = header.parent_hash;
        let Some(parent_number) = current_number.checked_sub(1) else {
            // Walked down to block 0, which has no parent to continue from.
            // Running out of chain says nothing about a fork.
            return Err(RpcError::Gap);
        };
        if parent_number < from_block {
            break;
        }
        current_hash = parent_hash;
        current_number = parent_number;
    }

    Ok(collected)
}

/// Fetch logs for a slice of canonical `(number, hash)` pairs using
/// `at_block_hash` filters — one request per block, ascending.
///
/// `at_block_hash` pins the query to the exact canonical block identified by
/// `hash`, so an orphaned block at that number can never contaminate the result.
/// The caller passes `pairs` in ascending order (from_block → tip).
pub(crate) async fn fetch_logs_by_hash_range(
    providers: &ProviderSettings,
    pairs: &[(u64, B256)],
    base_filter: Option<&Filter>,
) -> Result<Vec<LogRange>, RpcError> {
    let mut ranges: Vec<LogRange> = Vec::with_capacity(pairs.len());

    for &(number, hash) in pairs {
        let query = base_filter
            .cloned()
            .unwrap_or_else(Filter::new)
            .at_block_hash(hash);

        let (_, logs) =
            get_logs_with_http_fallback_retry(providers, &query, 0, number, number, None).await?;

        // One block per range, fetched by the hash that pins it: the canonical
        // identity of `to_block` is known here, so the range carries it.
        ranges.push(LogRange {
            from_block: number,
            to_block: number,
            logs,
            tip_hash: Some(hash),
        });
    }

    Ok(ranges)
}

/// Wraps `fut`'s aggregate work in a wall-clock bound so a pathologically slow
/// flush can't block the live head-consuming loop long enough to overflow
/// alloy's internal WS head-buffer (Q-BSC-2 Route B). `max_secs == 0` disables
/// the bound (old, unbounded behavior) — mirrors `tip_wait_max_total_secs`'s
/// own `0`-disables convention.
///
/// `label` identifies the providers the flush was working against — the
/// helper is provider-agnostic and puts the caller's label straight into the
/// timeout message, ahead of the prose, so identity survives even a tight
/// downstream cap. It claims nothing about which of them stalled: nothing
/// observes an in-flight provider today.
async fn bound_flush_time<F, T>(max_secs: u64, label: &str, fut: F) -> Result<T, RpcError>
where
    F: Future<Output = Result<T, RpcError>>,
{
    if max_secs == 0 {
        return fut.await;
    }
    match tokio::time::timeout(Duration::from_secs(max_secs), fut).await {
        Ok(result) => result,
        Err(_) => Err(RpcError::ConnectionError(format!(
            "{label}: flush exceeded its {max_secs}s aggregate timeout — provider \
             likely stalled mid-flush; switching provider"
        ))),
    }
}

/// The structured event name the live loop stamps on a `Gap`. Named here
/// rather than written inline at the raise site so a hermetic test can pin
/// it: a consumer's log-metric filter matches the literal string, so a
/// rename or typo would otherwise leave every gate green while the filter
/// silently stopped matching. Same reason `flush_failure_log_line` exists.
fn live_head_gap_event() -> &'static str {
    "live_head_gap"
}

/// The structured event name the live loop's reorg walk stamps on
/// `ReorgBeyondRing` — the one exit from that walk that is a claim about the
/// chain, not about a provider. The walk's other errors keep the walk's
/// existing free-text line; naming only this one is what lets a filter alarm
/// on a chain claim without also counting a stalled provider.
fn live_head_reorg_beyond_ring_event() -> &'static str {
    "live_head_reorg_beyond_ring"
}

/// Which structured event, if any, the reorg walk's dispatch site stamps on
/// `err`. `ReorgBeyondRing` is the walk's one exit that is a claim about the
/// chain; everything else — a spent budget, a transport fault reaching this
/// walk — keeps the walk's unnamed free-text line, so a filter on the named
/// event can never miscount a stalled provider as a chain claim.
///
/// Extracted, like `classify_flush_failure` and `flush_failure_log_line`, so
/// a hermetic test can assert the split directly: the live loop's own
/// dispatch arm has no hermetic seam (`TODO G.15`).
fn walk_failure_event(err: &RpcError) -> Option<&'static str> {
    match err {
        RpcError::ReorgBeyondRing => Some(live_head_reorg_beyond_ring_event()),
        _ => None,
    }
}

/// What the live loop must do with a failed by-hash flush.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FlushFailure {
    /// Yield the error and end the stream.
    EndStream,
    /// Retry the same window; the flush's HTTP fetch restarts at the same
    /// index, so this does not reach a different provider.
    SwitchProvider,
}

/// Separate a flush failure worth retrying from one no retry can fix.
///
/// A failed flush moves neither the cursor nor the pending span, so a retry
/// re-runs the identical window. For a transport fault that is the point —
/// retrying may still succeed once the provider tracker's backoff clears,
/// even though the retry's HTTP fetch restarts at the same index and never
/// reaches a different provider. `Gap` and
/// `ReorgBeyondRing` deny that premise: the answer is a property of the span
/// and the ring, not of who was asked, and a successful reconnect clears the
/// provider tracker's backoff on the way round, so nothing throttles the
/// repeat. Those claims belong to the consumer, the only party that can
/// re-anchor and resume.
///
/// `AllProvidersSuspended` and `AllProvidersIdle` belong with the transport
/// class, not the deny-the-premise one: both are self-clearing conditions, not
/// permanent claims about every provider. `ProviderErrorTracker`'s
/// `cleanup_old_errors`/`is_suspended` (`error_tracking.rs`) un-suspend a
/// provider once its errors age out of the sliding window, and
/// `AllProvidersIdle`'s own doc comment states it is retryable by contract —
/// a rotation-worthy transport signal, not a claim about the span or the ring.
///
/// Neither variant is constructed anywhere in `flush_window_range`'s call
/// graph today — the live generator raises both itself, at a
/// `yield Err(...); return;` site outside this dispatch, verified by tracing
/// every construction site. That is a fact about today's call graph, latent
/// rather than exercised; it says nothing about which `FlushFailure` would be
/// correct if a caller ever routed either through this classifier.
///
/// Exhaustive by design: a variant added later must be classified here rather
/// than inherit the retry default, which is how a claim came to be retried.
fn classify_flush_failure(err: &RpcError) -> FlushFailure {
    match err {
        RpcError::Gap | RpcError::ReorgBeyondRing | RpcError::Reorg { .. } => {
            FlushFailure::EndStream
        }
        RpcError::ConnectionError(_)
        | RpcError::SubscriptionError(_)
        | RpcError::LogFetchError(_)
        | RpcError::TransportError(_)
        | RpcError::CursorPastTip { .. }
        | RpcError::ProviderStalled { .. }
        | RpcError::AllProvidersSuspended(_)
        | RpcError::AllProvidersIdle { .. }
        | RpcError::Other(_) => FlushFailure::SwitchProvider,
    }
}

/// Builds the by-hash flush failure log line, bounded at the house limit
/// (`MAX_ERROR_MSG_LEN`) rather than the 100-byte cap other sites in this file
/// use for a foreign provider error string — `err`'s own text already carries
/// the provider identity `bound_flush_time` embedded, and a cap that fits
/// neither would cut it back off. Extracted so a hermetic test can assert on
/// the emitted line directly; this module has no log-capture dependency.
///
/// Naming the disposition is what makes the line diagnostic: the same error
/// text ends the stream or retries depending on `failure`, and an operator
/// reading only the error cannot tell which happened. Building it here also
/// leaves the dispatch site's match arms pure control flow — see the live
/// loop's `Err` arm for why that matters.
///
/// `SwitchProvider` says only "retrying the same window" — no claim about
/// which provider services the retry. The live loop's call site always
/// invokes `flush_window_range` with HTTP `provider_index` `0`, and
/// `get_logs_with_http_fallback_retry` restarts its fallback from that same
/// index on every call, so a retried flush's HTTP fetch never rotates, no
/// matter how many HTTP or WS providers are configured. What does rotate on
/// `SwitchProvider` is the live loop's WS session — a separate index this
/// flush never reads.
fn flush_failure_log_line(err: &RpcError, failure: FlushFailure) -> String {
    let disposition = match failure {
        FlushFailure::EndStream => "ending stream for consumer recovery",
        FlushFailure::SwitchProvider => "retrying the same window",
    };
    format!(
        "by-hash window flush failed: {} — {disposition}",
        truncate_error(err)
    )
}

/// Names the two providers a by-hash flush is working against: the WS stream's
/// own host, and the host its HTTP fallback starts from. Reads the fallback
/// through `first()` rather than `http_settings(0)`, whose modulo indexing
/// panics on an empty configured set — `flush_window_range`'s own guard is
/// what turns that configuration fault into a fail-closed error, and this
/// label is built before the flush can reach it.
fn flush_timeout_label(providers: &ProviderSettings, ws_host: &str) -> String {
    let fallback = providers
        .http_providers
        .first()
        .map(|settings| settings.host())
        .unwrap_or_else(|| "<none>".to_string());
    format!("ws={ws_host} fallback={fallback}")
}

/// Flush one pending window range from the coalescer by fetching all logs by
/// canonical block hash.
///
/// When the ring is missing hashes for some blocks — a boot gap, where the ring
/// bootstraps at the first live head while the flush cursor still sits where
/// backfill left it, or a flush that has failed repeatedly while heads kept
/// arriving — walks backward from `linkage.latest()` to collect
/// canonical `(number, hash)` pairs, records them into the ring (`extend_downward`),
/// and uses them directly. Never falls back to a by-number fetch — fail-closed is
/// the invariant. On every flush, whether or not that self-heal walk ran, also
/// runs a small bounded top-up that walks the ring downward from its own floor
/// toward its configured recovery window depth — see `REORG_RING_TOP_UP_STEPS`
/// — so a ring left shallow by a stream restart deepens across the next
/// several flushes instead of staying wherever forward observation alone last
/// left it. Only called when `linkage.enabled()`.
async fn flush_window_range(
    linkage: &mut HeadLinkage,
    coalescer: &mut HeadCoalescer,
    providers: &ProviderSettings,
    filter: Option<&Filter>,
    provider_index: usize,
    reused: Option<&[DynProvider<Ethereum>]>,
) -> Result<Vec<LogRange>, RpcError> {
    let Some((from_block, pending_to_block)) = coalescer.pending_range() else {
        return Ok(vec![]);
    };
    // Fail closed rather than let the modulo-indexed `http_settings`/`connect_http`
    // lookups below panic on an empty configured set — the same guard
    // `poll_providers_for_block_number` applies before its own `% num_providers`
    // indexing.
    if providers.http_providers.is_empty() {
        return Err(RpcError::ConnectionError(
            "No HTTP providers configured for window flush".to_string(),
        ));
    }
    let to_block = std::cmp::min(from_block + MAX_BLOCKS_PER_WS_REQUEST - 1, pending_to_block);

    // Build the (number, hash) pairs for [from_block, to_block].
    // If any hash is absent from the ring, self-heal: walk backward from the
    // latest known entry to fill the gap. `latest()` is Some whenever the flush
    // fires — `observe` bootstraps or re-anchors at the newest head before
    // `should_flush` can return true.
    let pairs: Vec<(u64, B256)> = if (from_block..=to_block).all(|n| linkage.hash_at(n).is_some()) {
        (from_block..=to_block)
            .map(|n| (n, linkage.hash_at(n).expect("just verified")))
            .collect()
    } else {
        // Anchored at the live head (`linkage.latest()`), never a backfill
        // cursor: only the live head is contiguous with the head stream by
        // construction. A backfill cursor is several heights stale by the
        // time the WS subscription delivers its first head, so seeding from
        // it would make the very next head arrive as `Detached` — a healthy
        // chain killing its own stream on every boot.
        let Some((top_n, top_hash)) = linkage.latest() else {
            // Ring is completely empty — no anchor for the walk, and no record
            // anywhere to disagree with.
            return Err(RpcError::Gap);
        };
        // The walk is sequential and fail-closed, so its wall-clock cost grows
        // with the shortfall it is asked to cover. Refuse a span that would park
        // the live loop instead of healing it, and say only what that refusal
        // establishes: we did not reconstruct our own view, not that the chain
        // did anything.
        let walk_blocks = top_n.saturating_sub(from_block) + 1;
        let walk_bound = SELF_HEAL_WALK_MAX_BLOCKS.saturating_add(linkage.recovery_window_depth());
        if walk_blocks > walk_bound {
            warn!(
                "flush window [{}, {}] would need a {}-block self-heal walk from ring anchor \
                 {} — beyond the {}-block bound; ending the flush rather than walking it",
                from_block, to_block, walk_blocks, top_n, walk_bound
            );
            return Err(RpcError::Gap);
        }
        let walk_provider = resolve_http_provider(providers, reused, provider_index);
        // `collect_window_hashes` walks strictly sequentially: each step needs the
        // previous block's parent hash, which is only known after fetching that
        // block, so there is nothing here for `fetch_concurrently` to parallelize.
        // That is inherent to a backward hash-chain walk, not an oversight — if a
        // very deep backlog ever makes this walk the bottleneck, fixing it needs a
        // different algorithm (e.g. walking by block number instead of by hash, if
        // that is even valid here), which is out of scope for this fix.
        // `top_n < from_block` means the ring's latest known block is already
        // behind the window we need — `collect_window_hashes` below no-ops via
        // its own `tip_number < from_block` guard, so nothing gets walked. Say
        // so plainly rather than reporting a "walking back N blocks" count that
        // would otherwise floor at 1 (via `saturating_sub`) and misdescribe a
        // no-op as a one-block walk in the wrong direction.
        warn!(
            "flush window [{}, {}] missing ring entries — self-heal walking back up \
             to {} blocks from ring anchor {} to {} ({})",
            from_block,
            to_block,
            top_n.saturating_sub(from_block) + 1,
            top_n,
            from_block,
            if top_n < from_block {
                "ring anchor already trails the window's start — the walk \
                 immediately no-ops, nothing is fetched"
            } else {
                "uses the same client-reuse mechanism as the main fetch path when \
                 available, but the walk itself is sequential; not covered by the \
                 concurrent fetch path"
            }
        );
        let mut pairs_desc = collect_window_hashes(
            &walk_provider,
            providers,
            reused,
            provider_index,
            top_hash,
            top_n,
            from_block,
        )
        .await?;
        // Reverse to ascending (from_block → top_n). Record the walk's pairs into
        // the ring before restricting to this flush's own window — they are
        // already fetched, and this is the only place the ring's floor ever
        // moves down from its live-head anchor toward the flush cursor, at
        // zero added RPC cost (the top-up below pays for everything deeper).
        // `extend_downward` discards the walk's own anchor pair (already
        // recorded at the ring's back, `top_n`/`top_hash` above) and anything
        // that would break the ring's contiguity.
        pairs_desc.reverse();
        linkage.extend_downward(&pairs_desc);
        pairs_desc
            .into_iter()
            .filter(|&(n, _)| n <= to_block)
            .collect()
    };

    // Fetch the entire batch BEFORE advancing the cursor, concurrently (bounded by the
    // provider's own max_concurrency). On any block's failure, the whole batch returns
    // Err with the cursor UNTOUCHED so the whole window range retries on the next
    // provider — never advance past a block whose logs were not delivered to the
    // consumer (fail-closed; no silent gap). Re-fetch on retry is idempotent.
    let last_pending = pairs.last().copied();
    // Two accepted tradeoffs, not oversights:
    // - Concurrent dispatch means a provider outage can now produce up to
    //   `bound * num_http_providers` failed fallback requests before this flush
    //   aborts, versus `num_http_providers` before concurrency — trading a bigger
    //   worst-case fan-out for a bounded wall-clock duration (fail-fast).
    // - `provider_index` here ranges over WS-endpoint indices (it's the live
    //   loop's WS provider position, reused as the HTTP-fallback start index —
    //   pre-existing conflation in this module), not HTTP-provider indices. It
    //   was already used this way for fallback start; it is now also load-bearing
    //   for which HTTP provider's `max_concurrency` gates this flush's dispatch.
    let bound = providers.http_settings(provider_index).max_concurrency as usize;
    let fetch = move |(n, hash): (u64, B256)| async move {
        let query = filter
            .cloned()
            .unwrap_or_else(Filter::new)
            .at_block_hash(hash);
        let (_, logs) =
            get_logs_with_http_fallback_retry(providers, &query, provider_index, n, n, reused)
                .await?;
        // Same by-hash rule as `fetch_logs_by_hash_range`: this range is one
        // block, pinned to the hash it was fetched with.
        Ok::<LogRange, RpcError>(LogRange {
            from_block: n,
            to_block: n,
            logs,
            tip_hash: Some(hash),
        })
    };
    let ranges = sort_ranges_ascending(fetch_concurrently(pairs, bound, fetch).await?);

    // Bounded top-up (settled decision 6: runs on every flush, not only when
    // the self-heal branch above fires). Placed here — after the batch
    // fetch, before the cursor advance — deliberately, and this call site's
    // position is the one thing in this function you must not move:
    // `bound_flush_time` (at this function's own call sites) is a
    // `tokio::time::timeout` that drops this whole future on expiry, and
    // `coalescer` is a `&mut` borrow that outlives the drop while the local
    // `ranges` does not. A top-up placed after `advance_cursor` would, on
    // timeout, leave the cursor moved past blocks whose logs were never
    // yielded — the silent gap the fail-closed invariant above forbids. Here
    // a timeout instead discards `ranges` with the cursor untouched,
    // identical to today's stalled-provider behavior. Pinned by
    // `flush_window_range_timeout_mid_top_up_drops_cursor_advance`.
    top_up_reorg_ring(linkage, providers, provider_index, reused).await;

    if let Some((last, _)) = last_pending {
        coalescer.advance_cursor(last + 1);
    }
    Ok(ranges)
}

/// Extend `linkage`'s ring downward toward its recovery window floor by up to
/// `REORG_RING_TOP_UP_STEPS` blocks. Errors are logged and swallowed
/// (settled decision 8) — the caller's own ranges are already fetched and
/// unaffected; the ring simply regrows at the pre-change rate on the next
/// flush. See `flush_window_range`'s call site for why this call's position
/// relative to the cursor advance is load-bearing, not stylistic.
async fn top_up_reorg_ring(
    linkage: &mut HeadLinkage,
    providers: &ProviderSettings,
    provider_index: usize,
    reused: Option<&[DynProvider<Ethereum>]>,
) {
    let (Some(floor), Some(target)) = (linkage.floor(), linkage.lowest_worth_recording()) else {
        return;
    };
    if floor <= target {
        return;
    }
    let floor_hash = linkage
        .hash_at(floor)
        .expect("the ring's own floor is always recorded at its own number");
    let walk_from = target.max(floor.saturating_sub(REORG_RING_TOP_UP_STEPS));
    let walk_provider = resolve_http_provider(providers, reused, provider_index);
    match collect_window_hashes(
        &walk_provider,
        providers,
        reused,
        provider_index,
        floor_hash,
        floor,
        walk_from,
    )
    .await
    {
        Ok(mut pairs_desc) => {
            pairs_desc.reverse();
            linkage.extend_downward(&pairs_desc);
            info!(
                "reorg ring top-up: floor {floor} -> {} (target {target})",
                linkage.floor().unwrap_or(floor)
            );
        }
        Err(err) => {
            // Degraded, not broken: the caller's own ranges are already
            // fetched and unaffected — the ring simply regrows at the
            // pre-change rate. A provider outage severe enough to matter
            // already surfaces through the live loop's own by-hash flush
            // failure `warn!` (fired when `flush_window_range` itself times
            // out or errors), so this stays at debug! rather than paging
            // someone for a top-up alone.
            debug!("reorg ring top-up failed, will retry next flush: {err}");
        }
    }
}

/// Runs `fetch` over `items` concurrently, bounded by `bound` in-flight futures at
/// once (clamped to at least 1 — see the `max_concurrency` doc on `HttpRpcSettings`),
/// failing fast on the first error: `try_buffer_unordered` drops the remaining
/// in-flight futures the instant any one resolves `Err`, rather than
/// `try_buffered`'s in-order wait (which can be slower than a sequential loop in
/// the worst case) or a collect-then-check shape that invokes every future before
/// checking any result. Results are returned in completion order, not input order —
/// callers that need input order (e.g. ascending block number) must sort separately.
///
/// Written as a plain `fn` returning a named `impl Future + Send` rather than an
/// `async fn`, so its `Send`-ness is declared here instead of left to inference —
/// see the `#[allow]` below for why that distinction matters.
#[allow(clippy::manual_async_fn)]
// This must stay a named `-> impl Future + Send` and NOT collapse back to `async
// fn`: an `async fn`'s returned future is opaque, so whether it is `Send` is left
// to rustc's inference at each call site. A caller that borrows locals into a
// spawned stream needs that future to be `Send` for ANY lifetime the `fetch`
// closure borrows over — a higher-ranked obligation inference cannot discharge
// through an opaque type. That failure surfaces as an "implementation of `Send`
// is not general enough" error at the *consumer's* call site, not here, so
// clippy's own suggestion to simplify this to `async fn` reintroduces the bug
// invisibly to every gate in this crate.
fn fetch_concurrently<In, Out, F, Fut>(
    items: Vec<In>,
    bound: usize,
    fetch: F,
) -> impl Future<Output = Result<Vec<Out>, RpcError>> + Send
where
    In: Send,
    Out: Send,
    F: Fn(In) -> Fut + Send,
    Fut: Future<Output = Result<Out, RpcError>> + Send,
{
    async move {
        futures_util::stream::iter(items.into_iter().map(fetch).map(Ok::<Fut, RpcError>))
            .try_buffer_unordered(bound.max(1))
            .try_collect()
            .await
    }
}

/// Restores ascending block-number order after `fetch_concurrently`'s unordered
/// dispatch. `flush_window_range`'s external contract yields blocks in order; this
/// is the only place that reimposes it — cheap, and only paid on the already-rare
/// "flush was behind" path concurrency exists to fix.
fn sort_ranges_ascending(mut ranges: Vec<LogRange>) -> Vec<LogRange> {
    ranges.sort_by_key(|range| range.from_block);
    ranges
}

/// Walk the new chain backward by hash until a block re-links to the recorded
/// canonical ring, returning the common ancestor's block number.
///
/// Invoked only on `LinkOutcome::Detached`, when the provider delivered a new-tip
/// head without re-emitting the intermediate new-chain blocks. Bounded to `depth`
/// sequential `get_block_by_hash` fetches against `provider` (the ring's own
/// span), plus at most `N - 1` more per step when a step has to fall back to
/// the other configured HTTP providers.
///
/// Only one exit here claims the chain: a fetched hash compared against a
/// recorded canonical hash at the ring's floor, and they differed
/// (`ReorgBeyondRing`). Every other exit — a spent budget, block 0, a height
/// the ring never recorded — reports `Gap`, which says only that we
/// could not establish what happened. The pure ring is untouched; only this
/// glue does I/O.
///
/// The walk is a PATH, not a search: every block has one parent, so each step
/// is determined, and hash identity is what makes it sound to take consecutive
/// steps from different providers — a block that hashes to the requested hash
/// is that block regardless of who served it, so its `parent_hash` is the same
/// either way. Which provider answers can change whether we SEE the next step,
/// never which step is next.
///
/// `provider` is the WS-style session that detected the detachment. We trust
/// our providers: its answer is either the requested block, verified outright,
/// or it is not an answer (`Ok(None)`, a transport error, or a hash mismatch)
/// and the step falls back to the `N` configured HTTP providers in sequence —
/// `provider` itself contributes no answer; it is the suspect, and its index
/// is a WS-endpoint position that does not map onto the HTTP ring.
async fn walk_to_common_ancestor(
    provider: &DynProvider<Ethereum>,
    providers: &ProviderSettings,
    reused: Option<&[DynProvider<Ethereum>]>,
    linkage: &HeadLinkage,
    detached_parent: B256,
    child_number: u64,
    depth: u64,
) -> Result<u64, RpcError> {
    let n = providers.http_providers.len();
    if let Some(err) = provider_set_preconditions(n, reused) {
        return Err(err);
    }

    // `parent_hash` is the new chain's hash at height `parent_number`.
    let mut parent_hash = detached_parent;
    let Some(mut parent_number) = child_number.checked_sub(1) else {
        // The detached head is block 0 and has no parent to walk from.
        return Err(RpcError::Gap);
    };
    let floor = linkage.floor().unwrap_or(u64::MAX);
    // `detached_parent` is the incoming push's own claim about its parent,
    // never a header we fetched and verified. Only from the first successful
    // step onward does `parent_hash` carry a hash-confirmed value, and only
    // then may a disagreement at the floor be reported as a fact about the
    // chain rather than about the provider that told us.
    let mut confirmed_a_step = false;
    // Carries which HTTP provider last answered, so a stalling provider costs
    // this walk one timeout rather than one per step. Seeded at 0 since the
    // first step has no prior answer to inherit; left alone on a step the WS
    // `provider` answers directly, since there is no fallback outcome to
    // advance onto.
    let mut http_cursor = 0;

    for _ in 0..depth {
        if linkage.matches(parent_number, parent_hash) {
            return Ok(parent_number);
        }
        if parent_number <= floor {
            // At the floor the ring does hold a record and `matches` just
            // rejected it, so the disagreement is real — provided the hash that
            // disagreed was one we fetched. Below the floor, and on the first
            // iteration, nothing was compared that we can stand behind.
            return if parent_number == floor && confirmed_a_step {
                Err(RpcError::ReorgBeyondRing)
            } else {
                Err(RpcError::Gap)
            };
        }
        let hash = parent_hash;
        let header = match provider.get_block_by_hash(hash).await {
            // Matching hash: trusted outright, no fallback, no extra RPC.
            Ok(Some(block)) if block.header.hash == hash => Box::new(block.header),
            // Null, wrong hash, or a transport error: the WS session did not
            // answer — try the configured HTTP providers in sequence, starting
            // where the previous step's fallback left off.
            _ => {
                let (answered_index, header) = get_block_by_hash_with_http_fallback(
                    "walk_to_common_ancestor",
                    providers,
                    reused,
                    http_cursor,
                    false,
                    hash,
                    |h| h.hash == hash,
                )
                .await?;
                http_cursor = answered_index;
                header
            }
        };
        parent_hash = header.parent_hash;
        confirmed_a_step = true;
        let Some(next) = parent_number.checked_sub(1) else {
            // Walked down to block 0 without re-linking.
            return Err(RpcError::Gap);
        };
        parent_number = next;
    }
    // The budget ran out with the ring intact and no disagreement observed:
    // a statement about how far we were willing to look, not about the chain.
    Err(RpcError::Gap)
}

fn fallback_http_index(start_index: usize, attempt: usize, num_http_providers: usize) -> usize {
    (start_index + attempt) % num_http_providers
}

fn fallback_http_exhausted_error(
    from_block: u64,
    to_block: u64,
    attempted_hosts: &[String],
    last_err: &str,
) -> RpcError {
    RpcError::LogFetchError(format!(
        "HTTP fallback exhausted for blocks {}-{} after trying providers [{}]: {}",
        from_block,
        to_block,
        attempted_hosts.join(", "),
        last_err
    ))
}

/// Resolves the HTTP client for `idx`: `Some(set)` reuses an already-built
/// client from `set` (modulo-indexed, the same out-of-range safety
/// `connect_http` has); `None` falls through to `providers.connect_http(idx)`
/// — today's per-call rebuild, unchanged. The seam that lets §5's tests prove
/// reuse vs. rebuild without touching a real network.
pub(crate) fn resolve_http_provider(
    providers: &ProviderSettings,
    reused: Option<&[DynProvider<Ethereum>]>,
    idx: usize,
) -> DynProvider<Ethereum> {
    assert!(
        !providers.http_providers.is_empty(),
        "resolve_http_provider: no HTTP providers configured"
    );
    match reused {
        Some(set) => set[idx % set.len()].clone(),
        None => providers.connect_http(idx),
    }
}

async fn get_logs_with_http_fallback_retry(
    providers: &ProviderSettings,
    query_filter: &Filter,
    start_index: usize,
    from_block: u64,
    to_block: u64,
    reused: Option<&[DynProvider<Ethereum>]>,
) -> Result<(usize, Vec<alloy::rpc::types::Log>), RpcError> {
    let num_http_providers = providers.http_providers.len();
    let mut attempted_hosts: Vec<String> = Vec::with_capacity(num_http_providers);
    let mut last_err = String::new();

    for attempt in 0..num_http_providers {
        let provider_idx = fallback_http_index(start_index, attempt, num_http_providers);
        let provider_host = providers.http_settings(provider_idx).host();
        attempted_hosts.push(provider_host.clone());

        let http_provider = resolve_http_provider(providers, reused, provider_idx);
        match http_provider.get_logs(query_filter).await {
            Ok(logs) => return Ok((provider_idx, logs)),
            Err(err) => {
                last_err = err.to_string();
                warn!(
                    "HTTP fallback {} failed for blocks {}-{}: {}",
                    provider_host,
                    from_block,
                    to_block,
                    truncate_error_short(&last_err, 100)
                );
            }
        }
    }

    Err(fallback_http_exhausted_error(
        from_block,
        to_block,
        &attempted_hosts,
        &last_err,
    ))
}

/// How far a non-empty `getLogs` response actually proves the queried range
/// was covered, decided by `yield_bounds`.
enum YieldBounds {
    /// Watermark == to_block: today's behavior verbatim.
    Full,
    /// Watermark B < to_block: yield (from, B), advance B+1, defer the tail.
    Partial(u64),
    /// No returned log carries a block number: the response proves nothing —
    /// treat it exactly as an empty response (do NOT yield these logs).
    Unattributable,
}

/// Decides how much of `[.., to_block]` a non-empty log batch proves covered.
///
/// The watermark is the highest `block_number` carried by any returned log —
/// a log at block B proves the provider's index reached >= B, which also
/// vouches for the emptiness of every logless block <= B in the range. Only
/// the tail strictly above the watermark is unproven.
fn yield_bounds(logs: &[Log], to_block: u64) -> YieldBounds {
    let Some(watermark) = logs.iter().filter_map(|log| log.block_number).max() else {
        return YieldBounds::Unattributable;
    };

    // A range query cannot legally return a block above what it asked for; a
    // watermark past to_block is a provider integrity violation. Clamp rather
    // than advance the cursor past the requested range.
    if watermark >= to_block {
        YieldBounds::Full
    } else {
        YieldBounds::Partial(watermark)
    }
}

/// Outcome of the empty-batch guard for one flushed chunk, decided by
/// `handle_empty_flush`. Callers map each variant onto their existing control
/// flow (mirrored across the WS and HTTP-fallback sites in
/// `stream_heads_with_logs`).
enum EmptyFlushOutcome {
    /// Non-capped: `defer_flush()` applied. Caller breaks the `'flush` loop.
    Deferred,
    /// Capped, tip >= to_block: caller yields the verified-empty range,
    /// advances the cursor, resets the gate.
    VerifiedEmpty,
    /// Capped, `wait_for_tip` caught up: caller re-queries (continue `'flush`).
    CaughtUp,
    /// Capped, terminal stall: caller yields `ProviderStalled` and returns.
    Stalled {
        to_block: u64,
        reported_tip: u64,
        stalled_cycles: u32,
    },
    /// Tip re-poll failed inside `wait_for_tip`: caller logs and switches provider.
    RepollFailed(String),
    /// Initial tip fetch failed: caller records the error and switches provider.
    TipFetchFailed(String),
}

/// Decides how to handle an empty log batch for one flushed chunk.
///
/// A non-capped chunk defers rather than confirming: a rare false-empty
/// (provider serving `[]` past its own tip) self-heals when the next head's
/// flush re-covers the same span from the unmoved cursor, so confirming every
/// quiet window buys nothing. A span-capped chunk (`to_block - from_block + 1
/// == MAX_BLOCKS_PER_WS_REQUEST`) always confirms against the provider's
/// reported tip — this bounds how far the cursor can advance unverified and is
/// what still catches a frozen or lying backend (the Base-outage failure
/// class), now at the span cap instead of per window.
async fn handle_empty_flush<F, Fut, E>(
    coalescer: &mut HeadCoalescer,
    gate: &mut TipGate,
    providers: &ProviderSettings,
    host: &str,
    to_block: u64,
    span_capped: bool,
    get_tip: F,
) -> EmptyFlushOutcome
where
    F: Fn() -> Fut,
    Fut: Future<Output = Result<u64, E>>,
    E: std::fmt::Display,
{
    if !span_capped {
        coalescer.defer_flush();
        return EmptyFlushOutcome::Deferred;
    }

    let reported_tip = match get_tip().await {
        Ok(tip) => tip,
        Err(e) => return EmptyFlushOutcome::TipFetchFailed(e.to_string()),
    };
    coalescer.record_tip(reported_tip);

    if next_cursor_after_batch(to_block, true, reported_tip).is_err() {
        match wait_for_tip(to_block, reported_tip, gate, providers, host, get_tip).await {
            TipWaitOutcome::CaughtUp => EmptyFlushOutcome::CaughtUp,
            TipWaitOutcome::Terminal {
                to_block,
                reported_tip,
                stalled_cycles,
            } => EmptyFlushOutcome::Stalled {
                to_block,
                reported_tip,
                stalled_cycles,
            },
            TipWaitOutcome::RepollFailed(err) => EmptyFlushOutcome::RepollFailed(err),
        }
    } else {
        EmptyFlushOutcome::VerifiedEmpty
    }
}

/// The head await's three distinguishable outcomes, once bounded by
/// [`IDLE_HEAD_AWAIT_SECS`].
enum IdleHeadAwait {
    /// A header arrived within the bound.
    Header(Box<Header>),
    /// The stream ended (`None` from the underlying stream).
    StreamEnded,
    /// No header arrived before the bound elapsed.
    Expired,
}

/// Awaits the next head, bounded by [`IDLE_HEAD_AWAIT_SECS`] — the testable
/// seam for the `else` arm of the head-await select, which otherwise has no
/// way to reach a hermetic test without a live WS connection.
async fn await_head_within_idle_bound<S>(s: &mut S) -> IdleHeadAwait
where
    S: Stream<Item = Header> + Unpin,
{
    match tokio::time::timeout(Duration::from_secs(IDLE_HEAD_AWAIT_SECS), s.next()).await {
        Ok(Some(header)) => IdleHeadAwait::Header(Box::new(header)),
        Ok(None) => IdleHeadAwait::StreamEnded,
        Err(_) => IdleHeadAwait::Expired,
    }
}

/// Counts consecutive `IdleHeadAwait::Expired` events across provider
/// rotations, so a full quiet rotation — every configured WS provider tried
/// in turn, none delivering a head — can be told apart from one provider's
/// ordinary silence. Any received header resets the count, including one
/// below the cursor: it is evidence the chain is not quiet, regardless of
/// what the coalescer does with it.
struct IdleRotationCounter {
    consecutive_expiries: usize,
}

/// Decision returned by `IdleRotationCounter::expire` for one idle-bound
/// expiry.
enum IdleRotation {
    /// Fewer than `threshold` consecutive expiries — keep rotating.
    Continue,
    /// `threshold` consecutive expiries with no header in between.
    AllIdle,
}

impl IdleRotationCounter {
    fn new() -> Self {
        Self {
            consecutive_expiries: 0,
        }
    }

    fn reset(&mut self) {
        self.consecutive_expiries = 0;
    }

    /// Called once per idle-bound expiry, before rotating to the next
    /// provider. `threshold` is the number of configured WS providers — a
    /// single-provider deployment reaches `AllIdle` on its first expiry,
    /// converting what would otherwise be a silent self-reconnect loop into
    /// a visible, consumer-policied signal.
    fn expire(&mut self, threshold: usize) -> IdleRotation {
        self.consecutive_expiries += 1;
        if self.consecutive_expiries >= threshold.max(1) {
            IdleRotation::AllIdle
        } else {
            IdleRotation::Continue
        }
    }
}

async fn stream_heads_provider(
    provider: &DynProvider<Ethereum>,
    provider_host: &str,
) -> impl Stream<Item = Header> + Send {
    stream! {
        let head_stream = provider.subscribe_blocks().await;

        match head_stream {
            Ok(heads) => {
                debug!("WebSocket connected, streaming headers...");
                let mut s = heads.into_stream();
                while let Some(header) = s.next().await {
                    yield header;
                }
            }
            Err(e) => {
                warn!(
                    "Failed to subscribe to blocks on {}: {} - retrying",
                    provider_host,
                    truncate_error_short(e, 100)
                );
            }
        }
    }
}

/// Yield contract: empty ranges are not yielded per window. A quiet stretch
/// yields nothing until either a non-empty flush (which covers the whole span
/// back to the unmoved cursor) or a span-cap tip-verification (which yields
/// the verified-empty `MAX_BLOCKS_PER_WS_REQUEST`-block chunk). The
/// RangeTooWide HTTP-fallback path is the exception — it still confirms every
/// empty response, per-window. Consumers' cursor persistence coarsens
/// accordingly: expect progress in bursts, not one update per coalesce window.
///
/// A yielded range's `block_end` is the highest block PROVEN by the response
/// — a returned log's block number — which may be below the queried
/// `to_block` when the serving backend's index lagged behind the requested
/// range. The unproven remainder above `block_end` is re-covered like a
/// deferred empty flush: it stays in front of the cursor until the next
/// head's flush picks it up.
/// See [`stream_heads_with_logs`]; additionally records scan progress into `progress` when
/// `Some`, so a consumer can read [`ScanProgress::scanned_to`] / [`ScanProgress::observed_tip`]
/// on demand. `progress: None` is byte-identical to `stream_heads_with_logs`. The returned
/// stream is `Send` and may be spawned onto an executor (e.g. `tokio::spawn`).
pub async fn stream_heads_with_logs_with_progress(
    providers: &ProviderSettings,
    filter: Option<&Filter>,
    progress: Option<&ScanProgress>,
) -> impl Stream<Item = Result<LogRange, RpcError>> + Send {
    let num_providers = providers.wss_endpoints.len();
    let progress = progress.cloned();

    stream! {
        // Initialize per-provider error tracking (same pattern as backfill)
        let mut provider_trackers: Vec<ProviderErrorTracker> = (0..num_providers)
            .map(|i| {
                let host = providers.wss_endpoints[i]
                    .host_str()
                    .unwrap_or("unknown")
                    .to_string();
                ProviderErrorTracker::new(host)
            })
            .collect();
        // One persistent HTTP client per configured provider, built once for this
        // stream invocation and reused across every flush and provider-fallback
        // attempt in it — not rebuilt per provider switch or per flush.
        let reused_http_clients = providers.build_reused_http_clients();

        let mut provider_index = 0;
        let mut coalescer = HeadCoalescer::new(
            filter.and_then(|f| f.get_from_block()),
            Duration::from_millis(providers.live_head_coalesce_window_ms),
        )
        .with_progress(progress);
        // Live-tip reorg detector. `recovery_window_depth == 0` (every non-mainnet-live
        // consumer) leaves `observe` inert, so this is a no-op on those paths.
        let mut linkage = HeadLinkage::new(providers.recovery_window_depth);
        let mut gate = TipGate::new();
        // Scoped to the whole stream, not one provider session: a full
        // quiet rotation is defined across provider switches.
        let mut idle_rotation = IdleRotationCounter::new();

        loop {
            // Find the next non-suspended provider (same pattern as backfill)
            let active_provider = find_active_provider(&mut provider_trackers, provider_index);
            let Some(idx) = active_provider else {
                yield Err(RpcError::AllProvidersSuspended(format!(
                    "All {} WebSocket providers suspended. Unable to continue streaming.",
                    num_providers
                )));
                return;
            };
            provider_index = idx;

            let provider = match providers.connect_ws(provider_index).await {
                Ok(p) => {
                    provider_trackers[provider_index].record_success();
                    p
                }
                Err(e) => {
                    let suspended = provider_trackers[provider_index].record_error();
                    let backoff = provider_trackers[provider_index].backoff_duration();

                    if suspended {
                        warn!(
                            "WebSocket provider {} suspended after connection failure: {}",
                            provider_trackers[provider_index].identifier(),
                            truncate_error_short(&e, 100)
                        );
                    } else {
                        warn!(
                            "Failed to connect to WebSocket {}: {} - retrying in {:?}",
                            provider_trackers[provider_index].identifier(),
                            truncate_error_short(&e, 100),
                            backoff
                        );
                        sleep(backoff).await;
                    }
                    provider_index = (provider_index + 1) % num_providers;
                    continue;
                }
            };

            // A new provider session must not inherit the previous session's stall
            // state: a stale last_tip makes the new provider's first observation count
            // as a stall instead of a seed (audit F1, early ProviderStalled).
            gate.reset();

            let provider_host = provider_trackers[provider_index].identifier().to_string();
            let s = stream_heads_provider(&provider, &provider_host).await;
            pin_mut!(s);
            let mut should_switch_provider = false;

            loop {
                if coalescer.should_flush(Instant::now()) {
                    // Flush from the cursor through the latest seen head in bounded chunks.
                    'flush: while let Some((from_block, pending_to_block)) = coalescer.pending_range() {
                        let to_block =
                            std::cmp::min(from_block + MAX_BLOCKS_PER_WS_REQUEST - 1, pending_to_block);

                        // When reorg detection is active fetch logs pinned to the canonical
                        // hash so a same-number orphaned block on a stale provider cannot
                        // contaminate the result. When the ring is missing a hash — a boot
                        // gap, or a flush that has failed repeatedly while heads kept
                        // arriving — `flush_window_range` self-heals by walking backward
                        // from the latest ring entry — never spinning, never falling back
                        // to a by-number fetch inside the window.
                        if linkage.enabled() {
                            // The label's fallback host tracks the `provider_index`
                            // the flush is called with below — `0`, the first
                            // configured provider. Naming both providers makes a
                            // timeout attributable without asserting which stalled.
                            let flush_timeout_label =
                                flush_timeout_label(providers, &provider_host);
                            match bound_flush_time(
                                providers.flush_max_total_secs,
                                &flush_timeout_label,
                                flush_window_range(
                                    &mut linkage,
                                    &mut coalescer,
                                    providers,
                                    filter,
                                    0,
                                    Some(&reused_http_clients),
                                ),
                            )
                            .await
                            {
                                Ok(ranges) => {
                                    for range in ranges {
                                        provider_trackers[provider_index].record_success();
                                        yield Ok(range);
                                    }
                                }
                                // Both arms are bare control flow on purpose: the
                                // generator reaches its provider through
                                // `connect_ws`, which needs a live WebSocket, so
                                // nothing hermetic can drive this dispatch and
                                // prove the two arms are not transposed.
                                // Everything testable — the classification and
                                // the log line — is therefore kept out of the
                                // arms, leaving the untestable remainder as small
                                // as it can be. Extracting a seam is `TODO G.15`.
                                Err(e) => {
                                    let failure = classify_flush_failure(&e);
                                    warn!("{}", flush_failure_log_line(&e, failure));
                                    match failure {
                                        FlushFailure::EndStream => {
                                            yield Err(e);
                                            return;
                                        }
                                        FlushFailure::SwitchProvider => {
                                            should_switch_provider = true;
                                            break 'flush;
                                        }
                                    }
                                }
                            }
                            continue;
                        }

                        let query_filter = filter
                            .cloned()
                            .unwrap_or_else(Filter::new)
                            .from_block(from_block)
                            .to_block(to_block);

                        let logs = provider.get_logs(&query_filter).await;

                        match logs {
                            Ok(logs) => {
                                provider_trackers[provider_index].record_success();

                                // A non-empty response only proves coverage up to the highest
                                // block number any returned log carries (the watermark); Partial
                                // means the tail above it is unproven and must not be crossed.
                                let watermark_bounds =
                                    (!logs.is_empty()).then(|| yield_bounds(&logs, to_block));

                                if let Some(YieldBounds::Partial(watermark)) = watermark_bounds {
                                    // The by-number path: this range was fetched by block
                                    // number and never learned its top block's hash.
                                    yield Ok(LogRange {
                                        from_block,
                                        to_block: watermark,
                                        logs,
                                        tip_hash: None,
                                    });
                                    coalescer.advance_cursor(watermark + 1);
                                    gate.reset();
                                    // Unproven tail [watermark+1, to_block] stays in front of the
                                    // cursor; the next head's flush re-covers it, same as an
                                    // empty flush's deferred-empty pattern.
                                    coalescer.defer_flush();
                                    break 'flush;
                                }

                                // Empty batches are ambiguous: they look identical whether the
                                // range is genuinely event-free or the provider silently returned
                                // [] for blocks past its actual tip. A non-capped chunk defers
                                // instead of confirming (see `handle_empty_flush`); a span-capped
                                // chunk still verifies against the WS provider's reported tip
                                // before advancing the cursor. Unattributable responses (logs
                                // present but none carry a block number) prove nothing and enter
                                // this same guard; the received logs are dropped, not yielded.
                                let treat_as_empty =
                                    !matches!(watermark_bounds, Some(YieldBounds::Full));
                                if treat_as_empty {
                                    let span_capped =
                                        to_block - from_block + 1 == MAX_BLOCKS_PER_WS_REQUEST;
                                    match handle_empty_flush(
                                        &mut coalescer,
                                        &mut gate,
                                        providers,
                                        &provider_host,
                                        to_block,
                                        span_capped,
                                        || provider.get_block_number(),
                                    )
                                    .await
                                    {
                                        EmptyFlushOutcome::Deferred => break 'flush,
                                        EmptyFlushOutcome::VerifiedEmpty => {}
                                        EmptyFlushOutcome::CaughtUp => continue 'flush,
                                        EmptyFlushOutcome::Stalled {
                                            to_block,
                                            reported_tip,
                                            stalled_cycles,
                                        } => {
                                            yield Err(RpcError::ProviderStalled {
                                                to_block,
                                                reported_tip,
                                                stalled_cycles,
                                            });
                                            return;
                                        }
                                        EmptyFlushOutcome::RepollFailed(err) => {
                                            let suspended = provider_trackers
                                                [provider_index]
                                                .record_error();
                                            if suspended {
                                                warn!(
                                                    "WebSocket provider {} suspended after tip re-poll failed during tip-wait for blocks {}-{}: {}",
                                                    provider_trackers[provider_index].identifier(),
                                                    from_block,
                                                    to_block,
                                                    truncate_error_short(&err, 100),
                                                );
                                            } else {
                                                let backoff = provider_trackers
                                                    [provider_index]
                                                    .backoff_duration();
                                                warn!(
                                                    "Tip re-poll failed during wait for blocks {}-{} from {}: {} - backing off {:?}",
                                                    from_block,
                                                    to_block,
                                                    provider_trackers[provider_index].identifier(),
                                                    truncate_error_short(&err, 100),
                                                    backoff
                                                );
                                                sleep(backoff).await;
                                            }
                                            should_switch_provider = true;
                                            break 'flush;
                                        }
                                        EmptyFlushOutcome::TipFetchFailed(err_str) => {
                                            let suspended =
                                                provider_trackers[provider_index].record_error();
                                            if suspended {
                                                warn!(
                                                    "WebSocket provider {} suspended after tip fetch failed during empty-batch guard for blocks {}-{}: {}",
                                                    provider_trackers[provider_index].identifier(),
                                                    from_block, to_block,
                                                    truncate_error_short(&err_str, 100)
                                                );
                                            } else {
                                                let backoff = provider_trackers[provider_index].backoff_duration();
                                                warn!(
                                                    "Tip fetch failed during empty-batch guard for blocks {}-{} from {}: {} - backing off {:?}",
                                                    from_block, to_block,
                                                    provider_trackers[provider_index].identifier(),
                                                    truncate_error_short(&err_str, 100),
                                                    backoff
                                                );
                                                sleep(backoff).await;
                                            }
                                            should_switch_provider = true;
                                            break 'flush;
                                        }
                                    }
                                }

                                let logs = if treat_as_empty { Vec::new() } else { logs };
                                yield Ok(LogRange {
                                    from_block,
                                    to_block,
                                    logs,
                                    tip_hash: None,
                                });
                                coalescer.advance_cursor(to_block + 1);
                                gate.reset();
                            }
                            Err(e) => {
                                let error_msg = e.to_string();
                                let error_category = ErrorCategory::from_error_msg(&error_msg);

                                match error_category {
                                    ErrorCategory::RangeTooWide => {
                                        // Fall back to HTTP provider for this batch
                                        warn!(
                                            "Range too wide for blocks {}-{}, falling back to HTTP RPC: {}",
                                            from_block, to_block, truncate_error_short(&error_msg, 100)
                                        );

                                        match get_logs_with_http_fallback_retry(
                                            providers,
                                            &query_filter,
                                            0,
                                            from_block,
                                            to_block,
                                            Some(&reused_http_clients),
                                        )
                                        .await
                                        {
                                            Ok((http_provider_idx, logs)) => {
                                                provider_trackers[provider_index].record_success();

                                                // Same watermark bound as the WS site: a non-empty
                                                // response only proves coverage up to the highest
                                                // block number a returned log carries. Unlike the
                                                // empty case below, Partial DOES defer here — it
                                                // already advanced the cursor to watermark+1 before
                                                // deferring, so each retry makes forward progress
                                                // and the WS-error -> fallback double-call objection
                                                // (see the comment below) does not apply.
                                                let watermark_bounds = (!logs.is_empty())
                                                    .then(|| yield_bounds(&logs, to_block));

                                                if let Some(YieldBounds::Partial(watermark)) =
                                                    watermark_bounds
                                                {
                                                    // By-number HTTP fallback: no
                                                    // canonical hash was learned.
                                                    yield Ok(LogRange {
                                                        from_block,
                                                        to_block: watermark,
                                                        logs,
                                                        tip_hash: None,
                                                    });
                                                    coalescer.advance_cursor(watermark + 1);
                                                    gate.reset();
                                                    coalescer.defer_flush();
                                                    break 'flush;
                                                }

                                                // Empty fallback responses are ambiguous — a lagging
                                                // HTTP provider can legitimately return [] for blocks
                                                // past its own tip. Verify against the HTTP provider
                                                // that served this response, not the WS provider.
                                                // Lazy does NOT apply here: a RangeTooWide error
                                                // followed by an empty fallback is already
                                                // contradictory (WS claimed too many results, HTTP
                                                // returned zero), and deferring would re-trigger the
                                                // WS-error -> fallback double-call on every head
                                                // until the span cap — the opposite of the saving.
                                                // Unattributable responses (logs present but none
                                                // carry a block number) prove nothing and enter this
                                                // same eager guard; the received logs are dropped.
                                                let treat_as_empty = !matches!(
                                                    watermark_bounds,
                                                    Some(YieldBounds::Full)
                                                );
                                                if treat_as_empty {
                                                    let http_provider = providers.connect_http(http_provider_idx);
                                                    let http_host = providers.http_settings(http_provider_idx).host();
                                                    match handle_empty_flush(
                                                        &mut coalescer,
                                                        &mut gate,
                                                        providers,
                                                        &http_host,
                                                        to_block,
                                                        true,
                                                        || http_provider.get_block_number(),
                                                    )
                                                    .await
                                                    {
                                                        EmptyFlushOutcome::Deferred => {
                                                            unreachable!(
                                                                "span_capped: true never defers"
                                                            )
                                                        }
                                                        EmptyFlushOutcome::VerifiedEmpty => {}
                                                        EmptyFlushOutcome::CaughtUp => {
                                                            continue 'flush
                                                        }
                                                        EmptyFlushOutcome::Stalled {
                                                            to_block,
                                                            reported_tip,
                                                            stalled_cycles,
                                                        } => {
                                                            yield Err(
                                                                RpcError::ProviderStalled {
                                                                    to_block,
                                                                    reported_tip,
                                                                    stalled_cycles,
                                                                },
                                                            );
                                                            return;
                                                        }
                                                        EmptyFlushOutcome::RepollFailed(err) => {
                                                            warn!(
                                                                "HTTP fallback {} tip re-poll failed during tip-wait for blocks {}-{}: {}",
                                                                http_host,
                                                                from_block,
                                                                to_block,
                                                                truncate_error_short(&err, 100),
                                                            );
                                                            should_switch_provider = true;
                                                            break 'flush;
                                                        }
                                                        EmptyFlushOutcome::TipFetchFailed(err) => {
                                                            warn!(
                                                                "HTTP fallback {} tip fetch failed during empty-batch guard for blocks {}-{}: {}",
                                                                http_host, from_block, to_block,
                                                                truncate_error_short(&err, 100)
                                                            );
                                                            should_switch_provider = true;
                                                            break 'flush;
                                                        }
                                                    }
                                                }

                                                let logs = if treat_as_empty {
                                                    Vec::new()
                                                } else {
                                                    logs
                                                };
                                                yield Ok(LogRange {
                                                    from_block,
                                                    to_block,
                                                    logs,
                                                    tip_hash: None,
                                                });
                                                coalescer.advance_cursor(to_block + 1);
                                                gate.reset();
                                            }
                                            Err(http_err) => {
                                                warn!(
                                                    "HTTP fallback retry exhausted for blocks {}-{}: {}",
                                                    from_block,
                                                    to_block,
                                                    truncate_error_short(&http_err, 100)
                                                );
                                                should_switch_provider = true;
                                                break;
                                            }
                                        }
                                    }
                                    ErrorCategory::RateLimit => {
                                        // Rate limit: apply backoff but stay on same provider
                                        provider_trackers[provider_index].record_error();
                                        let backoff = provider_trackers[provider_index].backoff_duration();
                                        warn!(
                                            "Rate limit hit on WS provider {} for blocks {}-{}: {} - backing off {:?}",
                                            provider_trackers[provider_index].identifier(),
                                            from_block, to_block,
                                            truncate_error_short(&error_msg, 100),
                                            backoff
                                        );
                                        sleep(backoff).await;
                                        // Retry same block range after backoff
                                        continue;
                                    }
                                    ErrorCategory::Connection | ErrorCategory::Other => {
                                        // Connection error or unknown: record error and switch provider
                                        let suspended = provider_trackers[provider_index].record_error();

                                        if suspended {
                                            warn!(
                                                "WebSocket provider {} suspended after error on blocks {}-{}: {}",
                                                provider_trackers[provider_index].identifier(),
                                                from_block, to_block,
                                                truncate_error_short(&error_msg, 100)
                                            );
                                        } else {
                                            let backoff = provider_trackers[provider_index].backoff_duration();
                                            warn!(
                                                "Error fetching logs for blocks {}-{} from {}: {} - backing off {:?}",
                                                from_block, to_block,
                                                provider_trackers[provider_index].identifier(),
                                                truncate_error_short(&error_msg, 100),
                                                backoff
                                            );
                                            sleep(backoff).await;
                                        }
                                        should_switch_provider = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if should_switch_provider {
                        break;
                    }

                    continue;
                }

                let maybe_header = if let Some(deadline) = coalescer.flush_deadline() {
                    tokio::select! {
                        maybe_header = s.next() => maybe_header,
                        _ = sleep_until(deadline) => {
                            continue;
                        }
                    }
                } else {
                    match await_head_within_idle_bound(&mut s).await {
                        IdleHeadAwait::Header(header) => Some(*header),
                        IdleHeadAwait::StreamEnded => None,
                        IdleHeadAwait::Expired => match idle_rotation.expire(num_providers) {
                            IdleRotation::Continue => {
                                warn!(
                                    "No head from {} in {}s - idle bound expired, rotating provider",
                                    provider_trackers[provider_index].identifier(),
                                    IDLE_HEAD_AWAIT_SECS
                                );
                                should_switch_provider = true;
                                break;
                            }
                            IdleRotation::AllIdle => {
                                warn!(
                                    "No head from any of {} configured provider(s) within {}s - a \
                                     full quiet rotation",
                                    num_providers, IDLE_HEAD_AWAIT_SECS
                                );
                                yield Err(RpcError::AllProvidersIdle {
                                    providers_tried: num_providers,
                                    idle_secs: IDLE_HEAD_AWAIT_SECS,
                                });
                                return;
                            }
                        },
                    }
                };

                match maybe_header {
                    Some(header) => {
                        idle_rotation.reset();
                        let now = Instant::now();
                        let head_number = header.number;
                        if !coalescer.observe_head(head_number, now) {
                            let from_block = coalescer.block_cursor().unwrap_or(head_number);
                            warn!(
                                "Skipping header {} as it's before the cursor {}",
                                head_number, from_block
                            );
                        }

                        // Reorg detection runs alongside the coalescer's number-based
                        // flush — a parallel `(number, hash, parent_hash)` linkage check.
                        // Disabled (depth 0) ⇒ `observe` is inert and this is a no-op.
                        // On a reorg we emit and end the stream; the consumer decides
                        // resume-from-ancestor (P3 rollback) vs terminate (P2).
                        match linkage.observe(head_number, header.hash, header.parent_hash) {
                            LinkOutcome::Linked => {}
                            LinkOutcome::Reorg { common_ancestor } => {
                                warn!(
                                    "reorg at head {}: common ancestor {} — ending stream for consumer recovery",
                                    head_number, common_ancestor
                                );
                                yield Err(RpcError::Reorg { common_ancestor });
                                return;
                            }
                            LinkOutcome::Gap { ring_tip } => {
                                // The event a consumer's log-metric filter keys
                                // on. Its three fields are the observed facts
                                // the error deliberately does not carry, read
                                // from the ring's own tip and the head that
                                // arrived.
                                warn!(
                                    event = live_head_gap_event(),
                                    ring_tip,
                                    head = head_number,
                                    gap = head_number.saturating_sub(ring_tip),
                                    "live heads skipped ahead of the recovery ring — ending stream for consumer recovery"
                                );
                                yield Err(RpcError::Gap);
                                return;
                            }
                            LinkOutcome::Detached {
                                parent_hash,
                                child_number,
                            } => {
                                // The parent is inside the ring and differs, so
                                // there is fork evidence to resolve. Only an
                                // `Ok` here names an ancestor; the walk's own
                                // errors already distinguish what they observed
                                // from what they merely failed to establish.
                                match walk_to_common_ancestor(
                                    &provider,
                                    providers,
                                    Some(&reused_http_clients),
                                    &linkage,
                                    parent_hash,
                                    child_number,
                                    providers.recovery_window_depth,
                                )
                                .await
                                {
                                    Ok(ancestor) => {
                                        warn!(
                                            "reorg at head {} (walked new chain): common ancestor {} — ending stream",
                                            head_number, ancestor
                                        );
                                        yield Err(RpcError::Reorg { common_ancestor: ancestor });
                                        return;
                                    }
                                    Err(err) => {
                                        match walk_failure_event(&err) {
                                            Some(event_name) => warn!(
                                                event = event_name,
                                                head = head_number,
                                                "reorg walk at head {head_number} found a canonical hash disagreement beyond the recovery ring — ending stream for consumer recovery"
                                            ),
                                            None => warn!(
                                                "reorg walk at head {} ended the stream: {}",
                                                head_number,
                                                truncate_error(&err)
                                            ),
                                        }
                                        yield Err(err);
                                        return;
                                    }
                                }
                            }
                            LinkOutcome::NoRecordedParent => {
                                warn!(
                                    "head {} has no canonical record at its parent's height — ending stream for consumer recovery",
                                    head_number
                                );
                                yield Err(RpcError::Gap);
                                return;
                            }
                        }
                    }
                    None => break,
                }
            }

            // Stream ended (connection lost) - record as error and switch provider
            if !should_switch_provider {
                // Stream ended naturally without explicit error
                provider_trackers[provider_index].record_error();
                let backoff = provider_trackers[provider_index].backoff_duration();
                warn!(
                    "WS connection to {} lost or stream ended - reconnecting in {:?}",
                    provider_trackers[provider_index].identifier(),
                    backoff
                );
                sleep(backoff).await;
            }

            // Move to next provider for round-robin (same pattern as backfill)
            provider_index = (provider_index + 1) % num_providers;
        }
    }
}

/// The returned stream is `Send` and may be spawned onto an executor (e.g. `tokio::spawn`).
pub async fn stream_heads_with_logs(
    providers: &ProviderSettings,
    filter: Option<&Filter>,
) -> impl Stream<Item = Result<LogRange, RpcError>> + Send {
    stream_heads_with_logs_with_progress(providers, filter, None).await
}

/// Round-robin `providers` for a block number, failing over to the next
/// configured provider on any error rather than ending the call. `fetch`
/// extracts the target block number from a connected provider; its
/// `Err(String)` covers both a transport failure and a provider that
/// answered without one but produced no usable result — either counts as
/// that provider's failed attempt and rotates. `empty_set_phrase` and
/// `attempt_phrase` name what's being fetched, in the empty-provider-set
/// guard and in the per-attempt/exhaustion messages respectively.
///
/// Eleven attempts (index 0..=10), `index % num_providers` rotation,
/// progressive backoff `(5 * index).min(50)` seconds between attempts:
/// `last_block`'s ladder, shared here so every caller fails over the same
/// way.
async fn poll_providers_for_block_number<F, Fut>(
    providers: &ProviderSettings,
    empty_set_phrase: &str,
    attempt_phrase: &str,
    fetch: F,
) -> Result<u64, RpcError>
where
    F: Fn(DynProvider<Ethereum>) -> Fut,
    Fut: Future<Output = Result<u64, String>>,
{
    let num_providers = providers.http_providers.len();
    if num_providers == 0 {
        return Err(RpcError::ConnectionError(format!(
            "No HTTP providers configured for {empty_set_phrase}"
        )));
    }

    let mut index: usize = 0;
    loop {
        // Round-robin provider selection so the fetch can fail over.
        let provider_index = index % num_providers;
        let provider = providers.connect_http(provider_index);
        match fetch(provider).await {
            Ok(block_number) => return Ok(block_number),
            Err(e) => {
                let provider_host = providers.http_settings(provider_index).host();
                if index >= 10 {
                    return Err(RpcError::ConnectionError(format!(
                        "Failed to fetch {attempt_phrase} after {} attempts from HTTP provider {}: {}",
                        index, provider_host, e
                    )));
                }
                index += 1;
                warn!(
                    "Failed to fetch {attempt_phrase} from HTTP provider {} (index {}) - retrying",
                    provider_host, provider_index
                );
                let progressive_sleep = (5 * index).min(50) as u64;
                sleep(Duration::from_secs(progressive_sleep)).await;
            }
        }
    }
}

pub async fn last_block(providers: &ProviderSettings) -> Result<u64, RpcError> {
    poll_providers_for_block_number(
        providers,
        "latest block fetch",
        "latest block number",
        |provider| async move { provider.get_block_number().await.map_err(|e| e.to_string()) },
    )
    .await
}

/// One-shot gate for the capture-policy announcement, one `Once` per policy
/// variant so `Latest`, `Lag`, and `Finalized` are silenced independently.
struct CapturePolicyNotice {
    latest: Once,
    lag: Once,
    finalized: Once,
}

impl CapturePolicyNotice {
    const fn new() -> Self {
        Self {
            latest: Once::new(),
            lag: Once::new(),
            finalized: Once::new(),
        }
    }

    /// The message to log the FIRST time this policy VARIANT is resolved in this process;
    /// `None` on every later call for that variant. Gating is per-variant, not per-value: a
    /// process resolving `Lag(64)` then later `Lag(200)` announces only the first — there is no
    /// real-process case where the configured target changes value mid-run, so this is
    /// deliberately the simpler of the two designs. `Latest`, `Lag`, and `Finalized` each have
    /// their own gate, so a process that resolves more than one variant (e.g. a config change
    /// between restarts within one long-lived process) announces each variant once.
    fn first_message(&self, target: CaptureTarget, block: u64) -> Option<String> {
        let gate = match target {
            CaptureTarget::Latest => &self.latest,
            CaptureTarget::Lag(_) => &self.lag,
            CaptureTarget::Finalized => &self.finalized,
        };
        let mut won = false;
        gate.call_once(|| won = true);
        if !won {
            return None;
        }
        Some(match target {
            CaptureTarget::Latest => format!(
                "ethl capture target is `Latest` (block {}): capturing to the raw chain \
                 tip with NO reorg protection — a reorg can rewrite recently captured \
                 blocks. Reorg-prone chains should opt into `Lag`/`Finalized`.",
                block,
            ),
            CaptureTarget::Lag(n) => format!(
                "ethl DEEP LAG ACTIVE (reorg-safety): capturing to tip - {} = block {}.\n\
                 This build AVOIDS reorgs by lagging; events within {} blocks of tip are DELAYED.",
                n, block, n,
            ),
            CaptureTarget::Finalized => format!(
                "ethl DEEP LAG ACTIVE (reorg-safety): capturing to `finalized` block {}.\n\
                 (~2 epochs ≈ 64 blocks ≈ 13 min behind chain tip).\n\
                 This build AVOIDS reorgs by lagging; events within ~64 blocks of tip are DELAYED.",
                block
            ),
        })
    }
}

static CAPTURE_POLICY_NOTICE: CapturePolicyNotice = CapturePolicyNotice::new();

/// Resolve the block number to use as the capture target based on `settings.capture_target`.
///
/// - `Latest` → current chain tip (existing behavior).
/// - `Lag(n)` → tip saturating_sub n.
/// - `Finalized` → the `finalized` tagged block, failing over across every
///   configured provider; `Err` only once every attempt is spent.
///
/// Emits a one-time `warn!` per capture policy variant, for every variant
/// including `Latest`, announcing the capture decision once per process.
pub async fn resolve_capture_target(settings: &ProviderSettings) -> Result<u64, RpcError> {
    match settings.capture_target {
        CaptureTarget::Latest => {
            let tip = last_block(settings).await?;
            if let Some(message) = CAPTURE_POLICY_NOTICE.first_message(settings.capture_target, tip)
            {
                warn!("{message}");
            }
            Ok(tip)
        }
        CaptureTarget::Lag(n) => {
            let tip = last_block(settings).await?;
            let target_block = tip.saturating_sub(n);
            if let Some(message) =
                CAPTURE_POLICY_NOTICE.first_message(settings.capture_target, target_block)
            {
                warn!("{message}");
            }
            Ok(target_block)
        }
        CaptureTarget::Finalized => {
            let finalized = poll_providers_for_block_number(
                settings,
                "finalized block fetch",
                "finalized block number",
                |provider| async move {
                    let result = provider
                        .get_block_by_number(BlockNumberOrTag::Finalized)
                        .await
                        .map_err(|e| e.to_string())?;
                    result.map(|block| block.header.number).ok_or_else(|| {
                        "Provider returned no finalized block; cannot determine safe capture target. \
                         Ensure the provider supports the `finalized` tag (mainnet only)."
                            .to_string()
                    })
                },
            )
            .await?;
            if let Some(message) =
                CAPTURE_POLICY_NOTICE.first_message(settings.capture_target, finalized)
            {
                warn!("{message}");
            }
            Ok(finalized)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        CapturePolicyNotice, EmptyFlushOutcome, FlushFailure, HeadCoalescer, HeadLinkage,
        IDLE_HEAD_AWAIT_SECS, IdleHeadAwait, IdleRotation, IdleRotationCounter, LinkOutcome,
        MAX_BLOCKS_PER_WS_REQUEST, REORG_RING_TOP_UP_STEPS, RpcError, SELF_HEAL_WALK_MAX_BLOCKS,
        TipGate, YieldBounds, await_head_within_idle_bound, bound_flush_time,
        classify_flush_failure, collect_window_hashes, fallback_http_exhausted_error,
        fallback_http_index, fetch_concurrently, fetch_logs_by_hash_range, flush_failure_log_line,
        flush_timeout_label, flush_window_range, handle_empty_flush, live_head_gap_event,
        live_head_reorg_beyond_ring_event, resolve_http_provider, sort_ranges_ascending,
        walk_failure_event, walk_to_common_ancestor, yield_bounds,
    };
    use crate::rpc::LogRange;
    use crate::rpc::config::{CaptureTarget, HttpRpcSettings, ProviderSettings};
    use alloy::network::Ethereum;
    use alloy::primitives::B256;
    use alloy::providers::{DynProvider, Provider, ProviderBuilder};
    use alloy::rpc::types::{Header, Log};
    use alloy::transports::mock::Asserter;
    use std::time::Duration;
    use tokio::time::Instant;

    /// Coalesce window for tests that previously anchored timing assertions on
    /// the module's `LIVE_HEAD_COALESCE_WINDOW` const, before it became the
    /// per-instance `HeadCoalescer::window` field.
    const WINDOW: Duration = Duration::from_millis(500);

    /// Distinct synthetic block hash; `byte` keeps old/new chains separable.
    fn hb(byte: u8) -> B256 {
        B256::repeat_byte(byte)
    }

    #[test]
    fn fallback_http_index_wraps_round_robin() {
        assert_eq!(fallback_http_index(0, 0, 3), 0);
        assert_eq!(fallback_http_index(0, 1, 3), 1);
        assert_eq!(fallback_http_index(0, 2, 3), 2);
        assert_eq!(fallback_http_index(0, 3, 3), 0);
        assert_eq!(fallback_http_index(2, 1, 3), 0);
    }

    #[test]
    fn fallback_http_exhausted_error_includes_hosts() {
        let err = fallback_http_exhausted_error(
            100,
            120,
            &["rpc.ankr.com".to_string(), "mainnet.infura.io".to_string()],
            "timeout",
        )
        .to_string();
        assert!(err.contains("rpc.ankr.com"));
        assert!(err.contains("mainnet.infura.io"));
        assert!(err.contains("timeout"));
    }

    #[test]
    fn head_coalescer_ignores_stale_heads_before_cursor() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(42), WINDOW);

        assert!(!coalescer.observe_head(41, now));
        assert_eq!(coalescer.pending_range(), None);
        assert_eq!(coalescer.flush_deadline(), None);
    }

    #[test]
    fn head_coalescer_keeps_first_flush_deadline_while_heads_accumulate() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);

        assert!(coalescer.observe_head(100, now));
        let deadline = coalescer.flush_deadline().unwrap();

        assert!(coalescer.observe_head(105, now + Duration::from_millis(50)));
        assert_eq!(coalescer.pending_range(), Some((100, 105)));
        assert_eq!(coalescer.flush_deadline(), Some(deadline));
        assert!(!coalescer.should_flush(now + WINDOW - Duration::from_millis(1)));
        assert!(coalescer.should_flush(now + WINDOW));
    }

    #[test]
    fn head_coalescer_flushes_immediately_when_pending_range_reaches_chunk_limit() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);

        assert!(coalescer.observe_head(MAX_BLOCKS_PER_WS_REQUEST, now));
        assert_eq!(
            coalescer.pending_range(),
            Some((1, MAX_BLOCKS_PER_WS_REQUEST))
        );
        assert!(coalescer.should_flush(now));
    }

    #[test]
    fn head_coalescer_preserves_pending_range_across_partial_cursor_advances() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(10), WINDOW);

        assert!(coalescer.observe_head(25, now));
        coalescer.advance_cursor(20);
        assert_eq!(coalescer.pending_range(), Some((20, 25)));
        assert!(coalescer.flush_deadline().is_some());

        coalescer.advance_cursor(26);
        assert_eq!(coalescer.pending_range(), None);
        assert_eq!(coalescer.flush_deadline(), None);
        assert_eq!(coalescer.block_cursor(), Some(26));
    }

    /// G.2.2 §2.2/§4.3 — `advance_cursor` is the single translation point shared by all five
    /// live-path call sites (`:429`, `:832`, `:938`, `:980`, `:1069` at `EXPECT_TIP`): every
    /// caller passes the *next* block to fetch, never the last-scanned one, so `advance_cursor`
    /// must record `next_block - 1`. Exercised directly here (no live-provider scaffolding
    /// needed — `HeadCoalescer` and `ScanProgress` are both plain synchronous types); the five
    /// call sites themselves are not reachable by the existing mock harness (see
    /// `test_event_streamer_head`'s `#[ignore]`), which is the disclosed residual in the REPORT.
    #[test]
    fn advance_cursor_records_scanned_to_as_next_block_minus_one() {
        let progress = crate::rpc::progress::ScanProgress::default();
        let mut coalescer =
            HeadCoalescer::new(Some(10), WINDOW).with_progress(Some(progress.clone()));

        assert_eq!(progress.scanned_to(), None);

        coalescer.advance_cursor(101);
        assert_eq!(progress.scanned_to(), Some(100));

        // Monotonic: an out-of-order lower advance must not move progress backwards.
        coalescer.advance_cursor(51);
        assert_eq!(progress.scanned_to(), Some(100));
    }

    /// `record_tip` is the shared point behind `handle_empty_flush`'s `get_tip()` resolution.
    #[test]
    fn record_tip_populates_progress_when_attached_and_is_a_no_op_otherwise() {
        let progress = crate::rpc::progress::ScanProgress::default();
        let with_progress = HeadCoalescer::new(None, WINDOW).with_progress(Some(progress.clone()));
        with_progress.record_tip(500);
        assert_eq!(progress.observed_tip(), Some(500));

        // No progress attached: must not panic, and there is nothing to observe.
        let without_progress = HeadCoalescer::new(None, WINDOW);
        without_progress.record_tip(500);
    }

    #[test]
    fn head_coalescer_handles_mainnet_slow_blocks() {
        // Ethereum mainnet: ~12 s/block. Each head must flush in a single 500 ms coalesce window;
        // the chunk-limit guard (MAX_BLOCKS_PER_WS_REQUEST) must never trigger for live cadence.
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(1_000_000), WINDOW);

        // First mainnet head observed.
        assert!(coalescer.observe_head(1_000_000, now));
        assert_eq!(coalescer.pending_range(), Some((1_000_000, 1_000_000)));

        // Must not flush before the coalesce window expires.
        assert!(!coalescer.should_flush(now + Duration::from_millis(499)));
        // Must flush once the window expires.
        assert!(coalescer.should_flush(now + WINDOW));

        // Advance cursor; simulate the next block arriving ~12 s later.
        coalescer.advance_cursor(1_000_001);
        assert_eq!(coalescer.pending_range(), None);

        let t12s = now + Duration::from_secs(12);
        assert!(coalescer.observe_head(1_000_001, t12s));
        assert_eq!(coalescer.pending_range(), Some((1_000_001, 1_000_001)));

        // One block in range: chunk limit (300) must not fire.
        assert!(!coalescer.should_flush(t12s));
        assert!(coalescer.should_flush(t12s + WINDOW));
    }

    /// The coalesce window is read from the constructed instance, not a fixed
    /// constant: two coalescers built with different windows must each flush at
    /// their own deadline, not a shared hard-coded value.
    #[test]
    fn head_coalescer_honors_its_own_window() {
        let now = Instant::now();
        let short_window = Duration::from_millis(100);
        let long_window = Duration::from_secs(5);

        let mut short = HeadCoalescer::new(Some(1), short_window);
        assert!(short.observe_head(1, now));
        assert!(!short.should_flush(now + short_window - Duration::from_millis(1)));
        assert!(short.should_flush(now + short_window));

        let mut long = HeadCoalescer::new(Some(1), long_window);
        assert!(long.observe_head(1, now));
        assert!(!long.should_flush(now + long_window - Duration::from_millis(1)));
        assert!(long.should_flush(now + long_window));
    }

    #[test]
    fn head_coalescer_defer_flush_clears_deadline_only() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        assert!(coalescer.observe_head(300, now));
        assert_eq!(coalescer.pending_range(), Some((1, 300)));
        assert!(coalescer.flush_deadline().is_some());

        coalescer.defer_flush();
        assert_eq!(
            coalescer.flush_deadline(),
            None,
            "defer_flush must clear the deadline"
        );
        assert_eq!(
            coalescer.pending_range(),
            Some((1, 300)),
            "defer_flush must not touch the pending range"
        );

        // A 300-wide span still should_flush()es with no deadline armed — the
        // span-cap arm of should_flush is deadline-free.
        assert!(coalescer.should_flush(now));
    }

    /// After a `Partial(b)` yield advances the cursor to `b + 1` and defers,
    /// the deferred-empty pattern applies verbatim: the deadline clears, the
    /// pending range starts at the unproven tail, and the next head re-arms.
    #[test]
    fn coalescer_partial_defer_reserves_unproven_tail_and_rearms() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(105, now);
        assert_eq!(coalescer.pending_range(), Some((100, 105)));

        // Simulate a Partial(102) yield: cursor advances only through the
        // proven watermark, then the unproven tail defers.
        coalescer.advance_cursor(103);
        coalescer.defer_flush();

        assert_eq!(
            coalescer.flush_deadline(),
            None,
            "defer_flush must clear the deadline after a Partial yield"
        );
        assert_eq!(
            coalescer.pending_range(),
            Some((103, 105)),
            "pending range must start at watermark+1, the unproven tail"
        );

        // The next head's flush re-arms the deadline over the still-unproven tail.
        assert!(coalescer.observe_head(105, now + Duration::from_millis(1)));
        assert!(coalescer.flush_deadline().is_some());
    }

    // ==================== log-watermark bound (yield_bounds) ====================

    /// Builds a `Log` fixture via the JSON shape already used for the
    /// `fetch_logs_by_hash_range` test (`"blockNumber": format!("0x{:x}", n)`),
    /// nulling `blockNumber` for the `None` case (the field is required by
    /// `Log`'s deserializer, so it cannot simply be omitted).
    fn log_fixture(block_number: Option<u64>) -> Log {
        let value = serde_json::json!({
            "address": "0x0000000000000000000000000000000000000001",
            "topics": [],
            "data": "0x",
            "blockHash": hb(0).to_string(),
            "blockNumber": block_number.map(|n| format!("0x{:x}", n)),
            "transactionHash": hb(0).to_string(),
            "transactionIndex": "0x0",
            "logIndex": "0x0",
            "removed": false
        });
        serde_json::from_value(value).expect("valid Log fixture")
    }

    #[test]
    fn yield_bounds_full_when_tail_has_logs() {
        let logs = vec![log_fixture(Some(101)), log_fixture(Some(102))];
        assert!(matches!(yield_bounds(&logs, 102), YieldBounds::Full));
    }

    #[test]
    fn yield_bounds_partial_stops_at_watermark() {
        let logs = vec![log_fixture(Some(101))];
        assert!(matches!(
            yield_bounds(&logs, 102),
            YieldBounds::Partial(101)
        ));
    }

    /// Logs at 101 and 104 with `to = 105`: blocks 102-103 are vouched by the
    /// 104 log (a log at block B proves the provider's index reached >= B);
    /// only 105, above the watermark, is unproven.
    #[test]
    fn yield_bounds_interior_gaps_are_proven() {
        let logs = vec![log_fixture(Some(101)), log_fixture(Some(104))];
        assert!(matches!(
            yield_bounds(&logs, 105),
            YieldBounds::Partial(104)
        ));
    }

    #[test]
    fn yield_bounds_mixed_none_uses_some_only() {
        let logs = vec![log_fixture(Some(101)), log_fixture(None)];
        assert!(matches!(
            yield_bounds(&logs, 102),
            YieldBounds::Partial(101)
        ));
    }

    #[test]
    fn yield_bounds_all_none_is_unattributable() {
        let logs = vec![log_fixture(None), log_fixture(None)];
        assert!(matches!(
            yield_bounds(&logs, 999),
            YieldBounds::Unattributable
        ));
    }

    /// A log claiming a block above `to_block` is a provider integrity
    /// violation (a range query cannot legally return higher blocks); clamp
    /// to `Full` rather than advance the cursor past the requested range.
    #[test]
    fn yield_bounds_watermark_above_range_clamps() {
        let logs = vec![log_fixture(Some(103))];
        assert!(matches!(yield_bounds(&logs, 102), YieldBounds::Full));
    }

    // ==================== lazy empty-verification (handle_empty_flush) ====================

    /// Non-capped empty flush defers without calling the tip at all. A reverted
    /// per-window confirm would call `get_block_number` and, against an asserter
    /// with zero queued responses, panic on the exhausted queue instead of
    /// returning `Deferred`.
    #[tokio::test]
    async fn lazy_empty_non_capped_defers_without_tip_call() {
        let asserter = Asserter::new(); // zero queued responses
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(105, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((100, 105)));

        let mut gate = TipGate::new();
        let outcome = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host",
            105,
            false,
            || http_provider.get_block_number(),
        )
        .await;

        assert!(
            matches!(outcome, EmptyFlushOutcome::Deferred),
            "expected Deferred"
        );
        assert_eq!(coalescer.flush_deadline(), None);
        assert_eq!(
            coalescer.pending_range(),
            Some((100, 105)),
            "cursor must stay unmoved by a deferred flush"
        );
    }

    /// After a deferred flush, the next `observe_head` re-arms the deadline and
    /// the pending range still starts at the ORIGINAL (unmoved) cursor — the
    /// self-heal shape: the next flush re-covers the deferred blocks.
    #[test]
    fn lazy_deferred_flush_rearms_and_spans_from_unmoved_cursor() {
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(105, now);
        assert_eq!(coalescer.pending_range(), Some((100, 105)));

        coalescer.defer_flush();
        assert_eq!(coalescer.flush_deadline(), None);

        coalescer.observe_head(110, now + Duration::from_millis(10));
        assert_eq!(
            coalescer.pending_range(),
            Some((100, 110)),
            "deferred span must extend from the original unmoved cursor"
        );
        assert!(
            coalescer.flush_deadline().is_some(),
            "the next observe_head must re-arm the deadline"
        );
    }

    /// Span-capped chunk, tip already at or past `to_block`: verified empty on
    /// the first tip check, no `wait_for_tip` episode.
    #[tokio::test]
    async fn span_cap_empty_tip_current_is_verified_empty() {
        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!("0x64")); // get_block_number → 100
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        coalescer.observe_head(100, Instant::now());
        let mut gate = TipGate::new();

        let outcome = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host",
            100,
            true,
            || http_provider.get_block_number(),
        )
        .await;

        assert!(
            matches!(outcome, EmptyFlushOutcome::VerifiedEmpty),
            "expected VerifiedEmpty"
        );
    }

    /// Span-capped chunk, tip behind `to_block`: enters `wait_for_tip`, which
    /// catches up on the first re-poll. `from_mock`'s `tip_wait_backoff_secs: 0`
    /// keeps the wait sleepless.
    #[tokio::test]
    async fn span_cap_empty_tip_behind_enters_tip_wait() {
        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!("0x63")); // initial tip → 99 (< to_block)
        asserter.push_success(&serde_json::json!("0x64")); // re-poll → 100 (caught up)
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        coalescer.observe_head(100, Instant::now());
        let mut gate = TipGate::new();

        let outcome = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host",
            100,
            true,
            || http_provider.get_block_number(),
        )
        .await;

        assert!(
            matches!(outcome, EmptyFlushOutcome::CaughtUp),
            "expected CaughtUp"
        );
    }

    /// Span-capped chunk, tip flat across every poll: `wait_for_tip` terminates
    /// via the stall gate. This plus the previous test is the Base-outage
    /// invariant — reverting the cap guard (making the span-capped arm defer
    /// too) fails both.
    #[tokio::test]
    async fn span_cap_empty_flat_tip_stalls() {
        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!("0x5a")); // initial tip → 90
        asserter.push_success(&serde_json::json!("0x5a")); // re-poll cycle 1 → 90 (flat)
        asserter.push_success(&serde_json::json!("0x5a")); // re-poll cycle 2 → 90 (flat, hits cap)
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        )
        .with_tip_wait_max_stall_cycles(2);
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        coalescer.observe_head(100, Instant::now());
        let mut gate = TipGate::new();

        let outcome = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host",
            100,
            true,
            || http_provider.get_block_number(),
        )
        .await;

        assert!(
            matches!(
                outcome,
                EmptyFlushOutcome::Stalled {
                    to_block: 100,
                    reported_tip: 90,
                    stalled_cycles: 2,
                }
            ),
            "expected Stalled(stalled_cycles=2), got non-matching outcome"
        );
    }

    /// F1 (0.1.29 core soundness audit): a `TipGate` is shared across
    /// provider sessions within one stream. Phase 1 reproduces the hazard —
    /// session A leaves the gate dirty (`RepollFailed`, the provider-switch
    /// path), and session B, run against the SAME never-reset gate, has its
    /// first observation miscounted as a regression instead of a fresh seed,
    /// so it hits `Stall(5)` on only 5 total tip polls instead of the 6 a
    /// freshly-seeded gate would need — one cycle early. Phase 2 shows the
    /// fix (`gate.reset()` between sessions, exactly what the connect-site
    /// change does): session B now correctly consumes 6 polls before
    /// `Stall(5)`. Each phase queues EXACTLY the responses its session B
    /// consumes, so an extra (correct-behavior) poll fails on an unqueued
    /// response rather than silently passing with the wrong arithmetic.
    #[tokio::test]
    async fn handle_empty_flush_stale_gate_stalls_one_cycle_early_without_reset() {
        // ---- Phase 1: no reset between sessions -- reproduce the miscount.
        let asserter = Asserter::new();
        // Session A: tip 990 (below to_block 999), then a transport error on
        // the wait-for-tip re-poll -- the RepollFailed provider-switch path
        // that leaves the gate dirty (audit F1 step 4-5).
        asserter.push_success(&serde_json::json!("0x3de")); // 990
        asserter.push_failure_msg("transport blip");
        // Session B, same gate, NOT reset: flat tip 988 (below A's stale
        // last_tip=990), so B's first observation counts as a regression
        // instead of a seed. 5 total get_tip calls (1 initial + 4 re-polls)
        // reach Stall(5) here -- one call short of a fresh gate's 6.
        for _ in 0..5 {
            asserter.push_success(&serde_json::json!("0x3dc")); // 988
        }
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        coalescer.observe_head(999, Instant::now());
        let mut gate = TipGate::new();

        let session_a = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host-a",
            999,
            true,
            || http_provider.get_block_number(),
        )
        .await;
        assert!(
            matches!(session_a, EmptyFlushOutcome::RepollFailed(_)),
            "expected RepollFailed for session A"
        );

        // Provider switch happens here in production, WITHOUT gate.reset() --
        // this is the bug this fix corrects.
        let session_b = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host-b",
            999,
            true,
            || http_provider.get_block_number(),
        )
        .await;
        assert!(
            matches!(
                session_b,
                EmptyFlushOutcome::Stalled {
                    to_block: 999,
                    reported_tip: 988,
                    stalled_cycles: 5,
                }
            ),
            "expected Stalled(stalled_cycles=5) one cycle early from the stale gate"
        );

        // ---- Phase 2: gate.reset() between sessions -- the fixed contract.
        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!("0x3de")); // 990
        asserter.push_failure_msg("transport blip");
        // Session B now gets a fresh seed observation, so it needs one MORE
        // flat poll (6 total: 1 initial + 5 re-polls) before Stall(5).
        for _ in 0..6 {
            asserter.push_success(&serde_json::json!("0x3dc")); // 988
        }
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let http_provider = settings.connect_http(0);

        let mut coalescer = HeadCoalescer::new(Some(1), WINDOW);
        coalescer.observe_head(999, Instant::now());
        let mut gate = TipGate::new();

        let session_a = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host-a",
            999,
            true,
            || http_provider.get_block_number(),
        )
        .await;
        assert!(
            matches!(session_a, EmptyFlushOutcome::RepollFailed(_)),
            "expected RepollFailed for session A"
        );

        // The connect-site fix: reset the gate before the new session.
        gate.reset();

        let session_b = handle_empty_flush(
            &mut coalescer,
            &mut gate,
            &settings,
            "host-b",
            999,
            true,
            || http_provider.get_block_number(),
        )
        .await;
        assert!(
            matches!(
                session_b,
                EmptyFlushOutcome::Stalled {
                    to_block: 999,
                    reported_tip: 988,
                    stalled_cycles: 5,
                }
            ),
            "expected Stalled(stalled_cycles=5) reached only after the full \
             6-poll budget once the gate is reset"
        );
    }

    /// Synthetic block with explicit `number`, own `hash`, and `parentHash`.
    ///
    /// Use this for tests that exercise `collect_window_hashes`, which trusts
    /// a response only when both `block.header.number == current_number` and
    /// `block.header.hash` match the hash actually queried at that walk step
    /// — every `push_success` site must supply the hash the walk queries, not
    /// a placeholder.
    fn block_with_parent_at(number: u64, hash: B256, parent: B256) -> serde_json::Value {
        let zero = hb(0).to_string();
        serde_json::json!({
            "hash":             hash.to_string(),
            "parentHash":       parent.to_string(),
            "sha3Uncles":       zero,
            "miner":            "0x0000000000000000000000000000000000000000",
            "stateRoot":        zero,
            "transactionsRoot": zero,
            "receiptsRoot":     zero,
            "logsBloom":        format!("0x{}", "0".repeat(512)),
            "difficulty":       "0x0",
            "number":           format!("0x{:x}", number),
            "gasLimit":         "0x0",
            "gasUsed":          "0x0",
            "timestamp":        "0x0",
            "extraData":        "0x",
            "mixHash":          zero,
            "nonce":            "0x0000000000000000",
            "transactions":     [],
            "uncles":           []
        })
    }

    /// Synthetic block whose meaningful fields are its own `hash` and
    /// `parentHash`; the block number is not checked by `walk_to_common_ancestor`,
    /// so it is always 0. `hash` must be the hash the walk step actually
    /// queried — a mismatch is trusted by no one and falls back to the next
    /// provider. Use `block_with_parent_at` when `collect_window_hashes` is
    /// under test (it also cross-checks the block number).
    fn block_with_parent(hash: B256, parent: B256) -> serde_json::Value {
        block_with_parent_at(0, hash, parent)
    }

    /// `ProviderSettings` configured with `n` HTTP providers at unreachable,
    /// never-dialed hosts — every sequential-fallback test supplies its own
    /// `reused` client set (`Some`), so `resolve_http_provider` never falls
    /// through to `connect_http` against these URLs. `n == 0` builds an empty
    /// set, for the precondition-guard tests.
    fn n_http_provider_settings(n: usize) -> ProviderSettings {
        let http_providers = (0..n)
            .map(|i| HttpRpcSettings::new(format!("http://unused-{i}"), 1, 100))
            .collect();
        ProviderSettings::new(
            http_providers,
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        )
    }

    /// One mocked HTTP `DynProvider` backed by `asserter`, the same
    /// construction every existing mock-provider test already uses.
    fn mock_http_provider(asserter: Asserter) -> DynProvider<Ethereum> {
        ProviderBuilder::new()
            .disable_recommended_fillers()
            .connect_mocked_client(asserter)
            .erased()
    }

    /// Seed a linkage with a clean canonical chain `[lo, hi]` (hash = `hb(n)`).
    fn seed_chain(depth: u64, lo: u64, hi: u64) -> HeadLinkage {
        let mut linkage = HeadLinkage::new(depth);
        for n in lo..=hi {
            let parent = if n == lo {
                hb((lo - 1) as u8)
            } else {
                hb((n - 1) as u8)
            };
            assert_eq!(linkage.observe(n, hb(n as u8), parent), LinkOutcome::Linked);
        }
        linkage
    }

    #[test]
    fn head_linkage_disabled_is_inert() {
        let mut linkage = HeadLinkage::new(0);
        // A blatant parent mismatch still returns Linked when depth == 0.
        assert_eq!(linkage.observe(100, hb(1), hb(9)), LinkOutcome::Linked);
        assert_eq!(linkage.observe(101, hb(2), hb(7)), LinkOutcome::Linked);
        assert_eq!(linkage.floor(), None);
    }

    #[test]
    fn head_linkage_clean_chain_advances_and_bounds_ring() {
        let linkage = seed_chain(3, 100, 103);
        // Ring is bounded at depth = 3; the oldest entry (100) is evicted.
        assert_eq!(linkage.floor(), Some(101));
        assert_eq!(linkage.hash_at(100), None);
        assert_eq!(linkage.hash_at(103), Some(hb(103)));
    }

    #[test]
    fn head_linkage_one_block_reorg_reports_parent_as_ancestor() {
        let mut linkage = seed_chain(8, 100, 103);
        // 103' replaces 103, still building on canonical 102 → ancestor 102.
        assert_eq!(
            linkage.observe(103, hb(203), hb(102)),
            LinkOutcome::Reorg {
                common_ancestor: 102
            }
        );
        // Ring re-anchored: 103 now records the new hash, clean extension resumes.
        assert_eq!(linkage.hash_at(103), Some(hb(203)));
        assert_eq!(linkage.observe(104, hb(204), hb(203)), LinkOutcome::Linked);
    }

    #[test]
    fn head_linkage_deep_reorg_via_reemit_reports_deeper_ancestor() {
        let mut linkage = seed_chain(8, 100, 105);
        // Provider re-emits the new chain from 101 (parent = canonical 100): a
        // five-block-deep reorg, resolved in-ring at common ancestor 100.
        assert_eq!(
            linkage.observe(101, hb(201), hb(100)),
            LinkOutcome::Reorg {
                common_ancestor: 100
            }
        );
    }

    #[test]
    fn head_linkage_skipped_intermediate_heads_detach() {
        let mut linkage = seed_chain(8, 100, 103);
        // Provider jumps to new tip 104' whose parent 103' (hb(203)) we never saw;
        // the parent at 103 differs from canonical → Detached, needs an RPC walk.
        match linkage.observe(104, hb(204), hb(203)) {
            LinkOutcome::Detached {
                parent_hash,
                child_number,
            } => {
                assert_eq!(parent_hash, hb(203));
                assert_eq!(child_number, 104);
            }
            other => panic!("expected Detached, got {other:?}"),
        }
    }

    /// The ring holds no entry at the parent's height, so `hash_at` returned
    /// `None` and nothing was compared. Absence of a record is not a divergence,
    /// however far below the floor the parent sits.
    #[test]
    fn head_linkage_parent_below_floor_has_no_recorded_parent() {
        // Ring covers [103, 105]; floor = 103.
        let mut linkage = seed_chain(3, 100, 105);
        assert_eq!(linkage.floor(), Some(103));
        // A head whose parent (102) is below the ring floor cannot be resolved,
        // and no ancestor is fabricated.
        assert_eq!(
            linkage.observe(103, hb(203), hb(202)),
            LinkOutcome::NoRecordedParent
        );
    }

    // ── I.4f §6.1: `lowest_worth_recording` / `extend_downward`, pure ────────

    #[test]
    fn lowest_worth_recording_is_none_on_an_empty_ring() {
        let linkage = HeadLinkage::new(8);
        assert_eq!(linkage.lowest_worth_recording(), None);
    }

    #[test]
    fn lowest_worth_recording_tracks_latest_at_depth() {
        let linkage = seed_chain(8, 100, 105);
        // latest = 105, depth = 8 → 105 - 7 = 98.
        assert_eq!(linkage.lowest_worth_recording(), Some(98));

        let deep = seed_chain(1, 100, 105);
        // depth = 1 → the accessor equals latest() itself.
        assert_eq!(deep.lowest_worth_recording(), Some(105));
    }

    #[test]
    fn extend_downward_records_pairs_below_the_floor() {
        let mut linkage = seed_chain(8, 103, 105);
        assert_eq!(linkage.floor(), Some(103));

        linkage.extend_downward(&[(101, hb(101)), (102, hb(102))]);

        assert_eq!(linkage.floor(), Some(101));
        assert_eq!(linkage.hash_at(101), Some(hb(101)));
        assert_eq!(linkage.hash_at(102), Some(hb(102)));
        // Existing entries and the tip are untouched.
        assert_eq!(linkage.hash_at(103), Some(hb(103)));
        assert_eq!(linkage.latest(), Some((105, hb(105))));
    }

    #[test]
    fn extend_downward_ignores_pairs_at_or_above_the_floor() {
        let mut linkage = seed_chain(8, 103, 105);
        let before = linkage.clone();
        // 103 (the floor itself) and 104 (already recorded, wrong hash here)
        // must both be dropped without duplicating or overwriting anything.
        linkage.extend_downward(&[(103, hb(103)), (104, hb(200))]);

        assert_eq!(
            linkage.floor(),
            before.floor(),
            "no-op: nothing below the floor"
        );
        assert_eq!(
            linkage.hash_at(104),
            Some(hb(104)),
            "an at-or-above pair must never overwrite an existing entry"
        );
        assert_eq!(linkage.ring.len(), before.ring.len());
    }

    #[test]
    fn extend_downward_batch_not_contiguous_with_front_records_nothing() {
        let mut linkage = seed_chain(8, 103, 105);
        // 100 is below the floor but not adjacent to it (103's predecessor is
        // 102, not 100) — a gap the ring cannot link across.
        linkage.extend_downward(&[(100, hb(100))]);
        assert_eq!(
            linkage.floor(),
            Some(103),
            "a non-contiguous batch is discarded whole"
        );
        assert_eq!(linkage.hash_at(100), None);
    }

    #[test]
    fn extend_downward_internal_gap_records_nothing() {
        let mut linkage = seed_chain(8, 103, 105);
        // Adjacent to the front (102 == 103 - 1), but 100 and 102 are not
        // adjacent to each other — a gap inside the batch itself.
        linkage.extend_downward(&[(100, hb(100)), (102, hb(102))]);
        assert_eq!(
            linkage.floor(),
            Some(103),
            "an internal gap is discarded whole"
        );
        assert_eq!(linkage.hash_at(102), None);
    }

    #[test]
    fn extend_downward_never_exceeds_depth() {
        // Ring already spans the full depth (3 entries for depth 3).
        let mut linkage = seed_chain(3, 103, 105);
        linkage.extend_downward(&[(100, hb(100)), (101, hb(101)), (102, hb(102))]);
        assert_eq!(
            linkage.floor(),
            Some(103),
            "a full ring must not extend further"
        );
        assert_eq!(linkage.ring.len(), 3);
    }

    #[test]
    fn extend_downward_caps_at_depth_even_when_pairs_go_deeper() {
        // Ring holds 3 of a 5-deep budget — room for exactly 2 more entries.
        let mut linkage = seed_chain(5, 103, 105);
        linkage.extend_downward(&[(99, hb(99)), (100, hb(100)), (101, hb(101)), (102, hb(102))]);
        assert_eq!(
            linkage.floor(),
            Some(101),
            "must stop exactly at depth, not walk past it"
        );
        assert_eq!(
            linkage.hash_at(100),
            None,
            "beyond depth must not be recorded"
        );
        assert_eq!(linkage.ring.len(), 5);
    }

    #[test]
    fn extend_downward_and_lowest_worth_recording_are_inert_at_depth_zero() {
        let mut linkage = HeadLinkage::new(0);
        assert_eq!(linkage.observe(100, hb(100), hb(99)), LinkOutcome::Linked);
        assert_eq!(linkage.lowest_worth_recording(), None);
        linkage.extend_downward(&[(99, hb(99))]);
        assert_eq!(
            linkage.floor(),
            None,
            "disabled linkage records nothing, ever"
        );
    }

    #[tokio::test]
    async fn walk_to_common_ancestor_walks_skipped_chain_to_common_ancestor() {
        // Canonical ring [100, 103]; new chain shares ancestor 101.
        let linkage = seed_chain(8, 100, 103);
        // New tip 104' detached at parent 103' (hb(203)); the walk fetches
        // 103' (parent 102' = hb(202)) then 102' (parent 101 = hb(101) ∈ ring).
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(203), hb(202)));
        asserter.push_success(&block_with_parent(hb(202), hb(101)));
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);

        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(203), 104, 8).await;
        assert!(matches!(err, Ok(101)), "got {err:?}");
    }

    /// A fetched hash reached the ring's floor and disagreed with the hash
    /// recorded there. That comparison is the one thing this walk can establish
    /// about the chain, so it is the one place `ReorgBeyondRing` is raised.
    #[tokio::test]
    async fn walk_to_common_ancestor_fetched_hash_at_floor_is_reorg_beyond_ring() {
        // Shallow ring [102, 103] (depth 2); floor = 102.
        let linkage = seed_chain(2, 100, 103);
        assert_eq!(linkage.floor(), Some(102));
        // New tip 104' detached at 103' (hb(203)); the walk fetches 103' (parent
        // 102' = hb(202)), which differs from canonical 102 at the floor.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(203), hb(202)));
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);

        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(203), 104, 2).await;
        assert!(matches!(err, Err(RpcError::ReorgBeyondRing)), "got {err:?}");
    }

    // ── Task A: pure observe shapes ──────────────────────────────────────────

    #[test]
    fn head_linkage_back_to_back_reorgs_ring_stays_coherent() {
        // Seed canonical [100, 105]; depth=8 so all fit and no eviction yet.
        let mut linkage = seed_chain(8, 100, 105);

        // ForkA: 104' replaces 104, building on canonical 103 → ancestor 103.
        assert_eq!(
            linkage.observe(104, hb(204), hb(103)),
            LinkOutcome::Reorg {
                common_ancestor: 103
            }
        );
        // Ring re-anchored at 103; 104 now records new-chain hash.
        assert_eq!(linkage.hash_at(104), Some(hb(204)));

        // Extend forkA's chain by one clean block.
        assert_eq!(linkage.observe(105, hb(205), hb(204)), LinkOutcome::Linked);

        // ForkB: a competing 105'' builds on forkA's 104 (canonical ancestor 104).
        // Use hb(49) for forkB's hash — a byte distinct from forkA's range (hb(200+)).
        assert_eq!(
            linkage.observe(105, hb(49), hb(204)),
            LinkOutcome::Reorg {
                common_ancestor: 104
            }
        );
        // Ring re-anchored at 104; 105 records forkB hash; ring stays bounded.
        assert_eq!(linkage.hash_at(105), Some(hb(49)));
        assert_eq!(linkage.hash_at(104), Some(hb(204))); // unchanged by forkB
        assert!(linkage.ring.len() as u64 <= 8);
    }

    #[test]
    fn head_linkage_multi_header_same_height_duplicate_vs_replace() {
        let mut linkage = seed_chain(8, 100, 104);
        // Re-observing the canonical tip with its exact hash → no-op (Linked).
        assert_eq!(linkage.observe(104, hb(104), hb(103)), LinkOutcome::Linked);
        assert_eq!(linkage.hash_at(104), Some(hb(104)));
        // A competing block at the same height with a different hash, same parent
        // → replace, ancestor = 103.
        assert_eq!(
            linkage.observe(104, hb(204), hb(103)),
            LinkOutcome::Reorg {
                common_ancestor: 103
            }
        );
        assert_eq!(linkage.hash_at(104), Some(hb(204)));
    }

    #[test]
    fn head_linkage_identical_hash_no_op() {
        // The `hash_at(number) == Some(hash)` branch: re-observing an already
        // recorded (number, hash) pair returns Linked and leaves the ring alone.
        let mut linkage = seed_chain(8, 100, 104);
        let floor_before = linkage.floor();
        let depth_before = linkage.ring.len();
        assert_eq!(linkage.observe(104, hb(104), hb(103)), LinkOutcome::Linked);
        assert_eq!(linkage.floor(), floor_before);
        assert_eq!(linkage.ring.len(), depth_before);
        assert_eq!(linkage.hash_at(104), Some(hb(104)));
    }

    #[test]
    fn head_linkage_forward_gap_reports_the_break_in_our_own_view() {
        // `number > tip + 1`: heads skipped ahead (e.g. across a reconnect).
        // The gap is missed observation, so it names the ring tip it broke from
        // rather than routing to the reorg walk, and the ring is left untouched
        // — no clear, no re-anchor, nothing fetched.
        let mut linkage = seed_chain(8, 100, 103); // tip = 103
        assert_eq!(
            linkage.observe(107, hb(107), hb(106)),
            LinkOutcome::Gap { ring_tip: 103 }
        );
        // Old ring state preserved — `seed_chain(8, 100, 103)` builds [100,101,102,103]
        // with no eviction at depth 8, so floor() (the ring front's number) is 100.
        assert_eq!(linkage.floor(), Some(100));
        assert_eq!(linkage.hash_at(103), Some(hb(103)));
    }

    #[test]
    fn head_linkage_idempotent_reanchor_bounds_ring() {
        // After a reorg, a clean chain links cleanly and the ring stays bounded.
        let mut linkage = seed_chain(5, 100, 106); // ring [102,103,104,105,106] (evicted 100,101)
        assert_eq!(linkage.floor(), Some(102));

        // Reorg: 105' replaces 105, ancestor 104.
        assert_eq!(
            linkage.observe(105, hb(205), hb(104)),
            LinkOutcome::Reorg {
                common_ancestor: 104
            }
        );
        assert_eq!(linkage.hash_at(105), Some(hb(205)));

        // Extend cleanly from the new chain tip.
        assert_eq!(linkage.observe(106, hb(206), hb(205)), LinkOutcome::Linked);
        assert_eq!(linkage.observe(107, hb(207), hb(206)), LinkOutcome::Linked);

        // Ring still bounded at depth 5; oldest entry evicted.
        assert!(linkage.ring.len() as u64 <= 5);
        assert_eq!(linkage.hash_at(105), Some(hb(205))); // new-chain hash retained
        assert_eq!(linkage.hash_at(102), None); // evicted
    }

    // ── Task B: walk_to_common_ancestor walk-depth matrix ────────────────────

    // Shared ring for the in-window rows: depth=15, canonical [100,109], floor=100,
    // tip=109. Each test detaches at child=111 (parent_number=110 ∉ ring).
    // k pushes → common ancestor at 110-k. Rings are distinct from catastrophe rows.

    #[tokio::test]
    async fn walk_to_common_ancestor_walk_depth_1() {
        let linkage = seed_chain(15, 100, 109);
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(200), hb(109))); // 110'→canonical 109
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 111, 15).await;
        assert!(matches!(err, Ok(109)), "got {err:?}");
    }

    #[tokio::test]
    async fn walk_to_common_ancestor_walk_depth_2() {
        let linkage = seed_chain(15, 100, 109);
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(200), hb(201))); // 110'→109'
        asserter.push_success(&block_with_parent(hb(201), hb(108))); // 109'→canonical 108
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 111, 15).await;
        assert!(matches!(err, Ok(108)), "got {err:?}");
    }

    #[tokio::test]
    async fn walk_to_common_ancestor_walk_depth_3() {
        let linkage = seed_chain(15, 100, 109);
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(200), hb(201))); // 110'→109'
        asserter.push_success(&block_with_parent(hb(201), hb(202))); // 109'→108'
        asserter.push_success(&block_with_parent(hb(202), hb(107))); // 108'→canonical 107
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 111, 15).await;
        assert!(matches!(err, Ok(107)), "got {err:?}");
    }

    #[tokio::test]
    async fn walk_to_common_ancestor_walk_depth_7() {
        let linkage = seed_chain(15, 100, 109);
        let asserter = Asserter::new();
        // Six intermediate new-chain blocks (hb(201)..hb(206)), then canonical 103.
        asserter.push_success(&block_with_parent(hb(200), hb(201)));
        asserter.push_success(&block_with_parent(hb(201), hb(202)));
        asserter.push_success(&block_with_parent(hb(202), hb(203)));
        asserter.push_success(&block_with_parent(hb(203), hb(204)));
        asserter.push_success(&block_with_parent(hb(204), hb(205)));
        asserter.push_success(&block_with_parent(hb(205), hb(206)));
        asserter.push_success(&block_with_parent(hb(206), hb(103))); // final→canonical 103
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 111, 15).await;
        assert!(matches!(err, Ok(103)), "got {err:?}");
    }

    #[tokio::test]
    async fn walk_to_common_ancestor_deepest_in_ring_resolves() {
        // Ring depth=5, canonical [100,104], floor=100. Child=105 → 4 fetches →
        // ancestor=100 (the floor). With depth=5 the loop runs 5 iterations: the
        // match check at the start of iter 4 fires after 4 prior fetches bring
        // parent_number to 100. Using child=106 would need 6 iterations (off by one).
        let linkage = seed_chain(5, 100, 104);
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(200), hb(201))); // 104'→103'
        asserter.push_success(&block_with_parent(hb(201), hb(202))); // 103'→102'
        asserter.push_success(&block_with_parent(hb(202), hb(203))); // 102'→101'
        asserter.push_success(&block_with_parent(hb(203), hb(100))); // 101'→canonical 100
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 105, 5).await;
        assert!(matches!(err, Ok(100)), "got {err:?}");
    }

    // ── G.8 §6: a gap never reaches the walk ─────────────────────────────────

    /// The change this task turns on, asserted at the seam that exists.
    ///
    /// A forward gap leaves `observe` as `LinkOutcome::Gap`, which the live
    /// loop reports as `RpcError::Gap` — it no longer produces the `Detached`
    /// that routes to `walk_to_common_ancestor`. The arm keys on
    /// `number > tip_number + 1` alone, so a 1,300-block gap costs exactly
    /// what a 2-block gap costs: nothing. Reverting the arm to `Detached`
    /// fails this outright.
    #[test]
    fn forward_gap_never_reaches_the_walk_whatever_its_length() {
        for gap in [2u64, 1_300] {
            // Canonical ring [100, 103], depth 8; a head arrives `gap` above the tip.
            let mut linkage = seed_chain(8, 100, 103);
            let head = 103 + gap;
            assert_eq!(
                linkage.observe(head, hb(207), hb(206)),
                LinkOutcome::Gap { ring_tip: 103 },
                "a gap of {gap} must report the break in our own view, never route \
                 to the reorg walk"
            );
            assert_eq!(
                linkage.latest(),
                Some((103, hb(103))),
                "a gap of {gap} must not mutate the ring"
            );
        }
    }

    /// The other half of the same proof: the walk still costs what it always
    /// cost — the per-block fetches the gap path no longer pays. Asserted by
    /// exhausting an `Asserter` primed with exactly the walk's expected steps,
    /// so a walk that fetched fewer or more would fail.
    #[tokio::test]
    async fn walk_still_spends_a_fetch_per_step_when_a_divergence_reaches_it() {
        // Canonical ring [100, 103], depth 8. A differing parent inside the
        // ring — the one arm that still reaches the walk.
        let mut linkage = seed_chain(8, 100, 103);
        assert_eq!(
            linkage.observe(104, hb(204), hb(203)),
            LinkOutcome::Detached {
                parent_hash: hb(203),
                child_number: 104,
            }
        );

        // Three steps down the new chain: 103'→102'→101'→ canonical 100.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(203), hb(202)));
        asserter.push_success(&block_with_parent(hb(202), hb(201)));
        asserter.push_success(&block_with_parent(hb(201), hb(100)));
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);

        let ancestor =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(203), 104, 8).await;
        assert!(matches!(ancestor, Ok(100)), "got {ancestor:?}");
    }

    /// A head the ring already records, re-observed. Neither an error nor a
    /// chain claim: the ring holds this exact `(number, hash)`, so nothing
    /// changed. A one-entry ring is the shape a restart leaves behind, where
    /// `hash_at(number - 1)` is `None` and the duplicate is the only thing
    /// standing between an identical block and a fabricated verdict.
    #[test]
    fn re_observing_the_only_recorded_head_is_not_a_divergence() {
        let mut linkage = HeadLinkage::new(96);
        assert_eq!(linkage.observe(500, hb(50), hb(49)), LinkOutcome::Linked);
        assert_eq!(linkage.floor(), Some(500));
        assert_eq!(
            linkage.hash_at(499),
            None,
            "the parent's height is genuinely unrecorded — that is the shape \
             this test exists for"
        );

        assert_eq!(
            linkage.observe(500, hb(50), hb(49)),
            LinkOutcome::Linked,
            "the same block at the same height is not new information"
        );
        assert_eq!(linkage.latest(), Some((500, hb(50))));
        assert_eq!(linkage.ring.len(), 1, "a duplicate must not grow the ring");
    }

    /// A differing parent exactly at the floor of a one-entry ring — the
    /// bootstrap shape, where `floor == tip` — reaches the walk's floor check on
    /// iteration zero, having fetched nothing. `parent_hash` is still
    /// `detached_parent`, the value the push supplied, so the only disagreement
    /// is with a provider's own word: `Gap`, never a chain claim.
    #[tokio::test]
    async fn walk_at_a_one_entry_rings_floor_claims_nothing_before_a_fetch() {
        let mut linkage = HeadLinkage::new(96);
        assert_eq!(linkage.observe(500, hb(50), hb(49)), LinkOutcome::Linked);
        assert_eq!(linkage.floor(), linkage.latest().map(|(n, _)| n));

        // A head at 501 whose parent hash disagrees with the recorded 500.
        assert_eq!(
            linkage.observe(501, hb(151), hb(150)),
            LinkOutcome::Detached {
                parent_hash: hb(150),
                child_number: 501,
            }
        );

        // No pushes: reaching a fetch at all would fail here.
        let provider = mock_http_provider(Asserter::new());
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(150), 501, 96).await;
        assert!(
            matches!(err, Err(RpcError::Gap)),
            "an unfetched disagreement at the floor must not claim a divergence; got {err:?}"
        );
    }

    /// The split the walk draws at its floor check, both halves against one
    /// ring. At the floor the ring holds a record, so a fetched hash that
    /// disagrees with it is a fact about the chain. Below the floor nothing was
    /// ever recorded, so there is nothing to disagree with and the same check
    /// may claim nothing.
    #[tokio::test]
    async fn walk_at_the_floor_diverges_but_below_it_only_discontinues() {
        // Ring [102, 103] (depth 2); floor = 102.
        let linkage = seed_chain(2, 100, 103);
        assert_eq!(linkage.floor(), Some(102));
        let settings = n_http_provider_settings(1);

        // At the floor: child 104 detaches at 103' (hb(203)); one confirmed step
        // puts a fetched hb(202) against the recorded canonical 102.
        let at_floor = Asserter::new();
        at_floor.push_success(&block_with_parent(hb(203), hb(202)));
        let err = walk_to_common_ancestor(
            &mock_http_provider(at_floor),
            &settings,
            None,
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ReorgBeyondRing)),
            "a fetched hash disagreeing with a recorded one at the floor is a \
             chain claim; got {err:?}"
        );

        // Below the floor: child 102 puts the first check at 101, a height the
        // ring never recorded. No pushes — reaching a fetch would fail here.
        let err = walk_to_common_ancestor(
            &mock_http_provider(Asserter::new()),
            &settings,
            None,
            &linkage,
            hb(202),
            102,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::Gap)),
            "a height the ring never recorded cannot diverge from it; got {err:?}"
        );
    }

    /// The budget ran out with the ring intact and no disagreement observed:
    /// a statement about how far we were willing to look, never about the chain.
    #[tokio::test]
    async fn walk_to_common_ancestor_loop_exhausted_is_a_gap() {
        // Depth cap (depth=3) prevents resolution: the loop exhausts its 3 iterations
        // without finding a matching canonical ancestor. Uses a distinct ring from the
        // in-window rows (depth=3, seed [100,109] → ring [107,108,109], floor=107).
        let linkage = seed_chain(3, 100, 109);
        assert_eq!(linkage.floor(), Some(107));
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent(hb(200), hb(201)));
        asserter.push_success(&block_with_parent(hb(201), hb(202)));
        asserter.push_success(&block_with_parent(hb(202), hb(203))); // loop ends after this fetch
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 111, 3).await;
        assert!(matches!(err, Err(RpcError::Gap)), "got {err:?}");
    }

    /// The floor check firing before any fetch: `detached_parent` is still the
    /// incoming push's own claim, so the disagreement is with a provider's word,
    /// not with a hash we confirmed. That is a gap, not a chain claim.
    #[tokio::test]
    async fn walk_to_common_ancestor_parent_at_floor_before_a_fetch_is_a_gap() {
        // `parent_number <= floor` fires before any fetch: detached_parent sits
        // exactly at the ring floor, which the walk cannot descend below.
        let linkage = seed_chain(10, 100, 109); // floor = 100
        let asserter = Asserter::new(); // no pushes needed
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);
        // child=101 → parent_number=100 = floor; first iteration hits the floor check.
        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(200), 101, 10).await;
        assert!(matches!(err, Err(RpcError::Gap)), "got {err:?}");
    }

    /// A single configured provider whose primary AND fallback both answer
    /// `Ok(None)` has simply not answered — exhaustion is a view claim, never
    /// a chain claim, so this is `ConnectionError`, not `ReorgBeyondRing`.
    #[tokio::test]
    async fn walk_to_common_ancestor_single_provider_absent_is_unresolved() {
        let linkage = seed_chain(15, 100, 109);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(1);
        let http_asserter = Asserter::new();
        http_asserter.push_success(&serde_json::json!(null));
        let reused = vec![mock_http_provider(http_asserter)];
        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(200),
            111,
            15,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// A mid-walk transport error is recoverable (the stream can restart and
    /// re-attempt) — same `ConnectionError` verdict as the null case above,
    /// mechanically unchanged by the trust rule.
    #[tokio::test]
    async fn walk_to_common_ancestor_transport_error_is_unresolved() {
        let linkage = seed_chain(15, 100, 109);
        let settings = n_http_provider_settings(1);
        let http_asserter = Asserter::new();
        http_asserter.push_failure_msg("transport blip");
        let reused = vec![mock_http_provider(http_asserter)];
        let asserter = Asserter::new();
        asserter.push_failure_msg("transport blip");
        let provider = mock_http_provider(asserter);
        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(200),
            111,
            15,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    // ── walk_to_common_ancestor: sequential fallback matrix ──────────────────
    // The WS primary contributes no answer of its own; a would-be-terminal
    // primary answer falls back to the configured HTTP providers, one at a
    // time, starting from the walk's own cursor (0 on the first step, then
    // wherever the previous step's fallback left off).

    /// THE REVERT-FAILS TEST FOR THE INCIDENT: a single provider's `Ok(None)`
    /// must not be conclusive when another configured HTTP provider serves
    /// the queried block. Fails against pre-trust-rule code that returns
    /// a walk verdict on the primary's first null without trying the other
    /// providers.
    #[tokio::test]
    async fn walk_to_common_ancestor_second_source_recovers_the_incident_scenario() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);

        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null));
        let voter1 = Asserter::new();
        voter1.push_success(&block_with_parent(hb(203), hb(102))); // recovers → parent 102 ∈ ring
        let voter2 = Asserter::new();
        voter2.push_success(&serde_json::json!(null));
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(matches!(err, Ok(102)), "got {err:?}");
    }

    /// N=3, all three HTTP providers null: every provider tried, none
    /// answered — a view claim, `ConnectionError`, never `ReorgBeyondRing`.
    #[tokio::test]
    async fn walk_to_common_ancestor_all_sources_absent_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let reused: Vec<_> = (0..3)
            .map(|_| {
                let a = Asserter::new();
                a.push_success(&serde_json::json!(null));
                mock_http_provider(a)
            })
            .collect();

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// N=3, 1 null + 2 transport-fail: the incident's actual weather — every
    /// provider still gets its own turn, and none answers.
    #[tokio::test]
    async fn walk_to_common_ancestor_lone_absent_answer_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null));
        let voter1 = Asserter::new();
        voter1.push_failure_msg("blip");
        let voter2 = Asserter::new();
        voter2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// N=3, 2 null + 1 transport-fail — a mixed reason for not answering is
    /// still "did not answer"; the walk still tries all three and reports
    /// `ConnectionError`.
    #[tokio::test]
    async fn walk_to_common_ancestor_two_of_three_absent_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null));
        let voter1 = Asserter::new();
        voter1.push_success(&serde_json::json!(null));
        let voter2 = Asserter::new();
        voter2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// N=2: 1 null + 1 transport-fail, and separately both null — either way
    /// every configured provider gets tried and none answers.
    #[tokio::test]
    async fn walk_to_common_ancestor_n_equals_2() {
        let linkage = seed_chain(8, 100, 103);
        let settings = n_http_provider_settings(2);

        {
            let ws_asserter = Asserter::new();
            ws_asserter.push_success(&serde_json::json!(null));
            let provider = mock_http_provider(ws_asserter);
            let voter0 = Asserter::new();
            voter0.push_success(&serde_json::json!(null));
            let voter1 = Asserter::new();
            voter1.push_failure_msg("blip");
            let reused = vec![mock_http_provider(voter0), mock_http_provider(voter1)];
            let err = walk_to_common_ancestor(
                &provider,
                &settings,
                Some(&reused),
                &linkage,
                hb(203),
                104,
                8,
            )
            .await;
            assert!(
                matches!(err, Err(RpcError::ConnectionError(_))),
                "got {err:?}"
            );
        }
        {
            let ws_asserter = Asserter::new();
            ws_asserter.push_success(&serde_json::json!(null));
            let provider = mock_http_provider(ws_asserter);
            let voter0 = Asserter::new();
            voter0.push_success(&serde_json::json!(null));
            let voter1 = Asserter::new();
            voter1.push_success(&serde_json::json!(null));
            let reused = vec![mock_http_provider(voter0), mock_http_provider(voter1)];
            let err = walk_to_common_ancestor(
                &provider,
                &settings,
                Some(&reused),
                &linkage,
                hb(203),
                104,
                8,
            )
            .await;
            assert!(
                matches!(err, Err(RpcError::ConnectionError(_))),
                "got {err:?}"
            );
        }
    }

    /// A primary transport failure is "did not answer," same as a null: one
    /// HTTP provider serving the block still recovers the walk; all
    /// providers transport-failing yields `ConnectionError`.
    #[tokio::test]
    async fn walk_to_common_ancestor_primary_transport_fail() {
        let linkage = seed_chain(8, 100, 103);
        let settings = n_http_provider_settings(3);

        {
            let ws_asserter = Asserter::new();
            ws_asserter.push_failure_msg("blip");
            let provider = mock_http_provider(ws_asserter);
            let voter0 = Asserter::new();
            voter0.push_success(&serde_json::json!(null));
            let voter1 = Asserter::new();
            voter1.push_success(&block_with_parent(hb(203), hb(102)));
            let voter2 = Asserter::new();
            voter2.push_success(&serde_json::json!(null));
            let reused = vec![
                mock_http_provider(voter0),
                mock_http_provider(voter1),
                mock_http_provider(voter2),
            ];
            let err = walk_to_common_ancestor(
                &provider,
                &settings,
                Some(&reused),
                &linkage,
                hb(203),
                104,
                8,
            )
            .await;
            assert!(matches!(err, Ok(102)), "got {err:?}");
        }
        {
            let ws_asserter = Asserter::new();
            ws_asserter.push_failure_msg("blip");
            let provider = mock_http_provider(ws_asserter);
            let reused: Vec<_> = (0..3)
                .map(|_| {
                    let a = Asserter::new();
                    a.push_failure_msg("blip");
                    mock_http_provider(a)
                })
                .collect();
            let err = walk_to_common_ancestor(
                &provider,
                &settings,
                Some(&reused),
                &linkage,
                hb(203),
                104,
                8,
            )
            .await;
            assert!(
                matches!(err, Err(RpcError::ConnectionError(_))),
                "got {err:?}"
            );
        }
    }

    /// Two recovered steps then a clean ring re-link, proving the walk's
    /// cursor carries forward instead of restarting at index 0 every step:
    /// step 1 starts at index 0, misses, and recovers at index 1; step 2
    /// starts from index 1 — not index 0 again — misses there, and recovers
    /// at index 2. Every `Asserter` is given EXACTLY the responses the
    /// sequential loop consumes.
    #[tokio::test]
    async fn walk_to_common_ancestor_two_recoveries_then_ring_relink() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null)); // step 1 trigger
        ws_asserter.push_success(&serde_json::json!(null)); // step 2 trigger
        let provider = mock_http_provider(ws_asserter.clone());
        let settings = n_http_provider_settings(3);

        // Index 0 misses step 1; the cursor then skips it on step 2, so its
        // second queued response is never read — asserted below.
        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null)); // step 1: miss
        voter0.push_success(&serde_json::json!(null)); // step 2: never read under the cursor
        // Index 1 recovers step 1 (hash hb(205)) with parent hb(204). The
        // cursor asks it first on step 2, where it misses.
        let voter1 = Asserter::new();
        voter1.push_success(&block_with_parent(hb(205), hb(204)));
        voter1.push_success(&serde_json::json!(null)); // step 2: miss
        // Index 2 is never reached in step 1 (index 1 already matched); it
        // recovers step 2 (hash hb(204)) with parent hb(102) ∈ ring.
        let voter2 = Asserter::new();
        voter2.push_success(&block_with_parent(hb(204), hb(102)));
        let reused = vec![
            mock_http_provider(voter0.clone()),
            mock_http_provider(voter1.clone()),
            mock_http_provider(voter2.clone()),
        ];

        // Detached at child=105 (parent_number starts at 104, one above the
        // linked ring): 104 → recovered to 103' (hb(204)) → recovered to 102 ∈ ring.
        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(205),
            105,
            8,
        )
        .await;
        assert!(matches!(err, Ok(102)), "got {err:?}");
        assert_eq!(
            ws_asserter.read_q().len(),
            0,
            "exactly 2 primary triggers, no third"
        );
        assert_eq!(
            voter0.read_q().len(),
            1,
            "cursor carries to index 1 on step 2; index 0's queued response is unread"
        );
        assert_eq!(voter1.read_q().len(), 0, "index 1 tried on both steps");
        assert_eq!(
            voter2.read_q().len(),
            0,
            "index 2 reached only once, on step 2"
        );
    }

    /// A step the WS `provider` answers directly, with no HTTP fallback call
    /// at all, must not reset the cursor a later step inherits. Step 1's
    /// fallback recovers at index 1; step 2 is answered by the WS provider
    /// directly; step 3's fallback must still start from index 1, not index
    /// 0, proving the WS-answered step in between left the cursor alone.
    #[tokio::test]
    async fn walk_to_common_ancestor_ws_answered_step_leaves_cursor_undisturbed() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null)); // step 1 trigger
        ws_asserter.push_success(&block_with_parent(hb(205), hb(204))); // step 2: WS answers directly
        ws_asserter.push_success(&serde_json::json!(null)); // step 3 trigger
        let provider = mock_http_provider(ws_asserter.clone());
        let settings = n_http_provider_settings(3);

        // Index 0 misses step 1; if the cursor were reset instead of carried
        // past step 2, step 3 would ask it again — its second response would
        // then be consumed. Asserted unread below.
        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null)); // step 1: miss
        voter0.push_success(&serde_json::json!(null)); // never read if the cursor survives
        // Index 1 recovers step 1 (hash hb(206)) with parent hb(205); step 2
        // never reaches it (WS answered directly). The cursor asks it first
        // on step 3, where it misses.
        let voter1 = Asserter::new();
        voter1.push_success(&block_with_parent(hb(206), hb(205)));
        voter1.push_success(&serde_json::json!(null)); // step 3: miss
        // Index 2 recovers step 3 (hash hb(204)) with parent hb(102) ∈ ring.
        let voter2 = Asserter::new();
        voter2.push_success(&block_with_parent(hb(204), hb(102)));
        let reused = vec![
            mock_http_provider(voter0.clone()),
            mock_http_provider(voter1.clone()),
            mock_http_provider(voter2.clone()),
        ];

        // Detached at child=106 (parent_number starts at 105): 105 →
        // recovered to 104' (hb(205)) → WS-answered to 103' (hb(204)) →
        // recovered to 102 ∈ ring.
        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(206),
            106,
            8,
        )
        .await;
        assert!(matches!(err, Ok(102)), "got {err:?}");
        assert_eq!(
            ws_asserter.read_q().len(),
            0,
            "exactly 3 primary triggers, no fourth"
        );
        assert_eq!(
            voter0.read_q().len(),
            1,
            "cursor still at index 1 on step 3; index 0's queued response is unread"
        );
        assert_eq!(voter1.read_q().len(), 0, "index 1 tried on steps 1 and 3");
        assert_eq!(
            voter2.read_q().len(),
            0,
            "index 2 reached only once, on step 3"
        );
    }

    /// A source answering `Ok(Some)` with the WRONG hash is neither a match
    /// nor evidence of anything about the chain — it is simply "did not
    /// answer," the same as a null or a transport error. This test asserts
    /// each in its own composition:
    ///
    /// - *the failure text proves every provider was tried* — 1 wrong hash +
    ///   1 null + 1 transport error, N=3: the returned error carries the
    ///   transport error's own text, which it can only do if the wrong-hash
    ///   answer was rejected and the walk moved on to ask the rest.
    /// - *not a match* — 1 wrong hash + 2 null. Accepting the wrong block
    ///   sends the walk down that block's parent pointer instead of trying
    ///   the other providers, so dropping the identity check inverts this
    ///   composition to `Ok(_)` instead of exhaustion.
    #[tokio::test]
    async fn walk_to_common_ancestor_wrong_block_is_not_a_recovery() {
        // Composition 1: wrong-identity must not short-circuit as a match.
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let voter0 = Asserter::new();
        // Answers Ok(Some) but with a DIFFERENT hash than queried (hb(203)) —
        // must not be treated as a match.
        voter0.push_success(&block_with_parent(hb(9), hb(1)));
        let voter1 = Asserter::new();
        voter1.push_success(&serde_json::json!(null));
        let voter2 = Asserter::new();
        voter2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        let Err(RpcError::ConnectionError(msg)) = err else {
            panic!("got {err:?}");
        };
        // The transport error's own text reaches the returned error — without it
        // a rate limit, a TLS reset, and a connect timeout are indistinguishable
        // to whoever reads this message.
        assert!(msg.contains("blip"), "provider error text dropped: {msg}");

        // Composition 2: wrong-identity must not be accepted as the block —
        // every provider tried, none answered, `ConnectionError`.
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let voter0 = Asserter::new();
        // Its parent hb(102) sits in the ring — the bait for a dropped check:
        // accepting this block would send the walk to Ok(102) instead of
        // exhaustion.
        voter0.push_success(&block_with_parent(hb(77), hb(102)));
        let voter1 = Asserter::new();
        voter1.push_success(&serde_json::json!(null));
        let voter2 = Asserter::new();
        voter2.push_success(&serde_json::json!(null));
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// The PRIMARY's own hash-identity check, which nothing else exercises:
    /// every other fixture hands the primary an honest block. Hash identity is
    /// what makes it sound to take consecutive walk steps from different
    /// providers, so losing it silently is the worst failure this module has.
    ///
    /// The primary answers `Ok(Some)` with a block whose own hash is NOT the
    /// one queried, but whose `parent_hash` IS in the ring. Drop the check and
    /// the walk accepts the wrong block, follows its parent pointer, and
    /// reports `Ok(102)` — a fabricated rollback target the consumer would act
    /// on. Keep it and the step falls back to the one configured HTTP
    /// provider, which reports null, and the walk fails closed with
    /// `ConnectionError`.
    #[tokio::test]
    async fn walk_to_common_ancestor_primary_wrong_hash_does_not_advance_the_walk() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        // Queried for hb(203); answers with a block whose hash is hb(77).
        // Its parent hb(102) sits in the ring — the bait for a dropped check.
        ws_asserter.push_success(&block_with_parent(hb(77), hb(102)));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(1);
        let source = Asserter::new();
        source.push_success(&serde_json::json!(null));
        let reused = vec![mock_http_provider(source)];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "a wrong-hash primary block must never advance the walk; got {err:?}"
        );
    }

    /// A primary transport error is "did not answer," exactly like a null —
    /// exhaustion is a view claim, never a chain claim, so this stays
    /// `ConnectionError` even when every configured provider also misses.
    #[tokio::test]
    async fn walk_to_common_ancestor_primary_transport_error_with_absent_quorum_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_failure_msg("primary socket died");
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let voter0 = Asserter::new();
        voter0.push_success(&serde_json::json!(null));
        let voter1 = Asserter::new();
        voter1.push_success(&serde_json::json!(null));
        let voter2 = Asserter::new();
        voter2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(voter0),
            mock_http_provider(voter1),
            mock_http_provider(voter2),
        ];

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    /// The `reused.len() != n` precondition, and why it is a correctness guard
    /// rather than tidiness: `resolve_http_provider` indexes the reused set
    /// modulo its length, so a set SHORTER than `n` silently aliases several
    /// ring positions onto one client — fewer independent fallback sources
    /// than configured, masquerading as `n` of them.
    ///
    /// The fixture makes that concrete: one client queued with 3 null
    /// answers against `n = 3`. The guard fails closed on the mismatch.
    /// Remove it and the sequential loop queries that one client under all
    /// three indices, silently substituting one host's opinion for three.
    #[tokio::test]
    async fn walk_to_common_ancestor_reused_length_mismatch_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let ws_asserter = Asserter::new();
        ws_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(ws_asserter);
        let settings = n_http_provider_settings(3);
        let lone = Asserter::new();
        lone.push_success(&serde_json::json!(null));
        lone.push_success(&serde_json::json!(null));
        lone.push_success(&serde_json::json!(null));
        let reused = vec![mock_http_provider(lone)]; // 1 client, n = 3

        let err = walk_to_common_ancestor(
            &provider,
            &settings,
            Some(&reused),
            &linkage,
            hb(203),
            104,
            8,
        )
        .await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "a short reused set must fail closed, never let one client vote \
             three times; got {err:?}"
        );
    }

    /// `N == 0` fails closed before any fetch, no panic (no HTTP providers
    /// configured is a configuration fault, not a walk outcome).
    #[tokio::test]
    async fn walk_to_common_ancestor_zero_http_providers_is_unresolved() {
        let linkage = seed_chain(8, 100, 103);
        let asserter = Asserter::new(); // no pushes needed — the guard fires first
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(0);

        let err =
            walk_to_common_ancestor(&provider, &settings, None, &linkage, hb(203), 104, 8).await;
        assert!(
            matches!(err, Err(RpcError::ConnectionError(_))),
            "got {err:?}"
        );
    }

    // ── P3.4: by-hash recovery for the reorg-exposed tail ───────────────────

    /// Canonical chain [100, 103]; `collect_window_hashes` walks backward from
    /// tip=103 (hash=hb(103)) to from_block=100 using `get_block_by_hash`.
    /// Each block response carries the parent hash. Then `fetch_logs_by_hash_range`
    /// issues one `get_logs` per block pinned to the canonical hash (ascending).
    /// Assert: four LogRanges covering [100,100]..[103,103], one log each.
    #[tokio::test]
    async fn by_hash_tail_fetch_over_mock() {
        // Asserter for the walk: three get_block_by_hash calls (103→102→101; 100 == from_block,
        // loop ends without fetching 100's parent). Must use block_with_parent_at so the
        // number cross-check in collect_window_hashes passes.
        let walk_asserter = Asserter::new();
        walk_asserter.push_success(&block_with_parent_at(103, hb(103), hb(102))); // block 103 → parent 102
        walk_asserter.push_success(&block_with_parent_at(102, hb(102), hb(101))); // block 102 → parent 101
        walk_asserter.push_success(&block_with_parent_at(101, hb(101), hb(100))); // block 101 → parent 100
        let walk_provider = mock_http_provider(walk_asserter);
        let walk_settings = n_http_provider_settings(1);

        let pairs_desc =
            collect_window_hashes(&walk_provider, &walk_settings, None, 0, hb(103), 103, 100)
                .await
                .expect("walk should succeed");

        // Pairs are in descending order: [(103,hb(103)), (102,hb(102)), (101,hb(101)), (100,hb(100))].
        assert_eq!(pairs_desc.len(), 4);
        assert_eq!(pairs_desc[0], (103, hb(103)));
        assert_eq!(pairs_desc[1], (102, hb(102)));
        assert_eq!(pairs_desc[2], (101, hb(101)));
        assert_eq!(pairs_desc[3], (100, hb(100)));

        // Reverse to ascending for the log fetch.
        let mut pairs = pairs_desc;
        pairs.reverse();

        // Asserter for the log fetches: four get_logs calls, one per block.
        // Each returns a single synthetic log tagged with the block number.
        let log_asserter = Asserter::new();
        for n in 100u64..=103 {
            log_asserter.push_success(&serde_json::json!([{
                "address": "0x0000000000000000000000000000000000000001",
                "topics": [],
                "data": "0x",
                "blockHash": hb(n as u8).to_string(),
                "blockNumber": format!("0x{:x}", n),
                "transactionHash": hb(0).to_string(),
                "transactionIndex": "0x0",
                "logIndex": "0x0",
                "removed": false
            }]));
        }
        let log_provider = ProviderBuilder::new()
            .disable_recommended_fillers()
            .connect_mocked_client(log_asserter)
            .erased();
        let settings = ProviderSettings::from_mock(log_provider);

        let ranges = fetch_logs_by_hash_range(&settings, &pairs, None)
            .await
            .expect("log fetch should succeed");

        // Four LogRanges, each a single block with one log.
        assert_eq!(ranges.len(), 4, "expected one range per block");
        for (i, range) in ranges.iter().enumerate() {
            let block_n = 100u64 + i as u64;
            assert_eq!(
                range.from_block, block_n,
                "from_block mismatch at index {i}"
            );
            assert_eq!(range.to_block, block_n, "to_block mismatch at index {i}");
            assert_eq!(range.logs.len(), 1, "expected one log at block {block_n}");
            assert_eq!(
                range.logs[0].block_number,
                Some(block_n),
                "log block number mismatch"
            );
            assert_eq!(
                range.tip_hash,
                Some(hb(block_n as u8)),
                "a by-hash range carries the hash it was fetched with"
            );
        }
    }

    /// Both by-hash producers stamp the range with the hash they fetched with.
    ///
    /// The live flush and the restart tail's `fetch_logs_by_hash_range` each
    /// yield one block per range, pinned by `at_block_hash`, so the canonical
    /// identity of the range's top block is known at construction. A production
    /// site reverted to `tip_hash: None` fails here. The `None` half of the rule
    /// lives with the by-number path that owns it, in `backfill`'s own tests.
    #[tokio::test]
    async fn by_hash_producers_stamp_the_range_with_its_canonical_tip_hash() {
        // The restart tail: one range per requested (number, hash) pair.
        let pairs = [(100u64, hb(100)), (101u64, hb(101))];
        let asserter = Asserter::new();
        for _ in 0..pairs.len() {
            asserter.push_success(&serde_json::json!([]));
        }
        let tail_settings = ProviderSettings::from_mock(mock_http_provider(asserter));
        let ranges = fetch_logs_by_hash_range(&tail_settings, &pairs, None)
            .await
            .expect("by-hash fetch should succeed");
        assert_eq!(ranges.len(), 2);
        for (range, &(number, hash)) in ranges.iter().zip(pairs.iter()) {
            assert_eq!((range.from_block, range.to_block), (number, number));
            assert_eq!(
                range.tip_hash,
                Some(hash),
                "the restart tail knows the hash it queried with"
            );
        }

        // The live flush: same rule, reached through the ring's own entry.
        let flush_asserter = Asserter::new();
        flush_asserter.push_success(&serde_json::json!([]));
        let flush_settings = ProviderSettings::from_mock(mock_http_provider(flush_asserter));
        // Depth 1 keeps the ring exactly full, so the top-up walk no-ops and
        // the single queued response is the flush's own.
        let mut linkage = HeadLinkage::new(1);
        assert_eq!(linkage.observe(300, hb(44), hb(43)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(300), WINDOW);
        coalescer.observe_head(300, Instant::now());
        let ranges =
            flush_window_range(&mut linkage, &mut coalescer, &flush_settings, None, 0, None)
                .await
                .expect("flush should succeed");
        assert_eq!(ranges.len(), 1);
        assert_eq!(
            ranges[0].tip_hash,
            Some(hb(44)),
            "the live flush fetches by the ring's canonical hash and carries it"
        );
    }

    /// Ring bootstrapped at a head far above the flush cursor: the self-heal
    /// branch fires because the window's hashes are absent, and the walk it
    /// would need spans one block more than the bound allows. The bound is the
    /// constant plus the configured window, so the shortfall is measured
    /// against both — a flush must refuse before its first fetch, and the
    /// empty `Asserter` would error on any request that got through. Shared by
    /// the two self-heal-bound tests below.
    fn self_heal_bound_exceeded_fixture() -> (
        ProviderSettings,
        HeadLinkage,
        HeadCoalescer,
        Option<(u64, u64)>,
    ) {
        let settings = ProviderSettings::from_mock(mock_http_provider(Asserter::new()));

        let depth = 96u64;
        let head = 10_000_000u64;
        let cursor = head - (SELF_HEAL_WALK_MAX_BLOCKS + depth);
        let mut linkage = HeadLinkage::new(depth);
        assert_eq!(linkage.observe(head, hb(7), hb(6)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(cursor), WINDOW);
        coalescer.observe_head(head, Instant::now());
        let pending_before = coalescer.pending_range();

        (settings, linkage, coalescer, pending_before)
    }

    /// G.17 — the self-heal walk stops at its length bound rather than walking a
    /// backlog that would park the live loop, and reports only what stopping
    /// establishes: we could not rebuild our own view.
    #[tokio::test]
    async fn flush_self_heal_walk_stops_at_its_length_bound() {
        let (settings, mut linkage, mut coalescer, pending_before) =
            self_heal_bound_exceeded_fixture();

        let err = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect_err("a walk past the bound must not run");
        assert!(matches!(err, RpcError::Gap), "got {err:?}");
        assert_eq!(
            coalescer.pending_range(),
            pending_before,
            "a refused flush leaves the cursor where it was — no silent gap"
        );
    }

    /// `bound_flush_time` passes the inner error through unchanged when
    /// `flush_max_total_secs == 0` — the default every chain runs — so the
    /// self-heal-bound error it raises reaches `classify_flush_failure` intact
    /// and classifies as `EndStream`, leaving the span a retry would re-run
    /// unchanged (asserted below).
    ///
    /// Does not pin the raise site to `Gap`: `classify_flush_failure`
    /// maps `Gap`, `ReorgBeyondRing` and `Reorg` all to
    /// `EndStream` (see `classify_flush_failure_rotates_only_on_a_transport_fault`),
    /// so retargeting the raise site to either of the other two leaves this
    /// test green.
    ///
    /// Residual: the live loop's dispatch arm has no hermetic seam — see the
    /// `Err(e)` arm in `stream_heads_with_logs_with_progress` (`TODO G.15`).
    #[tokio::test]
    async fn self_heal_bound_error_classifies_end_stream_and_moves_no_cursor() {
        let (settings, mut linkage, mut coalescer, pending_before) =
            self_heal_bound_exceeded_fixture();

        let err = bound_flush_time(
            settings.flush_max_total_secs,
            &flush_timeout_label(&settings, "ws=test-host"),
            flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None),
        )
        .await
        .expect_err("a walk past the bound must not run");

        assert_eq!(
            classify_flush_failure(&err),
            FlushFailure::EndStream,
            "a gap must reach the consumer, not another provider: {err:?}"
        );
        assert_eq!(
            coalescer.pending_range(),
            pending_before,
            "the span a retry would re-run is unchanged, so a retry cannot differ"
        );
    }

    /// `classify_flush_failure` over every `RpcError` variant: a transport
    /// fault, and the two self-clearing all-providers signals, keep the
    /// provider rotation; everything else ends the stream.
    ///
    /// The rotation half is what the branch must not break — a stalled or
    /// unconfigured provider is still another provider's to answer. This
    /// covers the classification alone; what the live loop then does with it
    /// has no hermetic seam (`TODO G.15`).
    #[test]
    fn classify_flush_failure_rotates_only_on_a_transport_fault() {
        for err in [
            RpcError::Gap,
            RpcError::ReorgBeyondRing,
            RpcError::Reorg {
                common_ancestor: 42,
            },
        ] {
            assert_eq!(
                classify_flush_failure(&err),
                FlushFailure::EndStream,
                "{err:?} states a conclusion no other provider can overturn"
            );
        }

        for err in [
            // What `bound_flush_time` raises on a stalled flush, and what
            // `flush_window_range` raises with no HTTP providers configured.
            RpcError::ConnectionError("stalled mid-flush".to_string()),
            RpcError::SubscriptionError("dropped".to_string()),
            RpcError::LogFetchError("eth_getLogs failed".to_string()),
            RpcError::TransportError("reset by peer".to_string()),
            RpcError::CursorPastTip {
                to_block: 10,
                reported_tip: 5,
            },
            RpcError::ProviderStalled {
                to_block: 10,
                reported_tip: 5,
                stalled_cycles: 3,
            },
            RpcError::Other("unclassified".to_string()),
        ] {
            assert_eq!(
                classify_flush_failure(&err),
                FlushFailure::SwitchProvider,
                "{err:?} is a transport-class failure another provider may answer"
            );
        }

        for err in [
            RpcError::AllProvidersSuspended("all down".to_string()),
            RpcError::AllProvidersIdle {
                providers_tried: 2,
                idle_secs: 30,
            },
        ] {
            assert_eq!(
                classify_flush_failure(&err),
                FlushFailure::SwitchProvider,
                "{err:?} is self-clearing, not a permanent claim about every provider"
            );
        }
    }

    /// The flush failure log line names which branch the dispatch took.
    ///
    /// The dispatch arm itself is untestable (see
    /// `self_heal_bound_error_classifies_end_stream_and_moves_no_cursor`'s
    /// residual), so this line is the only signal an operator has for which
    /// way an identical error was resolved. Pinning it keeps the two
    /// dispositions from collapsing into one indistinguishable message — and
    /// pins `SwitchProvider` against re-acquiring the "next provider" claim:
    /// the live loop's call site always retries `flush_window_range` from
    /// HTTP provider index 0, so no rotation happens on a retried flush
    /// regardless of configured provider count.
    #[test]
    fn flush_failure_log_line_states_the_disposition() {
        let err = RpcError::Gap;
        let ended = flush_failure_log_line(&err, FlushFailure::EndStream);
        let rotated = flush_failure_log_line(&err, FlushFailure::SwitchProvider);

        assert!(
            ended.contains("ending stream"),
            "an ended stream must say so: {ended}"
        );
        assert!(
            rotated.contains("retrying the same window"),
            "a retry must say so: {rotated}"
        );
        assert!(
            !rotated.contains("next provider"),
            "the retried flush's HTTP fetch never rotates off provider index \
             0 — the line must not claim a rotation this call site cannot \
             perform: {rotated}"
        );
        assert_ne!(
            ended, rotated,
            "one error text, two dispositions — the line must tell them apart"
        );
    }

    /// `LogRange` compares and hashes, as the tuple it replaced did for free.
    ///
    /// Compiling is most of the assertion — dropping a derive breaks this
    /// test's build. `tip_hash` carries the distinction that matters: two
    /// ranges over the same blocks on different chains are not the same range.
    #[test]
    fn log_ranges_compare_and_hash_across_every_field() {
        use std::collections::HashSet;

        let range = LogRange {
            from_block: 10,
            to_block: 12,
            logs: vec![],
            tip_hash: Some(hb(12)),
        };
        let same = range.clone();
        let competing_tip = LogRange {
            tip_hash: Some(hb(11)),
            ..range.clone()
        };

        assert_eq!(range, same);
        assert_ne!(range, competing_tip);

        let mut seen = HashSet::new();
        assert!(seen.insert(range));
        assert!(!seen.insert(same), "equal ranges must hash alike");
        assert!(seen.insert(competing_tip));
    }

    /// G.17 — the bound must clear the configured recovery window, never merely
    /// equal it. The self-heal branch's flush-failure trigger first fires with
    /// the cursor one block under a full ring's floor, so its first legitimate
    /// walk is `recovery_window_depth + 1` blocks long. A bound sized *at* the
    /// depth — what maximizing against the constant yields once a chain
    /// configures a window deeper than `SELF_HEAL_WALK_MAX_BLOCKS` — falls one
    /// block short of that walk and kills the stream during ordinary degraded
    /// operation. Adding the constant to the depth keeps its full headroom at
    /// every depth.
    ///
    /// Depth 2,000 is the only domain where the two formulas differ; at the
    /// depths in service today (96, and 0 on the L2s) the defect is inert, which
    /// is why `flush_self_heal_walk_stops_at_its_length_bound` cannot see it.
    #[tokio::test]
    async fn flush_self_heal_walk_succeeds_when_recovery_window_exceeds_the_constant_bound() {
        // One distinct hash per height: `hb` only spans 256 values, and the walk
        // rejects any block whose hash and number disagree with what it asked for.
        fn hash_at_height(number: u64) -> B256 {
            let mut bytes = [0u8; 32];
            bytes[24..].copy_from_slice(&number.to_be_bytes());
            B256::from(bytes)
        }

        let depth = 2_000u64;
        assert!(
            depth > SELF_HEAL_WALK_MAX_BLOCKS,
            "the defect is inert unless the configured window is the deeper of the two"
        );

        // A ring filled to its depth, with the flush cursor one block under its
        // floor — the shortfall a flush that kept failing while heads kept
        // arriving leaves behind the first time the self-heal branch fires.
        let tip = 10_000_000u64;
        let floor = tip - (depth - 1);
        let cursor = floor - 1;

        let mut linkage = HeadLinkage::new(depth);
        for number in floor..=tip {
            assert_eq!(
                linkage.observe(number, hash_at_height(number), hash_at_height(number - 1)),
                LinkOutcome::Linked
            );
        }

        // One `get_block_by_hash` per step from the ring anchor down to the
        // cursor, then the single pending block's logs.
        let asserter = Asserter::new();
        for number in (cursor + 1..=tip).rev() {
            asserter.push_success(&block_with_parent_at(
                number,
                hash_at_height(number),
                hash_at_height(number - 1),
            ));
        }
        asserter.push_success(&serde_json::json!([]));
        let settings = ProviderSettings::from_mock(mock_http_provider(asserter));

        let mut coalescer = HeadCoalescer::new(Some(cursor), WINDOW);
        coalescer.observe_head(cursor, Instant::now());

        let ranges = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect("the walk's first legitimate firing must not be refused by the bound");
        assert_eq!(ranges.len(), 1);
        assert_eq!(
            ranges[0].tip_hash,
            Some(hash_at_height(cursor)),
            "the healed window is fetched by the hash the walk established"
        );
    }

    /// A consumer's log-metric filter matches this exact string, and nothing
    /// else in the workspace reads it. Pinning it here is what makes a rename a
    /// test failure rather than a silently dead filter.
    #[test]
    fn live_head_gap_event_name_is_fixed() {
        assert_eq!(live_head_gap_event(), "live_head_gap");
    }

    /// Same contract as `live_head_gap_event_name_is_fixed`, for the event a
    /// future filter keys on to alarm on a chain claim specifically.
    #[test]
    fn live_head_reorg_beyond_ring_event_name_is_fixed() {
        assert_eq!(
            live_head_reorg_beyond_ring_event(),
            "live_head_reorg_beyond_ring"
        );
    }

    /// The walk's dispatch split, asserted directly since the live loop's own
    /// arm has no hermetic seam (`TODO G.15`). Only `ReorgBeyondRing` — the
    /// walk's one chain claim — earns the named event; every other exit,
    /// including a transport fault reaching the walk, must not, or a filter
    /// on the chain-claim event would count a stalled provider as one.
    #[test]
    fn walk_failure_event_names_only_the_chain_claim() {
        assert_eq!(
            walk_failure_event(&RpcError::ReorgBeyondRing),
            Some("live_head_reorg_beyond_ring"),
            "the chain claim must carry its own event"
        );

        for err in [
            RpcError::ConnectionError("stalled mid-walk".to_string()),
            RpcError::Gap,
            RpcError::Reorg {
                common_ancestor: 42,
            },
        ] {
            assert_eq!(
                walk_failure_event(&err),
                None,
                "{err:?} must keep the walk's unnamed line"
            );
        }
    }

    /// `flush_window_range` fetches in-window blocks by canonical hash only.
    ///
    /// Setup: ring holds canonical hb(200) for block 200. The mock has exactly one
    /// log response — the canonical log tagged with hb(200). The mock also has an
    /// "orphan" log queued second (tagged with a different hash). If by-number were
    /// used, the asserter would return responses in order and the test would get the
    /// canonical log (first) for the by-number call — so instead we prove by-number
    /// is never invoked structurally: `flush_window_range` is the by-hash-only path.
    /// The mock has only ONE response queued for `get_logs`. The ring is at depth 8
    /// with a single entry, so the unconditional top-up (I.4f) also fires on this
    /// flush and drains the queue a second time via `get_block_by_hash`; finding it
    /// empty, the mock transport errors — not a panic — and the top-up's
    /// non-propagating error arm (settled decision 8) swallows it.
    #[tokio::test]
    async fn orphan_rejection() {
        let canonical_log = serde_json::json!([{
            "address": "0xCAFECAFECAFECAFECAFECAFECAFECAFECAFECAFE",
            "topics": [],
            "data": "0x01",
            "blockHash": hb(200).to_string(),
            "blockNumber": "0xc8",
            "transactionHash": hb(1).to_string(),
            "transactionIndex": "0x0",
            "logIndex": "0x0",
            "removed": false
        }]);
        // One response only, for get_logs. The top-up's get_block_by_hash drains
        // the queue empty and errors — swallowed, not a panic (see the doc comment
        // above).
        let asserter = Asserter::new();
        asserter.push_success(&canonical_log);
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );

        // Ring holds canonical hash for block 200; coalescer has [200, 200] pending.
        let mut linkage = HeadLinkage::new(8);
        linkage.observe(200, hb(200), hb(199)); // bootstraps ring with (200, hb(200))
        let mut coalescer = HeadCoalescer::new(Some(200), WINDOW);
        coalescer.observe_head(200, Instant::now());

        let ranges = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect("flush should succeed");

        assert_eq!(ranges.len(), 1, "one range per block");
        let range = &ranges[0];
        assert_eq!((range.from_block, range.to_block), (200, 200));
        assert_eq!(range.logs.len(), 1, "canonical log returned");
        assert_eq!(
            range.logs[0].block_hash,
            Some(hb(200)),
            "log must carry the canonical block hash, not an orphan's"
        );
        assert_eq!(
            range.tip_hash,
            Some(hb(200)),
            "the live flush fetches by hash and carries it"
        );
        // Cursor advanced past block 200.
        assert_eq!(coalescer.pending_range(), None);
    }

    /// A null block and a transport error are both "the primary did not
    /// answer" — with a single configured HTTP provider there is nowhere
    /// left to fall back to, so both yield `ConnectionError`, a view claim,
    /// never `ReorgBeyondRing`.
    #[tokio::test]
    async fn hash_mismatch_null_and_transport_are_unresolved() {
        {
            let asserter = Asserter::new();
            asserter.push_success(&serde_json::json!(null));
            let provider = mock_http_provider(asserter);
            let settings = n_http_provider_settings(1);
            // Walk from block 5 (hash hb(5)) down to block 1; the first fetch returns null.
            let err = collect_window_hashes(&provider, &settings, None, 0, hb(5), 5, 1)
                .await
                .expect_err("null block must be an error");
            assert!(
                matches!(err, RpcError::ConnectionError(_)),
                "null block must yield ConnectionError, got {err:?}"
            );
        }
        {
            let asserter = Asserter::new();
            asserter.push_failure_msg("connection reset");
            let provider = mock_http_provider(asserter);
            let settings = n_http_provider_settings(1);
            let err = collect_window_hashes(&provider, &settings, None, 0, hb(5), 5, 1)
                .await
                .expect_err("transport error must be an error");
            assert!(
                matches!(err, RpcError::ConnectionError(_)),
                "transport fault must yield ConnectionError, got {err:?}"
            );
        }
    }

    /// When `depth == 0` the by-hash path is never entered.
    /// `HeadLinkage::enabled()` returns false; `observe` returns `Linked` for every
    /// head regardless of parent mismatch. No `get_block_by_hash` call is issued.
    #[test]
    fn dormancy_at_depth_zero() {
        let mut linkage = HeadLinkage::new(0);
        assert!(!linkage.enabled(), "depth=0 must be disabled");

        // Any head — even one with a bogus parent — must return Linked.
        assert_eq!(
            linkage.observe(100, hb(1), hb(99)),
            LinkOutcome::Linked,
            "depth=0 must not trigger reorg detection"
        );
        assert_eq!(
            linkage.observe(101, hb(2), hb(55)), // obviously wrong parent
            LinkOutcome::Linked,
            "depth=0 must not trigger reorg detection on bad parent"
        );
        // Ring stays empty: no state accrues when disabled.
        assert_eq!(
            linkage.floor(),
            None,
            "disabled linkage must not record state"
        );
    }

    /// After the boot gap is flushed by `flush_window_range`, the ring holds the
    /// first observed head. The production path for the NEXT head is a clean
    /// `observe` extension — no false reorg fires.
    ///
    /// In production: `stream_heads_with_logs` creates a fresh empty ring, then
    /// `observe(first_head)` bootstraps it. `flush_window_range` handles the gap
    /// [cursor, first_head] using the walked pairs directly (no ring seeding).
    /// The second head (first_head + 1) then links cleanly via the normal parent
    /// check — because `observe(first_head+1)` checks ring.back() = first_head.
    #[test]
    fn boot_tail_seeds_ring() {
        // Production state after first head 105 arrives: ring bootstrapped to {105}.
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(
            linkage.observe(105, hb(105), hb(104)),
            LinkOutcome::Linked,
            "bootstrap observe"
        );
        assert_eq!(linkage.hash_at(105), Some(hb(105)));

        // After flush_window_range handles [cursor=101, 105], the cursor moves to 106.
        // The next WS head is 106 with correct parent hb(105) — must link cleanly.
        assert_eq!(
            linkage.observe(106, hb(106), hb(105)),
            LinkOutcome::Linked,
            "first post-flush head must link without false reorg"
        );
        assert_eq!(linkage.hash_at(106), Some(hb(106)));

        // Subsequent heads also link cleanly.
        assert_eq!(linkage.observe(107, hb(107), hb(106)), LinkOutcome::Linked);
    }

    // ── P3.4 addendum: live flush self-heal + orphan rejection ──────────────

    /// REGRESSION — live flush with a head gap must not wedge.
    ///
    /// Scenario: depth=8, cursor=101, first WS head is 105 (gap [101,104]).
    /// Before the fix the flush found `hash_at(101) = None`, broke out of the for
    /// loop, and `continue`d the `'flush while` with the cursor unmoved — an
    /// infinite spin. After the fix `flush_window_range` self-heals by walking from
    /// ring.latest() (105) back to 101, then fetches logs for each block by hash.
    ///
    /// The test is bounded by tokio's async executor; a spin would deadlock it.
    #[tokio::test]
    async fn live_flush_gap_self_heals() {
        // Ring: observe(105) bootstraps to {105}. Cursor: 101.
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(105, hb(105), hb(104)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(101), WINDOW);
        coalescer.observe_head(105, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((101, 105)));

        // Mock: self-heal walk 105→104→103→102 (4 get_block_by_hash calls;
        // 101==from_block so no fetch for 101 itself). Then 5 get_logs
        // (at_block_hash) for blocks 101..=105. That leaves the ring at depth
        // 8 with only 5 entries (101..=105), so the unconditional top-up
        // (I.4f) also fires: it issues one more get_block_by_hash, finds the
        // queue drained, and errors — swallowed by the top-up's
        // non-propagating error arm (settled decision 8), not affecting the
        // assertions below.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent_at(105, hb(105), hb(104)));
        asserter.push_success(&block_with_parent_at(104, hb(104), hb(103)));
        asserter.push_success(&block_with_parent_at(103, hb(103), hb(102)));
        asserter.push_success(&block_with_parent_at(102, hb(102), hb(101)));
        for _ in 101u64..=105 {
            asserter.push_success(&serde_json::json!([]));
        }
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );

        let ranges = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect("flush must succeed, not spin");

        assert_eq!(ranges.len(), 5, "one LogRange per block 101..=105");
        for (i, range) in ranges.iter().enumerate() {
            let n = 101u64 + i as u64;
            assert_eq!((range.from_block, range.to_block), (n, n));
        }
        // Cursor advanced past all flushed blocks.
        assert_eq!(coalescer.pending_range(), None);
    }

    /// `collect_window_hashes`: a by-hash response whose `header.number` does
    /// not match the expected number is not an answer — the same bucket as a
    /// null or a wrong hash. With N=1 there is no other provider to fall
    /// back to, so this is `ConnectionError`, a view claim, never a verdict
    /// about the chain. The hash below is honestly the queried hash
    /// (hb(5)) precisely to prove that even a hash MATCH does not save a
    /// number mismatch.
    #[tokio::test]
    async fn collect_window_hashes_number_mismatch() {
        let asserter = Asserter::new();
        // Wrong number, but parent_hash (hb(4)) lands exactly on from_block:
        // if the number check is dropped, the walk accepts this block and
        // completes at Ok(vec![(5, hb(5)), (4, hb(4))]) instead of exhausting
        // — the sharpest signal a dropped guard can leave.
        asserter.push_success(&block_with_parent_at(99, hb(5), hb(4))); // wrong number
        let provider = mock_http_provider(asserter);
        let settings = n_http_provider_settings(1);

        let err = collect_window_hashes(&provider, &settings, None, 0, hb(5), 5, 4)
            .await
            .expect_err("number mismatch must be an error");
        assert!(
            matches!(err, RpcError::ConnectionError(_)),
            "number mismatch must yield ConnectionError, got {err:?}"
        );
    }

    /// `collect_window_hashes`'s own PRIMARY hash-identity check, which nothing
    /// else exercises: every other fixture hands the primary either an honest
    /// block or `null`. Hash identity is what makes it sound to collect a
    /// block from any provider into the window's `(number, hash)` pairs and
    /// later fetch logs by that hash, so losing it silently is the worst
    /// failure this function has.
    ///
    /// The primary answers `Ok(Some)` with a block whose own hash is NOT the
    /// one queried, but whose `number` IS correct — it must clear the
    /// (separately covered) number-integrity check and be caught by the
    /// hash-identity check instead. `parent_hash` sits one block short of
    /// `from_block`, so if the guard is dropped and the wrong block is
    /// accepted, the walk completes in a single further step instead of
    /// falling back to the other providers — `expect_err` below then fails
    /// outright rather than merely returning a different error, the
    /// sharpest signal a dropped guard can leave. Keep the guard and the
    /// primary's answer falls back to the other two providers, both null,
    /// and the walk fails closed with `ConnectionError`.
    #[tokio::test]
    async fn collect_window_hashes_primary_wrong_hash_does_not_answer_the_step() {
        let primary_asserter = Asserter::new();
        // Queried for hb(5); answers with a block of the correct number (5)
        // but hash hb(77) instead.
        primary_asserter.push_success(&block_with_parent_at(5, hb(77), hb(4)));
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);

        let corrob1 = Asserter::new();
        corrob1.push_success(&serde_json::json!(null));
        let corrob2 = Asserter::new();
        corrob2.push_success(&serde_json::json!(null));
        let reused = vec![
            mock_http_provider(Asserter::new()), // index 0: the primary, never dispatched
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let err = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 4)
            .await
            .expect_err("a wrong-hash primary block must never answer the step");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    // ── collect_window_hashes: sequential fallback matrix ────────────────────
    // The primary IS one of the N HTTP providers (`primary_index`); a miss
    // falls back to the other N-1, starting right after `primary_index`.

    /// N=3, primary null, one other provider serves the block (valid hash
    /// and number) → the walk continues; assert the full collected pair
    /// list, not just the outcome variant.
    #[tokio::test]
    async fn collect_window_hashes_second_source_continues_walk() {
        let primary_asserter = Asserter::new();
        primary_asserter.push_success(&serde_json::json!(null)); // step 1: triggers step resolution
        primary_asserter.push_success(&block_with_parent_at(4, hb(4), hb(3))); // step 2: direct match
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);

        let corrob1 = Asserter::new();
        corrob1.push_success(&block_with_parent_at(5, hb(5), hb(4))); // recovers step 1
        let corrob2 = Asserter::new();
        corrob2.push_success(&serde_json::json!(null));
        let reused = vec![
            mock_http_provider(Asserter::new()), // index 0: the primary, never dispatched
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let pairs_desc = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 3)
            .await
            .expect("one second source supplying the block must let the walk continue");
        assert_eq!(
            pairs_desc,
            vec![(5, hb(5)), (4, hb(4)), (3, hb(3))],
            "got {pairs_desc:?}"
        );
    }

    /// N=3, primary null, both other providers null: every provider tried,
    /// none answered — `ConnectionError`, a view claim, never a verdict about
    /// the chain.
    #[tokio::test]
    async fn collect_window_hashes_all_sources_absent_is_unresolved() {
        let primary_asserter = Asserter::new();
        primary_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);
        let corrob1 = Asserter::new();
        corrob1.push_success(&serde_json::json!(null));
        let corrob2 = Asserter::new();
        corrob2.push_success(&serde_json::json!(null));
        let reused = vec![
            mock_http_provider(Asserter::new()),
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let err = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 1)
            .await
            .expect_err("exhausting every provider must be an error");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// N=3, primary null, both other providers transport-fail: same
    /// exhaustion, different reason — still `ConnectionError`.
    #[tokio::test]
    async fn collect_window_hashes_lone_absent_answer_is_unresolved() {
        let primary_asserter = Asserter::new();
        primary_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);
        let corrob1 = Asserter::new();
        corrob1.push_failure_msg("blip");
        let corrob2 = Asserter::new();
        corrob2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(Asserter::new()),
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let err = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 1)
            .await
            .expect_err("exhausting every provider must be an error");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// N=3, primary null, one other provider null + one transport-fail: the
    /// primary's own miss no longer counts toward anything — it is simply
    /// tried, then skipped, and the other two are tried and also miss.
    #[tokio::test]
    async fn collect_window_hashes_primary_miss_does_not_shorten_fallback() {
        let primary_asserter = Asserter::new();
        primary_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);
        let corrob1 = Asserter::new();
        corrob1.push_success(&serde_json::json!(null));
        let corrob2 = Asserter::new();
        corrob2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(Asserter::new()),
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let err = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 1)
            .await
            .expect_err("exhausting every provider must be an error");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// A second source's block failing the number-integrity check is not a
    /// match — it folds into the same "did not answer" bucket a transport
    /// error does.
    #[tokio::test]
    async fn collect_window_hashes_wrong_number_is_not_a_recovery() {
        let primary_asserter = Asserter::new();
        primary_asserter.push_success(&serde_json::json!(null));
        let provider = mock_http_provider(primary_asserter);
        let settings = n_http_provider_settings(3);
        let corrob1 = Asserter::new();
        // Right hash, WRONG number — fails the identity check, must not match.
        corrob1.push_success(&block_with_parent_at(99, hb(5), hb(4)));
        let corrob2 = Asserter::new();
        corrob2.push_failure_msg("blip");
        let reused = vec![
            mock_http_provider(Asserter::new()),
            mock_http_provider(corrob1),
            mock_http_provider(corrob2),
        ];

        let err = collect_window_hashes(&provider, &settings, Some(&reused), 0, hb(5), 5, 1)
            .await
            .expect_err("wrong-number second source must not match");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// `flush_window_range`: when `latest()` is None (ring completely empty),
    /// the function returns `Gap` rather than panicking — no anchor
    /// to walk from, and no record anywhere to disagree with.
    #[tokio::test]
    async fn flush_window_range_empty_ring_is_fail_closed() {
        let asserter = Asserter::new(); // no responses needed
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );
        let mut linkage = HeadLinkage::new(8); // empty ring (no observe yet)
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(100, Instant::now());

        let err = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect_err("empty ring must be fail-closed");
        assert!(matches!(err, RpcError::Gap), "got {err:?}");
    }

    /// The flush's own zero-provider guard: a configuration fault, resolved
    /// before any fetch and never a panic — the same posture
    /// `walk_to_common_ancestor_zero_http_providers_is_unresolved` holds for
    /// the walk. `http_settings`/`connect_http` index by modulo, so an empty
    /// set has no safe reader; only this guard keeps it out of them.
    #[tokio::test]
    async fn flush_window_range_zero_http_providers_is_fail_closed() {
        let settings = n_http_provider_settings(0);
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(100, hb(100), hb(99)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(100, Instant::now());

        let err = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect_err("no configured HTTP provider must be fail-closed");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// The label is built at the call site BEFORE `flush_window_range` can
    /// reach the guard above, so it must not be the thing that panics on the
    /// configuration this repo deliberately tolerates: `http_settings(0)`
    /// computes `0 % 0` on an empty set.
    #[test]
    fn flush_timeout_label_survives_an_empty_provider_set() {
        let ws_host = "ws-provider.example.invalid";
        let label = flush_timeout_label(&n_http_provider_settings(0), ws_host);
        assert!(
            label.contains(ws_host),
            "the label must still name the WS host with no HTTP provider \
             configured: {label}"
        );
    }

    /// With providers configured the label names the first one — the same
    /// index the flush passes to `flush_window_range`.
    #[test]
    fn flush_timeout_label_names_the_first_configured_provider() {
        let label = flush_timeout_label(&n_http_provider_settings(2), "ws-host.invalid");
        assert!(
            label.contains("ws-host.invalid") && label.contains("unused-0"),
            "the label must name the WS host and the first HTTP provider: {label}"
        );
    }

    /// Minimal `tracing::Subscriber` enabled for every callsite, recording
    /// nothing. `warn!`'s arguments are only evaluated when some subscriber is
    /// both installed (via `tracing::subscriber::set_default`) and interested
    /// (`enabled` returning `true`, plus `tracing::callsite::rebuild_interest_cache`
    /// so a stale "nobody's listening" cache from an earlier test doesn't keep
    /// suppressing evaluation) — with neither, a regression test that only
    /// asserts "the call didn't panic" can pass even when the logged expression
    /// itself would panic, because it never actually runs. Installing this for
    /// the scope of a test forces that evaluation, so the assertion is real.
    struct AlwaysOnSubscriber;

    impl tracing::Subscriber for AlwaysOnSubscriber {
        fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
            true
        }
        fn new_span(&self, _span: &tracing::span::Attributes<'_>) -> tracing::span::Id {
            tracing::span::Id::from_u64(1)
        }
        fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
        fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
        fn event(&self, _event: &tracing::Event<'_>) {}
        fn enter(&self, _span: &tracing::span::Id) {}
        fn exit(&self, _span: &tracing::span::Id) {}
    }

    /// REGRESSION — `flush_window_range`'s self-heal walk when the ring's only
    /// entry (`top_n`) is *older* than the coalescer's `from_block` (a stale
    /// ring lagging a cursor that has already advanced past it). Before the
    /// fix, the self-heal `warn!` computed `top_n - from_block + 1` before
    /// reaching `collect_window_hashes`'s own `tip_number < from_block` guard —
    /// on a build where the `warn!` argument is evaluated (any binary with a
    /// subscriber installed at a level that enables it, e.g. the CLI's default
    /// INFO subscriber), that subtraction panics. This test drives exactly
    /// that ring/cursor shape end-to-end and asserts the call returns cleanly
    /// (empty ranges, since nothing above the stale ring's tip is resolvable)
    /// rather than panicking.
    ///
    /// `tracing::warn!` does not evaluate its argument expressions unless a
    /// subscriber is installed and interested — with none installed (the
    /// default in this test binary), the underflow-prone expression would
    /// never run and this test would pass identically whether or not the fix
    /// is in place. `AlwaysOnSubscriber` forces real evaluation for the scope
    /// of this call.
    #[tokio::test]
    async fn flush_window_range_self_heal_with_stale_ring_does_not_panic() {
        // No queued responses: Part A's self-heal guard no-ops (top_n < from_block)
        // before any RPC. The depth-8 ring's top-up (I.4f) then fires too (floor 50
        // > target 43) and does issue one get_block_by_hash call, but the empty
        // asserter errors it immediately, and the top-up's non-propagating error
        // arm swallows that the same way.
        let asserter = Asserter::new();
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );

        // Ring holds only an old block (top_n = 50)...
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(50, hb(50), hb(49)), LinkOutcome::Linked);

        // ...but the coalescer's cursor is already ahead of it (from_block = 100).
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(100, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((100, 100)));

        // Force the self-heal `warn!`'s arguments to actually be evaluated —
        // see `AlwaysOnSubscriber`'s doc comment.
        let subscriber_guard = tracing::subscriber::set_default(AlwaysOnSubscriber);
        tracing::callsite::rebuild_interest_cache();

        let ranges = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect(
                "a stale ring must not panic — collect_window_hashes's own guard \
                 no-ops the walk",
            );
        assert!(
            ranges.is_empty(),
            "no hashes are resolvable above the stale ring's tip"
        );

        // Restore the default and rebuild the cache again so no later test in
        // this binary inherits an "always interested" callsite cache from here.
        drop(subscriber_guard);
        tracing::callsite::rebuild_interest_cache();
    }

    /// REGRESSION — the self-heal walk's own `resolve_http_provider(providers,
    /// reused, provider_index)` call must resolve its client from the
    /// caller-supplied `reused` set, the same way the subsequent by-hash log
    /// fetch already does — not rebuild a fresh one via `connect_http`.
    ///
    /// Proven the same way `flush_window_range_dispatches_concurrently_and_
    /// restores_ascending_order` proves the log-fetch side's reuse:
    /// `settings`' own configured HTTP endpoint is unreachable, so a
    /// `connect_http` rebuild fails the walk's very first `get_block_by_hash`
    /// call outright, while `reused`'s working mock lets the flush succeed —
    /// success is only possible if the walk actually used the reused client.
    #[tokio::test]
    async fn flush_window_range_self_heal_walk_uses_reused_http_client() {
        // Ring: observe(105) bootstraps to {105}. Cursor: 101 — same shape as
        // `live_flush_gap_self_heals`, forcing the self-heal walk.
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(105, hb(105), hb(104)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(101), WINDOW);
        coalescer.observe_head(105, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((101, 105)));

        // The reused (working) client: walk 105→104→103→102 (4 get_block_by_hash
        // calls; 101==from_block so no fetch for 101 itself), then 5 get_logs.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent_at(105, hb(105), hb(104)));
        asserter.push_success(&block_with_parent_at(104, hb(104), hb(103)));
        asserter.push_success(&block_with_parent_at(103, hb(103), hb(102)));
        asserter.push_success(&block_with_parent_at(102, hb(102), hb(101)));
        for _ in 101u64..=105 {
            asserter.push_success(&serde_json::json!([]));
        }
        let reused = vec![mock_http_provider(asserter)];

        // `connect_http`, if the self-heal walk fell back to it, would build a
        // real client against this unreachable host and fail the walk.
        let settings = ProviderSettings::new(
            vec![HttpRpcSettings::new("http://unused".to_string(), 1, 100)],
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );

        let ranges = flush_window_range(
            &mut linkage,
            &mut coalescer,
            &settings,
            None,
            0,
            Some(&reused),
        )
        .await
        .expect(
            "self-heal walk must resolve its client from `reused`, not rebuild via connect_http",
        );

        assert_eq!(ranges.len(), 5, "one LogRange per block 101..=105");
        for (i, range) in ranges.iter().enumerate() {
            let n = 101u64 + i as u64;
            assert_eq!((range.from_block, range.to_block), (n, n));
        }
    }

    /// I.4f §6.2 — Part A alone: one flush from a ring bootstrapped one entry
    /// deep at the live head (105), cursor at 101 — the post-restart shape.
    /// The self-heal walk's already-fetched pairs land in the ring
    /// (`extend_downward`), and `depth` is sized so the ring is *exactly*
    /// full once they do (`depth == latest - from_block + 1 == 5`): the
    /// top-up then finds `floor() == lowest_worth_recording()` and skips,
    /// which is what isolates Part A from Part B's own deepening (settled
    /// decision 6 — Part B runs on every flush by design, so a looser
    /// `depth` would let it move the floor too, and the exact-cursor
    /// assertion below would no longer isolate anything).
    ///
    /// Reverting Part A (dropping the `extend_downward` call in the
    /// self-heal branch) leaves the ring at its pre-flush single entry —
    /// the floor stays at the live head (105), never reaching the cursor
    /// (101) — and this test fails.
    #[tokio::test]
    async fn flush_window_range_part_a_seeds_ring_down_to_the_flush_cursor() {
        let mut linkage = HeadLinkage::new(5);
        assert_eq!(linkage.observe(105, hb(105), hb(104)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(101), WINDOW);
        coalescer.observe_head(105, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((101, 105)));

        // Self-heal walk: 105 -> 104 -> 103 -> 102 (4 calls; 101 == from_block,
        // no fetch for 101 itself), then 5 log fetches (101..=105). Exactly 9
        // responses queued — the ring lands exactly full, so the top-up finds
        // nothing left and issues no 10th call; a drained Asserter queried a
        // 10th time would surface as an error the flush's own `Result` masks,
        // so the real proof is the floor assertion below, not silence alone.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent_at(105, hb(105), hb(104)));
        asserter.push_success(&block_with_parent_at(104, hb(104), hb(103)));
        asserter.push_success(&block_with_parent_at(103, hb(103), hb(102)));
        asserter.push_success(&block_with_parent_at(102, hb(102), hb(101)));
        for _ in 101u64..=105 {
            asserter.push_success(&serde_json::json!([]));
        }
        let reused = vec![mock_http_provider(asserter)];
        let settings = n_http_provider_settings(1);

        let ranges = flush_window_range(
            &mut linkage,
            &mut coalescer,
            &settings,
            None,
            0,
            Some(&reused),
        )
        .await
        .expect("flush must succeed");

        assert_eq!(ranges.len(), 5, "one LogRange per block 101..=105");
        assert_eq!(
            linkage.floor(),
            Some(101),
            "Part A must drop the floor to the flush cursor (from_block)"
        );
        assert_eq!(
            linkage.lowest_worth_recording(),
            linkage.floor(),
            "depth was sized so the ring is already full — the top-up has \
             nothing left to walk"
        );
    }

    /// I.4f §6.3 — Part B alone, and it must not ride Part A's branch. The
    /// ring holds only the live head (200, depth 96 — production magnitude),
    /// and every flush in this test asks for exactly that one block, so the
    /// self-heal branch (`heads.rs:544`'s ring-miss predicate) can never
    /// fire: whatever moves the floor here is Part B.
    ///
    /// Reverting Part B leaves the floor pinned at 200 on every flush; this
    /// test fails on the very first iteration, while §6.2's test (which
    /// never touches Part B in a way this scenario could distinguish) does
    /// not — the separation the mutation check (§6.5) depends on.
    #[tokio::test]
    async fn flush_window_range_part_b_deepens_ring_without_a_self_heal_walk() {
        const DEPTH: u64 = 96;
        const TIP: u64 = 200;
        const TARGET: u64 = TIP - (DEPTH - 1); // 105 — lowest_worth_recording

        let mut linkage = HeadLinkage::new(DEPTH);
        assert_eq!(
            linkage.observe(TIP, hb(TIP as u8), hb((TIP - 1) as u8)),
            LinkOutcome::Linked
        );

        // Cap-sized steps down to TARGET: eleven steps of the full cap (8),
        // then one shorter step (7) landing exactly on TARGET — mirrors the
        // prompt's own derivation (a 96-deep ring converges in ~12 flushes
        // at 8 steps/flush).
        let mut steps = vec![REORG_RING_TOP_UP_STEPS; 11];
        steps.push(TIP - TARGET - 11 * REORG_RING_TOP_UP_STEPS); // 7
        assert_eq!(
            steps.iter().sum::<u64>(),
            TIP - TARGET,
            "sanity: steps span the full descent"
        );

        // Queue each flush's one `get_logs` response, then that flush's
        // block-fetch responses (descending, matching the walk's own order).
        let asserter = Asserter::new();
        let mut floor = TIP;
        for &step in &steps {
            asserter.push_success(&serde_json::json!([]));
            for n in ((floor - step + 1)..=floor).rev() {
                asserter.push_success(&block_with_parent_at(n, hb(n as u8), hb((n - 1) as u8)));
            }
            floor -= step;
        }
        assert_eq!(floor, TARGET);

        // Kept to queue one more `get_logs` response for the final,
        // already-full-ring flush below — `Asserter` shares its queue
        // through an inner `Arc`, so this handle and the provider's own
        // stay in sync.
        let asserter_handle = asserter.clone();
        let reused = vec![mock_http_provider(asserter)];
        let settings = n_http_provider_settings(1);

        let mut expected_floor = TIP;
        for (i, &step) in steps.iter().enumerate() {
            let mut coalescer = HeadCoalescer::new(Some(TIP), WINDOW);
            coalescer.observe_head(TIP, Instant::now());
            assert_eq!(coalescer.pending_range(), Some((TIP, TIP)));

            flush_window_range(
                &mut linkage,
                &mut coalescer,
                &settings,
                None,
                0,
                Some(&reused),
            )
            .await
            .expect("flush must succeed");

            expected_floor -= step;
            assert_eq!(
                linkage.floor(),
                Some(expected_floor),
                "flush {i}: floor must descend by exactly this step"
            );
        }
        assert_eq!(
            steps[0], REORG_RING_TOP_UP_STEPS,
            "the first flush's descent must be the full cap"
        );
        assert_eq!(linkage.floor(), Some(TARGET));
        assert_eq!(linkage.lowest_worth_recording(), Some(TARGET));

        // Ring is now full: one more flush must not move the floor past
        // `lowest_worth_recording` — the top-up self-disables rather than
        // walking below it.
        let mut coalescer = HeadCoalescer::new(Some(TIP), WINDOW);
        coalescer.observe_head(TIP, Instant::now());
        asserter_handle.push_success(&serde_json::json!([])); // this flush's own get_logs(200)
        flush_window_range(
            &mut linkage,
            &mut coalescer,
            &settings,
            None,
            0,
            Some(&reused),
        )
        .await
        .expect("flush must succeed even once the ring is already full");
        assert_eq!(
            linkage.floor(),
            Some(TARGET),
            "floor must stop at the accessor, not below it"
        );
    }

    /// I.4f §6.4 — the incident, end to end (2026-08-14 01:17Z in miniature).
    /// A stream restart bootstraps the ring one entry deep at the live head.
    /// A reorg's common ancestor lies below that head but within `depth` —
    /// exactly the shape that produced a beyond-finality report against a ring
    /// that had never been filled.
    ///
    /// Two linkages, same detached-parent walk: `undeepened` never flushes
    /// (the ring stays exactly where a restart leaves it — "at `EXPECT_TIP`"
    /// in the goal's own words), `deepened` runs ordinary flushes first (Part
    /// B alone) so its floor passes the ancestor before the reorg arrives.
    /// `walk_to_common_ancestor` on `undeepened` reaches the floor with a
    /// fetched hash that disagrees with the one recorded there, so it reports
    /// `ReorgBeyondRing`; on `deepened` it resolves to the ancestor.
    #[tokio::test]
    async fn walk_to_common_ancestor_resolves_after_ring_deepens_past_the_ancestor() {
        const DEPTH: u64 = 96;
        const HEAD: u64 = 200;
        // Within DEPTH of HEAD (200 - 170 = 30 < 95), but below where the
        // ring's floor sits the instant a stream restarts (HEAD itself).
        const ANCESTOR: u64 = 170;
        const CHILD_NUMBER: u64 = HEAD + 2;

        // A byte range (50..=81) disjoint from the canonical chain's own
        // (105..=200), so no fork hash accidentally matches a ring entry.
        fn fork_hash(n: u64) -> B256 {
            hb((50 + (n - ANCESTOR)) as u8)
        }

        let detached_parent = fork_hash(CHILD_NUMBER - 1);

        // `undeepened`: the ring exactly as a restart leaves it — bootstrapped
        // one entry deep at HEAD, never flushed.
        let mut undeepened = HeadLinkage::new(DEPTH);
        assert_eq!(
            undeepened.observe(HEAD, hb(HEAD as u8), hb((HEAD - 1) as u8)),
            LinkOutcome::Linked
        );
        assert_eq!(undeepened.floor(), Some(HEAD));

        let undeepened_asserter = Asserter::new();
        // One step: the walk fetches CHILD_NUMBER - 1's block, finds its
        // parent (at HEAD) doesn't match the ring, and HEAD is the floor —
        // a confirmed disagreement without a second fetch.
        undeepened_asserter.push_success(&block_with_parent(detached_parent, fork_hash(HEAD)));
        let undeepened_provider = mock_http_provider(undeepened_asserter);
        let settings = n_http_provider_settings(1);

        let undeepened_result = walk_to_common_ancestor(
            &undeepened_provider,
            &settings,
            None,
            &undeepened,
            detached_parent,
            CHILD_NUMBER,
            DEPTH,
        )
        .await;
        assert!(
            matches!(undeepened_result, Err(RpcError::ReorgBeyondRing)),
            "got {undeepened_result:?}"
        );

        // `deepened`: the same bootstrap, then ordinary flushes (Part B
        // alone — the window is always covered by the ring's own tip, same
        // shape as §6.3's test) carry the floor down past ANCESTOR before
        // the reorg arrives.
        let mut deepened = HeadLinkage::new(DEPTH);
        assert_eq!(
            deepened.observe(HEAD, hb(HEAD as u8), hb((HEAD - 1) as u8)),
            LinkOutcome::Linked
        );
        // The top-up's own stop condition is `lowest_worth_recording`
        // (HEAD - (DEPTH - 1) = 105), not ANCESTOR — the fixtures below must
        // match what the real implementation actually walks toward, and the
        // outer loop below simply stops queuing once that real progression
        // has carried the floor at or below ANCESTOR.
        let lowest_worth_recording = HEAD - (DEPTH - 1);
        let flush_asserter = Asserter::new();
        let mut floor = HEAD;
        while floor > ANCESTOR {
            flush_asserter.push_success(&serde_json::json!([])); // this flush's get_logs(HEAD)
            let walk_from =
                lowest_worth_recording.max(floor.saturating_sub(REORG_RING_TOP_UP_STEPS));
            for n in ((walk_from + 1)..=floor).rev() {
                flush_asserter.push_success(&block_with_parent_at(
                    n,
                    hb(n as u8),
                    hb((n - 1) as u8),
                ));
            }
            floor = walk_from;
        }
        let flush_reused = vec![mock_http_provider(flush_asserter)];
        while deepened.floor().expect("bootstrapped") > ANCESTOR {
            let mut coalescer = HeadCoalescer::new(Some(HEAD), WINDOW);
            coalescer.observe_head(HEAD, Instant::now());
            flush_window_range(
                &mut deepened,
                &mut coalescer,
                &settings,
                None,
                0,
                Some(&flush_reused),
            )
            .await
            .expect("flush must succeed");
        }
        assert!(
            deepened.floor().expect("bootstrapped") <= ANCESTOR,
            "the ring must deepen past the ancestor before the reorg arrives"
        );

        // The reorg walk itself: CHILD_NUMBER - 1 down to ANCESTOR + 1, where
        // the fork's parent hash finally matches the ring's canonical entry.
        let walk_asserter = Asserter::new();
        for n in ((ANCESTOR + 1)..CHILD_NUMBER).rev() {
            let parent = if n == ANCESTOR + 1 {
                hb(ANCESTOR as u8)
            } else {
                fork_hash(n - 1)
            };
            walk_asserter.push_success(&block_with_parent(fork_hash(n), parent));
        }
        let walk_provider = mock_http_provider(walk_asserter);

        let deepened_result = walk_to_common_ancestor(
            &walk_provider,
            &settings,
            None,
            &deepened,
            detached_parent,
            CHILD_NUMBER,
            DEPTH,
        )
        .await;
        assert!(
            matches!(deepened_result, Ok(ANCESTOR)),
            "got {deepened_result:?}"
        );
    }

    /// REGRESSION — `flush_window_range` with zero configured HTTP providers must
    /// return `Err`, not panic. Before the fix, the concurrent path's
    /// `providers.http_settings(provider_index)` call did `idx % http_providers.len()`
    /// with no guard, so an empty `http_providers` divided by zero and panicked —
    /// on an input for which the pre-fix sequential code (and
    /// `poll_providers_for_block_number`'s own `num_providers == 0` guard, the
    /// convention this mirrors) both cleanly returned `Err`. The ring is fully
    /// populated here (no self-heal walk) so this isolates the `http_settings`
    /// guard specifically.
    #[tokio::test]
    async fn flush_window_range_empty_http_providers_is_fail_closed_not_a_panic() {
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(100, hb(100), hb(99)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(100), WINDOW);
        coalescer.observe_head(100, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((100, 100)));

        let settings = ProviderSettings::new(
            vec![], // zero configured HTTP providers
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );

        let err = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect_err("zero HTTP providers must be fail-closed, not panic");
        assert!(matches!(err, RpcError::ConnectionError(_)), "got {err:?}");
    }

    /// `resolve_http_provider` is unreachable at `N == 0` in production (every
    /// caller fails closed first), but the arithmetic underneath it still
    /// divides by zero if that guard is ever removed. The guard's message must
    /// name the misconfiguration, not the arithmetic.
    #[test]
    #[should_panic(expected = "resolve_http_provider: no HTTP providers configured")]
    fn resolve_http_provider_panics_with_labeled_message_on_empty_http_providers() {
        let settings = ProviderSettings::new(
            vec![], // zero configured HTTP providers
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );
        resolve_http_provider(&settings, None, 0);
    }

    /// The backfill window boundary: blocks strictly below `tip - depth` are
    /// fetched by number (the normal backfill path); blocks `>= tip - depth` (within
    /// the reorg-exposed window) are fetched by hash.
    ///
    /// This test exercises the predicate logic directly: given a specific tip and
    /// depth, verify that `from_block >= tip.saturating_sub(depth)` correctly
    /// partitions the range.
    #[test]
    fn window_boundary() {
        // tip = 1000, depth = 50: window starts at 950.
        let tip: u64 = 1000;
        let depth: u64 = 50;
        let window_floor = tip.saturating_sub(depth); // 950

        // Blocks below the window floor are served by the backfill-by-number path.
        for n in [0u64, 500, 949] {
            assert!(
                n < window_floor,
                "block {n} should be below the window floor {window_floor}"
            );
        }

        // The window floor itself and everything above it is in the by-hash zone.
        for n in [950u64, 975, 1000] {
            assert!(
                n >= window_floor,
                "block {n} should be inside the by-hash window (floor {window_floor})"
            );
        }

        // Saturating_sub at depth == 0 yields u64::MAX (no window) — the by-hash
        // path is never entered, matching the dormancy_at_depth_zero invariant.
        let no_window_floor = tip.saturating_sub(0);
        assert_eq!(no_window_floor, tip, "depth=0 must not create a window");

        // Depth larger than tip saturates at 0: the entire history is in the window.
        let huge_depth_floor = tip.saturating_sub(tip + 1);
        assert_eq!(
            huge_depth_floor, 0,
            "depth > tip must floor at 0 (all blocks in window)"
        );
    }

    /// REGRESSION — a partial failure in a multi-block flush must not silently
    /// skip earlier blocks.
    ///
    /// Before the fix, `flush_window_range` advanced `coalescer.advance_cursor`
    /// inside the fetch loop. If block 201's fetch failed after 200 succeeded,
    /// the cursor advanced past 200 and its logs were discarded. On reconnect the
    /// stream resumed from 201, silently skipping block 200.
    ///
    /// After the fix the cursor is only advanced once the ENTIRE batch succeeds.
    /// This test fails against the pre-fix code (cursor at 201) and passes after
    /// (cursor stays at 200 — the whole range retries on the next provider).
    #[tokio::test]
    async fn flush_window_range_partial_failure_leaves_cursor_unmoved() {
        // Ring: blocks 200 and 201 observed (clean chain).
        let mut linkage = HeadLinkage::new(8);
        assert_eq!(linkage.observe(200, hb(200), hb(199)), LinkOutcome::Linked);
        assert_eq!(linkage.observe(201, hb(201), hb(200)), LinkOutcome::Linked);

        // Coalescer: cursor at 200, head 201 seen → pending [200, 201].
        let mut coalescer = HeadCoalescer::new(Some(200), WINDOW);
        coalescer.observe_head(201, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((200, 201)));

        // Single mocked HTTP provider (from_mock): one queued success (block 200's
        // get_logs), then one queued failure (block 201's get_logs). With a single
        // provider, one failure exhausts all retry attempts.
        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!([])); // block 200 logs succeed
        asserter.push_failure_msg("transient error"); // block 201 logs fail

        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );

        let result =
            flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None).await;

        // Must return Err — the batch did not complete.
        assert!(result.is_err(), "partial failure must return Err");

        // The cursor must NOT have advanced past block 200 — the whole range must
        // retry on the next provider so block 200 is not silently skipped.
        assert_eq!(
            coalescer.pending_range(),
            Some((200, 201)),
            "cursor must stay at 200 so block 200 is not silently skipped on reconnect"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn bound_flush_time_disabled_at_zero_awaits_normally() {
        let result: Result<u32, RpcError> = bound_flush_time(0, "unused at max_secs=0", async {
            tokio::time::sleep(Duration::from_millis(50)).await;
            Ok(42)
        })
        .await;
        assert_eq!(
            result.unwrap(),
            42,
            "max_secs=0 must not time out, however long the future takes"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn bound_flush_time_fires_on_a_slow_future() {
        let result: Result<u32, RpcError> = bound_flush_time(1, "ws=test-host", async {
            tokio::time::sleep(Duration::from_millis(1200)).await;
            Ok(42)
        })
        .await;
        assert!(
            matches!(result, Err(RpcError::ConnectionError(_))),
            "a future exceeding max_secs must yield ConnectionError, got {result:?}"
        );
    }

    /// Proves both G.5 checkboxes together: the timeout names the WS host and
    /// the fallback host it was given, ahead of the prose so identity survives
    /// even a tight cap, and the flush-failure log line carries that message
    /// complete through "switching provider" rather than cutting it mid-word.
    /// Reverting the label (checkbox 1) fails the host assertions below;
    /// reverting the log line's bound back to a 100-byte cap (checkbox 2)
    /// fails the tail assertion, since the labeled message is longer than 100
    /// bytes on its own.
    #[tokio::test(start_paused = true)]
    async fn bound_flush_time_timeout_names_both_providers_and_keeps_the_tail() {
        let ws_host = "ws-provider.example.invalid";
        let fallback_host = "fallback-provider.example.invalid";
        let label = format!("ws={ws_host} fallback={fallback_host}");

        let result: Result<u32, RpcError> = bound_flush_time(1, &label, async {
            tokio::time::sleep(Duration::from_millis(1200)).await;
            Ok(42)
        })
        .await;
        let err = result.expect_err("a future exceeding max_secs must time out");
        let display = err.to_string();

        let ws_pos = display
            .find(ws_host)
            .expect("timeout message must name the WS host");
        let fallback_pos = display
            .find(fallback_host)
            .expect("timeout message must name the fallback host");
        assert!(
            ws_pos < 100 && fallback_pos < 100,
            "both hosts must land before byte 100 of the error's Display output \
             so identity survives a tight cap, got ws@{ws_pos} fallback@{fallback_pos}: \
             {display}"
        );

        let log_line = flush_failure_log_line(&err, classify_flush_failure(&err));
        assert!(
            log_line.contains("stalled mid-flush; switching provider"),
            "the log line must carry the message complete through \
             'switching provider', not cut mid-word: {log_line}"
        );
    }

    /// SETTLING TEST for the top-up's placement invariant: `top_up_reorg_ring`'s
    /// call site inside `flush_window_range` must sit before
    /// `coalescer.advance_cursor`, never after. A `bound_flush_time` timeout
    /// firing mid-top-up must drop the top-up's own effect together with the
    /// already-fetched log ranges, never advance the cursor past blocks whose
    /// logs were not yielded. Moving the call after `advance_cursor` (the
    /// regression the placement comment on that call site warns against)
    /// makes this test fail: the cursor would advance to (last + 1) before the
    /// top-up's timeout is ever reached, so `pending_range()` would come back
    /// changed, not unchanged.
    ///
    /// `get_block_by_hash` returns a concrete builder type (`EthGetBlock`), not
    /// an `async fn` trait method, so the `Provider`-trait override this file
    /// otherwise uses for `get_logs` (see
    /// `flush_window_range_dispatches_concurrently_and_restores_ascending_order`)
    /// does not reach it. `DelayingTransport` intercepts one level lower, at the
    /// `tower::Service<RequestPacket>` the `RpcClient` dispatches through,
    /// delaying only `eth_getBlockByHash` requests so the flush's own `get_logs`
    /// call still resolves immediately.
    #[tokio::test(start_paused = true)]
    async fn flush_window_range_timeout_mid_top_up_drops_cursor_advance() {
        use alloy::rpc::client::RpcClient;
        use alloy::rpc::json_rpc::{RequestPacket, ResponsePacket};
        use alloy::transports::TransportError;
        use alloy::transports::TransportFut;
        use alloy::transports::mock::MockTransport;

        #[derive(Clone)]
        struct DelayingTransport {
            inner: MockTransport,
            delay: Duration,
        }

        impl tower::Service<RequestPacket> for DelayingTransport {
            type Response = ResponsePacket;
            type Error = TransportError;
            type Future = TransportFut<'static>;

            fn poll_ready(
                &mut self,
                cx: &mut std::task::Context<'_>,
            ) -> std::task::Poll<Result<(), Self::Error>> {
                tower::Service::<RequestPacket>::poll_ready(&mut self.inner, cx)
            }

            fn call(&mut self, req: RequestPacket) -> Self::Future {
                let mut inner = self.inner.clone();
                let delay_this = req.method_names().any(|m| m == "eth_getBlockByHash");
                let delay = self.delay;
                Box::pin(async move {
                    if delay_this {
                        tokio::time::sleep(delay).await;
                    }
                    tower::Service::call(&mut inner, req).await
                })
            }
        }

        // Depth 96 (BSC's finality depth), ring at a single entry (200): floor
        // (200) sits far above target (200 - 95 = 105), so the top-up has real
        // steps to walk. The flush's own in-window fetch (block 200) is already
        // covered by the ring, so the self-heal branch never fires — only the
        // top-up calls `get_block_by_hash`.
        let mut linkage = HeadLinkage::new(96);
        assert_eq!(linkage.observe(200, hb(200), hb(199)), LinkOutcome::Linked);
        let mut coalescer = HeadCoalescer::new(Some(200), WINDOW);
        coalescer.observe_head(200, Instant::now());
        let pending_before_flush = coalescer.pending_range();

        let asserter = Asserter::new();
        asserter.push_success(&serde_json::json!([])); // the one in-window get_logs call
        let transport = DelayingTransport {
            inner: MockTransport::new(asserter),
            delay: Duration::from_millis(1_200),
        };
        let provider: DynProvider<Ethereum> = ProviderBuilder::new()
            .disable_recommended_fillers()
            .connect_client(RpcClient::new(transport, false))
            .erased();
        let settings = ProviderSettings::from_mock(provider);

        let result = bound_flush_time(
            1,
            "ws=test-host fallback=test-host",
            flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None),
        )
        .await;

        assert!(
            matches!(result, Err(RpcError::ConnectionError(_))),
            "a top-up stalled past the flush bound must surface as a timeout, got {result:?}"
        );
        assert_eq!(
            coalescer.pending_range(),
            pending_before_flush,
            "a timeout mid-top-up must leave the cursor exactly where the flush found it — \
             the fetched ranges and the top-up's own walk both dropped together"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn idle_head_await_returns_a_header_well_within_the_bound() {
        let mut s = futures_util::stream::iter(vec![Header::default()]);
        let outcome = await_head_within_idle_bound(&mut s).await;
        assert!(
            matches!(outcome, IdleHeadAwait::Header(_)),
            "a stream with a ready header must resolve to it, not expire"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn idle_head_await_distinguishes_stream_ended_from_expiry() {
        let mut s = futures_util::stream::empty::<Header>();
        let outcome = await_head_within_idle_bound(&mut s).await;
        assert!(
            matches!(outcome, IdleHeadAwait::StreamEnded),
            "an ended stream must resolve to StreamEnded, not Expired"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn idle_head_await_expires_on_a_silent_stream() {
        let mut s = futures_util::stream::pending::<Header>();
        // Race the helper against its own outer bound rather than awaiting it
        // directly: under paused time, a reverted helper (no internal
        // timeout) registers no timer at all and would hang the test
        // forever. The outer timeout always registers one, so it fires
        // regardless of whether the helper is bounded — turning "no expiry"
        // into a clean assertion failure instead of a deadlock.
        let outcome = tokio::time::timeout(
            Duration::from_secs(IDLE_HEAD_AWAIT_SECS + 60),
            await_head_within_idle_bound(&mut s),
        )
        .await
        .expect("the idle bound must expire on its own, not hang past it");
        assert!(
            matches!(outcome, IdleHeadAwait::Expired),
            "a silently pending stream must resolve to Expired once the idle bound elapses"
        );
    }

    #[test]
    fn idle_rotation_counter_continues_below_threshold() {
        let mut counter = IdleRotationCounter::new();
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
    }

    #[test]
    fn idle_rotation_counter_fires_at_exactly_the_configured_provider_count() {
        let mut counter = IdleRotationCounter::new();
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::AllIdle));
    }

    #[test]
    fn idle_rotation_counter_fires_at_one_for_a_single_provider() {
        let mut counter = IdleRotationCounter::new();
        assert!(matches!(counter.expire(1), IdleRotation::AllIdle));
    }

    #[test]
    fn idle_rotation_counter_header_resets_the_count() {
        let mut counter = IdleRotationCounter::new();
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        counter.reset();
        // Without the reset, this third expiry would have hit the threshold.
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::Continue));
        assert!(matches!(counter.expire(3), IdleRotation::AllIdle));
    }

    /// Hermetic wiring proof for the live consumption loop:
    ///   observe_head → observe → should_flush → flush_window_range → [ranges]
    ///   → observe_reorg → LinkOutcome::Reorg
    ///
    /// This directly sequences the operations `stream_heads_with_logs` performs
    /// in its inner loop and asserts the correct outcomes at each step. It covers
    /// the two behaviors that had no hermetic test: the gap self-heal path and the
    /// reorg-terminate path.
    ///
    /// Residual: the outer WS-reconnect/failover loop in `stream_heads_with_logs`
    /// is exercised only by the `#[ignore]`d network test (`test_event_streamer_head`
    /// in `tests/events_test.rs`). A full seam extraction was evaluated and deferred
    /// to avoid restructuring the core stream at a release gate.
    #[tokio::test]
    async fn live_loop_wiring_gap_then_reorg() {
        // Coalescer: cursor at 101 (live filter from_block = 101).
        // Linkage: depth 8.
        let now = Instant::now();
        let mut coalescer = HeadCoalescer::new(Some(101), WINDOW);
        let mut linkage = HeadLinkage::new(8);

        // Step 1: head 105 arrives with a gap (101-104 skipped).
        // observe_head extends the coalescer's pending range to [101, 105].
        assert!(coalescer.observe_head(105, now));
        assert_eq!(coalescer.pending_range(), Some((101, 105)));

        // observe bootstraps the ring to {105} (bootstrap path: first observe on an
        // empty ring pushes and returns Linked).
        assert_eq!(linkage.observe(105, hb(105), hb(104)), LinkOutcome::Linked);
        assert_eq!(linkage.latest(), Some((105, hb(105))));

        // Step 2: simulate time advancing past the coalesce window by querying
        // should_flush with a synthetic instant past the deadline — no real or
        // paused sleep needed since this step never awaits.
        let after_window = now + WINDOW + Duration::from_millis(1);
        assert!(
            coalescer.should_flush(after_window),
            "coalesce window expired — flush must fire"
        );

        // Step 3: flush_window_range self-heals the gap [101, 105].
        // Walk: get_block_by_hash for hb(105)→hb(104)→hb(103)→hb(102) (4 fetches;
        // 101==from_block so the walk stops after pushing block 101).
        // Logs: 5 get_logs at_block_hash for blocks 101..=105.
        // Both walk and log calls use the same mocked HTTP provider.
        let asserter = Asserter::new();
        asserter.push_success(&block_with_parent_at(105, hb(105), hb(104)));
        asserter.push_success(&block_with_parent_at(104, hb(104), hb(103)));
        asserter.push_success(&block_with_parent_at(103, hb(103), hb(102)));
        asserter.push_success(&block_with_parent_at(102, hb(102), hb(101)));
        for _ in 101u64..=105 {
            asserter.push_success(&serde_json::json!([]));
        }
        let settings = ProviderSettings::from_mock(
            ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(asserter)
                .erased(),
        );

        let ranges = flush_window_range(&mut linkage, &mut coalescer, &settings, None, 0, None)
            .await
            .expect("gap self-heal must succeed");

        assert_eq!(ranges.len(), 5, "one range per block 101..=105");
        for (i, range) in ranges.iter().enumerate() {
            let n = 101u64 + i as u64;
            assert_eq!(
                (range.from_block, range.to_block),
                (n, n),
                "range at index {i} must be block {n}"
            );
        }
        // Cursor advanced past the full batch — no silent gap.
        assert_eq!(
            coalescer.pending_range(),
            None,
            "cursor must be at 106 after flush"
        );

        // Step 4: two more clean heads arrive and link.
        assert_eq!(linkage.observe(106, hb(106), hb(105)), LinkOutcome::Linked);
        assert_eq!(linkage.observe(107, hb(107), hb(106)), LinkOutcome::Linked);

        // Step 5: a competing block 107 with the same parent (hb(106)) but a
        // different hash (hb(250)) triggers a reorg. The ring has canonical hb(107)
        // at 107; a new block with parent matching canonical hb(106) at 106 produces
        // Reorg { common_ancestor: 106 }. `stream_heads_with_logs` would yield
        // Err(RpcError::Reorg { common_ancestor: 106 }) and return here.
        let outcome = linkage.observe(107, hb(250), hb(106));
        assert!(
            matches!(
                outcome,
                LinkOutcome::Reorg {
                    common_ancestor: 106
                }
            ),
            "competing block at 107 with canonical parent must produce Reorg{{106}}, got {outcome:?}"
        );
    }

    #[test]
    fn capture_policy_notice_speaks_once_per_policy() {
        // A fresh instance — never the process-global static, which `Once`
        // makes a one-shot resource shared across every test in this binary.
        let notice = CapturePolicyNotice::new();

        let latest_block = 1_000u64;
        let latest_first = notice.first_message(CaptureTarget::Latest, latest_block);
        assert!(
            latest_first.is_some(),
            "first Latest resolution must announce"
        );
        let latest_message = latest_first.unwrap();
        assert!(
            !latest_message.contains("DEEP LAG"),
            "Latest must not claim deep lag: {latest_message}"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Latest, latest_block)
                .is_none(),
            "second Latest resolution must be silent"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Latest, latest_block)
                .is_none(),
            "third Latest resolution must be silent"
        );

        let lag_block = 900u64;
        assert!(
            notice
                .first_message(CaptureTarget::Lag(64), lag_block)
                .is_some(),
            "first Lag resolution must announce (Latest already having spoken must not \
             consume Lag's independent gate)"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Lag(64), lag_block)
                .is_none(),
            "second Lag resolution must be silent"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Lag(64), lag_block)
                .is_none(),
            "third Lag resolution must be silent"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Lag(200), lag_block)
                .is_none(),
            "gating is per-variant, not per-value: a distinct Lag(n) must not re-arm the gate"
        );

        let finalized_block = 500u64;
        let finalized_first = notice.first_message(CaptureTarget::Finalized, finalized_block);
        assert!(
            finalized_first.is_some(),
            "first Finalized resolution must announce (Latest and Lag having already \
             spoken must not consume Finalized's independent gate)"
        );
        let finalized_message = finalized_first.unwrap();
        assert!(
            finalized_message.contains("DEEP LAG ACTIVE"),
            "Finalized message must claim deep lag: {finalized_message}"
        );
        assert!(
            finalized_message.contains(&finalized_block.to_string()),
            "Finalized message must report the resolved block: {finalized_message}"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Finalized, finalized_block)
                .is_none(),
            "second Finalized resolution must be silent"
        );
        assert!(
            notice
                .first_message(CaptureTarget::Finalized, finalized_block)
                .is_none(),
            "third Finalized resolution must be silent"
        );
    }

    // ── B.7 addendum: reused HTTP clients + concurrent flush dispatch ───────

    /// `resolve_http_provider`: `Some(reused)` at the same index returns the
    /// identical client handle on every call; `None` rebuilds a fresh one every
    /// call — today's `connect_http` behavior, unchanged. Built against a real
    /// (non-mock) `ProviderSettings`: `from_mock`'s `injected_http` short-circuit
    /// would make both branches return the same cloned instance, making this
    /// distinction unobservable (see the settled decision this test proves).
    #[test]
    fn resolve_http_provider_reuses_vs_rebuilds() {
        let settings = ProviderSettings::new(
            vec![HttpRpcSettings::new(
                "http://127.0.0.1:9".to_string(),
                1,
                100,
            )],
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );
        let reused = settings.build_reused_http_clients();
        assert_eq!(reused.len(), 1, "one client per configured HTTP provider");

        // Some(&reused) at the same index: identical handle every call.
        let a = resolve_http_provider(&settings, Some(&reused), 0);
        let b = resolve_http_provider(&settings, Some(&reused), 0);
        assert!(
            std::sync::Weak::ptr_eq(&a.weak_client(), &b.weak_client()),
            "Some(reused) at the same index must return the identical client"
        );

        // None: a fresh client every call.
        let c = resolve_http_provider(&settings, None, 0);
        let d = resolve_http_provider(&settings, None, 0);
        assert!(
            !std::sync::Weak::ptr_eq(&c.weak_client(), &d.weak_client()),
            "None must rebuild a fresh client on every call, not reuse one"
        );
    }

    /// `fetch_concurrently`: dispatch is genuinely concurrent, not one-at-a-time.
    /// Fails against a revert to a sequential (e.g. `for` loop) dispatch shape,
    /// which would never see more than one in-flight fetch.
    #[tokio::test(start_paused = true)]
    async fn fetch_concurrently_runs_items_in_parallel_up_to_bound() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let bound = 4usize;
        let n = 10usize;
        let in_flight = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));

        let items: Vec<usize> = (0..n).collect();
        let in_flight_for_fetch = in_flight.clone();
        let peak_for_fetch = peak.clone();
        let fetch = move |_: usize| {
            let in_flight = in_flight_for_fetch.clone();
            let peak = peak_for_fetch.clone();
            async move {
                let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
                peak.fetch_max(now, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(50)).await;
                in_flight.fetch_sub(1, Ordering::SeqCst);
                Ok::<usize, RpcError>(0)
            }
        };

        let result = fetch_concurrently(items, bound, fetch).await;
        assert!(result.is_ok(), "all items succeed: {result:?}");

        let observed_peak = peak.load(Ordering::SeqCst);
        assert!(
            observed_peak > 1,
            "expected concurrent dispatch (peak > 1), got peak={observed_peak}"
        );
        assert!(
            observed_peak <= bound,
            "peak in-flight {observed_peak} exceeded the bound {bound}"
        );
    }

    /// `fetch_concurrently`: fail-fast, not collect-then-check. An early item's
    /// error must short-circuit before every item is invoked — distinguishes
    /// `try_buffer_unordered` from a `join_all`-style shape that always invokes
    /// and awaits all N items before checking any result (the Concurrency test
    /// above doesn't by itself rule this out: a collect-then-check dispatch can
    /// still run several items concurrently, just never stop early).
    #[tokio::test]
    async fn fetch_concurrently_fails_fast_not_collect_then_check() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let bound = 3usize;
        let n = 10usize;
        let items: Vec<usize> = (0..n).collect();

        let invoked = Arc::new(AtomicUsize::new(0));
        let invoked_for_fetch = invoked.clone();
        let fetch = move |i: usize| {
            invoked_for_fetch.fetch_add(1, Ordering::SeqCst);
            async move {
                if i == 0 {
                    Err(RpcError::LogFetchError("early failure".to_string()))
                } else {
                    Ok::<usize, RpcError>(i)
                }
            }
        };

        let result = fetch_concurrently(items, bound, fetch).await;
        assert!(result.is_err(), "an early failure must surface as Err");

        let invoked_count = invoked.load(Ordering::SeqCst);
        assert!(
            invoked_count < n,
            "expected fewer than {n} closures invoked under fail-fast, got {invoked_count}"
        );
    }

    /// `fetch_concurrently`: fail-fast even when an earlier-indexed neighbor is
    /// slow. Distinguishes `try_buffer_unordered` (surfaces the first error the
    /// instant it occurs, dropping remaining in-flight futures) from
    /// `try_buffered` (holds a `FuturesOrdered`, so an error at index 1 would
    /// wait for index 0 to resolve first) — the Fail-fast test above alone
    /// can't tell the two apart, since an error at an early index surfaces
    /// quickly under either combinator.
    #[tokio::test(start_paused = true)]
    async fn fetch_concurrently_fails_fast_under_early_slow_neighbor() {
        let bound = 2usize;
        let items = vec![0usize, 1usize];
        let long_sleep = Duration::from_secs(3600);

        let fetch = move |i: usize| async move {
            if i == 0 {
                tokio::time::sleep(long_sleep).await;
                Ok::<usize, RpcError>(0)
            } else {
                Err(RpcError::LogFetchError("fast failure".to_string()))
            }
        };

        let start = Instant::now();
        let result = fetch_concurrently(items, bound, fetch).await;
        let elapsed = start.elapsed();

        assert!(result.is_err(), "overall result must be Err");
        assert!(
            elapsed < long_sleep,
            "Err must be observable before item 0's sleep elapses, elapsed={elapsed:?}"
        );
    }

    /// `sort_ranges_ascending`: restores ascending block-number order from
    /// synthetic out-of-order input. Cheaper and more direct than proving the same
    /// thing by driving `flush_window_range` end-to-end (see
    /// `flush_window_range_dispatches_concurrently_and_restores_ascending_order`
    /// below for that integration-level proof).
    #[test]
    fn sort_ranges_ascending_orders_by_block_number() {
        let unordered: Vec<LogRange> = [105u64, 100, 103]
            .into_iter()
            .map(|n| LogRange {
                from_block: n,
                to_block: n,
                logs: vec![],
                tip_hash: None,
            })
            .collect();

        let sorted = sort_ranges_ascending(unordered);

        let numbers: Vec<u64> = sorted.iter().map(|range| range.from_block).collect();
        assert_eq!(numbers, vec![100, 103, 105]);
    }

    /// `flush_window_range` end-to-end at a real concurrency bound
    /// (`max_concurrency > 1`), which every other mock-backed test in this file
    /// cannot exercise: they all build `ProviderSettings` via `from_mock`, which
    /// pins `max_concurrency: 1` (see the comment on `from_mock` in `config.rs`).
    /// Reverting `flush_window_range`'s dispatch to the old sequential `for` loop
    /// (no `fetch_concurrently`, no `sort_ranges_ascending`) makes this test fail:
    /// peak in-flight would never exceed 1, and the deliberately-out-of-order
    /// completion this test forces could never happen.
    ///
    /// Uses a small hand-rolled `Provider` double instead of the `Asserter`/mock
    /// transport this file otherwise uses: `Asserter`'s FIFO queue is content-blind
    /// and resolves each request synchronously with no real async delay, so it
    /// can't demonstrate genuine overlap between concurrently in-flight fetches —
    /// see the settled decision this test proves directly instead.
    #[tokio::test(start_paused = true)]
    async fn flush_window_range_dispatches_concurrently_and_restores_ascending_order() {
        use alloy::network::Ethereum;
        use alloy::providers::{DynProvider, RootProvider};
        use alloy::rpc::types::Filter;
        use alloy::transports::TransportResult;
        use std::sync::Arc;
        use std::sync::Mutex;
        use std::sync::atomic::{AtomicUsize, Ordering};

        /// `root()` delegates to an unused stub provider. This test's ring covers
        /// the whole flushed range, so `flush_window_range` never takes the
        /// self-heal `get_block_by_hash` walk — but the ring is short of `depth`
        /// (4 of 8), so the unconditional top-up (I.4f) does call `get_block_by_hash`
        /// through this stub's `root()`, drains its empty `Asserter`, and errors,
        /// which the top-up logs and swallows (settled decision 8) rather than
        /// failing the flush. `get_logs` is overridden to inject a controllable
        /// async delay per call and record (a)
        /// peak concurrently in-flight calls and (b) the order calls complete in —
        /// proof of real concurrency and real out-of-order resolution, not just
        /// that the code compiles against a bound > 1.
        #[derive(Clone)]
        struct DelayedLogsProvider {
            stub_root: DynProvider<Ethereum>,
            call_order: Arc<AtomicUsize>,
            delays_by_call_order: Arc<Vec<Duration>>,
            in_flight: Arc<AtomicUsize>,
            peak_in_flight: Arc<AtomicUsize>,
            completion_order: Arc<Mutex<Vec<usize>>>,
        }

        #[async_trait::async_trait]
        impl Provider<Ethereum> for DelayedLogsProvider {
            fn root(&self) -> &RootProvider<Ethereum> {
                self.stub_root.root()
            }

            async fn get_logs(&self, _filter: &Filter) -> TransportResult<Vec<Log>> {
                let call_index = self.call_order.fetch_add(1, Ordering::SeqCst);
                let now_in_flight = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
                self.peak_in_flight
                    .fetch_max(now_in_flight, Ordering::SeqCst);
                let delay = self
                    .delays_by_call_order
                    .get(call_index)
                    .copied()
                    .unwrap_or(Duration::ZERO);
                tokio::time::sleep(delay).await;
                self.in_flight.fetch_sub(1, Ordering::SeqCst);
                self.completion_order.lock().unwrap().push(call_index);
                Ok(Vec::new())
            }
        }

        // Ring: blocks 300..=303 observed (clean chain — no self-heal walk needed).
        let mut linkage = HeadLinkage::new(8);
        for n in 300u64..=303 {
            assert_eq!(
                linkage.observe(n, hb(n as u8), hb((n - 1) as u8)),
                LinkOutcome::Linked
            );
        }
        let mut coalescer = HeadCoalescer::new(Some(300), WINDOW);
        coalescer.observe_head(303, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((300, 303)));

        // Dispatch order follows ascending block order (300, 301, 302, 303 — see
        // `pairs` construction in `flush_window_range`). Block 300's fetch, the
        // first dispatched, is deliberately the slowest: under the old sequential
        // dispatch nothing could ever finish before it. Under concurrent dispatch,
        // 301-303 must resolve first.
        let delays_by_call_order = vec![
            Duration::from_millis(500), // block 300
            Duration::from_millis(10),  // block 301
            Duration::from_millis(20),  // block 302
            Duration::from_millis(30),  // block 303
        ];
        let peak_in_flight = Arc::new(AtomicUsize::new(0));
        let completion_order = Arc::new(Mutex::new(Vec::new()));
        let unused_asserter = Asserter::new(); // queried by the top-up walk; drained, so it errors and is swallowed
        let double = DelayedLogsProvider {
            stub_root: ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(unused_asserter)
                .erased(),
            call_order: Arc::new(AtomicUsize::new(0)),
            delays_by_call_order: Arc::new(delays_by_call_order),
            in_flight: Arc::new(AtomicUsize::new(0)),
            peak_in_flight: peak_in_flight.clone(),
            completion_order: completion_order.clone(),
        };
        let reused = vec![double.erased()];

        // max_concurrency 4 (>= the 4 pending blocks) so every fetch launches at
        // once — the bound this test needs to prove overlap, unreachable through
        // `from_mock`'s pinned `max_concurrency: 1`.
        let settings = ProviderSettings::new(
            vec![HttpRpcSettings::new("http://unused".to_string(), 4, 100)],
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );

        let ranges = flush_window_range(
            &mut linkage,
            &mut coalescer,
            &settings,
            None,
            0,
            Some(&reused),
        )
        .await
        .expect("flush must succeed");

        assert_eq!(
            peak_in_flight.load(Ordering::SeqCst),
            4,
            "all 4 blocks' fetches must be in flight together, not one at a time"
        );

        let observed_completion_order = completion_order.lock().unwrap().clone();
        assert_eq!(
            &observed_completion_order[0..3],
            &[1, 2, 3],
            "the 3 fast fetches (301-303) must resolve before the slow one (300), \
             got order {observed_completion_order:?}"
        );
        assert_eq!(
            observed_completion_order[3], 0,
            "the slow fetch (300) must resolve last, proving it did not block the \
             others, got order {observed_completion_order:?}"
        );

        // Despite resolving out of order above, the output `flush_window_range`
        // yields is still restored to ascending block-number order.
        assert_eq!(ranges.len(), 4);
        let numbers: Vec<u64> = ranges.iter().map(|range| range.from_block).collect();
        assert_eq!(numbers, vec![300, 301, 302, 303]);
    }

    /// `flush_window_range`: peak in-flight dispatch tracks the *configured*
    /// `max_concurrency`, not a value hardcoded inside `flush_window_range`.
    /// The test above (4 pending blocks, `max_concurrency: 4`) can't
    /// distinguish "bound comes from configuration" from "bound is hardcoded
    /// to something >= 4" — a dispatch bound hardcoded to, say, 64 would still
    /// pass it. Here the pending-block count (6) and `max_concurrency` (2)
    /// differ, and peak in-flight must land on exactly 2 — not 4 (the other
    /// test's value), not 6 (dispatch-all), not 1 (a sequential fallback).
    #[tokio::test(start_paused = true)]
    async fn flush_window_range_peak_in_flight_tracks_configured_max_concurrency() {
        use alloy::network::Ethereum;
        use alloy::providers::{DynProvider, RootProvider};
        use alloy::rpc::types::Filter;
        use alloy::transports::TransportResult;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        /// Tracks only peak concurrently in-flight calls — this test needs no
        /// per-call delay staggering or completion-order proof, just the bound.
        #[derive(Clone)]
        struct PeakTrackingLogsProvider {
            stub_root: DynProvider<Ethereum>,
            in_flight: Arc<AtomicUsize>,
            peak_in_flight: Arc<AtomicUsize>,
        }

        #[async_trait::async_trait]
        impl Provider<Ethereum> for PeakTrackingLogsProvider {
            fn root(&self) -> &RootProvider<Ethereum> {
                self.stub_root.root()
            }

            async fn get_logs(&self, _filter: &Filter) -> TransportResult<Vec<Log>> {
                let now_in_flight = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
                self.peak_in_flight
                    .fetch_max(now_in_flight, Ordering::SeqCst);
                tokio::time::sleep(Duration::from_millis(20)).await;
                self.in_flight.fetch_sub(1, Ordering::SeqCst);
                Ok(Vec::new())
            }
        }

        // Ring: 6 pending blocks, clean chain, no self-heal walk needed.
        let mut linkage = HeadLinkage::new(8);
        for n in 400u64..=405 {
            assert_eq!(
                linkage.observe(n, hb(n as u8), hb((n - 1) as u8)),
                LinkOutcome::Linked
            );
        }
        let mut coalescer = HeadCoalescer::new(Some(400), WINDOW);
        coalescer.observe_head(405, Instant::now());
        assert_eq!(coalescer.pending_range(), Some((400, 405)));

        let peak_in_flight = Arc::new(AtomicUsize::new(0));
        // The ring (6 of depth 8) is short of full depth, so the unconditional
        // top-up (I.4f) queries this stub's `root()` via `get_block_by_hash`;
        // its `Asserter` is empty, so the walk errors and the top-up logs and
        // swallows it (settled decision 8) rather than failing the flush.
        let unused_asserter = Asserter::new();
        let double = PeakTrackingLogsProvider {
            stub_root: ProviderBuilder::new()
                .disable_recommended_fillers()
                .connect_mocked_client(unused_asserter)
                .erased(),
            in_flight: Arc::new(AtomicUsize::new(0)),
            peak_in_flight: peak_in_flight.clone(),
        };
        let reused = vec![double.erased()];

        // max_concurrency 2, strictly below the 6 pending blocks.
        let settings = ProviderSettings::new(
            vec![HttpRpcSettings::new("http://unused".to_string(), 2, 100)],
            vec!["ws://127.0.0.1:9".parse().expect("static url")],
        );

        let ranges = flush_window_range(
            &mut linkage,
            &mut coalescer,
            &settings,
            None,
            0,
            Some(&reused),
        )
        .await
        .expect("flush must succeed");

        assert_eq!(
            peak_in_flight.load(Ordering::SeqCst),
            2,
            "peak in-flight must equal the configured max_concurrency (2), not \
             the pending block count (6) or any other hardcoded bound"
        );
        assert_eq!(ranges.len(), 6);
    }
}