fuel-core 0.48.0

Fuel client library is aggregation of all fuels service. It contains the all business logic of the fuel protocol.
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
use crate::{
    fuel_core_graphql_api::ports::ConsensusModulePort,
    service::adapters::{
        BlockImporterAdapter,
        BlockProducerAdapter,
        P2PAdapter,
        PoAAdapter,
        TxPoolAdapter,
    },
};
use anyhow::anyhow;
use fuel_core_importer::ports::{
    BlockReconciliationWritePort,
    ImporterDatabase,
};
use fuel_core_metrics::poa_metrics::poa_metrics;
use fuel_core_poa::{
    ports::{
        BlockImporter,
        BlockReconciliationReadPort,
        LeaderState,
        P2pPort,
        PredefinedBlocks,
        TransactionPool,
        TransactionsSource,
    },
    service::{
        Mode,
        SharedState,
    },
};
use fuel_core_services::stream::BoxStream;
use fuel_core_storage::transactional::Changes;
use fuel_core_types::{
    blockchain::{
        SealedBlock,
        block::Block,
        primitives::BlockId,
    },
    fuel_types::BlockHeight,
    services::{
        block_importer::{
            BlockImportInfo,
            UncommittedResult as UncommittedImporterResult,
        },
        executor::UncommittedResult,
    },
    tai64::Tai64,
};
use std::{
    collections::HashMap,
    path::{
        Path,
        PathBuf,
    },
    time::Duration,
};
use tokio::{
    sync::{
        Mutex,
        watch,
    },
    time::{
        Instant,
        sleep,
        timeout,
    },
};
use tokio_stream::{
    StreamExt,
    wrappers::BroadcastStream,
};
use tracing::error;

pub mod pre_confirmation_signature;

const CHECK_LEASE_OWNER_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/check_lease_owner.lua"
));

const RELEASE_LOCK_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/release_lock.lua"
));

const PROMOTE_LEADER_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/promote_leader.lua"
));

const WRITE_BLOCK_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/write_block.lua"
));

const READ_STREAM_ENTRIES_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/read_stream_entries.lua"
));

const READ_LATEST_STREAM_ENTRY_SCRIPT: &str = include_str!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/redis_leader_lease_adapter_scripts/read_latest_stream_entry.lua"
));

struct RedisNode {
    redis_client: redis::Client,
    cached_connection: Mutex<Option<redis::aio::MultiplexedConnection>>,
}

impl Clone for RedisNode {
    fn clone(&self) -> Self {
        Self {
            redis_client: self.redis_client.clone(),
            cached_connection: Mutex::new(None),
        }
    }
}

pub struct RedisLeaderLeaseAdapter {
    redis_nodes: Vec<RedisNode>,
    quorum: usize,
    quorum_disruption_budget: u32,
    lease_key: String,
    epoch_key: String,
    block_stream_key: String,
    lease_owner_token: String,
    drop_release_guard: std::sync::Arc<()>,
    current_epoch_token: std::sync::Arc<std::sync::Mutex<Option<u64>>>,
    lease_ttl_millis: u64,
    lease_drift_millis: u64,
    node_timeout: Duration,
    retry_delay_millis: u64,
    max_retry_delay_offset_millis: u64,
    max_attempts: usize,
    stream_max_len: u32,
}

impl Clone for RedisLeaderLeaseAdapter {
    fn clone(&self) -> Self {
        Self {
            redis_nodes: self.redis_nodes.clone(),
            quorum: self.quorum,
            quorum_disruption_budget: self.quorum_disruption_budget,
            lease_key: self.lease_key.clone(),
            epoch_key: self.epoch_key.clone(),
            block_stream_key: self.block_stream_key.clone(),
            lease_owner_token: self.lease_owner_token.clone(),
            drop_release_guard: self.drop_release_guard.clone(),
            current_epoch_token: self.current_epoch_token.clone(),
            lease_ttl_millis: self.lease_ttl_millis,
            lease_drift_millis: self.lease_drift_millis,
            node_timeout: self.node_timeout,
            retry_delay_millis: self.retry_delay_millis,
            max_retry_delay_offset_millis: self.max_retry_delay_offset_millis,
            max_attempts: self.max_attempts,
            stream_max_len: self.stream_max_len,
        }
    }
}

#[derive(Default, Clone)]
pub struct NoopReconciliationAdapter;

#[allow(clippy::large_enum_variant)]
pub enum ReconciliationAdapter {
    Redis(RedisLeaderLeaseAdapter),
    Noop(NoopReconciliationAdapter),
}

impl RedisLeaderLeaseAdapter {
    fn calculate_quorum(redis_nodes_len: usize, quorum_disruption_budget: u32) -> usize {
        let majority = redis_nodes_len
            .checked_div(2)
            .unwrap_or(0)
            .saturating_add(1);
        let disruption_budget = usize::try_from(quorum_disruption_budget).unwrap_or(0);
        majority
            .saturating_add(disruption_budget)
            .min(redis_nodes_len)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new(
        redis_urls: Vec<String>,
        lease_key: String,
        lease_ttl: Duration,
        node_timeout: Duration,
        retry_delay: Duration,
        max_retry_delay_offset: Duration,
        max_attempts: u32,
        stream_max_len: u32,
    ) -> anyhow::Result<Self> {
        let redis_nodes = redis_urls
            .into_iter()
            .map(|redis_url| {
                redis::Client::open(redis_url).map(|redis_client| RedisNode {
                    redis_client,
                    cached_connection: Mutex::new(None),
                })
            })
            .collect::<Result<Vec<_>, _>>()?;
        if redis_nodes.is_empty() {
            return Err(anyhow!(
                "At least one redis url is required for leader lock"
            ));
        }
        let quorum_disruption_budget = 0u32;
        let quorum = Self::calculate_quorum(redis_nodes.len(), quorum_disruption_budget);
        let lease_ttl_millis = u64::try_from(lease_ttl.as_millis())?;
        let retry_delay_millis = u64::try_from(retry_delay.as_millis())?;
        let max_retry_delay_offset_millis =
            u64::try_from(max_retry_delay_offset.as_millis())?;
        let max_attempts = usize::try_from(max_attempts)?.max(1);
        let lease_owner_token = uuid::Uuid::new_v4().to_string();
        let epoch_key = format!("{lease_key}:epoch:token");
        let block_stream_key = format!("{lease_key}:block:stream");
        let lease_drift_millis = lease_ttl_millis
            .checked_div(100)
            .unwrap_or(0)
            .saturating_add(2);
        Ok(Self {
            redis_nodes,
            quorum,
            quorum_disruption_budget,
            lease_key,
            epoch_key,
            block_stream_key,
            lease_owner_token,
            drop_release_guard: std::sync::Arc::new(()),
            current_epoch_token: std::sync::Arc::new(std::sync::Mutex::new(None)),
            lease_ttl_millis,
            lease_drift_millis,
            node_timeout,
            retry_delay_millis,
            max_retry_delay_offset_millis,
            max_attempts,
            stream_max_len,
        })
    }

    pub fn with_quorum_disruption_budget(
        mut self,
        quorum_disruption_budget: u32,
    ) -> Self {
        self.quorum_disruption_budget = quorum_disruption_budget;
        self.quorum =
            Self::calculate_quorum(self.redis_nodes.len(), quorum_disruption_budget);
        self
    }

    async fn multiplexed_connection(
        &self,
        redis_node: &RedisNode,
    ) -> anyhow::Result<redis::aio::MultiplexedConnection> {
        if let Some(connection) =
            redis_node.cached_connection.lock().await.as_ref().cloned()
        {
            return Ok(connection);
        }

        let new_connection = timeout(
            self.node_timeout,
            redis_node.redis_client.get_multiplexed_async_connection(),
        )
        .await
        .map_err(|_| anyhow!("Timed out while connecting to redis leader-lock node"))??;
        let mut cached_connection = redis_node.cached_connection.lock().await;
        if let Some(connection) = cached_connection.as_ref().cloned() {
            return Ok(connection);
        }
        *cached_connection = Some(new_connection.clone());
        Ok(new_connection)
    }

    async fn clear_cached_connection(&self, redis_node: &RedisNode) {
        let mut cached_connection = redis_node.cached_connection.lock().await;
        *cached_connection = None;
        poa_metrics().connection_reset_total.inc();
    }

    async fn check_lease_owner_on_node(&self, redis_node: &RedisNode) -> bool {
        let mut connection = match self.multiplexed_connection(redis_node).await {
            Ok(connection) => connection,
            Err(_) => return false,
        };
        let is_owner = timeout(
            self.node_timeout,
            redis::Script::new(CHECK_LEASE_OWNER_SCRIPT)
                .key(&self.lease_key)
                .arg(&self.lease_owner_token)
                .invoke_async::<i32>(&mut connection),
        )
        .await;
        match is_owner {
            Ok(Ok(is_owner)) => is_owner == 1,
            Err(_) => {
                self.clear_cached_connection(redis_node).await;
                false
            }
            Ok(Err(_)) => {
                self.clear_cached_connection(redis_node).await;
                false
            }
        }
    }

    async fn promote_leader_on_node(
        &self,
        redis_node: &RedisNode,
    ) -> anyhow::Result<Option<u64>> {
        let mut connection = match self.multiplexed_connection(redis_node).await {
            Ok(connection) => connection,
            Err(_) => return Ok(None),
        };
        let promoted = timeout(
            self.node_timeout,
            redis::Script::new(PROMOTE_LEADER_SCRIPT)
                .key(&self.lease_key)
                .key(&self.epoch_key)
                .arg(&self.lease_owner_token)
                .arg(self.lease_ttl_millis)
                .invoke_async::<u64>(&mut connection),
        )
        .await;
        match promoted {
            Ok(Ok(token)) => Ok(Some(token)),
            Ok(Err(err)) => {
                if err.to_string().contains("LOCK_HELD:") {
                    return Ok(None);
                }
                self.clear_cached_connection(redis_node).await;
                Ok(None)
            }
            Err(_) => {
                self.clear_cached_connection(redis_node).await;
                Ok(None)
            }
        }
    }

    async fn release_lease_on_node(&self, redis_node: &RedisNode) -> bool {
        let mut connection = match self.multiplexed_connection(redis_node).await {
            Ok(connection) => connection,
            Err(_) => return false,
        };
        let released = timeout(
            self.node_timeout,
            redis::Script::new(RELEASE_LOCK_SCRIPT)
                .key(&self.lease_key)
                .arg(&self.lease_owner_token)
                .invoke_async::<i32>(&mut connection),
        )
        .await;
        match released {
            Ok(Ok(released)) => released == 1,
            Err(_) => {
                self.clear_cached_connection(redis_node).await;
                false
            }
            Ok(Err(_)) => {
                self.clear_cached_connection(redis_node).await;
                false
            }
        }
    }

    fn quorum_reached(&self, success_count: usize) -> bool {
        success_count >= self.quorum
    }

    fn calculate_remaining_validity_millis(&self, elapsed_millis: u64) -> u64 {
        self.lease_ttl_millis
            .saturating_sub(elapsed_millis.saturating_add(self.lease_drift_millis))
    }

    fn random_retry_delay_offset_millis(&self) -> u64 {
        if self.max_retry_delay_offset_millis == 0 {
            return 0;
        }
        rand::random::<u64>()
            .checked_rem(self.max_retry_delay_offset_millis.saturating_add(1))
            .unwrap_or(0)
    }

    async fn release_lease_on_all_nodes(&self) {
        let _ = futures::future::join_all(
            self.redis_nodes
                .iter()
                .map(|redis_node| self.release_lease_on_node(redis_node)),
        )
        .await;
    }

    async fn delay_next_retry(&self) {
        let retry_delay_millis = self
            .retry_delay_millis
            .saturating_add(self.random_retry_delay_offset_millis());
        sleep(Duration::from_millis(retry_delay_millis)).await;
    }

    async fn has_lease_owner_quorum(&self) -> anyhow::Result<bool> {
        let ownership = futures::future::join_all(
            self.redis_nodes
                .iter()
                .map(|redis_node| self.check_lease_owner_on_node(redis_node)),
        )
        .await;
        let owner_count = ownership.iter().filter(|&&is_owner| is_owner).count();
        if !self.quorum_reached(owner_count) {
            return Ok(false);
        }

        // Best-effort: acquire the lock on nodes we don't own yet.
        // Expands write coverage beyond minimum quorum so block data
        // is replicated to more nodes, improving fault tolerance.
        // If a newly-acquired node returns a higher epoch (from
        // election storm drift), adopt it so write_block.lua uses
        // a consistent epoch across all owned nodes.
        let non_owned: Vec<&RedisNode> = self
            .redis_nodes
            .iter()
            .zip(ownership.iter())
            .filter(|(_, is_owner)| !**is_owner)
            .map(|(node, _)| node)
            .collect();

        if !non_owned.is_empty() {
            let results = futures::future::join_all(
                non_owned
                    .into_iter()
                    .map(|redis_node| self.promote_leader_on_node(redis_node)),
            )
            .await;

            if let Some(max_new) =
                results.into_iter().filter_map(|r| r.ok().flatten()).max()
                && let Ok(mut epoch) = self.current_epoch_token.lock()
            {
                let current = epoch.unwrap_or(0);
                if max_new > current {
                    tracing::debug!(
                        old_epoch = current,
                        new_epoch = max_new,
                        "Adopted higher epoch from lock expansion"
                    );
                    *epoch = Some(max_new);
                }
            }
        }

        Ok(true)
    }

    async fn acquire_lease_if_free(&self) -> anyhow::Result<bool> {
        let promotion_start = std::time::Instant::now();
        for attempt_index in 0..self.max_attempts {
            let start = std::time::Instant::now();
            let promoted_nodes = futures::future::join_all(
                self.redis_nodes
                    .iter()
                    .map(|redis_node| self.promote_leader_on_node(redis_node)),
            )
            .await;
            let promoted_tokens = promoted_nodes
                .into_iter()
                .filter_map(|token| token.ok().flatten())
                .collect::<Vec<_>>();
            let acquired_count = promoted_tokens.len();
            let elapsed_millis =
                u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
            let validity_millis =
                self.calculate_remaining_validity_millis(elapsed_millis);
            if self.quorum_reached(acquired_count) && validity_millis > 0 {
                // Record epoch drift across quorum nodes
                if promoted_tokens.len() > 1
                    && let (Some(min_tok), Some(max_tok)) = (
                        promoted_tokens.iter().copied().min(),
                        promoted_tokens.iter().copied().max(),
                    )
                {
                    poa_metrics().epoch_max_drift.set(
                        i64::try_from(max_tok.saturating_sub(min_tok))
                            .unwrap_or(i64::MAX),
                    );
                }
                if let Some(max_token) = promoted_tokens.into_iter().max() {
                    let mut current_epoch_token = self
                        .current_epoch_token
                        .lock()
                        .map_err(|e| anyhow!("epoch token lock poisoned: {}", e))?;
                    *current_epoch_token = Some(max_token);
                    poa_metrics()
                        .leader_epoch
                        .set(i64::try_from(max_token).unwrap_or(i64::MAX));
                }
                poa_metrics().promotion_success_total.inc();
                poa_metrics()
                    .promotion_duration_s
                    .observe(promotion_start.elapsed().as_secs_f64());
                return Ok(true);
            }
            self.release_lease_on_all_nodes().await;
            let is_last_attempt = attempt_index.saturating_add(1) == self.max_attempts;
            if !is_last_attempt {
                self.delay_next_retry().await;
            }
        }
        poa_metrics().promotion_failure_total.inc();
        poa_metrics()
            .promotion_duration_s
            .observe(promotion_start.elapsed().as_secs_f64());
        Ok(false)
    }

    async fn release_lease_on_client(
        redis_client: redis::Client,
        lease_key: String,
        lease_owner_token: String,
        node_timeout: Duration,
    ) {
        let connection = timeout(
            node_timeout,
            redis_client.get_multiplexed_async_connection(),
        )
        .await;
        let mut connection = match connection {
            Ok(Ok(connection)) => connection,
            Err(_) => return,
            Ok(Err(_)) => return,
        };
        let _ = timeout(
            node_timeout,
            redis::Script::new(RELEASE_LOCK_SCRIPT)
                .key(lease_key)
                .arg(lease_owner_token)
                .invoke_async::<i32>(&mut connection),
        )
        .await;
    }

    async fn release_lease_on_clients(
        redis_clients: Vec<redis::Client>,
        lease_key: String,
        lease_owner_token: String,
        node_timeout: Duration,
    ) {
        let _ =
            futures::future::join_all(redis_clients.into_iter().map(|redis_client| {
                Self::release_lease_on_client(
                    redis_client,
                    lease_key.clone(),
                    lease_owner_token.clone(),
                    node_timeout,
                )
            }))
            .await;
    }

    fn release_lease_on_clients_sync(
        redis_clients: Vec<redis::Client>,
        lease_key: String,
        lease_owner_token: String,
    ) {
        redis_clients.into_iter().for_each(|redis_client| {
            let Ok(mut connection) = redis_client.get_connection() else {
                return;
            };
            let _ = redis::Script::new(RELEASE_LOCK_SCRIPT)
                .key(&lease_key)
                .arg(&lease_owner_token)
                .invoke::<i32>(&mut connection);
        });
    }

    async fn read_latest_stream_entry_on_node(
        &self,
        redis_node: &RedisNode,
    ) -> anyhow::Result<Option<(u32, String)>> {
        let mut connection = self.multiplexed_connection(redis_node).await?;
        let latest_entry = timeout(
            self.node_timeout,
            redis::Script::new(READ_LATEST_STREAM_ENTRY_SCRIPT)
                .key(&self.block_stream_key)
                .invoke_async::<Vec<String>>(&mut connection),
        )
        .await;
        match latest_entry {
            Err(_) => {
                self.clear_cached_connection(redis_node).await;
                Err(anyhow!(
                    "Timed out reading latest stream entry from Redis node"
                ))
            }
            Ok(Err(e)) => {
                self.clear_cached_connection(redis_node).await;
                Err(anyhow!(
                    "Failed to read latest stream entry from Redis node: {e}"
                ))
            }
            Ok(Ok(entry)) => {
                if entry.len() != 2 {
                    return Ok(None);
                }
                let height = entry[0]
                    .parse::<u32>()
                    .map_err(|e| anyhow!("Invalid latest stream entry height: {e}"))?;
                Ok(Some((height, entry[1].clone())))
            }
        }
    }

    async fn should_reconcile_from_stream(
        &self,
        next_height: BlockHeight,
    ) -> anyhow::Result<bool> {
        let next_height = u32::from(next_height);
        let latest_results = futures::future::join_all(
            self.redis_nodes
                .iter()
                .map(|redis_node| self.read_latest_stream_entry_on_node(redis_node)),
        )
        .await;
        let mut successful_reads = 0usize;
        let mut failed_count = 0usize;
        let mut nodes_indicating_backlog = 0usize;
        for result in latest_results {
            match result {
                Ok(Some((latest_height, _latest_stream_id))) => {
                    successful_reads = successful_reads.saturating_add(1);
                    if latest_height >= next_height {
                        nodes_indicating_backlog =
                            nodes_indicating_backlog.saturating_add(1);
                    }
                }
                Ok(None) => {
                    successful_reads = successful_reads.saturating_add(1);
                }
                Err(e) => {
                    tracing::warn!("Redis latest stream read failed: {e}");
                    failed_count = failed_count.saturating_add(1);
                }
            }
        }
        if !self.quorum_reached(successful_reads) {
            return Err(anyhow!(
                "Cannot reconcile: only {}/{} Redis nodes responded ({} failed)",
                successful_reads,
                self.redis_nodes.len(),
                failed_count
            ));
        }
        Ok(nodes_indicating_backlog > 0)
    }

    async fn read_stream_entries_on_node(
        &self,
        redis_node: &RedisNode,
        next_height: u32,
        max_entries: usize,
    ) -> anyhow::Result<Vec<(u32, u64, SealedBlock)>> {
        if max_entries == 0 {
            return Ok(Vec::new());
        }

        let mut connection = self.multiplexed_connection(redis_node).await?;
        let count = u32::try_from(max_entries).unwrap_or(u32::MAX);
        let stream_entries = timeout(
            self.node_timeout,
            redis::Script::new(READ_STREAM_ENTRIES_SCRIPT)
                .key(&self.block_stream_key)
                .arg(next_height)
                .arg(count)
                .invoke_async::<Vec<(u32, u64, Vec<u8>, String)>>(&mut connection),
        )
        .await;

        let entries = match stream_entries {
            Err(_) => {
                self.clear_cached_connection(redis_node).await;
                return Err(anyhow!("Timed out reading stream entries from Redis node"));
            }
            Ok(Err(e)) => {
                self.clear_cached_connection(redis_node).await;
                return Err(anyhow!(
                    "Failed to read stream entries from Redis node: {e}"
                ));
            }
            Ok(Ok(entries)) => entries,
        };

        let mut blocks = Vec::new();
        for (height, epoch, bytes, _stream_id) in entries {
            match postcard::from_bytes::<SealedBlock>(&bytes) {
                Ok(block) => blocks.push((height, epoch, block)),
                Err(e) => {
                    tracing::warn!(
                        "Skipping stream entry: failed to deserialize block at height {height}: {e}"
                    );
                }
            }
        }

        Ok(blocks)
    }

    async fn unreconciled_blocks(
        &self,
        next_height: BlockHeight,
    ) -> anyhow::Result<Vec<SealedBlock>> {
        if !self.should_reconcile_from_stream(next_height).await? {
            return Ok(Vec::new());
        }
        let mut reconciled = Vec::new();
        let max_reconcile_blocks_per_round =
            usize::try_from(self.stream_max_len).unwrap_or(usize::MAX);
        let next_height_u32 = u32::from(next_height);
        let read_results =
            futures::future::join_all(self.redis_nodes.iter().map(|redis_node| {
                self.read_stream_entries_on_node(
                    redis_node,
                    next_height_u32,
                    max_reconcile_blocks_per_round,
                )
            }))
            .await;

        let mut successful_reads = Vec::new();
        let mut failed_count = 0usize;
        for result in read_results {
            match result {
                Ok(entries) => successful_reads.push(entries),
                Err(e) => {
                    tracing::warn!("Redis stream read failed: {e}");
                    failed_count = failed_count.saturating_add(1);
                }
            }
        }

        if !self.quorum_reached(successful_reads.len()) {
            return Err(anyhow!(
                "Cannot reconcile: only {}/{} Redis nodes responded ({} failed)",
                successful_reads.len(),
                self.redis_nodes.len(),
                failed_count
            ));
        }

        let blocks_by_node = successful_reads
            .into_iter()
            .map(|entries| {
                entries.into_iter().fold(
                    HashMap::<u32, HashMap<u64, SealedBlock>>::new(),
                    |mut blocks_by_height, (height, epoch, block)| {
                        blocks_by_height
                            .entry(height)
                            .or_default()
                            .insert(epoch, block);
                        blocks_by_height
                    },
                )
            })
            .collect::<Vec<_>>();

        // Compute stream trim headroom: min stream height - local committed height
        let min_stream_height = blocks_by_node
            .iter()
            .flat_map(|blocks_by_height| blocks_by_height.keys().copied())
            .min();
        if let Some(min_h) = min_stream_height {
            let local_committed = i64::from(u32::from(next_height).saturating_sub(1));
            let headroom = i64::from(min_h).saturating_sub(local_committed);
            poa_metrics().stream_trim_headroom.set(headroom);
        }

        let mut current_height = u32::from(next_height);

        for _ in 0..max_reconcile_blocks_per_round {
            let nodes_with_height = blocks_by_node
                .iter()
                .filter(|blocks_by_height| blocks_by_height.contains_key(&current_height))
                .count();

            tracing::debug!(
                "unreconciled_blocks: height={current_height} nodes_with_height={nodes_with_height}/{}",
                blocks_by_node.len()
            );

            if nodes_with_height == 0 {
                if reconciled.is_empty() {
                    return Err(anyhow!(
                        "Backlog unresolved at height {current_height}: \
                         stream indicates backlog but no entries found at next height"
                    ));
                }
                break;
            }

            let votes = blocks_by_node
                .iter()
                .filter_map(|blocks_by_height| blocks_by_height.get(&current_height))
                .flat_map(|blocks_by_epoch| blocks_by_epoch.iter())
                .fold(
                    HashMap::<(u64, BlockId), (usize, SealedBlock)>::new(),
                    |mut votes, (epoch, block)| {
                        let vote_key = (*epoch, block.entity.id());
                        match votes.get_mut(&vote_key) {
                            Some((count, _)) => {
                                *count = count.saturating_add(1);
                            }
                            None => {
                                votes.insert(vote_key, (1, block.clone()));
                            }
                        }
                        votes
                    },
                );

            let winner = votes
                .into_iter()
                .max_by_key(|((epoch, _), _)| *epoch)
                .map(|(_, (count, block))| (count, block));

            if let Some((count, block)) = winner {
                if self.quorum_reached(count) {
                    // Block already has quorum — reconcile it directly
                    reconciled.push(block);
                } else {
                    // Sub-quorum block: repropose to all nodes to reach quorum.
                    // This repairs orphaned partial writes from failed leaders.
                    // HEIGHT_EXISTS on nodes that already have the block returns
                    // Ok(false), and nodes missing it accept the write.
                    tracing::info!(
                        "Repairing sub-quorum block at height {current_height} \
                         (found on {count}/{} nodes)",
                        blocks_by_node.len()
                    );
                    match self.repair_sub_quorum_block(&block, count) {
                        Ok(true) => {
                            tracing::info!(
                                "Repair succeeded — block at height {current_height} \
                                 now has quorum"
                            );
                            reconciled.push(block);
                        }
                        Ok(false) => {
                            tracing::warn!(
                                "Repair failed to reach quorum at height \
                                 {current_height} — will retry next round"
                            );
                            if reconciled.is_empty() {
                                return Err(anyhow!(
                                    "Backlog unresolved at height {current_height}: \
                                     repair failed to reach quorum"
                                ));
                            }
                            break;
                        }
                        Err(e) => {
                            tracing::warn!(
                                "Repair error at height {current_height}: {e}"
                            );
                            if reconciled.is_empty() {
                                return Err(anyhow!(
                                    "Backlog unresolved at height {current_height}: \
                                     repair error: {e}"
                                ));
                            }
                            break;
                        }
                    }
                }
            } else {
                if reconciled.is_empty() {
                    return Err(anyhow!(
                        "Backlog unresolved at height {current_height}: \
                         no winning block candidate"
                    ));
                }
                break;
            }

            let Some(next) = current_height.checked_add(1) else {
                break;
            };
            current_height = next;
        }

        Ok(reconciled)
    }

    async fn can_produce_block(&self) -> anyhow::Result<bool> {
        tracing::debug!("Checking Redis leader lock");
        if self.has_lease_owner_quorum().await? {
            return Ok(true);
        }
        self.acquire_lease_if_free().await
    }

    async fn release_if_owner(&self) -> anyhow::Result<()> {
        tracing::debug!("Releasing Redis leader lock");
        if !self.has_lease_owner_quorum().await? {
            let mut current_epoch_token = self
                .current_epoch_token
                .lock()
                .map_err(|_| anyhow!("cannot access epoch token, poisoned lock"))?;
            *current_epoch_token = None;
            return Ok(());
        }

        let releases = futures::future::join_all(
            self.redis_nodes
                .iter()
                .map(|redis_node| self.release_lease_on_node(redis_node)),
        )
        .await;
        let released_count = releases.into_iter().filter(|released| *released).count();
        if self.quorum_reached(released_count) {
            let mut current_epoch_token = self
                .current_epoch_token
                .lock()
                .map_err(|_| anyhow!("cannot access epoch token, poisoned lock"))?;
            *current_epoch_token = None;
            Ok(())
        } else {
            Err(anyhow!("Failed to release lease on quorum"))
        }
    }

    fn publish_block_on_node(
        &self,
        redis_node: &RedisNode,
        epoch: u64,
        block: &SealedBlock,
        block_data: &[u8],
    ) -> anyhow::Result<WriteBlockResult> {
        let mut connection = redis_node
            .redis_client
            .get_connection_with_timeout(self.node_timeout)?;
        connection.set_read_timeout(Some(self.node_timeout))?;
        connection.set_write_timeout(Some(self.node_timeout))?;
        let block_height = u32::from(*block.entity.header().height());
        let lua_start = std::time::Instant::now();
        let write_result = redis::Script::new(WRITE_BLOCK_SCRIPT)
            .key(&self.block_stream_key)
            .key(&self.epoch_key)
            .key(&self.lease_key)
            .arg(epoch)
            .arg(&self.lease_owner_token)
            .arg(block_height)
            .arg(block_data)
            .arg(self.lease_ttl_millis)
            .arg(self.stream_max_len)
            .invoke::<String>(&mut connection);
        poa_metrics()
            .write_block_duration_s
            .observe(lua_start.elapsed().as_secs_f64());
        match write_result {
            Ok(_) => {
                poa_metrics().write_block_success_total.inc();
                Ok(WriteBlockResult::Written)
            }
            Err(err) if err.to_string().contains("HEIGHT_EXISTS:") => {
                poa_metrics().write_block_height_exists_total.inc();
                tracing::debug!(
                    "write_block: height already exists (height={block_height})"
                );
                Ok(WriteBlockResult::HeightExists)
            }
            Err(err) if err.to_string().contains("FENCING_ERROR:") => {
                poa_metrics().write_block_fencing_error_total.inc();
                tracing::warn!(
                    "write_block: fencing rejected (height={block_height}): {err}"
                );
                Ok(WriteBlockResult::FencingRejected)
            }
            Err(err) => {
                poa_metrics().write_block_error_total.inc();
                Err(err.into())
            }
        }
    }

    /// Repropose a sub-quorum block to all Redis nodes to reach quorum.
    /// Called during reconciliation when a block exists on some nodes but
    /// below quorum — possibly from a leader that published and committed
    /// locally but whose write only reached a subset of nodes.
    ///
    /// `pre_existing_count` is the number of nodes already confirmed to
    /// have this specific block during the reconciliation read phase.
    ///
    /// Uses `publish_block_on_node` which runs `write_block.lua`:
    /// - Written: node accepted the block (counted toward quorum)
    /// - HEIGHT_EXISTS: node has *some* block at this height — may be a
    ///   different block from a competing partial write, so NOT counted
    /// - FENCING_ERROR: lost the lock — abort the repair
    /// - The total (pre_existing + newly written) must reach quorum
    fn repair_sub_quorum_block(
        &self,
        block: &SealedBlock,
        pre_existing_count: usize,
    ) -> anyhow::Result<bool> {
        let epoch = match *self
            .current_epoch_token
            .lock()
            .map_err(|_| anyhow!("cannot access epoch token, poisoned lock"))?
        {
            Some(epoch) => epoch,
            None => {
                return Err(anyhow!(
                    "Cannot repair block because fencing token is not initialized"
                ));
            }
        };
        let block_data = postcard::to_allocvec(block)?;
        // Start from the pre-existing count (nodes already confirmed to
        // have this specific block during reconciliation). Only count
        // newly Written nodes — HeightExists means the node has *some*
        // block at this height, but it might be a different block from
        // a competing leader's partial write.
        let mut total_with_block = pre_existing_count;
        for redis_node in &self.redis_nodes {
            match self.publish_block_on_node(redis_node, epoch, block, &block_data) {
                Ok(WriteBlockResult::Written) => {
                    total_with_block = total_with_block.saturating_add(1);
                }
                Ok(WriteBlockResult::HeightExists) => {
                    // Node has some block at this height — may or may
                    // not be ours. Don't count it; the pre_existing_count
                    // already includes nodes confirmed to have our block.
                }
                Ok(WriteBlockResult::FencingRejected) => {
                    // Lost the lock — repair is invalid, abort
                    return Err(anyhow!(
                        "Lost lock during repair — another leader took over"
                    ));
                }
                Err(err) => {
                    tracing::debug!("Repair write to node failed: {err}");
                }
            }
        }
        let reached_quorum = self.quorum_reached(total_with_block);
        if reached_quorum {
            poa_metrics().repair_success_total.inc();
        } else {
            poa_metrics().repair_failure_total.inc();
        }
        Ok(reached_quorum)
    }
}

/// Result of a `write_block.lua` invocation on a single Redis node.
enum WriteBlockResult {
    /// Block was successfully written to the stream.
    Written,
    /// A block at this height already exists in the stream.
    HeightExists,
    /// Lock lost or epoch is stale — another leader holds the lock.
    FencingRejected,
}

impl PoAAdapter {
    pub fn new(shared_state: Option<SharedState>) -> Self {
        Self { shared_state }
    }

    pub async fn manually_produce_blocks(
        &self,
        start_time: Option<Tai64>,
        mode: Mode,
    ) -> anyhow::Result<()> {
        self.shared_state
            .as_ref()
            .ok_or(anyhow!("The block production is disabled"))?
            .manually_produce_block(start_time, mode)
            .await
    }
}

#[async_trait::async_trait]
impl BlockReconciliationReadPort for NoopReconciliationAdapter {
    async fn leader_state(
        &self,
        _next_height: BlockHeight,
    ) -> anyhow::Result<LeaderState> {
        Ok(LeaderState::ReconciledLeader)
    }

    async fn release(&self) -> anyhow::Result<()> {
        Ok(())
    }
}

#[async_trait::async_trait]
impl BlockReconciliationReadPort for RedisLeaderLeaseAdapter {
    async fn leader_state(
        &self,
        next_height: BlockHeight,
    ) -> anyhow::Result<LeaderState> {
        if self.can_produce_block().await? {
            poa_metrics().is_leader.set(1);
            if let Ok(epoch) = self.current_epoch_token.lock()
                && let Some(epoch) = *epoch
            {
                poa_metrics()
                    .leader_epoch
                    .set(i64::try_from(epoch).unwrap_or(i64::MAX));
            }
            let reconcile_start = std::time::Instant::now();
            let unreconciled_blocks = self.unreconciled_blocks(next_height).await?;
            poa_metrics()
                .reconciliation_duration_s
                .observe(reconcile_start.elapsed().as_secs_f64());
            if unreconciled_blocks.is_empty() {
                Ok(LeaderState::ReconciledLeader)
            } else {
                Ok(LeaderState::UnreconciledBlocks(unreconciled_blocks))
            }
        } else {
            poa_metrics().is_leader.set(0);
            Ok(LeaderState::ReconciledFollower)
        }
    }

    async fn release(&self) -> anyhow::Result<()> {
        self.release_if_owner().await
    }
}

#[async_trait::async_trait]
impl BlockReconciliationReadPort for ReconciliationAdapter {
    async fn leader_state(
        &self,
        next_height: BlockHeight,
    ) -> anyhow::Result<LeaderState> {
        match self {
            Self::Redis(adapter) => adapter.leader_state(next_height).await,
            Self::Noop(adapter) => adapter.leader_state(next_height).await,
        }
    }

    async fn release(&self) -> anyhow::Result<()> {
        match self {
            Self::Redis(adapter) => adapter.release().await,
            Self::Noop(adapter) => adapter.release().await,
        }
    }
}

impl Drop for RedisLeaderLeaseAdapter {
    fn drop(&mut self) {
        if std::sync::Arc::strong_count(&self.drop_release_guard) != 1 {
            return;
        }

        let redis_clients = self
            .redis_nodes
            .iter()
            .map(|redis_node| redis_node.redis_client.clone())
            .collect::<Vec<_>>();
        if let Ok(runtime_handle) = tokio::runtime::Handle::try_current() {
            let release_future = timeout(
                Duration::from_millis(100),
                Self::release_lease_on_clients(
                    redis_clients,
                    self.lease_key.clone(),
                    self.lease_owner_token.clone(),
                    self.node_timeout,
                ),
            );
            drop(runtime_handle.spawn(async move {
                if release_future.await.is_err() {
                    error!("Failed to release leader lease: timeout");
                }
            }));
            return;
        }

        Self::release_lease_on_clients_sync(
            redis_clients,
            self.lease_key.clone(),
            self.lease_owner_token.clone(),
        );
    }
}

impl BlockReconciliationWritePort for RedisLeaderLeaseAdapter {
    fn publish_produced_block(&self, block: &SealedBlock) -> anyhow::Result<()> {
        let epoch = match *self
            .current_epoch_token
            .lock()
            .map_err(|_| anyhow!("cannot access epoch token, poisoned lock"))?
        {
            Some(epoch) => epoch,
            None => {
                if matches!(
                    block.consensus,
                    fuel_core_types::blockchain::consensus::Consensus::Genesis(_)
                ) {
                    tracing::debug!(
                        "Skipping redis block publish for genesis block because fencing token is not initialized"
                    );
                    return Ok(());
                }
                return Err(anyhow!(
                    "Cannot publish block because fencing token is not initialized"
                ));
            }
        };
        let block_data = postcard::to_allocvec(block)?;
        let successes = self
            .redis_nodes
            .iter()
            .map(|redis_node| {
                match self.publish_block_on_node(redis_node, epoch, block, &block_data) {
                    Ok(WriteBlockResult::Written) => true,
                    Ok(_) => false,
                    Err(err) => {
                        tracing::debug!("Redis publish on node failed: {err}");
                        false
                    }
                }
            })
            .filter(|success| *success)
            .count();
        if self.quorum_reached(successes) {
            Ok(())
        } else {
            Err(anyhow!(
                "Failed to publish block to redis quorum with fencing checks"
            ))
        }
    }
}

#[async_trait::async_trait]
impl ConsensusModulePort for PoAAdapter {
    async fn manually_produce_blocks(
        &self,
        start_time: Option<Tai64>,
        number_of_blocks: u32,
    ) -> anyhow::Result<()> {
        self.manually_produce_blocks(start_time, Mode::Blocks { number_of_blocks })
            .await
    }
}

#[cfg(feature = "p2p")]
impl P2pPort for P2PAdapter {
    fn reserved_peers_count(&self) -> BoxStream<usize> {
        if let Some(service) = &self.service {
            Box::pin(
                BroadcastStream::new(service.subscribe_reserved_peers_count())
                    .filter_map(|result| result.ok()),
            )
        } else {
            Box::pin(tokio_stream::pending())
        }
    }
}

#[cfg(not(feature = "p2p"))]
impl P2pPort for P2PAdapter {
    fn reserved_peers_count(&self) -> BoxStream<usize> {
        Box::pin(tokio_stream::pending())
    }
}

pub struct InDirectoryPredefinedBlocks {
    path_to_directory: Option<PathBuf>,
}

impl InDirectoryPredefinedBlocks {
    pub fn new(path_to_directory: Option<PathBuf>) -> Self {
        Self { path_to_directory }
    }
}

impl PredefinedBlocks for InDirectoryPredefinedBlocks {
    fn get_block(&self, height: &BlockHeight) -> anyhow::Result<Option<Block>> {
        let Some(path) = &self.path_to_directory else {
            return Ok(None);
        };

        let block_height: u32 = (*height).into();
        if block_exists(path.as_path(), block_height) {
            let block_path = block_path(path.as_path(), block_height);
            let block_bytes = std::fs::read(block_path)?;
            let block: Block = serde_json::from_slice(block_bytes.as_slice())?;
            Ok(Some(block))
        } else {
            Ok(None)
        }
    }
}

pub fn block_path(path_to_directory: &Path, block_height: u32) -> PathBuf {
    path_to_directory.join(format!("{block_height}.json"))
}

pub fn block_exists(path_to_directory: &Path, block_height: u32) -> bool {
    block_path(path_to_directory, block_height).exists()
}

impl TransactionPool for TxPoolAdapter {
    fn new_txs_watcher(&self) -> watch::Receiver<()> {
        self.service.get_new_executable_txs_notifier()
    }
}

#[async_trait::async_trait]
impl fuel_core_poa::ports::BlockProducer for BlockProducerAdapter {
    async fn produce_and_execute_block(
        &self,
        height: BlockHeight,
        block_time: Tai64,
        source: TransactionsSource,
        deadline: Instant,
    ) -> anyhow::Result<UncommittedResult<Changes>> {
        match source {
            TransactionsSource::TxPool => {
                self.block_producer
                    .produce_and_execute_block_txpool(height, block_time, deadline)
                    .await
            }
            TransactionsSource::SpecificTransactions(txs) => {
                self.block_producer
                    .produce_and_execute_block_transactions(height, block_time, txs)
                    .await
            }
        }
    }

    async fn produce_predefined_block(
        &self,
        block: &Block,
    ) -> anyhow::Result<UncommittedResult<Changes>> {
        self.block_producer
            .produce_and_execute_predefined(block, ())
            .await
    }
}

#[async_trait::async_trait]
impl BlockImporter for BlockImporterAdapter {
    async fn commit_result(
        &self,
        result: UncommittedImporterResult<Changes>,
    ) -> anyhow::Result<()> {
        self.block_importer
            .commit_result(result)
            .await
            .map_err(Into::into)
    }

    async fn execute_and_commit(&self, block: SealedBlock) -> anyhow::Result<()> {
        self.block_importer
            .execute_and_commit(block)
            .await
            .map_err(Into::into)
    }

    fn block_stream(&self) -> BoxStream<BlockImportInfo> {
        Box::pin(
            BroadcastStream::new(self.block_importer.subscribe())
                .filter_map(|result| result.ok())
                .map(|result| BlockImportInfo::from(result.shared_result)),
        )
    }

    fn latest_block_height(&self) -> anyhow::Result<Option<BlockHeight>> {
        self.database.latest_block_height().map_err(Into::into)
    }
}

#[cfg(all(test, feature = "leader_lock", not(feature = "not_leader_lock")))]
#[allow(non_snake_case)]
mod tests {
    use super::*;
    use fuel_core_importer::ports::BlockReconciliationWritePort;
    use fuel_core_poa::ports::BlockReconciliationReadPort;
    use fuel_core_types::blockchain::consensus::Consensus;
    use std::{
        net::{
            SocketAddrV4,
            TcpListener,
            TcpStream,
        },
        process::{
            Child,
            Command,
            Stdio,
        },
        thread,
        time::Duration,
    };

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_same_height_has_multiple_stream_entries_then_returns_highest_epoch_block()
     {
        // given
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:stream-conflict".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![redis.redis_url()],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");

        let low_epoch_block = poa_block_at_time(1, 10);
        let high_epoch_block = poa_block_at_time(1, 20);

        let low_epoch_data =
            postcard::to_allocvec(&low_epoch_block).expect("serialize block");
        let high_epoch_data =
            postcard::to_allocvec(&high_epoch_block).expect("serialize block");

        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        append_stream_block(&mut conn, &stream_key, 1, &low_epoch_data, 1);
        append_stream_block(&mut conn, &stream_key, 1, &high_epoch_data, 2);

        // when
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then
        let unreconciled_blocks = match leader_state {
            LeaderState::UnreconciledBlocks(blocks) => blocks,
            other => panic!("Expected unreconciled blocks, got: {other:?}"),
        };
        assert_eq!(unreconciled_blocks.len(), 1);
        assert_eq!(
            unreconciled_blocks[0].entity.header().time(),
            high_epoch_block.entity.header().time(),
            "Expected reconciliation to pick the highest epoch block for the same height",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_same_height_same_epoch_has_multiple_stream_entries_then_keeps_latest_entry()
     {
        // given
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:equal-epoch-latest-entry".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![redis.redis_url()],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");

        let stale_block = poa_block_at_time(1, 10);
        let retry_block = poa_block_at_time(1, 20);
        let stale_data =
            postcard::to_allocvec(&stale_block).expect("stale block should serialize");
        let retry_data =
            postcard::to_allocvec(&retry_block).expect("retry block should serialize");

        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        append_stream_block(&mut conn, &stream_key, 1, &stale_data, 1);
        append_stream_block(&mut conn, &stream_key, 1, &retry_data, 1);

        // when
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then
        let unreconciled_blocks = match leader_state {
            LeaderState::UnreconciledBlocks(blocks) => blocks,
            other => panic!("Expected unreconciled blocks, got: {other:?}"),
        };
        assert_eq!(unreconciled_blocks.len(), 1);
        assert_eq!(
            unreconciled_blocks[0].entity.id(),
            retry_block.entity.id(),
            "Expected reconciliation to keep latest stream entry for equal epoch",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_height_has_disagreeing_block_ids_then_repairs_with_highest_epoch_block()
     {
        // given: two different blocks at height 1 on different nodes, same epoch
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:epoch-quorum-block-mismatch".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = new_test_adapter(
            vec![
                redis_a.redis_url(),
                redis_b.redis_url(),
                redis_c.redis_url(),
            ],
            lease_key,
        );
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter should acquire lease"
        );

        let block_a = poa_block_at_time(1, 10);
        let block_b = poa_block_at_time(1, 20);
        let block_a_data =
            postcard::to_allocvec(&block_a).expect("block a should serialize");
        let block_b_data =
            postcard::to_allocvec(&block_b).expect("block b should serialize");

        let redis_a_client =
            redis::Client::open(redis_a.redis_url()).expect("redis a client should open");
        let redis_b_client =
            redis::Client::open(redis_b.redis_url()).expect("redis b client should open");
        let mut conn_a = redis_a_client
            .get_connection()
            .expect("redis a connection should open");
        let mut conn_b = redis_b_client
            .get_connection()
            .expect("redis b connection should open");

        // Both at epoch 7 but different block data — each on 1 node (sub-quorum)
        append_stream_block(&mut conn_a, &stream_key, 1, &block_a_data, 7);
        append_stream_block(&mut conn_b, &stream_key, 1, &block_b_data, 7);

        // when: leader reconciles — should pick one and repair to quorum
        // The repair writes to node C (empty), giving the winner 2/3
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then: one of the blocks is repaired and returned
        assert!(
            matches!(leader_state, LeaderState::UnreconciledBlocks(ref blocks) if blocks.len() == 1),
            "Expected repair to pick one block and reach quorum, got {leader_state:?}",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_same_height_entry_exists_on_less_than_quorum_nodes_then_repairs_it()
     {
        // given: orphan block on only 1 of 3 nodes (below quorum)
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:below-quorum".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = new_test_adapter(
            vec![
                redis_a.redis_url(),
                redis_b.redis_url(),
                redis_c.redis_url(),
            ],
            lease_key,
        );
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter should acquire lease"
        );

        let orphan_block = poa_block_at_time(1, 10);
        let orphan_block_data =
            postcard::to_allocvec(&orphan_block).expect("orphan block should serialize");

        let redis_client =
            redis::Client::open(redis_a.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        append_stream_block(&mut conn, &stream_key, 1, &orphan_block_data, 1);

        // when: leader reconciles — should repair the orphan to quorum
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then: orphan was reproposed to other nodes and returned for import
        assert!(
            matches!(leader_state, LeaderState::UnreconciledBlocks(ref blocks) if blocks.len() == 1),
            "Expected sub-quorum entry to be repaired and returned, got {leader_state:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_contiguous_heights_have_quorum_then_repairs_sub_quorum_tail()
     {
        // given: h1, h2 on quorum (a,b). h3 below quorum (a only).
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:contiguous-quorum".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = new_test_adapter(
            vec![
                redis_a.redis_url(),
                redis_b.redis_url(),
                redis_c.redis_url(),
            ],
            lease_key,
        );
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter should acquire lease"
        );

        let h1 = poa_block_at_time(1, 10);
        let h2 = poa_block_at_time(2, 20);
        let h3 = poa_block_at_time(3, 30);
        let h1_data = postcard::to_allocvec(&h1).expect("h1 should serialize");
        let h2_data = postcard::to_allocvec(&h2).expect("h2 should serialize");
        let h3_data = postcard::to_allocvec(&h3).expect("h3 should serialize");

        let redis_a_client =
            redis::Client::open(redis_a.redis_url()).expect("redis a client should open");
        let redis_b_client =
            redis::Client::open(redis_b.redis_url()).expect("redis b client should open");
        let mut conn_a = redis_a_client
            .get_connection()
            .expect("redis a connection should open");
        let mut conn_b = redis_b_client
            .get_connection()
            .expect("redis b connection should open");

        // h1 on quorum (a,b)
        append_stream_block(&mut conn_a, &stream_key, 1, &h1_data, 1);
        append_stream_block(&mut conn_b, &stream_key, 1, &h1_data, 1);
        // h2 on quorum (a,b)
        append_stream_block(&mut conn_a, &stream_key, 2, &h2_data, 1);
        append_stream_block(&mut conn_b, &stream_key, 2, &h2_data, 1);
        // h3 below quorum (a only)
        append_stream_block(&mut conn_a, &stream_key, 3, &h3_data, 1);

        // when: leader reconciles — h3 should be repaired to quorum
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then: all 3 heights returned (h3 was repaired)
        let unreconciled_blocks = match leader_state {
            LeaderState::UnreconciledBlocks(blocks) => blocks,
            other => panic!("Expected unreconciled blocks, got: {other:?}"),
        };
        assert_eq!(
            unreconciled_blocks
                .iter()
                .map(|b| u32::from(*b.entity.header().height()))
                .collect::<Vec<_>>(),
            vec![1, 2, 3],
            "Expected all heights including repaired sub-quorum h3",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_contiguous_quorum_blocks_are_present_then_returns_all_available_contiguous_blocks()
     {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:contiguous-over-128".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![
                redis_a.redis_url(),
                redis_b.redis_url(),
                redis_c.redis_url(),
            ],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");
        let redis_a_client =
            redis::Client::open(redis_a.redis_url()).expect("redis a client should open");
        let redis_b_client =
            redis::Client::open(redis_b.redis_url()).expect("redis b client should open");
        let redis_c_client =
            redis::Client::open(redis_c.redis_url()).expect("redis c client should open");
        let mut conn_a = redis_a_client
            .get_connection()
            .expect("redis a connection should open");
        let mut conn_b = redis_b_client
            .get_connection()
            .expect("redis b connection should open");
        let mut conn_c = redis_c_client
            .get_connection()
            .expect("redis c connection should open");
        let _ = &mut conn_c;

        (1_u32..=129_u32).for_each(|height| {
            let block = poa_block_at_time(height, u64::from(height));
            let block_data =
                postcard::to_allocvec(&block).expect("block should serialize");
            append_stream_block(&mut conn_a, &stream_key, height, &block_data, 1);
            append_stream_block(&mut conn_b, &stream_key, height, &block_data, 1);
        });

        // when
        let leader_state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");

        // then
        let unreconciled_blocks = match leader_state {
            LeaderState::UnreconciledBlocks(blocks) => blocks,
            other => panic!("Expected unreconciled blocks, got: {other:?}"),
        };
        assert_eq!(
            unreconciled_blocks.len(),
            129,
            "Expected all contiguous quorum-backed heights to reconcile in one call",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn publish_produced_block__when_fencing_token_is_uninitialized_then_returns_error()
     {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:missing-epoch".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = new_test_adapter(redis_urls, lease_key);
        let block = poa_block_at_time(1, 100);

        // when
        let publish_result = adapter.publish_produced_block(&block);

        // then
        assert!(
            publish_result.is_err(),
            "Publish should fail when fencing token is not initialized"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn release__when_adapter_is_not_lease_owner_then_returns_ok() {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:release-follower".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = new_test_adapter(redis_urls, lease_key);

        // when
        let release_result = adapter.release().await;

        // then
        assert!(
            release_result.is_ok(),
            "Release should be idempotent for adapters that do not own quorum lease"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn drop__when_non_last_clone_is_dropped_then_does_not_release_shared_lease() {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:drop-non-last-clone".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Adapter should acquire lease"
        );
        let adapter_clone = adapter.clone();
        let owner_token = adapter.lease_owner_token.clone();

        // when
        drop(adapter_clone);
        sleep(Duration::from_millis(50)).await;

        // then
        let owners = redis_urls
            .iter()
            .filter(|redis_url| {
                read_lease_owner(redis_url, &lease_key).as_deref()
                    == Some(owner_token.as_str())
            })
            .count();
        assert!(
            owners >= 2,
            "Dropping a non-last clone must not release quorum lease ownership"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_lease_is_free_then_acquires_quorum_ownership() {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:acquire-on-leader-state".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = RedisLeaderLeaseAdapter::new(
            redis_urls.clone(),
            lease_key.clone(),
            Duration::from_millis(500),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");

        // when
        let state = adapter
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");
        let owners = redis_urls
            .iter()
            .filter(|redis_url| {
                read_lease_owner(redis_url, &lease_key).as_deref()
                    == Some(adapter.lease_owner_token.as_str())
            })
            .count();

        // then
        assert!(
            matches!(state, LeaderState::ReconciledLeader),
            "leader_state should acquire and report leader ownership when lease is free"
        );
        assert!(
            owners >= 2,
            "Lease ownership should be present on quorum after acquisition"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn leader_state__when_lease_expires_then_another_adapter_becomes_leader() {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:ttl-expiry-handoff".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let first_adapter = RedisLeaderLeaseAdapter::new(
            redis_urls.clone(),
            lease_key.clone(),
            Duration::from_millis(300),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("first adapter should be created");
        let second_adapter = RedisLeaderLeaseAdapter::new(
            redis_urls.clone(),
            lease_key.clone(),
            Duration::from_millis(300),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("second adapter should be created");

        let first_state = first_adapter
            .leader_state(1.into())
            .await
            .expect("first leader_state should succeed");
        sleep(Duration::from_millis(900)).await;

        // when
        let second_state = second_adapter
            .leader_state(1.into())
            .await
            .expect("second leader_state should succeed");
        let second_owner_count = redis_urls
            .iter()
            .filter(|redis_url| {
                read_lease_owner(redis_url, &lease_key).as_deref()
                    == Some(second_adapter.lease_owner_token.as_str())
            })
            .count();

        // then
        assert!(
            matches!(first_state, LeaderState::ReconciledLeader),
            "First adapter should acquire lease initially"
        );
        assert!(
            matches!(second_state, LeaderState::ReconciledLeader),
            "Second adapter should become leader after TTL expiry"
        );
        assert!(
            second_owner_count >= 2,
            "Second adapter should own lease on quorum nodes after takeover"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn publish_produced_block__when_previous_leader_writes_after_handoff_then_rejects_zombie_write()
     {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:zombie-leader".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let old_leader = new_test_adapter(redis_urls.clone(), lease_key.clone());
        let current_leader = new_test_adapter(redis_urls, lease_key.clone());
        let block = poa_block_at_time(1, 111);

        assert!(
            old_leader
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Old leader should acquire initial lease"
        );
        clear_lease_on_nodes(
            &[
                redis_a.redis_url(),
                redis_b.redis_url(),
                redis_c.redis_url(),
            ],
            &lease_key,
        );
        assert!(
            current_leader
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Current leader should acquire lease after handoff"
        );

        // when
        let zombie_write = old_leader.publish_produced_block(&block);

        // then
        assert!(
            zombie_write.is_err(),
            "Old leader write should be fenced after handoff"
        );
        let current_state = current_leader
            .leader_state(1.into())
            .await
            .expect("leader_state should succeed");
        assert!(
            matches!(current_state, LeaderState::ReconciledLeader),
            "Zombie partial writes must not be considered committed"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn publish_produced_block__when_epoch_is_behind_on_one_node_then_first_write_heals_epoch()
     {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:epoch-healing".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = new_test_adapter(redis_urls, lease_key.clone());
        let epoch_key = format!("{lease_key}:epoch:token");
        let block = poa_block_at_time(1, 222);
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Adapter should acquire lease"
        );
        let leader_epoch = (*adapter.current_epoch_token.lock().expect("poisoned lock"))
            .expect("epoch should be initialized");
        let stale_epoch = leader_epoch.saturating_sub(1);
        set_epoch(&redis_a.redis_url(), &epoch_key, stale_epoch);

        // when
        let publish_result = adapter.publish_produced_block(&block);

        // then
        assert!(
            publish_result.is_ok(),
            "Publish should still succeed on quorum"
        );
        let healed_epoch = read_epoch(&redis_a.redis_url(), &epoch_key);
        assert_eq!(
            healed_epoch, leader_epoch,
            "First successful write should heal lagging epoch"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn publish_produced_block__when_write_succeeds_then_extends_lease_ttl() {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:publish-extends-lease-ttl".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = RedisLeaderLeaseAdapter::new(
            redis_urls.clone(),
            lease_key.clone(),
            Duration::from_millis(700),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");
        let block = poa_block_at_time(1, 444);
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Adapter should acquire lease"
        );
        sleep(Duration::from_millis(500)).await;

        // when
        let publish_result = adapter.publish_produced_block(&block);
        sleep(Duration::from_millis(400)).await;
        let owners = redis_urls
            .iter()
            .filter(|redis_url| {
                read_lease_owner(redis_url, &lease_key).as_deref()
                    == Some(adapter.lease_owner_token.as_str())
            })
            .count();

        // then
        assert!(publish_result.is_ok(), "Publish should succeed on quorum");
        assert!(
            owners >= 2,
            "Successful write should extend lease TTL on quorum beyond original window"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn publish_produced_block__when_write_succeeds_on_less_than_quorum_then_entry_is_not_reconciled()
     {
        // given
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:partial-write".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];
        let adapter = new_test_adapter(redis_urls, lease_key.clone());
        let block = poa_block_at_time(1, 333);
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Adapter should acquire lease"
        );
        set_lease_owner(
            &redis_b.redis_url(),
            &lease_key,
            "other-owner",
            adapter.lease_ttl_millis,
        );
        set_lease_owner(
            &redis_c.redis_url(),
            &lease_key,
            "other-owner",
            adapter.lease_ttl_millis,
        );

        // when
        let publish_result = adapter.publish_produced_block(&block);
        let unreconciled = adapter.unreconciled_blocks(1.into()).await;

        // then
        assert!(
            publish_result.is_err(),
            "Publish must fail when fewer than quorum nodes accept write"
        );
        assert!(
            unreconciled.is_err(),
            "Unresolved backlog should return an error instead of empty result"
        );
        assert_eq!(
            stream_len(&redis_a.redis_url(), &stream_key),
            1,
            "One orphan entry should exist on the single successful node"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn unreconciled_blocks__when_quorum_latest_height_is_below_next_height_then_returns_empty()
     {
        // given
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:cursor-fast-path".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![redis.redis_url()],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");
        let block = poa_block_at_time(1, 10);
        let block_data = postcard::to_allocvec(&block).expect("serialize block");
        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        append_stream_block(&mut conn, &stream_key, 1, &block_data, 1);

        // when
        let blocks = adapter
            .unreconciled_blocks(2.into())
            .await
            .expect("reconciliation read should succeed");

        // then
        assert!(
            blocks.is_empty(),
            "Expected fast path to skip full reconciliation"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn read_stream_entries_on_node__when_next_height_is_provided_then_reads_matching_entries()
     {
        // given
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:cursor-incremental-read".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![redis.redis_url()],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");
        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        let h1 = poa_block_at_time(1, 10);
        let h2 = poa_block_at_time(2, 20);
        let h3 = poa_block_at_time(3, 30);
        let h1_data = postcard::to_allocvec(&h1).expect("serialize block");
        let h2_data = postcard::to_allocvec(&h2).expect("serialize block");
        let h3_data = postcard::to_allocvec(&h3).expect("serialize block");
        append_stream_block(&mut conn, &stream_key, 1, &h1_data, 1);
        append_stream_block(&mut conn, &stream_key, 2, &h2_data, 1);
        let redis_node = adapter.redis_nodes[0].clone();

        // when
        let first_read = adapter
            .read_stream_entries_on_node(&redis_node, 1, 1000)
            .await
            .expect("first read should succeed");
        append_stream_block(&mut conn, &stream_key, 3, &h3_data, 1);
        let second_read = adapter
            .read_stream_entries_on_node(&redis_node, 3, 1000)
            .await
            .expect("second read should succeed");

        // then
        assert_eq!(
            first_read.len(),
            2,
            "Expected initial read to include existing entries"
        );
        assert_eq!(
            second_read.len(),
            1,
            "Expected height-filtered read to include only matching entries"
        );
        assert_eq!(
            u32::from(*second_read[0].2.entity.header().height()),
            3,
            "Expected only the requested next height"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn read_stream_entries_on_node__when_max_entries_is_small_then_caps_results() {
        // given
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:cursor-pagination".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let adapter = RedisLeaderLeaseAdapter::new(
            vec![redis.redis_url()],
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created");
        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        let h1 = poa_block_at_time(1, 10);
        let h2 = poa_block_at_time(2, 20);
        let h3 = poa_block_at_time(3, 30);
        let h1_data = postcard::to_allocvec(&h1).expect("serialize block");
        let h2_data = postcard::to_allocvec(&h2).expect("serialize block");
        let h3_data = postcard::to_allocvec(&h3).expect("serialize block");
        append_stream_block(&mut conn, &stream_key, 1, &h1_data, 1);
        append_stream_block(&mut conn, &stream_key, 2, &h2_data, 1);
        append_stream_block(&mut conn, &stream_key, 3, &h3_data, 1);
        let redis_node = adapter.redis_nodes[0].clone();

        // when
        let first_page = adapter
            .read_stream_entries_on_node(&redis_node, 1, 2)
            .await
            .expect("first page should succeed");
        let second_page = adapter
            .read_stream_entries_on_node(&redis_node, 3, 2)
            .await
            .expect("second page should succeed");

        // then
        assert_eq!(first_page.len(), 2, "Expected first page to be capped");
        assert_eq!(
            u32::from(*first_page[0].2.entity.header().height()),
            1,
            "Expected first page to start from earliest height"
        );
        assert_eq!(
            u32::from(*first_page[1].2.entity.header().height()),
            2,
            "Expected first page to include second height"
        );
        assert_eq!(
            second_page.len(),
            1,
            "Expected height filter to return only matching trailing entry"
        );
        assert_eq!(
            u32::from(*second_page[0].2.entity.header().height()),
            3,
            "Expected second read to include only the requested next height"
        );
    }

    /// When a partial publish leaves a stale entry at a given height,
    /// a subsequent write at the same height is rejected by
    /// write_block.lua's HEIGHT_EXISTS check. This prevents two blocks
    /// at the same height from coexisting in the stream, which would
    /// cause a fork if a different leader also achieved quorum at that
    /// height.
    #[tokio::test(flavor = "multi_thread")]
    async fn partial_publish_then_retry_at_same_height__new_leader_reconciles_stale_block()
     {
        let redis = RedisTestServer::spawn();
        let lease_key = "poa:test:fork-repro".to_string();
        let stream_key = format!("{lease_key}:block:stream");

        let adapter_a = new_test_adapter(vec![redis.redis_url()], lease_key.clone());
        assert!(
            adapter_a
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter_a should acquire lease"
        );
        let epoch_a = (*adapter_a.current_epoch_token.lock().expect("lock"))
            .expect("epoch should be set");

        // Simulate stale partial publish by writing directly to stream
        let block_a = poa_block_at_time(1, 100);
        let block_a_data = postcard::to_allocvec(&block_a).expect("serialize block_a");
        let redis_client =
            redis::Client::open(redis.redis_url()).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        append_stream_block(&mut conn, &stream_key, 1, &block_a_data, epoch_a as u32);

        // Leader A retries with a different block at the same height —
        // this should FAIL because height 1 already exists in the stream.
        let block_b = poa_block_at_time(1, 999);
        assert_ne!(
            block_a.entity.header().time(),
            block_b.entity.header().time()
        );

        let result = adapter_a.publish_produced_block(&block_b);
        assert!(
            result.is_err(),
            "publish at same height should fail due to HEIGHT_EXISTS"
        );

        // Stream should still have only the original entry
        assert_eq!(stream_len(&redis.redis_url(), &stream_key), 1);

        adapter_a.release().await.expect("release should succeed");

        // A new leader reconciles and sees block_a (the only entry)
        let adapter_b = new_test_adapter(vec![redis.redis_url()], lease_key.clone());
        assert!(
            adapter_b
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter_b should acquire lease"
        );

        let unreconciled = adapter_b
            .unreconciled_blocks(1.into())
            .await
            .expect("reconciliation should succeed");

        assert_eq!(unreconciled.len(), 1, "Should reconcile exactly one block");
        assert_eq!(
            unreconciled[0].entity.header().time(),
            block_a.entity.header().time(),
            "Reconciliation should return block_a (the only entry in the stream)"
        );
    }

    struct RedisTestServer {
        child: Option<Child>,
        port: u16,
        redis_url: String,
    }

    impl RedisTestServer {
        fn spawn() -> Self {
            let mut server = Self::new_stopped();
            server.start();
            server
        }

        fn new_stopped() -> Self {
            let port = bind_unused_port();
            Self {
                child: None,
                port,
                redis_url: format!("redis://127.0.0.1:{port}/"),
            }
        }

        fn start(&mut self) {
            if self.child.is_some() {
                return;
            }
            let child = spawn_redis_server(self.port);
            wait_for_redis_ready(self.port);
            self.child = Some(child);
        }

        fn stop(&mut self) {
            if let Some(child) = self.child.as_mut() {
                let _ = child.kill();
                let _ = child.wait();
            }
            self.child = None;
        }

        fn redis_url(&self) -> String {
            self.redis_url.clone()
        }
    }

    impl Drop for RedisTestServer {
        fn drop(&mut self) {
            if let Some(child) = self.child.as_mut() {
                let _ = child.kill();
                let _ = child.wait();
            }
        }
    }

    fn bind_unused_port() -> u16 {
        let socket =
            TcpListener::bind(SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, 0))
                .expect("Should bind an ephemeral port");
        let port = socket.local_addr().expect("Should get local addr").port();
        drop(socket);
        port
    }

    fn spawn_redis_server(port: u16) -> Child {
        Command::new("redis-server")
            .arg("--port")
            .arg(port.to_string())
            .arg("--save")
            .arg("")
            .arg("--appendonly")
            .arg("no")
            .arg("--bind")
            .arg("127.0.0.1")
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .expect("Failed to spawn redis-server")
    }

    fn wait_for_redis_ready(port: u16) {
        let addr = SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port);
        let start = std::time::Instant::now();
        let timeout = Duration::from_secs(5);
        while start.elapsed() < timeout {
            if TcpStream::connect(addr).is_ok() {
                return;
            }
            thread::sleep(Duration::from_millis(10));
        }
        panic!("Redis server did not become ready on port {port}");
    }

    fn poa_block_at_time(height: u32, timestamp: u64) -> SealedBlock {
        let mut block = Block::default();
        block.header_mut().set_block_height(height.into());
        block
            .header_mut()
            .set_time(fuel_core_types::tai64::Tai64(timestamp));
        block.header_mut().recalculate_metadata();
        SealedBlock {
            entity: block,
            consensus: Consensus::PoA(Default::default()),
        }
    }

    fn append_stream_block(
        conn: &mut redis::Connection,
        stream_key: &str,
        height: u32,
        data: &[u8],
        epoch: u32,
    ) {
        let _: String = redis::cmd("XADD")
            .arg(stream_key)
            .arg("*")
            .arg("height")
            .arg(height)
            .arg("data")
            .arg(data)
            .arg("epoch")
            .arg(epoch)
            .arg("timestamp")
            .arg(epoch)
            .query(conn)
            .expect("stream write should succeed");
    }

    fn new_test_adapter(
        redis_urls: Vec<String>,
        lease_key: String,
    ) -> RedisLeaderLeaseAdapter {
        RedisLeaderLeaseAdapter::new(
            redis_urls,
            lease_key,
            Duration::from_secs(2),
            Duration::from_millis(100),
            Duration::from_millis(50),
            Duration::from_millis(0),
            1,
            1000,
        )
        .expect("adapter should be created")
    }

    fn set_epoch(redis_url: &str, epoch_key: &str, epoch: u64) {
        let redis_client =
            redis::Client::open(redis_url).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        let _: () = redis::cmd("SET")
            .arg(epoch_key)
            .arg(epoch)
            .query(&mut conn)
            .expect("epoch set should succeed");
    }

    fn read_epoch(redis_url: &str, epoch_key: &str) -> u64 {
        let redis_client =
            redis::Client::open(redis_url).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        let epoch: Option<u64> = redis::cmd("GET")
            .arg(epoch_key)
            .query(&mut conn)
            .expect("epoch get should succeed");
        epoch.expect("epoch should exist")
    }

    fn set_lease_owner(
        redis_url: &str,
        lease_key: &str,
        owner: &str,
        lease_ttl_millis: u64,
    ) {
        let redis_client =
            redis::Client::open(redis_url).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        let _: () = redis::cmd("SET")
            .arg(lease_key)
            .arg(owner)
            .arg("PX")
            .arg(lease_ttl_millis)
            .query(&mut conn)
            .expect("lease owner set should succeed");
    }

    fn read_lease_owner(redis_url: &str, lease_key: &str) -> Option<String> {
        let redis_client =
            redis::Client::open(redis_url).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        redis::cmd("GET")
            .arg(lease_key)
            .query(&mut conn)
            .expect("lease owner get should succeed")
    }

    fn clear_lease_on_nodes(redis_urls: &[String], lease_key: &str) {
        redis_urls.iter().for_each(|redis_url| {
            let redis_client = redis::Client::open(redis_url.as_str())
                .expect("redis client should open");
            let mut conn = redis_client
                .get_connection()
                .expect("redis connection should open");
            let _: () = redis::cmd("DEL")
                .arg(lease_key)
                .query(&mut conn)
                .expect("lease delete should succeed");
        });
    }

    fn stream_len(redis_url: &str, stream_key: &str) -> usize {
        let redis_client =
            redis::Client::open(redis_url).expect("redis client should open");
        let mut conn = redis_client
            .get_connection()
            .expect("redis connection should open");
        redis::cmd("XLEN")
            .arg(stream_key)
            .query(&mut conn)
            .expect("stream length query should succeed")
    }

    /// When Redis read calls fail on a quorum of nodes,
    /// `unreconciled_blocks` must return an error — not silently
    /// return an empty list that would let the caller produce
    /// a divergent block.
    #[tokio::test(flavor = "multi_thread")]
    async fn unreconciled_blocks__when_reads_fail_on_quorum_nodes__returns_error() {
        // given — 3 Redis nodes, leader A publishes block to all 3
        let mut redis_a = RedisTestServer::spawn();
        let mut redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:read-failure-fork".to_string();
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        let adapter_a = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter_a
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Leader A should acquire lease"
        );

        let block = poa_block_at_time(1, 100);
        adapter_a
            .publish_produced_block(&block)
            .expect("publish should succeed on all 3 nodes");

        // Verify block exists on all 3 nodes
        let stream_key = format!("{lease_key}:block:stream");
        assert_eq!(stream_len(&redis_a.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_b.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_c.redis_url(), &stream_key), 1);

        // Simulate A releasing lease
        adapter_a.release().await.expect("release should succeed");

        // when — kill 2 of 3 Redis nodes BEFORE new leader reconciles
        redis_a.stop();
        redis_b.stop();

        let adapter_b = new_test_adapter(redis_urls.clone(), lease_key.clone());
        // Manually set epoch so we can call unreconciled_blocks directly
        {
            let mut epoch = adapter_b.current_epoch_token.lock().expect("lock");
            *epoch = Some(99);
        }

        let result = adapter_b.unreconciled_blocks(1.into()).await;

        // then — must return Err, not Ok([])
        assert!(
            result.is_err(),
            "unreconciled_blocks must return error when reads fail on quorum of nodes"
        );
    }

    /// Proves that when a Redis node restarts (losing all in-memory data),
    /// a block that was published to exactly quorum nodes drops below quorum
    /// and reconciliation cannot find it — enabling a fork.
    #[tokio::test(flavor = "multi_thread")]
    async fn unreconciled_blocks__when_redis_node_restarts_and_loses_data__drops_block_below_quorum()
     {
        // given — 3 Redis nodes, leader A publishes block to nodes A and B only
        // (simulating a partial publish where node C timed out)
        let redis_a = RedisTestServer::spawn();
        let mut redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:data-loss-fork".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        let adapter_a = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter_a
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Leader A should acquire lease"
        );
        let epoch_a = (*adapter_a.current_epoch_token.lock().expect("lock"))
            .expect("epoch should be set");

        // Publish block to nodes A and B only (simulating node C timeout).
        // We write directly to simulate the partial publish that still
        // reaches quorum (2/3).
        let block = poa_block_at_time(1, 100);
        let block_data = postcard::to_allocvec(&block).expect("serialize");

        let client_a = redis::Client::open(redis_a.redis_url()).expect("client");
        let mut conn_a = client_a.get_connection().expect("conn");
        let client_b = redis::Client::open(redis_b.redis_url()).expect("client");
        let mut conn_b = client_b.get_connection().expect("conn");

        append_stream_block(&mut conn_a, &stream_key, 1, &block_data, epoch_a as u32);
        append_stream_block(&mut conn_b, &stream_key, 1, &block_data, epoch_a as u32);
        // Node C has no entry (simulated timeout during publish)

        // Verify: block on A and B, not on C
        assert_eq!(stream_len(&redis_a.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_b.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_c.redis_url(), &stream_key), 0);

        // Confirm reconciliation works BEFORE data loss — quorum=2, both A and B have it
        let pre_loss = adapter_a
            .unreconciled_blocks(1.into())
            .await
            .expect("reconciliation should succeed");
        assert_eq!(
            pre_loss.len(),
            1,
            "Block should be reconcilable with 2/3 nodes having it"
        );

        // when — Redis node B restarts (pod eviction / rolling deploy / AMI drift)
        // All in-memory data is lost (no persistence configured)
        drop(conn_b);
        drop(client_b);
        redis_b.stop();
        redis_b.start();

        // Verify node B lost its stream data
        assert_eq!(
            stream_len(&redis_b.redis_url(), &stream_key),
            0,
            "Restarted node should have empty stream"
        );

        // Release A's lease so B can acquire
        adapter_a.release().await.expect("release should succeed");

        // New leader acquires
        let adapter_b = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter_b
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "New leader should acquire lease"
        );

        let post_loss = adapter_b
            .unreconciled_blocks(1.into())
            .await
            .expect("reconciliation should succeed");

        // then — repair reproposed the block from node A to node B (now empty)
        // and node C, reaching quorum again. The block is recovered.
        assert_eq!(
            post_loss.len(),
            1,
            "Repair should recover the block by reproposing from node A to the other nodes"
        );
    }

    /// After an election storm where leader A wins on nodes 1,2 but
    /// another candidate held node 3, `has_lease_owner_quorum` should
    /// expand the lock to node 3 once it's free. Subsequent block
    /// writes then go to all 3 nodes instead of just 2.
    #[tokio::test(flavor = "multi_thread")]
    async fn has_lease_owner_quorum__expands_lock_to_non_owned_nodes() {
        // given — 3 Redis nodes
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:lock-expansion".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        // Simulate election storm: candidate B grabs node C first
        let candidate_b = new_test_adapter(redis_urls.clone(), lease_key.clone());
        // Manually acquire on node C only (simulate B winning SET NX on C)
        {
            let client = redis::Client::open(redis_c.redis_url()).expect("client");
            let mut conn = client.get_connection().expect("conn");
            let _: () = redis::cmd("SET")
                .arg(&lease_key)
                .arg(&candidate_b.lease_owner_token)
                .arg("PX")
                .arg(5000u64)
                .query(&mut conn)
                .expect("set should succeed");
        }

        // Leader A acquires — gets nodes A,B but not C (B holds it)
        let adapter_a = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter_a
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Leader A should acquire quorum (2/3)"
        );

        // Verify A owns nodes A,B but NOT node C
        let owns_a = read_lease_owner(&redis_a.redis_url(), &lease_key)
            == Some(adapter_a.lease_owner_token.clone());
        let owns_b = read_lease_owner(&redis_b.redis_url(), &lease_key)
            == Some(adapter_a.lease_owner_token.clone());
        let owns_c = read_lease_owner(&redis_c.redis_url(), &lease_key)
            == Some(adapter_a.lease_owner_token.clone());
        assert!(owns_a && owns_b, "A should own nodes A and B");
        assert!(!owns_c, "A should NOT own node C (held by B)");

        // Candidate B releases node C (simulating failed-quorum cleanup)
        clear_lease_on_nodes(&[redis_c.redis_url()], &lease_key);
        assert!(
            read_lease_owner(&redis_c.redis_url(), &lease_key).is_none(),
            "Node C should be free after B releases"
        );

        // when — A calls has_lease_owner_quorum (which now expands)
        let has_quorum = adapter_a
            .has_lease_owner_quorum()
            .await
            .expect("quorum check should succeed");
        assert!(has_quorum, "A should still have quorum");

        // then — A should now own node C too
        let owns_c_after = read_lease_owner(&redis_c.redis_url(), &lease_key)
            == Some(adapter_a.lease_owner_token.clone());
        assert!(owns_c_after, "Lock expansion should have acquired node C");

        // Verify writes now go to all 3 nodes
        let block = poa_block_at_time(1, 100);
        adapter_a
            .publish_produced_block(&block)
            .expect("publish should succeed");

        assert_eq!(stream_len(&redis_a.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_b.redis_url(), &stream_key), 1);
        assert_eq!(
            stream_len(&redis_c.redis_url(), &stream_key),
            1,
            "Block should be written to expanded node C"
        );
    }

    /// When lock expansion acquires a node with a higher epoch
    /// (from election storm drift), the leader adopts the higher epoch
    /// so write_block.lua succeeds on all nodes.
    #[tokio::test(flavor = "multi_thread")]
    async fn has_lease_owner_quorum__adopts_higher_epoch_from_expanded_node() {
        // given — 3 Redis nodes
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:epoch-adoption".to_string();
        let epoch_key = format!("{lease_key}:epoch:token");
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        // Simulate election storm: B promotes on node C (incrementing epoch)
        // then fails quorum and releases the lock, leaving epoch drifted
        let candidate_b = new_test_adapter(redis_urls.clone(), lease_key.clone());
        {
            let client = redis::Client::open(redis_c.redis_url()).expect("client");
            let mut conn = client.get_connection().expect("conn");
            // Simulate B's promote_leader.lua on node C: SET NX + INCR
            let _: () = redis::cmd("SET")
                .arg(&lease_key)
                .arg(&candidate_b.lease_owner_token)
                .arg("PX")
                .arg(5000u64)
                .query(&mut conn)
                .expect("set should succeed");
            let _: u64 = redis::cmd("INCR")
                .arg(&epoch_key)
                .query(&mut conn)
                .expect("incr should succeed");
            // B releases (failed quorum cleanup)
        }
        clear_lease_on_nodes(&[redis_c.redis_url()], &lease_key);

        // Node C now has epoch=1 but no lock owner
        let epoch_c_before = read_epoch(&redis_c.redis_url(), &epoch_key);

        // Leader A acquires on all free nodes (A,B,C all free now)
        let adapter_a = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter_a
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
        );
        let epoch_a = (*adapter_a.current_epoch_token.lock().expect("lock"))
            .expect("epoch should be set");

        // A's epoch should be max across all 3 nodes
        // Node C had epoch=1 from B's INCR, then A's promote INCR'd it to 2
        // Nodes A,B were at 0, A's promote INCR'd them to 1
        // A takes max(1, 1, 2) = 2
        assert!(
            epoch_a > epoch_c_before,
            "Leader's epoch ({epoch_a}) should be > node C's pre-acquisition epoch ({epoch_c_before})"
        );

        // Verify writes succeed on ALL nodes with the adopted epoch
        let block = poa_block_at_time(1, 100);
        adapter_a
            .publish_produced_block(&block)
            .expect("publish should succeed on all 3 nodes");

        assert_eq!(stream_len(&redis_a.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_b.redis_url(), &stream_key), 1);
        assert_eq!(stream_len(&redis_c.redis_url(), &stream_key), 1);
    }

    /// Exercises promotion, block write, fencing rejection, repair, and
    /// reconciliation, then dumps `encode_metrics()` to verify all PoA
    /// metrics appear on the /v1/metrics endpoint with expected values.
    #[tokio::test(flavor = "multi_thread")]
    async fn metrics__poa_metrics_appear_in_encoded_output_after_exercising_all_paths() {
        // --- setup: 3 Redis nodes ---
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:metrics-smoke".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        // 1. Promotion (success path)
        let adapter = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "adapter should acquire lease"
        );

        // 2. Successful block write
        let block1 = poa_block_at_time(1, 100);
        adapter
            .publish_produced_block(&block1)
            .expect("publish should succeed");

        // 3. HEIGHT_EXISTS — write same height again
        let block1_dup = poa_block_at_time(1, 200);
        let dup_result = adapter.publish_produced_block(&block1_dup);
        assert!(dup_result.is_err(), "duplicate height should fail");

        // 4. Fencing rejection — old leader tries to write after handoff
        let old_adapter = new_test_adapter(redis_urls.clone(), lease_key.clone());
        // Give old_adapter a stale epoch so it thinks it's leader
        {
            let mut epoch = old_adapter.current_epoch_token.lock().expect("lock");
            *epoch = Some(1);
        }
        let _zombie = old_adapter.publish_produced_block(&poa_block_at_time(2, 300));

        // 5. Reconciliation with sub-quorum repair
        //    Put an orphan block on node A only at height 2
        let orphan = poa_block_at_time(2, 400);
        let orphan_data = postcard::to_allocvec(&orphan).expect("serialize orphan");
        let client_a = redis::Client::open(redis_a.redis_url()).expect("redis client");
        let mut conn_a = client_a.get_connection().expect("redis connection");
        let epoch_val =
            (*adapter.current_epoch_token.lock().expect("lock")).expect("epoch set");
        #[allow(clippy::cast_possible_truncation)]
        let epoch_u32 = epoch_val as u32;
        append_stream_block(&mut conn_a, &stream_key, 2, &orphan_data, epoch_u32);

        // 6. leader_state triggers reconciliation + repair
        let state = adapter
            .leader_state(2.into())
            .await
            .expect("leader_state should succeed");
        assert!(
            matches!(
                state,
                LeaderState::UnreconciledBlocks(ref blocks) if !blocks.is_empty()
            ),
            "Should have unreconciled blocks: {state:?}"
        );

        // --- encode and verify ---
        let encoded =
            fuel_core_metrics::encode_metrics().expect("encode_metrics should succeed");

        // Print full output for visual inspection
        let poa_lines: Vec<&str> =
            encoded.lines().filter(|l| l.contains("poa_")).collect();
        for line in &poa_lines {
            eprintln!("{line}");
        }

        // Verify all metric names appear.
        // Counters get `_total` appended by prometheus-client automatically.
        let expected_names = [
            "poa_leader_epoch",
            "poa_is_leader",
            "poa_epoch_max_drift",
            "poa_stream_trim_headroom",
            "poa_write_block_success_total",
            "poa_write_block_height_exists_total",
            "poa_write_block_fencing_error_total",
            "poa_write_block_error_total",
            "poa_repair_success_total",
            "poa_promotion_success_total",
            "poa_promotion_duration_s",
            "poa_write_block_duration_s",
            "poa_reconciliation_duration_s",
            "poa_connection_reset_total",
        ];
        for name in &expected_names {
            assert!(
                encoded.contains(name),
                "Metric '{name}' missing from /v1/metrics output"
            );
        }

        // Verify key metrics have non-zero values.
        // For counters, the data line is e.g. `poa_write_block_success_total 3`.
        // For gauges, it's e.g. `poa_leader_epoch 2`.
        // We find the line that starts with the name, excluding sub-metric
        // lines (like `_bucket`, `_sum`, `_count`).
        let non_zero_metrics = [
            "poa_leader_epoch",
            "poa_is_leader",
            "poa_write_block_success_total",
            "poa_promotion_success_total",
            "poa_repair_success_total",
        ];
        for name in &non_zero_metrics {
            let metric_line = encoded
                .lines()
                .find(|l| {
                    l.starts_with(name)
                        && !l.starts_with(&format!("{name}_"))
                        && !l.starts_with('#')
                })
                .unwrap_or_else(|| panic!("No data line for {name}"));
            assert!(
                !metric_line.ends_with(" 0"),
                "Metric '{name}' should be non-zero, got: {metric_line}"
            );
        }
    }

    /// When quorum reads fail during reconciliation, a subsequent call
    /// should still be able to read the same backlog entries.
    #[tokio::test(flavor = "multi_thread")]
    async fn unreconciled_blocks__after_quorum_read_failure_then_backlog_remains_readable()
     {
        // given — 3 Redis nodes, block published to all 3
        let mut redis_a = RedisTestServer::spawn();
        let mut redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:cursor-restore-quorum".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        let adapter = new_test_adapter(redis_urls.clone(), lease_key.clone());
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Should acquire lease"
        );

        let block = poa_block_at_time(1, 100);
        adapter
            .publish_produced_block(&block)
            .expect("publish should succeed on all 3 nodes");
        adapter.release().await.expect("release should succeed");

        // when — kill 2 nodes so quorum read fails
        redis_a.stop();
        redis_b.stop();

        let adapter_b = new_test_adapter(redis_urls.clone(), lease_key.clone());
        {
            let mut epoch = adapter_b.current_epoch_token.lock().expect("lock");
            *epoch = Some(99);
        }
        let result = adapter_b.unreconciled_blocks(1.into()).await;
        assert!(result.is_err(), "Should fail with quorum read failure");

        // Restart the killed nodes — all 3 now reachable
        redis_a.start();
        redis_b.start();

        // Re-publish block to the restarted nodes so they have data
        let client_a = redis::Client::open(redis_a.redis_url()).expect("client");
        let mut conn_a = client_a.get_connection().expect("conn");
        let client_b = redis::Client::open(redis_b.redis_url()).expect("client");
        let mut conn_b = client_b.get_connection().expect("conn");
        let block_data = postcard::to_allocvec(&block).expect("serialize");
        append_stream_block(&mut conn_a, &stream_key, 1, &block_data, 1);
        append_stream_block(&mut conn_b, &stream_key, 1, &block_data, 1);

        // then — subsequent call must still see the block on node C
        let blocks = adapter_b
            .unreconciled_blocks(1.into())
            .await
            .expect("reconciliation should succeed now");
        assert_eq!(
            blocks.len(),
            1,
            "Quorum read failure should not make backlog entries unreadable"
        );
    }

    /// When sub-quorum repair fails, the next reconciliation round
    /// should still be able to re-read and retry.
    #[tokio::test(flavor = "multi_thread")]
    async fn unreconciled_blocks__after_repair_failure_then_backlog_remains_readable() {
        // given — 3 Redis nodes, block published to only 1 node (sub-quorum)
        let redis_a = RedisTestServer::spawn();
        let redis_b = RedisTestServer::spawn();
        let redis_c = RedisTestServer::spawn();
        let lease_key = "poa:test:cursor-restore-repair".to_string();
        let stream_key = format!("{lease_key}:block:stream");
        let redis_urls = vec![
            redis_a.redis_url(),
            redis_b.redis_url(),
            redis_c.redis_url(),
        ];

        let block = poa_block_at_time(1, 100);
        let block_data = postcard::to_allocvec(&block).expect("serialize");

        // Write block to only node A — sub-quorum (1/3)
        let client_a = redis::Client::open(redis_a.redis_url()).expect("client");
        let mut conn_a = client_a.get_connection().expect("conn");
        append_stream_block(&mut conn_a, &stream_key, 1, &block_data, 1);

        // Adapter without a lease — repair will fail (no lock held)
        let adapter = new_test_adapter(redis_urls.clone(), lease_key.clone());
        // Set epoch but do NOT acquire lease — repair_sub_quorum_block
        // will get FencingRejected or fail to reach quorum
        {
            let mut epoch = adapter.current_epoch_token.lock().expect("lock");
            *epoch = Some(99);
        }

        // First call reads entries, then repair fails because we don't hold the lock.
        let result = adapter.unreconciled_blocks(1.into()).await;
        // Repair failure now returns an error because backlog remains unresolved.
        assert!(
            result.is_err(),
            "Should return error when repair fails and backlog remains unresolved"
        );

        // Now acquire the lease so repair can succeed
        assert!(
            adapter
                .acquire_lease_if_free()
                .await
                .expect("acquire should succeed"),
            "Should acquire lease"
        );

        // then — second call must still see the sub-quorum block
        let blocks = adapter
            .unreconciled_blocks(1.into())
            .await
            .expect("reconciliation should succeed with lock held");
        assert_eq!(
            blocks.len(),
            1,
            "Repair failure should not make backlog unreadable on the next round"
        );
    }
}