sof 0.17.1

Solana Observer Framework for low-latency shred ingestion and plugin-driven transaction observation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
//! Experimental derived-state feed types for official stateful extensions.
//!
//! This module is the first code scaffold for the architecture proposed in
//! `docs/architecture/adr/0010-dedicated-derived-state-feed.md`.
//! It defines the feed envelope, event families, checkpoints, and consumer-facing
//! fault types without yet wiring a runtime producer.

use std::{
    cell::RefCell,
    collections::HashMap,
    fmt,
    fs::{self, File, OpenOptions},
    io::{self, Read, Write},
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex, OnceLock,
        atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering},
        mpsc,
    },
    thread::JoinHandle,
    time::{SystemTime, UNIX_EPOCH},
};

use arcshift::ArcShift;
use crossbeam_channel as channel;
use crossbeam_queue::ArrayQueue;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sof_types::{PubkeyBytes, SignatureBytes};
use solana_transaction::versioned::VersionedTransaction;
use thiserror::Error;

use crate::{
    event::{ForkSlotStatus, TxCommitmentStatus, TxKind},
    framework::{
        AccountTouchEvent, BlockMetaEvent, ClusterTopologyEvent, ControlPlaneSource,
        LeaderScheduleEvent, ObservedRecentBlockhashEvent, ReorgEvent, SlotStatusEvent,
        TransactionEvent, TransactionStatusEvent,
    },
};

#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
/// Static feed subscriptions requested by one derived-state consumer during host construction.
pub struct DerivedStateConsumerConfig {
    /// Enables `TransactionApplied` feed delivery.
    pub transaction_applied: bool,
    /// Enables `TransactionStatusObserved` feed delivery.
    pub transaction_status_observed: bool,
    /// Enables `BlockMetaObserved` feed delivery.
    pub block_meta_observed: bool,
    /// Enables `AccountTouchObserved` feed delivery.
    pub account_touch_observed: bool,
    /// Requests writable/read-only key partitions on account-touch events.
    pub account_touch_key_partitions: bool,
    /// Enables control-plane derived-state events beyond slot/reorg/barrier.
    pub control_plane_observed: bool,
}

impl DerivedStateConsumerConfig {
    /// Creates an empty consumer config with all optional feeds disabled.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enables `TransactionApplied`.
    #[must_use]
    pub const fn with_transaction_applied(mut self) -> Self {
        self.transaction_applied = true;
        self
    }

    /// Enables `TransactionStatusObserved`.
    #[must_use]
    pub const fn with_transaction_status_observed(mut self) -> Self {
        self.transaction_status_observed = true;
        self
    }

    /// Enables `BlockMetaObserved`.
    #[must_use]
    pub const fn with_block_meta_observed(mut self) -> Self {
        self.block_meta_observed = true;
        self
    }

    /// Enables `AccountTouchObserved`.
    #[must_use]
    pub const fn with_account_touch_observed(mut self) -> Self {
        self.account_touch_observed = true;
        self
    }

    /// Enables account-touch key partitions.
    #[must_use]
    pub const fn with_account_touch_key_partitions(mut self) -> Self {
        self.account_touch_observed = true;
        self.account_touch_key_partitions = true;
        self
    }

    /// Enables control-plane derived-state events.
    #[must_use]
    pub const fn with_control_plane_observed(mut self) -> Self {
        self.control_plane_observed = true;
        self
    }
}

#[derive(Debug, Clone)]
/// Context passed to derived-state consumer lifecycle hooks.
pub struct DerivedStateConsumerContext {
    /// Consumer identifier.
    pub consumer_name: &'static str,
}

#[derive(Debug, Clone, Error, Eq, PartialEq)]
#[error("{reason}")]
/// Setup failure reported by one derived-state consumer implementation.
pub struct DerivedStateConsumerSetupError {
    /// Human-readable startup failure reason.
    reason: String,
}

impl DerivedStateConsumerSetupError {
    /// Creates a setup error with a human-readable reason.
    #[must_use]
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
        }
    }
}

/// One runtime feed session identity.
///
/// A new session id is expected whenever feed continuity cannot be assumed across process
/// lifetimes or replay sources.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct FeedSessionId(pub u128);

/// Monotonic sequence number for the derived-state feed within one session.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct FeedSequence(pub u64);

impl FeedSequence {
    /// Returns the next sequence value when `u64` space has not been exhausted.
    #[must_use]
    pub const fn next(self) -> Option<Self> {
        match self.0.checked_add(1) {
            Some(value) => Some(Self(value)),
            None => None,
        }
    }
}

/// Runtime truth watermarks visible to derived-state consumers.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct FeedWatermarks {
    /// Current canonical tip slot.
    pub canonical_tip_slot: Option<u64>,
    /// Highest processed slot visible to the runtime.
    pub processed_slot: Option<u64>,
    /// Highest confirmed slot visible to the runtime.
    pub confirmed_slot: Option<u64>,
    /// Highest finalized slot visible to the runtime.
    pub finalized_slot: Option<u64>,
}

impl FeedWatermarks {
    /// Computes the current transaction commitment classification for one slot.
    #[must_use]
    pub fn commitment_for_slot(self, slot: u64) -> TxCommitmentStatus {
        TxCommitmentStatus::from_slot(slot, self.confirmed_slot, self.finalized_slot)
    }

    /// Builds watermark state from a slot-status transition event.
    #[must_use]
    pub const fn from_slot_status(event: &SlotStatusEvent) -> Self {
        Self {
            canonical_tip_slot: event.tip_slot,
            processed_slot: match event.status {
                ForkSlotStatus::Processed => Some(event.slot),
                ForkSlotStatus::Confirmed
                | ForkSlotStatus::Finalized
                | ForkSlotStatus::Orphaned => event.tip_slot,
            },
            confirmed_slot: event.confirmed_slot,
            finalized_slot: event.finalized_slot,
        }
    }

    /// Builds watermark state from a reorg event.
    #[must_use]
    pub const fn from_reorg(event: &ReorgEvent) -> Self {
        Self {
            canonical_tip_slot: Some(event.new_tip),
            processed_slot: Some(event.new_tip),
            confirmed_slot: event.confirmed_slot,
            finalized_slot: event.finalized_slot,
        }
    }
}

/// Built-in maximum lag for recent-blockhash freshness in the derived-state control plane.
const CONTROL_PLANE_MAX_RECENT_BLOCKHASH_SLOT_LAG: u64 = 32;
/// Built-in maximum lag for cluster-topology freshness in the derived-state control plane.
const CONTROL_PLANE_MAX_CLUSTER_TOPOLOGY_SLOT_LAG: u64 = 64;
/// Built-in maximum lag for leader-schedule freshness in the derived-state control plane.
const CONTROL_PLANE_MAX_LEADER_SCHEDULE_SLOT_LAG: u64 = 128;
/// Built-in maximum spread allowed across control-plane input slots before degradation.
const CONTROL_PLANE_MAX_SLOT_SPREAD: u64 = 32;

/// One envelope delivered to a derived-state consumer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DerivedStateFeedEnvelope {
    /// Feed session identity.
    pub session_id: FeedSessionId,
    /// Monotonic sequence within the session.
    pub sequence: FeedSequence,
    /// Wall-clock time when the runtime emitted the envelope.
    pub emitted_at: SystemTime,
    /// Runtime truth watermarks at emission time.
    pub watermarks: FeedWatermarks,
    /// Derived-state event payload.
    pub event: DerivedStateFeedEvent,
}

/// Event families intended for authoritative stateful consumers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DerivedStateFeedEvent {
    /// Decoded transaction apply record.
    TransactionApplied(TransactionAppliedEvent),
    /// Transaction-status observation from processed-provider ingest.
    TransactionStatusObserved(TransactionStatusObservedEvent),
    /// Block-metadata observation from processed-provider ingest.
    BlockMetaObserved(BlockMetaObservedEvent),
    /// Recent blockhash observation suitable for direct-submit consumers.
    RecentBlockhashObserved(ObservedRecentBlockhashEvent),
    /// Cluster topology diff/snapshot suitable for direct-submit consumers.
    ClusterTopologyChanged(ClusterTopologyEvent),
    /// Leader schedule diff/snapshot suitable for direct-submit consumers.
    LeaderScheduleUpdated(LeaderScheduleEvent),
    /// Canonical control-plane freshness and quality state derived from feed inputs.
    ControlPlaneStateUpdated(DerivedStateControlPlaneStateEvent),
    /// Explicit invalidation boundary for replay, reorg, or degraded control-plane state.
    StateInvalidated(DerivedStateInvalidationEvent),
    /// Tx outcome feedback emitted by services layered on top of SOF.
    TxOutcomeObserved(DerivedStateTxOutcomeEvent),
    /// Slot lifecycle transition.
    SlotStatusChanged(SlotStatusChangedEvent),
    /// Canonical branch switch requiring consumer rollback/reconciliation.
    BranchReorged(BranchReorgedEvent),
    /// Transaction-derived account-touch metadata.
    AccountTouchObserved(AccountTouchObservedEvent),
    /// Consumer checkpoint barrier.
    CheckpointBarrier(CheckpointBarrierEvent),
}

impl DerivedStateFeedEvent {
    /// Returns whether this event kind is always delivered to every consumer.
    #[must_use]
    const fn is_universally_delivered(&self) -> bool {
        matches!(
            self,
            Self::SlotStatusChanged(_) | Self::BranchReorged(_) | Self::CheckpointBarrier(_)
        )
    }
}

/// Freshness classification for one control-plane input.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateFreshnessState {
    /// No observation has been recorded yet.
    Missing,
    /// Freshness cannot be evaluated yet.
    Unknown,
    /// Observation is present and within the current freshness budget.
    Fresh,
    /// Observation exceeded the current freshness budget.
    Stale,
}

/// Freshness metadata for one control-plane input in the derived-state feed.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStateInputFreshness {
    /// Slot of the latest observation for this input.
    pub observed_slot: Option<u64>,
    /// Canonical tip slot used to evaluate freshness.
    pub tip_slot: Option<u64>,
    /// Lag between `tip_slot` and `observed_slot` when known.
    pub slot_lag: Option<u64>,
    /// Maximum lag allowed by the built-in control-plane classifier.
    pub max_allowed_slot_lag: Option<u64>,
    /// Freshness classification for this input.
    pub state: DerivedStateFreshnessState,
}

/// Coarse quality classification for the observer-side control plane.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateControlPlaneQuality {
    /// Required inputs are present and within policy.
    Stable,
    /// Inputs are coherent but not yet beyond a provisional confirmation boundary.
    Provisional,
    /// Inputs are coherent but still carry elevated reorg risk.
    ReorgRisk,
    /// Inputs exist, but they are not coherent enough to trust as one control-plane view.
    Degraded,
    /// Required inputs exist but at least one is stale.
    Stale,
    /// Required inputs are still missing.
    IncompleteControlPlane,
}

/// Canonical control-plane snapshot emitted by the derived-state feed.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStateControlPlaneStateEvent {
    /// Slot of the latest recent-blockhash observation.
    pub recent_blockhash_slot: Option<u64>,
    /// Slot of the latest cluster-topology update.
    pub cluster_topology_slot: Option<u64>,
    /// Slot of the latest leader-schedule update.
    pub leader_schedule_slot: Option<u64>,
    /// Canonical tip slot at emission time.
    pub tip_slot: Option<u64>,
    /// Number of nodes visible in the latest topology snapshot.
    pub known_cluster_nodes: usize,
    /// Number of leader-slot assignments visible in the latest schedule snapshot.
    pub known_leader_slots: usize,
    /// Latest topology source when known.
    pub cluster_topology_source: Option<ControlPlaneSource>,
    /// Latest leader-schedule source when known.
    pub leader_schedule_source: Option<ControlPlaneSource>,
    /// Wallclock skew budget observed across topology nodes when known.
    pub cluster_topology_max_wallclock_skew_ms: Option<u64>,
    /// Freshness metadata for the recent blockhash input.
    pub recent_blockhash_freshness: DerivedStateInputFreshness,
    /// Freshness metadata for the cluster topology input.
    pub cluster_topology_freshness: DerivedStateInputFreshness,
    /// Freshness metadata for the leader schedule input.
    pub leader_schedule_freshness: DerivedStateInputFreshness,
    /// Spread across observed control-plane input slots when enough data exists.
    pub control_plane_slot_spread: Option<u64>,
    /// Whether control-plane inputs are aligned under the built-in classifier.
    pub inputs_aligned: bool,
    /// True when the current control-plane snapshot is safe to use for strategy decisions.
    pub strategy_safe: bool,
    /// True when conflicting source or slot regressions have been observed.
    pub conflicts_detected: bool,
    /// Total number of detected control-plane conflicts in this host session.
    pub conflict_count: u64,
    /// Coarse quality classification for the control-plane snapshot.
    pub quality: DerivedStateControlPlaneQuality,
}

/// Explicit invalidation reason for derived-state consumers.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateInvalidationReason {
    /// Canonical branch switched and prior state must be reconsidered.
    Reorg,
    /// Control-plane quality is no longer strategy-safe.
    ControlPlaneUnsafe,
    /// Replay continuity was lost and consumer state must be rebuilt.
    ReplayGap,
}

/// Explicit invalidation envelope for replay/reorg-aware consumers.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStateInvalidationEvent {
    /// Root cause for the invalidation.
    pub reason: DerivedStateInvalidationReason,
    /// Detached slots affected by the invalidation.
    pub detached_slots: Vec<u64>,
    /// Current control-plane quality when invalidation is control-plane driven.
    pub control_plane_quality: Option<DerivedStateControlPlaneQuality>,
}

/// Outcome classification reported by services layered on top of SOF.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateTxOutcomeKind {
    /// Transaction landed on chain.
    Landed,
    /// Transaction expired before landing.
    Expired,
    /// Transaction was dropped before landing.
    Dropped,
    /// Intended leader window was missed.
    LeaderMissed,
    /// Submit path used a stale blockhash.
    BlockhashStale,
    /// Selected route was unhealthy.
    UnhealthyRoute,
    /// Submit was rejected due to stale inputs.
    RejectedDueToStaleness,
    /// Submit was rejected due to reorg risk.
    RejectedDueToReorgRisk,
    /// Submit was rejected due to state drift.
    RejectedDueToStateDrift,
    /// Submit was rejected while replay recovery was pending.
    RejectedDueToReplayRecovery,
    /// Submit was suppressed by a built-in key.
    Suppressed,
}

/// Derived-state tx outcome feedback emitted by higher-level services.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStateTxOutcomeEvent {
    /// Transaction signature when known.
    pub signature: Option<SignatureBytes>,
    /// Outcome classification.
    pub kind: DerivedStateTxOutcomeKind,
    /// Decision-state version used by the service when known.
    pub decision_state_version: Option<u64>,
    /// Current service/runtime state version when known.
    pub current_state_version: Option<u64>,
    /// Opportunity age at outcome time in milliseconds when known.
    pub opportunity_age_ms: Option<u64>,
}

/// Decoded transaction apply record for the derived-state feed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionAppliedEvent {
    /// Slot containing the transaction.
    pub slot: u64,
    /// Transaction position within the canonical derived-state stream for the slot.
    pub tx_index: u32,
    /// Transaction signature when present.
    pub signature: Option<SignatureBytes>,
    /// Transaction kind classification.
    pub kind: TxKind,
    /// Decoded versioned transaction payload.
    pub transaction: Arc<VersionedTransaction>,
    /// Commitment status at emission time.
    pub commitment_status: TxCommitmentStatus,
}

impl From<(u32, TransactionEvent)> for TransactionAppliedEvent {
    fn from((tx_index, event): (u32, TransactionEvent)) -> Self {
        Self {
            slot: event.slot,
            tx_index,
            signature: event.signature,
            kind: event.kind,
            transaction: event.tx,
            commitment_status: event.commitment_status,
        }
    }
}

/// Transaction-status observation for the derived-state feed.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct TransactionStatusObservedEvent {
    /// Slot containing the observed transaction status.
    pub slot: u64,
    /// Commitment status at emission time.
    pub commitment_status: TxCommitmentStatus,
    /// Latest observed confirmed slot watermark when event was emitted.
    pub confirmed_slot: Option<u64>,
    /// Latest observed finalized slot watermark when event was emitted.
    pub finalized_slot: Option<u64>,
    /// Transaction signature carried by the upstream status update.
    pub signature: SignatureBytes,
    /// Whether the upstream provider marked this as a vote transaction.
    pub is_vote: bool,
    /// Transaction index within the slot when the provider included it.
    pub index: Option<u64>,
    /// Transaction error detail when execution failed.
    pub err: Option<String>,
}

impl From<TransactionStatusEvent> for TransactionStatusObservedEvent {
    fn from(event: TransactionStatusEvent) -> Self {
        Self {
            slot: event.slot,
            commitment_status: event.commitment_status,
            confirmed_slot: event.confirmed_slot,
            finalized_slot: event.finalized_slot,
            signature: event.signature,
            is_vote: event.is_vote,
            index: event.index,
            err: event.err,
        }
    }
}

/// Block-metadata observation for the derived-state feed.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct BlockMetaObservedEvent {
    /// Slot whose block metadata was observed.
    pub slot: u64,
    /// Commitment status at emission time.
    pub commitment_status: TxCommitmentStatus,
    /// Latest observed confirmed slot watermark when event was emitted.
    pub confirmed_slot: Option<u64>,
    /// Latest observed finalized slot watermark when event was emitted.
    pub finalized_slot: Option<u64>,
    /// Current blockhash for this slot.
    pub blockhash: [u8; 32],
    /// Parent slot for this block.
    pub parent_slot: u64,
    /// Parent blockhash for this block.
    pub parent_blockhash: [u8; 32],
    /// Provider-reported block time when available.
    pub block_time: Option<i64>,
    /// Provider-reported block height when available.
    pub block_height: Option<u64>,
    /// Number of executed transactions in this block.
    pub executed_transaction_count: u64,
    /// Number of entries in this block.
    pub entries_count: u64,
}

impl From<BlockMetaEvent> for BlockMetaObservedEvent {
    fn from(event: BlockMetaEvent) -> Self {
        Self {
            slot: event.slot,
            commitment_status: event.commitment_status,
            confirmed_slot: event.confirmed_slot,
            finalized_slot: event.finalized_slot,
            blockhash: event.blockhash,
            parent_slot: event.parent_slot,
            parent_blockhash: event.parent_blockhash,
            block_time: event.block_time,
            block_height: event.block_height,
            executed_transaction_count: event.executed_transaction_count,
            entries_count: event.entries_count,
        }
    }
}

/// Slot lifecycle transition record for the derived-state feed.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub struct SlotStatusChangedEvent {
    /// Slot whose state changed.
    pub slot: u64,
    /// Parent slot when known.
    pub parent_slot: Option<u64>,
    /// Previous status when known.
    pub previous_status: Option<ForkSlotStatus>,
    /// New runtime-visible status.
    pub status: ForkSlotStatus,
}

impl From<SlotStatusEvent> for SlotStatusChangedEvent {
    fn from(event: SlotStatusEvent) -> Self {
        Self {
            slot: event.slot,
            parent_slot: event.parent_slot,
            previous_status: event.previous_status,
            status: event.status,
        }
    }
}

/// Canonical branch switch record for the derived-state feed.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct BranchReorgedEvent {
    /// Previous canonical tip.
    pub old_tip: u64,
    /// New canonical tip.
    pub new_tip: u64,
    /// Lowest common ancestor when known.
    pub common_ancestor: Option<u64>,
    /// Slots detached from the old branch.
    pub detached_slots: Arc<[u64]>,
    /// Slots attached from the new branch.
    pub attached_slots: Arc<[u64]>,
}

impl From<ReorgEvent> for BranchReorgedEvent {
    fn from(event: ReorgEvent) -> Self {
        Self {
            old_tip: event.old_tip,
            new_tip: event.new_tip,
            common_ancestor: event.common_ancestor,
            detached_slots: Arc::from(event.detached_slots),
            attached_slots: Arc::from(event.attached_slots),
        }
    }
}

/// Transaction-derived account-touch metadata for stateful consumers.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct AccountTouchObservedEvent {
    /// Slot containing the transaction.
    pub slot: u64,
    /// Transaction position within the canonical derived-state stream for the slot.
    pub tx_index: u32,
    /// Transaction signature when present.
    pub signature: Option<SignatureBytes>,
    /// All static message account keys touched by the transaction.
    pub account_keys: Arc<[PubkeyBytes]>,
    /// Writable static account keys touched by the transaction.
    pub writable_account_keys: Arc<[PubkeyBytes]>,
    /// Read-only static account keys touched by the transaction.
    pub readonly_account_keys: Arc<[PubkeyBytes]>,
    /// Lookup-table account keys referenced by the transaction.
    pub lookup_table_account_keys: Arc<[PubkeyBytes]>,
}

impl From<(u32, AccountTouchEvent)> for AccountTouchObservedEvent {
    fn from((tx_index, event): (u32, AccountTouchEvent)) -> Self {
        Self {
            slot: event.slot,
            tx_index,
            signature: event.signature,
            account_keys: event.account_keys,
            writable_account_keys: event.writable_account_keys,
            readonly_account_keys: event.readonly_account_keys,
            lookup_table_account_keys: event.lookup_table_account_keys,
        }
    }
}

/// Checkpoint barrier emitted by the derived-state feed.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub struct CheckpointBarrierEvent {
    /// Highest contiguous sequence fully covered by the barrier.
    pub barrier_sequence: FeedSequence,
    /// Why the barrier was emitted.
    pub reason: CheckpointBarrierReason,
}

/// Reasons for emitting a checkpoint barrier.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
pub enum CheckpointBarrierReason {
    /// Periodic background checkpoint opportunity.
    Periodic,
    /// Runtime is beginning graceful shutdown.
    ShutdownRequested,
    /// Replay catch-up hit a stable boundary.
    ReplayBoundary,
}

/// Durable checkpoint shape for one derived-state consumer.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStateCheckpoint {
    /// Feed session against which this checkpoint was created.
    pub session_id: FeedSessionId,
    /// Highest contiguous sequence fully applied by the consumer.
    pub last_applied_sequence: FeedSequence,
    /// Runtime truth watermarks at the checkpoint boundary.
    pub watermarks: FeedWatermarks,
    /// Consumer-owned schema/state version.
    pub state_version: u32,
    /// Consumer implementation version string.
    pub extension_version: String,
}

impl DerivedStateCheckpoint {
    /// Returns the next sequence the consumer should request or apply.
    #[must_use]
    pub const fn next_sequence(&self) -> Option<FeedSequence> {
        self.last_applied_sequence.next()
    }

    /// Returns whether this checkpoint matches one consumer contract pair.
    #[must_use]
    pub fn matches_contract(&self, state_version: u32, extension_version: &str) -> bool {
        self.state_version == state_version && self.extension_version == extension_version
    }
}

/// One persisted derived-state consumer snapshot bundled with its durable checkpoint.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct DerivedStatePersistedCheckpoint<T> {
    /// Durable derived-state checkpoint cursor.
    pub checkpoint: DerivedStateCheckpoint,
    /// Consumer-owned persisted state payload.
    pub state: T,
}

impl<T> DerivedStatePersistedCheckpoint<T> {
    /// Creates a new persisted checkpoint/state bundle.
    #[must_use]
    pub const fn new(checkpoint: DerivedStateCheckpoint, state: T) -> Self {
        Self { checkpoint, state }
    }

    /// Returns whether the bundled checkpoint matches one consumer contract pair.
    #[must_use]
    pub fn is_compatible(&self, state_version: u32, extension_version: &str) -> bool {
        self.checkpoint
            .matches_contract(state_version, extension_version)
    }

    /// Splits the bundle into its checkpoint and state payload.
    #[must_use]
    pub fn into_parts(self) -> (DerivedStateCheckpoint, T) {
        (self.checkpoint, self.state)
    }
}

/// Small file-backed checkpoint store for derived-state consumers.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DerivedStateCheckpointStore {
    /// Filesystem path used for persisted checkpoint/state bundles.
    path: PathBuf,
}

impl DerivedStateCheckpointStore {
    /// Creates a checkpoint store rooted at `path`.
    #[must_use]
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Returns the underlying checkpoint path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Loads a previously persisted checkpoint/state bundle when present.
    ///
    /// # Errors
    /// Returns [`DerivedStateConsumerFaultKind::CheckpointWriteFailed`] when the bundle
    /// cannot be read or deserialized.
    pub fn load<T>(
        &self,
    ) -> Result<Option<DerivedStatePersistedCheckpoint<T>>, DerivedStateConsumerFault>
    where
        T: DeserializeOwned,
    {
        if !self.path.exists() {
            return Ok(None);
        }
        let bytes = fs::read(&self.path).map_err(|error| {
            DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                None,
                format!(
                    "failed to read derived-state checkpoint {}: {error}",
                    self.path.display()
                ),
            )
        })?;
        let persisted = serde_json::from_slice::<DerivedStatePersistedCheckpoint<T>>(&bytes)
            .map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    None,
                    format!(
                        "failed to parse derived-state checkpoint {}: {error}",
                        self.path.display()
                    ),
                )
            })?;
        Ok(Some(persisted))
    }

    /// Loads a persisted bundle only when its checkpoint matches one consumer contract pair.
    ///
    /// # Errors
    /// Returns any read or deserialization failure from [`Self::load`].
    pub fn load_compatible<T>(
        &self,
        state_version: u32,
        extension_version: &str,
    ) -> Result<Option<DerivedStatePersistedCheckpoint<T>>, DerivedStateConsumerFault>
    where
        T: DeserializeOwned,
    {
        Ok(self
            .load::<T>()?
            .filter(|persisted| persisted.is_compatible(state_version, extension_version)))
    }

    /// Persists one checkpoint/state bundle atomically.
    ///
    /// # Errors
    /// Returns [`DerivedStateConsumerFaultKind::CheckpointWriteFailed`] when the bundle
    /// cannot be serialized or written to disk.
    pub fn store<T>(
        &self,
        checkpoint: &DerivedStateCheckpoint,
        state: &T,
    ) -> Result<(), DerivedStateConsumerFault>
    where
        T: Serialize,
    {
        #[derive(Serialize)]
        struct PersistedRef<'state, T> {
            /// Durable derived-state checkpoint payload.
            checkpoint: &'state DerivedStateCheckpoint,
            /// Consumer-owned serialized state payload.
            state: &'state T,
        }

        let bytes =
            serde_json::to_vec_pretty(&PersistedRef { checkpoint, state }).map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    Some(checkpoint.last_applied_sequence),
                    format!("failed to serialize derived-state checkpoint: {error}"),
                )
            })?;
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent).map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    Some(checkpoint.last_applied_sequence),
                    format!(
                        "failed to create derived-state checkpoint directory {}: {error}",
                        parent.display()
                    ),
                )
            })?;
        }

        let temp_path = self.path.with_extension("checkpoint.tmp");
        {
            let mut file = File::create(&temp_path).map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    Some(checkpoint.last_applied_sequence),
                    format!(
                        "failed to create temporary derived-state checkpoint {}: {error}",
                        temp_path.display()
                    ),
                )
            })?;
            file.write_all(&bytes).map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    Some(checkpoint.last_applied_sequence),
                    format!(
                        "failed to write temporary derived-state checkpoint {}: {error}",
                        temp_path.display()
                    ),
                )
            })?;
            file.sync_all().map_err(|error| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    Some(checkpoint.last_applied_sequence),
                    format!(
                        "failed to fsync temporary derived-state checkpoint {}: {error}",
                        temp_path.display()
                    ),
                )
            })?;
        }

        fs::rename(&temp_path, &self.path).map_err(|error| {
            drop(fs::remove_file(&temp_path));
            DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                Some(checkpoint.last_applied_sequence),
                format!(
                    "failed to move derived-state checkpoint into place {}: {error}",
                    self.path.display()
                ),
            )
        })?;
        Ok(())
    }
}

/// Structured fault categories for authoritative derived-state consumers.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DerivedStateConsumerFaultKind {
    /// Consumer lag exceeded the runtime policy threshold.
    LagExceeded,
    /// Consumer queue overflowed and live continuity was lost.
    QueueOverflow,
    /// Consumer failed to durably persist a checkpoint.
    CheckpointWriteFailed,
    /// Replay source could not provide the required contiguous sequence range.
    ReplayGap,
    /// Consumer failed to apply one envelope.
    ConsumerApplyFailed,
}

impl DerivedStateConsumerFaultKind {
    /// Returns whether this fault breaks live continuity for the affected consumer.
    #[must_use]
    pub const fn breaks_live_continuity(self) -> bool {
        matches!(
            self,
            Self::LagExceeded | Self::QueueOverflow | Self::ReplayGap | Self::ConsumerApplyFailed
        )
    }

    /// Returns the compact storage representation used in atomics.
    #[must_use]
    const fn into_u8(self) -> u8 {
        match self {
            Self::LagExceeded => 0,
            Self::QueueOverflow => 1,
            Self::CheckpointWriteFailed => 2,
            Self::ReplayGap => 3,
            Self::ConsumerApplyFailed => 4,
        }
    }

    /// Decodes a compact storage representation used in atomics.
    #[must_use]
    const fn from_u8(value: u8) -> Self {
        match value {
            1 => Self::QueueOverflow,
            2 => Self::CheckpointWriteFailed,
            3 => Self::ReplayGap,
            4 => Self::ConsumerApplyFailed,
            _ => Self::LagExceeded,
        }
    }
}

/// Structured consumer fault returned by the feed scaffold.
#[derive(Debug, Clone, Eq, PartialEq, Error)]
#[error("{kind:?}: {message}")]
pub struct DerivedStateConsumerFault {
    /// Fault category.
    pub kind: DerivedStateConsumerFaultKind,
    /// Last relevant feed sequence when known.
    pub sequence: Option<FeedSequence>,
    /// Diagnostic context for operators and tests.
    pub message: String,
}

impl DerivedStateConsumerFault {
    /// Creates a new structured fault with free-form diagnostic context.
    #[must_use]
    pub fn new(
        kind: DerivedStateConsumerFaultKind,
        sequence: Option<FeedSequence>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            sequence,
            message: message.into(),
        }
    }
}

/// Snapshot of one registered derived-state consumer's live-feed health and counters.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DerivedStateConsumerTelemetry {
    /// Stable consumer name used in logs and telemetry.
    pub name: &'static str,
    /// Whether live continuity has been lost for this consumer.
    pub unhealthy: bool,
    /// Recovery state for the consumer.
    pub recovery_state: DerivedStateConsumerRecoveryState,
    /// Total number of successfully applied envelopes.
    pub applied_events: u64,
    /// Total number of successfully flushed checkpoints.
    pub checkpoint_flushes: u64,
    /// Total number of structured faults recorded for the consumer.
    pub fault_count: u64,
    /// Highest applied sequence when known.
    pub last_applied_sequence: Option<FeedSequence>,
    /// Highest fault-associated sequence when known.
    pub last_fault_sequence: Option<FeedSequence>,
    /// Last structured fault kind when known.
    pub last_fault_kind: Option<DerivedStateConsumerFaultKind>,
}

/// Recovery state for one derived-state consumer.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DerivedStateConsumerRecoveryState {
    /// Consumer is live and receiving feed events.
    Live,
    /// Consumer should attempt replay-based recovery from its durable checkpoint.
    ReplayRecoveryPending,
    /// Consumer cannot be recovered from the retained replay tail and needs a rebuild.
    RebuildRequired,
}

impl DerivedStateConsumerRecoveryState {
    /// Returns the compact storage representation used in atomics.
    #[must_use]
    const fn into_u8(self) -> u8 {
        match self {
            Self::Live => 0,
            Self::ReplayRecoveryPending => 1,
            Self::RebuildRequired => 2,
        }
    }

    /// Decodes a compact storage representation used in atomics.
    #[must_use]
    const fn from_u8(value: u8) -> Self {
        match value {
            1 => Self::ReplayRecoveryPending,
            2 => Self::RebuildRequired,
            _ => Self::Live,
        }
    }
}

/// Replay backend telemetry snapshot exposed to runtime logs and tests.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct DerivedStateReplayTelemetry {
    /// Whether the runtime installed a replay backend.
    pub enabled: bool,
    /// Stable backend identifier.
    pub backend: DerivedStateReplayBackend,
    /// Number of retained sessions visible to the backend.
    pub retained_sessions: usize,
    /// Number of retained envelopes visible to the backend.
    pub retained_envelopes: usize,
    /// Number of envelopes truncated by retention policy.
    pub truncated_envelopes: u64,
    /// Number of backend append failures.
    pub append_failures: u64,
    /// Number of backend load/decode failures.
    pub load_failures: u64,
    /// Number of compaction runs performed by the backend.
    pub compactions: u64,
}

/// Backend used for retained derived-state replay.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateReplayBackend {
    /// In-process retained feed tail.
    #[default]
    Memory,
    /// Disk-backed retained feed tail.
    Disk,
}

impl DerivedStateReplayBackend {
    /// Returns the stable env/config representation for the backend.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Memory => "memory",
            Self::Disk => "disk",
        }
    }

    /// Parses one env/config value into a backend.
    #[must_use]
    pub const fn from_config_value(value: &str) -> Option<Self> {
        if value.eq_ignore_ascii_case("memory") {
            Some(Self::Memory)
        } else if value.eq_ignore_ascii_case("disk") {
            Some(Self::Disk)
        } else {
            None
        }
    }
}

impl fmt::Display for DerivedStateReplayBackend {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Recovery attempt summary returned by the derived-state host.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct DerivedStateRecoveryReport {
    /// Number of unhealthy consumers considered for recovery.
    pub attempted: u64,
    /// Number of consumers returned to live state.
    pub recovered: u64,
    /// Number of consumers still waiting for replay-based recovery.
    pub still_pending: u64,
    /// Number of consumers that require a full rebuild.
    pub rebuild_required: u64,
}

/// Replay errors returned by derived-state feed sources.
#[derive(Debug, Clone, Eq, PartialEq, Error)]
pub enum DerivedStateReplayError {
    /// No retained session was available for the requested checkpoint.
    #[error("replay session unavailable: {0:?}")]
    SessionUnavailable(FeedSessionId),
    /// The retained feed did not contain the expected contiguous next sequence.
    #[error("replay sequence gap at {sequence:?}")]
    SequenceGap {
        /// Session that contained the gap.
        session_id: FeedSessionId,
        /// First missing or mismatched sequence.
        sequence: FeedSequence,
    },
    /// The replay source truncated older envelopes before the requested sequence.
    #[error("replay truncated before {sequence:?}")]
    Truncated {
        /// Session that retained only a later tail.
        session_id: FeedSessionId,
        /// First requested sequence that was no longer retained.
        sequence: FeedSequence,
        /// Oldest sequence still retained for the session.
        oldest_retained_sequence: FeedSequence,
    },
    /// The replay backend could not load or decode the retained feed.
    #[error("replay backend failure for {session_id:?}: {message}")]
    BackendFailure {
        /// Session whose retained log could not be loaded.
        session_id: FeedSessionId,
        /// Free-form backend diagnostic.
        message: String,
    },
}

/// Ordered replay source for retained derived-state feed envelopes.
pub trait DerivedStateReplaySource: Send + Sync + 'static {
    /// Records one emitted envelope into the replay source.
    fn append(&self, envelope: DerivedStateFeedEnvelope);

    /// Records a batch of emitted envelopes into the replay source.
    fn append_batch(&self, envelopes: &[DerivedStateFeedEnvelope]) {
        for envelope in envelopes {
            self.append(envelope.clone());
        }
    }

    /// Records a shared batch of emitted envelopes into the replay source.
    fn append_shared_batch(&self, envelopes: &[DerivedStateFeedEnvelope]) {
        self.append_batch(envelopes);
    }

    /// Returns retained envelopes starting at the requested sequence boundary.
    ///
    /// # Errors
    /// Returns a replay error when the retained stream cannot satisfy continuity.
    fn replay_from(
        &self,
        session_id: FeedSessionId,
        next_sequence: FeedSequence,
    ) -> Result<Vec<DerivedStateFeedEnvelope>, DerivedStateReplayError>;

    /// Returns operator-facing telemetry for this replay backend.
    #[must_use]
    fn telemetry(&self) -> DerivedStateReplayTelemetry {
        DerivedStateReplayTelemetry::default()
    }
}

/// In-memory replay source used by the scaffold and tests.
#[derive(Default)]
pub struct InMemoryDerivedStateReplaySource {
    /// Retained feed envelopes grouped by session id.
    sessions: Mutex<HashMap<FeedSessionId, Vec<DerivedStateFeedEnvelope>>>,
    /// Optional bounded retention policy applied per session.
    max_envelopes_per_session: Option<usize>,
    /// Total number of envelopes truncated by the retention policy.
    truncated_envelopes: AtomicU64,
}

impl InMemoryDerivedStateReplaySource {
    /// Creates an empty in-memory replay source.
    #[must_use]
    pub fn new() -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
            max_envelopes_per_session: None,
            truncated_envelopes: AtomicU64::new(0),
        }
    }

    /// Creates an in-memory replay source with bounded per-session retention.
    #[must_use]
    pub fn with_max_envelopes_per_session(max_envelopes_per_session: usize) -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
            max_envelopes_per_session: Some(max_envelopes_per_session),
            truncated_envelopes: AtomicU64::new(0),
        }
    }

    /// Returns the total number of envelopes truncated across all sessions.
    #[must_use]
    pub fn truncated_envelopes(&self) -> u64 {
        self.truncated_envelopes.load(Ordering::Relaxed)
    }

    /// Returns the number of envelopes currently retained for one session.
    #[must_use]
    pub fn retained_envelopes(&self, session_id: FeedSessionId) -> usize {
        self.sessions
            .lock()
            .ok()
            .and_then(|sessions| sessions.get(&session_id).map(Vec::len))
            .unwrap_or(0)
    }
}

impl DerivedStateReplaySource for InMemoryDerivedStateReplaySource {
    fn append(&self, envelope: DerivedStateFeedEnvelope) {
        if let Ok(mut sessions) = self.sessions.lock() {
            let retained = sessions.entry(envelope.session_id).or_default();
            retained.push(envelope);
            if let Some(max_envelopes_per_session) = self.max_envelopes_per_session {
                let truncated = retained.len().saturating_sub(max_envelopes_per_session);
                if truncated > 0 {
                    retained.drain(..truncated);
                    let _ = self
                        .truncated_envelopes
                        .fetch_add(truncated as u64, Ordering::Relaxed);
                }
            }
        }
    }

    fn replay_from(
        &self,
        session_id: FeedSessionId,
        next_sequence: FeedSequence,
    ) -> Result<Vec<DerivedStateFeedEnvelope>, DerivedStateReplayError> {
        let Ok(sessions) = self.sessions.lock() else {
            return Err(DerivedStateReplayError::SessionUnavailable(session_id));
        };
        let Some(envelopes) = sessions.get(&session_id) else {
            return Err(DerivedStateReplayError::SessionUnavailable(session_id));
        };
        validate_replayed_envelopes(session_id, envelopes, next_sequence)
    }

    fn telemetry(&self) -> DerivedStateReplayTelemetry {
        let (retained_sessions, retained_envelopes) = self
            .sessions
            .lock()
            .map(|sessions| {
                let retained_sessions = sessions.len();
                let retained_envelopes = sessions.values().map(Vec::len).sum();
                (retained_sessions, retained_envelopes)
            })
            .unwrap_or((0, 0));
        DerivedStateReplayTelemetry {
            enabled: true,
            backend: DerivedStateReplayBackend::Memory,
            retained_sessions,
            retained_envelopes,
            truncated_envelopes: self.truncated_envelopes(),
            append_failures: 0,
            load_failures: 0,
            compactions: 0,
        }
    }
}

/// Disk-backed replay source for retained derived-state feed envelopes.
pub struct DiskDerivedStateReplaySource {
    /// Root directory that stores one retained log directory per session.
    root_dir: PathBuf,
    /// Bounded retention policy applied per session.
    max_envelopes_per_session: usize,
    /// Maximum number of retained session logs on disk.
    max_retained_sessions: usize,
    /// Durability policy used for disk writes.
    durability: DerivedStateReplayDurability,
    /// Lightweight per-session metadata cached in-process.
    session_metadata: Arc<Mutex<HashMap<FeedSessionId, DiskDerivedStateSessionMetadata>>>,
    /// Total number of envelopes truncated by the retention policy.
    truncated_envelopes: Arc<AtomicU64>,
    /// Total number of backend append failures.
    append_failures: Arc<AtomicU64>,
    /// Total number of backend load failures.
    load_failures: Arc<AtomicU64>,
    /// Total number of disk compaction runs.
    compactions: Arc<AtomicU64>,
    /// Dedicated writer path for replay appends so dataset workers do not block on disk IO.
    writer_tx: mpsc::Sender<Vec<DerivedStateFeedEnvelope>>,
    /// Join handle for the dedicated replay writer thread.
    writer_handle: Option<std::thread::JoinHandle<()>>,
}

/// Lightweight retained-session metadata for the disk replay backend.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
struct DiskDerivedStateSessionMetadata {
    /// Ordered retained segment metadata for the session.
    segments: Vec<DiskDerivedStateSegmentMetadata>,
    /// Number of retained envelopes for the session.
    retained_envelopes: usize,
}

/// Lightweight metadata for one retained session segment on disk.
#[derive(Debug, Clone, Eq, PartialEq)]
struct DiskDerivedStateSegmentMetadata {
    /// Filesystem path of the segment file.
    path: PathBuf,
    /// First sequence stored in the segment.
    first_sequence: FeedSequence,
    /// Last sequence stored in the segment.
    last_sequence: FeedSequence,
    /// Number of retained envelopes stored in the segment.
    retained_envelopes: usize,
}

/// Target number of envelopes kept in one disk replay segment before rolling to a new file.
const DISK_REPLAY_TARGET_SEGMENT_ENVELOPES: usize = 256;

thread_local! {
    /// Per-thread cache of open replay segment append handles.
    static DISK_REPLAY_APPENDERS: RefCell<HashMap<PathBuf, File>> = RefCell::new(HashMap::new());
}

/// Durability policy for the disk-backed replay source.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Serialize, Deserialize)]
pub enum DerivedStateReplayDurability {
    /// Flush buffered writes to the OS before returning.
    #[default]
    Flush,
    /// Flush buffered writes and issue `fsync`/`sync_all`.
    Fsync,
}

impl DerivedStateReplayDurability {
    /// Returns the stable env/config representation for the durability mode.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Flush => "flush",
            Self::Fsync => "fsync",
        }
    }

    /// Parses one env/config value into a durability mode.
    #[must_use]
    pub const fn from_config_value(value: &str) -> Option<Self> {
        if value.eq_ignore_ascii_case("flush") {
            Some(Self::Flush)
        } else if value.eq_ignore_ascii_case("fsync") {
            Some(Self::Fsync)
        } else {
            None
        }
    }
}

impl fmt::Display for DerivedStateReplayDurability {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl DiskDerivedStateReplaySource {
    /// Creates a disk-backed replay source rooted at one directory.
    ///
    /// # Errors
    /// Returns an IO error when the replay directory cannot be created.
    pub fn new(root_dir: impl Into<PathBuf>, max_envelopes_per_session: usize) -> io::Result<Self> {
        Self::with_policy(
            root_dir,
            max_envelopes_per_session,
            4,
            DerivedStateReplayDurability::Flush,
        )
    }

    /// Creates a disk-backed replay source with explicit retention and durability policy.
    ///
    /// # Errors
    /// Returns an IO error when the replay directory cannot be created.
    pub fn with_policy(
        root_dir: impl Into<PathBuf>,
        max_envelopes_per_session: usize,
        max_retained_sessions: usize,
        durability: DerivedStateReplayDurability,
    ) -> io::Result<Self> {
        let root_dir = root_dir.into();
        fs::create_dir_all(&root_dir)?;
        let session_metadata = Arc::new(Mutex::new(HashMap::new()));
        let truncated_envelopes = Arc::new(AtomicU64::new(0));
        let append_failures = Arc::new(AtomicU64::new(0));
        let load_failures = Arc::new(AtomicU64::new(0));
        let compactions = Arc::new(AtomicU64::new(0));
        let (writer_tx, writer_rx) = mpsc::channel::<Vec<DerivedStateFeedEnvelope>>();
        let writer_root_dir = root_dir.clone();
        let writer_session_metadata = Arc::clone(&session_metadata);
        let writer_truncated_envelopes = Arc::clone(&truncated_envelopes);
        let writer_append_failures = Arc::clone(&append_failures);
        let writer_compactions = Arc::clone(&compactions);
        let thread_name = String::from("sof-ds-replay");
        let writer_handle = std::thread::Builder::new()
            .name(thread_name)
            .spawn(move || {
                let (dummy_tx, _dummy_rx) = mpsc::channel::<Vec<DerivedStateFeedEnvelope>>();
                let writer_backend = Self {
                    root_dir: writer_root_dir,
                    max_envelopes_per_session,
                    max_retained_sessions: max_retained_sessions.max(1),
                    durability,
                    session_metadata: writer_session_metadata,
                    truncated_envelopes: writer_truncated_envelopes,
                    append_failures: Arc::clone(&writer_append_failures),
                    load_failures: Arc::new(AtomicU64::new(0)),
                    compactions: writer_compactions,
                    writer_tx: dummy_tx,
                    writer_handle: None,
                };
                while let Ok(envelopes) = writer_rx.recv() {
                    let Some(first_envelope) = envelopes.first() else {
                        continue;
                    };
                    let session_id = first_envelope.session_id;
                    if let Err(error) = writer_backend.append_batch_inline(envelopes.as_slice()) {
                        let _ = writer_append_failures.fetch_add(1, Ordering::Relaxed);
                        tracing::warn!(
                            session_id = ?session_id,
                            error = %error,
                            "failed to append derived-state replay envelope batch to disk"
                        );
                    }
                }
            })?;
        Ok(Self {
            root_dir,
            max_envelopes_per_session,
            max_retained_sessions: max_retained_sessions.max(1),
            durability,
            session_metadata,
            truncated_envelopes,
            append_failures,
            load_failures,
            compactions,
            writer_tx,
            writer_handle: Some(writer_handle),
        })
    }

    /// Returns the replay directory root.
    #[must_use]
    pub fn root_dir(&self) -> &Path {
        &self.root_dir
    }

    /// Returns the total number of envelopes truncated across all sessions.
    #[must_use]
    pub fn truncated_envelopes(&self) -> u64 {
        self.truncated_envelopes.load(Ordering::Relaxed)
    }

    /// Returns the total number of append failures observed by the backend.
    #[must_use]
    pub fn append_failures(&self) -> u64 {
        self.append_failures.load(Ordering::Relaxed)
    }

    /// Returns the total number of load/decode failures observed by the backend.
    #[must_use]
    pub fn load_failures(&self) -> u64 {
        self.load_failures.load(Ordering::Relaxed)
    }

    /// Returns the total number of compaction runs observed by the backend.
    #[must_use]
    pub fn compactions(&self) -> u64 {
        self.compactions.load(Ordering::Relaxed)
    }

    /// Returns the number of envelopes currently retained for one session.
    #[must_use]
    pub fn retained_envelopes(&self, session_id: FeedSessionId) -> usize {
        self.session_metadata(session_id)
            .map(|metadata| metadata.retained_envelopes)
            .unwrap_or(0)
    }

    /// Returns the directory path for one retained replay session.
    fn session_path(&self, session_id: FeedSessionId) -> PathBuf {
        self.root_dir.join(format!("{:032x}", session_id.0))
    }

    /// Returns the file path for one retained session segment.
    fn segment_path(&self, session_id: FeedSessionId, first_sequence: FeedSequence) -> PathBuf {
        self.session_path(session_id)
            .join(format!("{:020}.segment", first_sequence.0))
    }

    /// Serializes one feed envelope into an on-disk record payload.
    fn encode_envelope(envelope: &DerivedStateFeedEnvelope) -> io::Result<Vec<u8>> {
        bincode::serialize(envelope)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error.to_string()))
    }

    /// Deserializes one feed envelope from an on-disk record payload.
    fn decode_envelope(bytes: &[u8]) -> io::Result<DerivedStateFeedEnvelope> {
        bincode::deserialize(bytes)
            .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error.to_string()))
    }

    /// Appends one length-prefixed record to an existing session log.
    fn append_encoded_records(&self, path: &Path, encoded_records: &[Vec<u8>]) -> io::Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let total_len = encoded_records
            .iter()
            .map(Vec::len)
            .fold(0_usize, usize::saturating_add);
        let mut record = Vec::with_capacity(total_len);
        for encoded in encoded_records {
            record.extend_from_slice(encoded);
        }
        DISK_REPLAY_APPENDERS.with(|appenders| -> io::Result<()> {
            let mut appenders = appenders.borrow_mut();
            let file = if let Some(file) = appenders.get_mut(path) {
                file
            } else {
                appenders
                    .entry(path.to_path_buf())
                    .or_insert(OpenOptions::new().create(true).append(true).open(path)?)
            };
            file.write_all(&record)?;
            file.flush()?;
            self.sync_file(file)
        })?;
        Ok(())
    }

    /// Inline batch append used by the dedicated replay writer thread.
    fn append_batch_inline(&self, envelopes: &[DerivedStateFeedEnvelope]) -> io::Result<()> {
        let Some(first_envelope) = envelopes.first() else {
            return Ok(());
        };
        let session_id = first_envelope.session_id;
        let mut metadata = self.session_metadata(session_id)?;
        fs::create_dir_all(self.session_path(session_id))?;
        let segment_capacity = self.segment_envelope_capacity();
        let mut envelope_index = 0_usize;
        while envelope_index < envelopes.len() {
            let current_path = if let Some(segment) = metadata.segments.last()
                && segment.retained_envelopes < segment_capacity
            {
                segment.path.clone()
            } else {
                let Some(envelope) = envelopes.get(envelope_index) else {
                    break;
                };
                let path = self.segment_path(session_id, envelope.sequence);
                metadata.segments.push(DiskDerivedStateSegmentMetadata {
                    path: path.clone(),
                    first_sequence: envelope.sequence,
                    last_sequence: envelope.sequence,
                    retained_envelopes: 0,
                });
                path
            };
            let Some(segment) = metadata.segments.last_mut() else {
                break;
            };
            let remaining_capacity = segment_capacity.saturating_sub(segment.retained_envelopes);
            let batch_len = remaining_capacity.min(envelopes.len().saturating_sub(envelope_index));
            let Some(batch) =
                envelopes.get(envelope_index..envelope_index.saturating_add(batch_len))
            else {
                break;
            };
            let mut encoded_records = Vec::with_capacity(batch.len());
            for envelope in batch {
                let encoded = Self::encode_envelope(envelope)?;
                let encoded_len = u32::try_from(encoded.len()).map_err(|_error| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        "derived-state replay envelope exceeded u32 record length",
                    )
                })?;
                let mut record = Vec::with_capacity(encoded.len().saturating_add(4));
                record.extend_from_slice(&encoded_len.to_le_bytes());
                record.extend_from_slice(&encoded);
                encoded_records.push(record);
            }
            self.append_encoded_records(&current_path, &encoded_records)?;
            segment.last_sequence = batch
                .last()
                .map(|envelope| envelope.sequence)
                .unwrap_or(segment.last_sequence);
            segment.retained_envelopes = segment.retained_envelopes.saturating_add(batch.len());
            metadata.retained_envelopes = metadata.retained_envelopes.saturating_add(batch.len());
            envelope_index = envelope_index.saturating_add(batch.len());
        }
        let overflow = metadata
            .retained_envelopes
            .saturating_sub(self.max_envelopes_per_session.max(1));
        if overflow > 0 {
            let truncated = self.truncate_oldest_envelopes(session_id, &mut metadata, overflow)?;
            let _ = self
                .truncated_envelopes
                .fetch_add(truncated as u64, Ordering::Relaxed);
        }
        self.update_session_metadata(session_id, metadata);
        self.compact_sessions(session_id)
    }

    /// Rewrites one retained segment from the currently in-memory tail.
    fn rewrite_records(
        &self,
        old_path: &Path,
        new_path: &Path,
        envelopes: &[DerivedStateFeedEnvelope],
    ) -> io::Result<()> {
        Self::evict_cached_appender(old_path);
        Self::evict_cached_appender(new_path);
        let temp_path = new_path.with_extension("segment.tmp");
        {
            let mut file = File::create(&temp_path)?;
            for envelope in envelopes {
                let encoded = Self::encode_envelope(envelope)?;
                let encoded_len = u32::try_from(encoded.len()).map_err(|_error| {
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        "derived-state replay envelope exceeded u32 record length",
                    )
                })?;
                file.write_all(&encoded_len.to_le_bytes())?;
                file.write_all(&encoded)?;
            }
            file.flush()?;
            self.sync_file(&file)?;
        }
        fs::rename(&temp_path, new_path)?;
        if old_path != new_path && old_path.exists() {
            fs::remove_file(old_path)?;
        }
        if let DerivedStateReplayDurability::Fsync = self.durability {
            let directory = File::open(
                new_path
                    .parent()
                    .unwrap_or_else(|| Path::new(&self.root_dir)),
            )?;
            directory.sync_all()?;
        }
        Ok(())
    }

    /// Loads one retained replay segment from disk into memory.
    fn load_segment_from_disk(&self, path: &Path) -> io::Result<Vec<DerivedStateFeedEnvelope>> {
        if !path.exists() {
            return Ok(Vec::new());
        }
        let mut file = File::open(path)?;
        let mut envelopes = Vec::new();
        loop {
            let mut length_bytes = [0_u8; 4];
            match file.read_exact(&mut length_bytes) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
                Err(error) => return Err(error),
            }
            let encoded_len = u32::from_le_bytes(length_bytes);
            let mut encoded = vec![0_u8; encoded_len as usize];
            file.read_exact(&mut encoded)?;
            envelopes.push(Self::decode_envelope(&encoded)?);
        }
        Ok(envelopes)
    }

    /// Scans one retained replay segment to reconstruct lightweight metadata.
    fn scan_segment_metadata(
        &self,
        path: &Path,
    ) -> io::Result<Option<DiskDerivedStateSegmentMetadata>> {
        if !path.exists() {
            return Ok(None);
        }
        let mut file = File::open(path)?;
        let mut count = 0_usize;
        let mut first_sequence = None;
        let mut last_sequence = None;
        loop {
            let mut length_bytes = [0_u8; 4];
            match file.read_exact(&mut length_bytes) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => break,
                Err(error) => return Err(error),
            }
            let encoded_len = u32::from_le_bytes(length_bytes);
            let mut encoded = vec![0_u8; encoded_len as usize];
            file.read_exact(&mut encoded)?;
            let envelope = Self::decode_envelope(&encoded)?;
            first_sequence.get_or_insert(envelope.sequence);
            last_sequence = Some(envelope.sequence);
            count = count.saturating_add(1);
        }
        let Some(first_sequence) = first_sequence else {
            return Ok(None);
        };
        let Some(last_sequence) = last_sequence else {
            return Ok(None);
        };
        Ok(Some(DiskDerivedStateSegmentMetadata {
            path: path.to_path_buf(),
            first_sequence,
            last_sequence,
            retained_envelopes: count,
        }))
    }

    /// Returns the number of retained session directories currently visible on disk.
    fn retained_session_dirs(&self) -> usize {
        fs::read_dir(&self.root_dir)
            .ok()
            .map(|entries| {
                entries
                    .flatten()
                    .filter(|entry| entry.path().is_dir())
                    .count()
            })
            .unwrap_or(0)
    }

    /// Returns one parsed session id from a retained replay session directory when possible.
    fn parse_session_id(path: &Path) -> Option<FeedSessionId> {
        let name = path.file_name()?.to_str()?;
        u128::from_str_radix(name, 16).ok().map(FeedSessionId)
    }

    /// Returns one parsed first-sequence boundary from a retained segment filename when possible.
    fn parse_segment_first_sequence(path: &Path) -> Option<FeedSequence> {
        let stem = path.file_stem()?.to_str()?;
        stem.parse::<u64>().ok().map(FeedSequence)
    }

    /// Returns the target envelope count per disk segment.
    #[must_use]
    fn segment_envelope_capacity(&self) -> usize {
        if self.max_envelopes_per_session < DISK_REPLAY_TARGET_SEGMENT_ENVELOPES {
            self.max_envelopes_per_session.max(1)
        } else {
            DISK_REPLAY_TARGET_SEGMENT_ENVELOPES
        }
    }

    /// Closes one cached append handle before the underlying segment path is rewritten or removed.
    fn evict_cached_appender(path: &Path) {
        DISK_REPLAY_APPENDERS.with(|appenders| {
            appenders.borrow_mut().remove(path);
        });
    }

    /// Closes cached append handles rooted under one directory before compacting it away.
    fn evict_cached_appenders_in_dir(dir: &Path) {
        DISK_REPLAY_APPENDERS.with(|appenders| {
            appenders
                .borrow_mut()
                .retain(|path, _file| !path.starts_with(dir));
        });
    }

    /// Reconstructs lightweight retained-session metadata by scanning the session directory.
    fn scan_session_metadata(
        &self,
        session_id: FeedSessionId,
    ) -> io::Result<DiskDerivedStateSessionMetadata> {
        let session_dir = self.session_path(session_id);
        if !session_dir.exists() {
            return Ok(DiskDerivedStateSessionMetadata::default());
        }
        let mut segments = fs::read_dir(&session_dir)?
            .flatten()
            .filter_map(|entry| {
                let path = entry.path();
                (path.extension().is_some_and(|ext| ext == "segment")).then_some(path)
            })
            .collect::<Vec<_>>();
        segments.sort_by_key(|path| {
            Self::parse_segment_first_sequence(path).unwrap_or(FeedSequence(0))
        });

        let mut retained_envelopes = 0_usize;
        let mut segment_metadata = Vec::new();
        for path in segments {
            if let Some(metadata) = self.scan_segment_metadata(&path)? {
                retained_envelopes = retained_envelopes.saturating_add(metadata.retained_envelopes);
                segment_metadata.push(metadata);
            }
        }
        Ok(DiskDerivedStateSessionMetadata {
            segments: segment_metadata,
            retained_envelopes,
        })
    }

    /// Returns lightweight retained-session metadata, populating the cache on demand.
    fn session_metadata(
        &self,
        session_id: FeedSessionId,
    ) -> io::Result<DiskDerivedStateSessionMetadata> {
        if let Ok(metadata) = self.session_metadata.lock()
            && let Some(metadata) = metadata.get(&session_id).cloned()
        {
            return Ok(metadata);
        }
        let metadata = self.scan_session_metadata(session_id)?;
        if let Ok(mut cached) = self.session_metadata.lock() {
            if metadata.segments.is_empty() {
                let _ = cached.remove(&session_id);
            } else {
                cached.insert(session_id, metadata.clone());
            }
        }
        Ok(metadata)
    }

    /// Stores updated retained-session metadata after one append or truncation event.
    fn update_session_metadata(
        &self,
        session_id: FeedSessionId,
        session_metadata: DiskDerivedStateSessionMetadata,
    ) {
        if let Ok(mut cached) = self.session_metadata.lock() {
            if session_metadata.segments.is_empty() {
                let _ = cached.remove(&session_id);
            } else {
                cached.insert(session_id, session_metadata);
            }
        }
    }

    /// Truncates the oldest retained envelopes from one session without rewriting the full tail.
    fn truncate_oldest_envelopes(
        &self,
        session_id: FeedSessionId,
        metadata: &mut DiskDerivedStateSessionMetadata,
        mut envelopes_to_remove: usize,
    ) -> io::Result<usize> {
        let mut removed = 0_usize;
        while envelopes_to_remove > 0 {
            let Some(oldest_segment) = metadata.segments.first().cloned() else {
                break;
            };
            if oldest_segment.retained_envelopes <= envelopes_to_remove {
                Self::evict_cached_appender(&oldest_segment.path);
                fs::remove_file(&oldest_segment.path)?;
                metadata.segments.remove(0);
                metadata.retained_envelopes = metadata
                    .retained_envelopes
                    .saturating_sub(oldest_segment.retained_envelopes);
                envelopes_to_remove =
                    envelopes_to_remove.saturating_sub(oldest_segment.retained_envelopes);
                removed = removed.saturating_add(oldest_segment.retained_envelopes);
                continue;
            }

            let mut retained = self.load_segment_from_disk(&oldest_segment.path)?;
            retained.drain(..envelopes_to_remove);
            let Some(new_first_sequence) = retained.first().map(|envelope| envelope.sequence)
            else {
                break;
            };
            let Some(new_last_sequence) = retained.last().map(|envelope| envelope.sequence) else {
                break;
            };
            let new_path = self.segment_path(session_id, new_first_sequence);
            self.rewrite_records(&oldest_segment.path, &new_path, &retained)?;
            let Some(oldest_segment_metadata) = metadata.segments.first_mut() else {
                break;
            };
            *oldest_segment_metadata = DiskDerivedStateSegmentMetadata {
                path: new_path,
                first_sequence: new_first_sequence,
                last_sequence: new_last_sequence,
                retained_envelopes: retained.len(),
            };
            metadata.retained_envelopes = metadata
                .retained_envelopes
                .saturating_sub(envelopes_to_remove);
            removed = removed.saturating_add(envelopes_to_remove);
            envelopes_to_remove = 0;
        }
        Ok(removed)
    }

    /// Applies the configured durability policy to one open file handle.
    fn sync_file(&self, file: &File) -> io::Result<()> {
        match self.durability {
            DerivedStateReplayDurability::Flush => Ok(()),
            DerivedStateReplayDurability::Fsync => file.sync_all(),
        }
    }

    /// Compacts old session logs when the backend exceeds its retention budget.
    fn compact_sessions(&self, current_session_id: FeedSessionId) -> io::Result<()> {
        let mut retained_sessions = fs::read_dir(&self.root_dir)?
            .flatten()
            .filter_map(|entry| {
                let path = entry.path();
                path.is_dir()
                    .then(|| Self::parse_session_id(&path).map(|session_id| (session_id, path)))
                    .flatten()
            })
            .collect::<Vec<_>>();
        retained_sessions.sort_by_key(|(session_id, _path)| *session_id);
        let mut removed_any = false;
        while retained_sessions.len() > self.max_retained_sessions {
            let Some((session_id, path)) = retained_sessions.first().cloned() else {
                break;
            };
            if session_id == current_session_id {
                break;
            }
            Self::evict_cached_appenders_in_dir(&path);
            fs::remove_dir_all(&path)?;
            self.update_session_metadata(session_id, DiskDerivedStateSessionMetadata::default());
            retained_sessions.remove(0);
            removed_any = true;
        }
        if removed_any {
            let _ = self.compactions.fetch_add(1, Ordering::Relaxed);
        }
        Ok(())
    }
}

impl Drop for DiskDerivedStateReplaySource {
    fn drop(&mut self) {
        let (dummy_tx, _dummy_rx) = mpsc::channel::<Vec<DerivedStateFeedEnvelope>>();
        let writer_tx = std::mem::replace(&mut self.writer_tx, dummy_tx);
        drop(writer_tx);
        if let Some(writer_handle) = self.writer_handle.take()
            && writer_handle.join().is_err()
        {
            tracing::warn!("derived-state replay writer thread panicked during shutdown");
        }
    }
}

impl DerivedStateReplaySource for DiskDerivedStateReplaySource {
    fn append(&self, envelope: DerivedStateFeedEnvelope) {
        let session_id = envelope.session_id;
        if let Err(error) = self.writer_tx.send(vec![envelope]) {
            let _ = self.append_failures.fetch_add(1, Ordering::Relaxed);
            tracing::warn!(
                session_id = ?session_id,
                error = %error,
                "failed to enqueue derived-state replay envelope for disk append"
            );
        }
    }

    fn append_batch(&self, envelopes: &[DerivedStateFeedEnvelope]) {
        let Some(first_envelope) = envelopes.first() else {
            return;
        };
        let session_id = first_envelope.session_id;
        if let Err(error) = self.writer_tx.send(envelopes.to_vec()) {
            let _ = self.append_failures.fetch_add(1, Ordering::Relaxed);
            tracing::warn!(
                session_id = ?session_id,
                error = %error,
                "failed to enqueue derived-state replay envelope batch for disk append"
            );
        }
    }

    fn append_shared_batch(&self, envelopes: &[DerivedStateFeedEnvelope]) {
        let Some(first_envelope) = envelopes.first() else {
            return;
        };
        let session_id = first_envelope.session_id;
        if let Err(error) = self.writer_tx.send(envelopes.to_vec()) {
            let _ = self.append_failures.fetch_add(1, Ordering::Relaxed);
            tracing::warn!(
                session_id = ?session_id,
                error = %error,
                "failed to enqueue shared derived-state replay envelope batch for disk append"
            );
        }
    }

    fn replay_from(
        &self,
        session_id: FeedSessionId,
        next_sequence: FeedSequence,
    ) -> Result<Vec<DerivedStateFeedEnvelope>, DerivedStateReplayError> {
        let metadata = self.session_metadata(session_id).map_err(|error| {
            let _ = self.load_failures.fetch_add(1, Ordering::Relaxed);
            DerivedStateReplayError::BackendFailure {
                session_id,
                message: error.to_string(),
            }
        })?;
        if metadata.segments.is_empty() {
            return Err(DerivedStateReplayError::SessionUnavailable(session_id));
        }
        if metadata
            .segments
            .last()
            .and_then(|segment| segment.last_sequence.next())
            .is_some_and(|expected_next| next_sequence == expected_next)
        {
            return Ok(Vec::new());
        }
        if metadata
            .segments
            .first()
            .is_some_and(|segment| next_sequence < segment.first_sequence)
        {
            let Some(oldest_segment) = metadata.segments.first() else {
                return Err(DerivedStateReplayError::SessionUnavailable(session_id));
            };
            return Err(DerivedStateReplayError::Truncated {
                session_id,
                sequence: next_sequence,
                oldest_retained_sequence: oldest_segment.first_sequence,
            });
        }

        let mut envelopes = Vec::new();
        let mut started = false;
        for segment in &metadata.segments {
            if !started && segment.last_sequence < next_sequence {
                continue;
            }
            started = true;
            let mut loaded = self
                .load_segment_from_disk(&segment.path)
                .map_err(|error| {
                    let _ = self.load_failures.fetch_add(1, Ordering::Relaxed);
                    DerivedStateReplayError::BackendFailure {
                        session_id,
                        message: error.to_string(),
                    }
                })?;
            envelopes.append(&mut loaded);
        }
        validate_replayed_envelopes(session_id, &envelopes, next_sequence)
    }

    fn telemetry(&self) -> DerivedStateReplayTelemetry {
        let retained_sessions = self.retained_session_dirs();
        let retained_envelopes = fs::read_dir(&self.root_dir)
            .ok()
            .map(|entries| {
                entries
                    .flatten()
                    .filter_map(|entry| {
                        let path = entry.path();
                        path.is_dir()
                            .then(|| Self::parse_session_id(&path))
                            .flatten()
                    })
                    .map(|session_id| {
                        self.session_metadata(session_id)
                            .map(|metadata| metadata.retained_envelopes)
                            .unwrap_or(0)
                    })
                    .sum()
            })
            .unwrap_or(0);
        DerivedStateReplayTelemetry {
            enabled: true,
            backend: DerivedStateReplayBackend::Disk,
            retained_sessions,
            retained_envelopes,
            truncated_envelopes: self.truncated_envelopes(),
            append_failures: self.append_failures(),
            load_failures: self.load_failures(),
            compactions: self.compactions(),
        }
    }
}

/// Validates that one retained session tail can satisfy replay continuity.
fn validate_replayed_envelopes(
    session_id: FeedSessionId,
    envelopes: &[DerivedStateFeedEnvelope],
    next_sequence: FeedSequence,
) -> Result<Vec<DerivedStateFeedEnvelope>, DerivedStateReplayError> {
    if let Some(last_retained_sequence) = envelopes.last().map(|envelope| envelope.sequence)
        && last_retained_sequence
            .next()
            .is_some_and(|expected_next| next_sequence == expected_next)
    {
        return Ok(Vec::new());
    }
    if let Some(oldest_retained_sequence) = envelopes.first().map(|envelope| envelope.sequence)
        && next_sequence < oldest_retained_sequence
    {
        return Err(DerivedStateReplayError::Truncated {
            session_id,
            sequence: next_sequence,
            oldest_retained_sequence,
        });
    }
    let Some(start_index) = envelopes
        .iter()
        .position(|envelope| envelope.sequence == next_sequence)
    else {
        if envelopes.is_empty() && next_sequence == FeedSequence(0) {
            return Ok(Vec::new());
        }
        return Err(DerivedStateReplayError::SequenceGap {
            session_id,
            sequence: next_sequence,
        });
    };
    let Some(replayed) = envelopes.get(start_index..) else {
        return Err(DerivedStateReplayError::SequenceGap {
            session_id,
            sequence: next_sequence,
        });
    };
    let replayed = replayed.to_vec();
    let mut expected_sequence = next_sequence;
    for envelope in &replayed {
        if envelope.sequence != expected_sequence {
            return Err(DerivedStateReplayError::SequenceGap {
                session_id,
                sequence: expected_sequence,
            });
        }
        let Some(next) = expected_sequence.next() else {
            break;
        };
        expected_sequence = next;
    }
    Ok(replayed)
}

/// Stateful consumer interface for the dedicated derived-state feed scaffold.
///
/// This trait is intentionally synchronous for the initial scaffold so implementers can model
/// deterministic state application and checkpointing before runtime dispatch details are fixed.
pub trait DerivedStateConsumer: Send + Sync + 'static {
    /// Stable consumer name used in logs and telemetry.
    fn name(&self) -> &'static str;

    /// Consumer-owned schema/state version written into durable checkpoints.
    fn state_version(&self) -> u32;

    /// Stable consumer implementation version written into durable checkpoints.
    fn extension_version(&self) -> &'static str;

    /// Loads the most recent durable checkpoint when present.
    ///
    /// # Errors
    /// Returns a structured fault when the checkpoint cannot be loaded or decoded.
    fn load_checkpoint(
        &mut self,
    ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault>;

    /// Returns static feed subscriptions requested by this consumer.
    fn config(&self) -> DerivedStateConsumerConfig {
        DerivedStateConsumerConfig::default()
    }

    /// Called once after the worker thread is created and before any replay or live apply.
    ///
    /// # Errors
    /// Returns a startup error when the consumer cannot initialize its runtime-owned resources.
    fn setup(
        &mut self,
        _ctx: DerivedStateConsumerContext,
    ) -> Result<(), DerivedStateConsumerSetupError> {
        Ok(())
    }

    /// Called once before the worker thread exits.
    fn shutdown(&mut self, _ctx: DerivedStateConsumerContext) {}

    /// Applies one feed envelope in canonical sequence order.
    ///
    /// # Errors
    /// Returns a structured fault when the consumer cannot apply the event.
    fn apply(
        &mut self,
        envelope: &DerivedStateFeedEnvelope,
    ) -> Result<(), DerivedStateConsumerFault>;

    /// Persists a durable checkpoint for later replay or recovery.
    ///
    /// # Errors
    /// Returns a structured fault when checkpoint persistence fails.
    fn flush_checkpoint(
        &mut self,
        checkpoint: DerivedStateCheckpoint,
    ) -> Result<(), DerivedStateConsumerFault>;
}

/// Bounded command queue capacity for each dedicated derived-state consumer worker.
const DERIVED_STATE_CONSUMER_QUEUE_CAPACITY: usize = 1024;

/// Commands sent from the host thread into one consumer-owned worker thread.
enum DerivedStateConsumerCommand {
    /// Ensures the consumer startup hook has completed successfully.
    EnsureStarted {
        /// One-shot reply channel for the startup outcome.
        response: channel::Sender<Result<(), DerivedStateConsumerFault>>,
    },
    /// Loads the latest durable checkpoint from the consumer.
    LoadCheckpoint {
        /// One-shot reply channel for the checkpoint result.
        response:
            channel::Sender<Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault>>,
    },
    /// Applies a preordered live batch of shared envelopes.
    ApplySharedBatch {
        /// Live batch to apply in sequence order.
        envelopes: SharedDerivedStateEnvelopeBatch,
    },
    /// Applies a preordered replay batch.
    ApplyBatch {
        /// Replay batch to apply in sequence order.
        envelopes: Vec<DerivedStateFeedEnvelope>,
        /// One-shot reply channel for batch progress and any fault.
        response: channel::Sender<DerivedStateConsumerBatchApplyReply>,
    },
    /// Applies one final envelope and then persists a checkpoint.
    FlushCheckpoint {
        /// Final envelope that advances the consumer before checkpointing.
        envelope: Arc<DerivedStateFeedEnvelope>,
        /// Active host session id written into the checkpoint.
        session_id: FeedSessionId,
        /// Watermarks paired with the checkpoint barrier.
        watermarks: FeedWatermarks,
        /// One-shot reply channel for the checkpoint flush outcome.
        response: channel::Sender<Option<DerivedStateConsumerFault>>,
    },
    /// Requests cooperative worker shutdown.
    Shutdown,
}

/// Result summary returned from replay-batch application.
struct DerivedStateConsumerBatchApplyReply {
    /// Number of envelopes the consumer applied before stopping.
    applied_events: u64,
    /// Highest successfully applied sequence in the batch, when known.
    last_sequence: Option<FeedSequence>,
    /// First consumer fault encountered during the batch, when any.
    fault: Option<DerivedStateConsumerFault>,
}

/// Shared live-batch representation reused across derived-state consumers.
enum SharedDerivedStateEnvelopeBatch {
    /// Full emitted batch accepted by the consumer without filtering.
    Full(Arc<Vec<DerivedStateFeedEnvelope>>),
    /// Filtered subset accepted by the consumer, referenced by index into one shared batch.
    Indexed {
        /// Shared emitted batch.
        envelopes: Arc<Vec<DerivedStateFeedEnvelope>>,
        /// Accepted envelope indexes in canonical order.
        indexes: Vec<usize>,
    },
}

impl SharedDerivedStateEnvelopeBatch {
    /// Returns the highest sequence in the batch when one exists.
    #[must_use]
    fn last_sequence(&self) -> Option<FeedSequence> {
        match self {
            Self::Full(envelopes) => envelopes.last().map(|envelope| envelope.sequence),
            Self::Indexed { envelopes, indexes } => indexes
                .last()
                .and_then(|index| envelopes.get(*index))
                .map(|envelope| envelope.sequence),
        }
    }
}

/// Dedicated worker state for one derived-state consumer instance.
struct DerivedStateConsumerWorker {
    /// Bounded command queue feeding the worker thread.
    queue: Arc<ArrayQueue<DerivedStateConsumerCommand>>,
    /// Handle to the worker thread for direct unparking.
    worker_thread: Arc<OnceLock<std::thread::Thread>>,
    /// Cooperative shutdown flag shared with the worker thread.
    shutdown: Arc<AtomicBool>,
    /// Structured startup fault captured when the worker could not be spawned.
    startup_fault: Option<DerivedStateConsumerFault>,
    /// Cached startup outcome so the lifecycle runs exactly once.
    startup_state: OnceLock<Result<(), DerivedStateConsumerFault>>,
    /// Join handle for the worker thread when startup succeeded.
    worker_handle: Option<JoinHandle<()>>,
    /// Reused reply receiver for the live shared-batch path.
    apply_shared_batch_reply_rx: channel::Receiver<DerivedStateConsumerBatchApplyReply>,
}

impl DerivedStateConsumerWorker {
    /// Spawns one dedicated worker thread for one derived-state consumer.
    fn spawn(name: &'static str, mut consumer: Box<dyn DerivedStateConsumer>) -> Self {
        let queue = Arc::new(ArrayQueue::new(DERIVED_STATE_CONSUMER_QUEUE_CAPACITY));
        let worker_thread = Arc::new(OnceLock::new());
        let shutdown = Arc::new(AtomicBool::new(false));
        let (apply_shared_batch_reply_tx, apply_shared_batch_reply_rx) = channel::bounded(1);
        let worker_queue = queue.clone();
        let worker_thread_ref = worker_thread.clone();
        let worker_shutdown = shutdown.clone();
        let worker_handle = std::thread::Builder::new()
            .name(format!("derived-state-{name}"))
            .spawn(move || {
                drop(worker_thread_ref.set(std::thread::current()));
                let mut started = false;
                while !worker_shutdown.load(Ordering::Relaxed) {
                    let Some(command) = worker_queue.pop() else {
                        std::thread::park();
                        continue;
                    };
                    match command {
                        DerivedStateConsumerCommand::EnsureStarted { response } => {
                            if started {
                                drop(response.send(Ok(())));
                                continue;
                            }
                            let startup_result = consumer
                                .setup(DerivedStateConsumerContext {
                                    consumer_name: name,
                                })
                                .map_err(|error| {
                                    DerivedStateConsumerFault::new(
                                        DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                                        None,
                                        format!("derived-state consumer startup failed: {error}"),
                                    )
                                });
                            if let Err(fault) = startup_result.as_ref() {
                                tracing::error!(
                                    consumer = name,
                                    reason = %fault,
                                    "derived-state consumer startup failed"
                                );
                                drop(response.send(Err(fault.clone())));
                                return;
                            }
                            started = true;
                            drop(response.send(Ok(())));
                        }
                        DerivedStateConsumerCommand::LoadCheckpoint { response } => {
                            drop(response.send(consumer.load_checkpoint()));
                        }
                        DerivedStateConsumerCommand::ApplySharedBatch { envelopes } => {
                            let mut applied_events = 0_u64;
                            let mut last_sequence = None;
                            let mut fault = None;
                            match envelopes {
                                SharedDerivedStateEnvelopeBatch::Full(envelopes) => {
                                    for envelope in envelopes.iter() {
                                        match consumer.apply(envelope) {
                                            Ok(()) => {
                                                applied_events = applied_events.saturating_add(1);
                                                last_sequence = Some(envelope.sequence);
                                            }
                                            Err(error) => {
                                                fault = Some(error);
                                                break;
                                            }
                                        }
                                    }
                                }
                                SharedDerivedStateEnvelopeBatch::Indexed { envelopes, indexes } => {
                                    for index in indexes {
                                        let Some(envelope) = envelopes.get(index) else {
                                            continue;
                                        };
                                        match consumer.apply(envelope) {
                                            Ok(()) => {
                                                applied_events = applied_events.saturating_add(1);
                                                last_sequence = Some(envelope.sequence);
                                            }
                                            Err(error) => {
                                                fault = Some(error);
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            drop(apply_shared_batch_reply_tx.send(
                                DerivedStateConsumerBatchApplyReply {
                                    applied_events,
                                    last_sequence,
                                    fault,
                                },
                            ));
                        }
                        DerivedStateConsumerCommand::ApplyBatch {
                            envelopes,
                            response,
                        } => {
                            let mut applied_events = 0_u64;
                            let mut last_sequence = None;
                            let mut fault = None;
                            for envelope in envelopes {
                                match consumer.apply(&envelope) {
                                    Ok(()) => {
                                        applied_events = applied_events.saturating_add(1);
                                        last_sequence = Some(envelope.sequence);
                                    }
                                    Err(error) => {
                                        fault = Some(error);
                                        break;
                                    }
                                }
                            }
                            drop(response.send(DerivedStateConsumerBatchApplyReply {
                                applied_events,
                                last_sequence,
                                fault,
                            }));
                        }
                        DerivedStateConsumerCommand::FlushCheckpoint {
                            envelope,
                            session_id,
                            watermarks,
                            response,
                        } => {
                            let fault = match consumer.apply(envelope.as_ref()) {
                                Ok(()) => consumer
                                    .flush_checkpoint(DerivedStateCheckpoint {
                                        session_id,
                                        last_applied_sequence: envelope.sequence,
                                        watermarks,
                                        state_version: consumer.state_version(),
                                        extension_version: consumer.extension_version().to_owned(),
                                    })
                                    .err(),
                                Err(error) => Some(error),
                            };
                            drop(response.send(fault));
                        }
                        DerivedStateConsumerCommand::Shutdown => break,
                    }
                }
                if started {
                    consumer.shutdown(DerivedStateConsumerContext {
                        consumer_name: name,
                    });
                }
            });
        let (startup_fault, worker_handle) = match worker_handle {
            Ok(handle) => (None, Some(handle)),
            Err(error) => (
                Some(DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                    None,
                    format!("failed to spawn derived-state consumer worker: {error}"),
                )),
                None,
            ),
        };
        Self {
            queue,
            worker_thread,
            shutdown,
            startup_fault,
            startup_state: OnceLock::new(),
            worker_handle,
            apply_shared_batch_reply_rx,
        }
    }

    /// Enqueues one command and blocks until the worker accepts it.
    fn push_blocking(&self, command: DerivedStateConsumerCommand) {
        if self.startup_fault.is_some() {
            return;
        }
        let mut command = command;
        loop {
            match self.queue.push(command) {
                Ok(()) => {
                    self.notify();
                    return;
                }
                Err(returned) => {
                    command = returned;
                    self.notify();
                    std::thread::yield_now();
                }
            }
        }
    }

    /// Ensures the consumer startup hook has completed successfully once.
    fn startup(&self) -> Result<(), DerivedStateConsumerFault> {
        self.startup_state
            .get_or_init(|| {
                if let Some(fault) = self.startup_fault.as_ref() {
                    return Err(fault.clone());
                }
                let (response_tx, response_rx) = channel::bounded(1);
                self.push_blocking(DerivedStateConsumerCommand::EnsureStarted {
                    response: response_tx,
                });
                response_rx.recv().unwrap_or_else(|_| {
                    Err(DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                        None,
                        "derived-state consumer worker exited during startup",
                    ))
                })
            })
            .clone()
    }

    /// Loads the most recent checkpoint through the consumer worker.
    fn load_checkpoint(&self) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
        self.startup()?;
        let (response_tx, response_rx) = channel::bounded(1);
        self.push_blocking(DerivedStateConsumerCommand::LoadCheckpoint {
            response: response_tx,
        });
        response_rx.recv().unwrap_or_else(|_| {
            Err(DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                None,
                "derived-state consumer worker exited during checkpoint load",
            ))
        })
    }

    /// Applies one replay batch through the consumer worker.
    fn apply_batch(
        &self,
        envelopes: Vec<DerivedStateFeedEnvelope>,
    ) -> DerivedStateConsumerBatchApplyReply {
        let last_sequence = envelopes.last().map(|envelope| envelope.sequence);
        if let Err(fault) = self.startup() {
            return DerivedStateConsumerBatchApplyReply {
                applied_events: 0,
                last_sequence,
                fault: Some(fault),
            };
        }
        let (response_tx, response_rx) = channel::bounded(1);
        self.push_blocking(DerivedStateConsumerCommand::ApplyBatch {
            envelopes,
            response: response_tx,
        });
        response_rx
            .recv()
            .unwrap_or_else(|_| DerivedStateConsumerBatchApplyReply {
                applied_events: 0,
                last_sequence,
                fault: Some(DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                    last_sequence,
                    "derived-state consumer worker exited during batch apply",
                )),
            })
    }

    /// Enqueues one live shared batch and returns the reply receiver when startup succeeded.
    fn begin_apply_shared_batch(
        &self,
        envelopes: SharedDerivedStateEnvelopeBatch,
    ) -> Result<Option<FeedSequence>, DerivedStateConsumerBatchApplyReply> {
        let last_sequence = envelopes.last_sequence();
        if let Err(fault) = self.startup() {
            return Err(DerivedStateConsumerBatchApplyReply {
                applied_events: 0,
                last_sequence,
                fault: Some(fault),
            });
        }
        self.push_blocking(DerivedStateConsumerCommand::ApplySharedBatch { envelopes });
        Ok(last_sequence)
    }

    /// Waits for one live shared-batch reply from the consumer worker.
    fn recv_apply_shared_batch_reply(
        &self,
        last_sequence: Option<FeedSequence>,
    ) -> DerivedStateConsumerBatchApplyReply {
        self.apply_shared_batch_reply_rx.recv().unwrap_or_else(|_| {
            DerivedStateConsumerBatchApplyReply {
                applied_events: 0,
                last_sequence,
                fault: Some(DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                    last_sequence,
                    "derived-state consumer worker exited during shared batch apply",
                )),
            }
        })
    }

    /// Flushes one checkpoint barrier through the consumer worker.
    fn flush_checkpoint(
        &self,
        envelope: Arc<DerivedStateFeedEnvelope>,
        session_id: FeedSessionId,
        watermarks: FeedWatermarks,
    ) -> Result<(), DerivedStateConsumerFault> {
        self.startup()?;
        let sequence = envelope.sequence;
        let (response_tx, response_rx) = channel::bounded(1);
        self.push_blocking(DerivedStateConsumerCommand::FlushCheckpoint {
            envelope,
            session_id,
            watermarks,
            response: response_tx,
        });
        match response_rx.recv() {
            Ok(Some(fault)) => Err(fault),
            Ok(None) => Ok(()),
            Err(_) => Err(DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                Some(sequence),
                "derived-state consumer worker exited during checkpoint flush",
            )),
        }
    }

    /// Wakes the worker thread after enqueueing a new command.
    fn notify(&self) {
        if let Some(thread) = self.worker_thread.get() {
            thread.unpark();
        }
    }
}

impl Drop for DerivedStateConsumerWorker {
    fn drop(&mut self) {
        self.shutdown.store(true, Ordering::Relaxed);
        drop(self.queue.push(DerivedStateConsumerCommand::Shutdown));
        self.notify();
        if let Some(handle) = self.worker_handle.take()
            && handle.join().is_err()
        {
            tracing::error!("derived-state consumer worker panicked during shutdown");
        }
    }
}

/// Builder for [`DerivedStateHost`].
#[derive(Default)]
pub struct DerivedStateHostBuilder {
    /// Registered consumers in dispatch order.
    consumers: Vec<RegisteredDerivedStateConsumer>,
    /// Optional retained replay source used during checkpoint resume.
    replay_source: Option<Arc<dyn DerivedStateReplaySource>>,
    /// Explicit session id override for replay/testing flows.
    session_id: Option<FeedSessionId>,
}

impl DerivedStateHostBuilder {
    /// Creates an empty host builder.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            consumers: Vec::new(),
            replay_source: None,
            session_id: None,
        }
    }

    /// Registers one derived-state consumer.
    #[must_use]
    pub fn add_consumer<C>(mut self, consumer: C) -> Self
    where
        C: DerivedStateConsumer,
    {
        let name = consumer.name();
        let config = consumer.config();
        let subscriptions = DerivedStateConsumerSubscriptions {
            transaction_applied: config.transaction_applied,
            transaction_status_observed: config.transaction_status_observed,
            block_meta_observed: config.block_meta_observed,
            account_touch_observed: config.account_touch_observed,
            account_touch_key_partitions: config.account_touch_key_partitions,
            control_plane_observed: config.control_plane_observed,
        };
        self.consumers.push(RegisteredDerivedStateConsumer {
            name,
            worker: DerivedStateConsumerWorker::spawn(name, Box::new(consumer)),
            subscriptions,
            unhealthy: AtomicBool::new(false),
            recovery_state: AtomicU8::new(DerivedStateConsumerRecoveryState::Live.into_u8()),
            applied_events: AtomicU64::new(0),
            checkpoint_flushes: AtomicU64::new(0),
            fault_count: AtomicU64::new(0),
            last_applied_sequence: AtomicU64::new(0),
            has_last_applied_sequence: AtomicBool::new(false),
            last_fault_sequence: AtomicU64::new(0),
            has_last_fault_sequence: AtomicBool::new(false),
            last_fault_kind: AtomicU8::new(0),
            has_last_fault_kind: AtomicBool::new(false),
        });
        self
    }

    /// Registers one replay source used to resume from retained feed envelopes.
    #[must_use]
    pub fn with_replay_source(mut self, replay_source: Arc<dyn DerivedStateReplaySource>) -> Self {
        self.replay_source = Some(replay_source);
        self
    }

    /// Overrides the generated session id.
    #[must_use]
    pub const fn with_session_id(mut self, session_id: FeedSessionId) -> Self {
        self.session_id = Some(session_id);
        self
    }

    /// Builds an immutable derived-state host.
    #[must_use]
    pub fn build(self) -> DerivedStateHost {
        DerivedStateHost {
            inner: Arc::new(DerivedStateHostInner {
                consumers: Arc::from(self.consumers),
                session_id: self.session_id.unwrap_or_else(generate_session_id),
                replay_source: self.replay_source,
                runtime_replay_source: OnceLock::new(),
                dispatch_ticket_cursor: AtomicU64::new(0),
                next_dispatch_ticket: AtomicU64::new(0),
                next_sequence: AtomicU64::new(0),
                last_sequence: AtomicU64::new(0),
                has_last_sequence: AtomicBool::new(false),
                last_watermarks: AtomicFeedWatermarks::default(),
                control_plane_state: ArcShift::new(DerivedStateControlPlaneTracker::default()),
                fault_count: AtomicU64::new(0),
                initialized: AtomicBool::new(false),
                slot_tx_indexes: Mutex::new(HashMap::new()),
            }),
        }
    }
}

/// Immutable host for derived-state consumers.
#[derive(Clone)]
pub struct DerivedStateHost {
    /// Shared host state and dispatch bookkeeping.
    inner: Arc<DerivedStateHostInner>,
}

impl Default for DerivedStateHost {
    fn default() -> Self {
        DerivedStateHostBuilder::new().build()
    }
}

impl DerivedStateHost {
    /// Returns the configured replay source or the runtime-installed fallback when present.
    #[must_use]
    fn replay_source(&self) -> Option<&Arc<dyn DerivedStateReplaySource>> {
        self.inner
            .replay_source
            .as_ref()
            .or_else(|| self.inner.runtime_replay_source.get())
    }

    /// Maps replay-source failures into structured consumer faults.
    fn replay_fault(
        checkpoint: &DerivedStateCheckpoint,
        error: &DerivedStateReplayError,
    ) -> DerivedStateConsumerFault {
        match error {
            DerivedStateReplayError::SessionUnavailable(session_id) => {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ReplayGap,
                    checkpoint
                        .next_sequence()
                        .or(Some(checkpoint.last_applied_sequence)),
                    format!(
                        "derived-state replay session unavailable for checkpoint session {:?}; requested {:?}",
                        session_id,
                        checkpoint.next_sequence()
                    ),
                )
            }
            DerivedStateReplayError::SequenceGap {
                session_id,
                sequence,
            } => DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ReplayGap,
                Some(*sequence),
                format!(
                    "derived-state replay gap in session {:?} at sequence {:?}",
                    session_id, sequence
                ),
            ),
            DerivedStateReplayError::Truncated {
                session_id,
                sequence,
                oldest_retained_sequence,
            } => DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ReplayGap,
                Some(*sequence),
                format!(
                    "derived-state replay truncated in session {:?} before sequence {:?}; oldest retained {:?}",
                    session_id, sequence, oldest_retained_sequence
                ),
            ),
            DerivedStateReplayError::BackendFailure {
                session_id,
                message,
            } => DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ReplayGap,
                checkpoint
                    .next_sequence()
                    .or(Some(checkpoint.last_applied_sequence)),
                format!(
                    "derived-state replay backend failure in session {:?}: {}",
                    session_id, message
                ),
            ),
        }
    }

    /// Starts a new derived-state host builder.
    #[must_use]
    pub const fn builder() -> DerivedStateHostBuilder {
        DerivedStateHostBuilder::new()
    }

    /// Returns `true` when no consumers are registered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.consumers.is_empty()
    }

    /// Returns the number of registered consumers.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.consumers.len()
    }

    /// Returns true when at least one consumer wants transaction-applied events.
    #[must_use]
    pub fn wants_transaction_applied(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.transaction_applied)
    }

    /// Returns true when at least one consumer wants transaction-status observations.
    #[must_use]
    pub fn wants_transaction_status_observed(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.transaction_status_observed)
    }

    /// Returns true when at least one consumer wants block-meta observations.
    #[must_use]
    pub fn wants_block_meta_observed(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.block_meta_observed)
    }

    /// Returns true when at least one consumer wants account-touch events.
    #[must_use]
    pub fn wants_account_touch_observed(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.account_touch_observed)
    }

    /// Returns true when any account-touch consumer needs writable/read-only key partitions.
    #[must_use]
    pub fn wants_account_touch_key_partitions(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.account_touch_key_partitions)
    }

    /// Returns true when at least one consumer wants control-plane observed events.
    #[must_use]
    pub fn wants_control_plane_observed(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(|consumer| consumer.subscriptions.control_plane_observed)
    }

    /// Returns registered consumer names in registration order.
    #[must_use]
    pub fn consumer_names(&self) -> Vec<&'static str> {
        self.inner
            .consumers
            .iter()
            .map(|consumer| consumer.name)
            .collect()
    }

    /// Returns the current feed session id.
    #[must_use]
    pub fn session_id(&self) -> FeedSessionId {
        self.inner.session_id
    }

    /// Installs a runtime-owned replay source when the builder did not configure one.
    ///
    /// Returns `true` when the source was installed for this host. A builder-provided replay
    /// source always takes precedence.
    pub fn install_runtime_replay_source(
        &self,
        replay_source: Arc<dyn DerivedStateReplaySource>,
    ) -> bool {
        if self.inner.replay_source.is_some() {
            return false;
        }
        self.inner.runtime_replay_source.set(replay_source).is_ok()
    }

    /// Returns the total number of structured consumer faults observed by the host.
    #[must_use]
    pub fn fault_count(&self) -> u64 {
        self.inner.fault_count.load(Ordering::Relaxed)
    }

    /// Returns the number of registered consumers still considered healthy for live apply.
    #[must_use]
    pub fn healthy_consumer_count(&self) -> usize {
        self.inner
            .consumers
            .iter()
            .filter(|consumer| !consumer.is_unhealthy())
            .count()
    }

    /// Returns `true` when at least one consumer has lost live continuity.
    #[must_use]
    pub fn has_unhealthy_consumers(&self) -> bool {
        self.inner
            .consumers
            .iter()
            .any(RegisteredDerivedStateConsumer::is_unhealthy)
    }

    /// Returns the names of consumers that are no longer receiving live feed events.
    #[must_use]
    pub fn unhealthy_consumer_names(&self) -> Vec<&'static str> {
        self.inner
            .consumers
            .iter()
            .filter(|consumer| consumer.is_unhealthy())
            .map(|consumer| consumer.name)
            .collect()
    }

    /// Returns `true` when at least one consumer requires replay-based resync or rebuild.
    #[must_use]
    pub fn has_consumers_requiring_resync(&self) -> bool {
        self.has_unhealthy_consumers()
    }

    /// Returns the names of consumers that require replay-based resync or rebuild.
    #[must_use]
    pub fn consumers_requiring_resync(&self) -> Vec<&'static str> {
        self.unhealthy_consumer_names()
    }

    /// Returns the names of consumers that can still attempt replay-based recovery.
    #[must_use]
    pub fn consumers_pending_recovery(&self) -> Vec<&'static str> {
        self.inner
            .consumers
            .iter()
            .filter(|consumer| {
                consumer.recovery_state()
                    == DerivedStateConsumerRecoveryState::ReplayRecoveryPending
            })
            .map(|consumer| consumer.name)
            .collect()
    }

    /// Returns the names of consumers that now require a full rebuild.
    #[must_use]
    pub fn consumers_requiring_rebuild(&self) -> Vec<&'static str> {
        self.inner
            .consumers
            .iter()
            .filter(|consumer| {
                consumer.recovery_state() == DerivedStateConsumerRecoveryState::RebuildRequired
            })
            .map(|consumer| consumer.name)
            .collect()
    }

    /// Returns per-consumer live-feed telemetry snapshots in registration order.
    #[must_use]
    pub fn consumer_telemetry(&self) -> Vec<DerivedStateConsumerTelemetry> {
        self.inner
            .consumers
            .iter()
            .map(RegisteredDerivedStateConsumer::telemetry)
            .collect()
    }

    /// Returns operator-facing telemetry for the configured replay backend when present.
    #[must_use]
    pub fn replay_telemetry(&self) -> Option<DerivedStateReplayTelemetry> {
        self.replay_source()
            .map(|replay_source| replay_source.telemetry())
    }

    /// Returns the highest sequence emitted by this host when one exists.
    #[must_use]
    pub fn last_emitted_sequence(&self) -> Option<FeedSequence> {
        self.inner
            .has_last_sequence
            .load(Ordering::Relaxed)
            .then(|| FeedSequence(self.inner.last_sequence.load(Ordering::Relaxed)))
    }

    /// Returns the latest runtime watermarks recorded by this host.
    #[must_use]
    pub fn current_watermarks(&self) -> FeedWatermarks {
        self.inner.last_watermarks.load()
    }

    /// Initializes registered consumers by attempting to load their durable checkpoints once.
    pub fn initialize(&self) {
        let was_uninitialized = self
            .inner
            .initialized
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .is_ok();
        if !was_uninitialized {
            return;
        }

        for registered in self.inner.consumers.iter() {
            if registered.is_unhealthy() {
                continue;
            }
            match registered.worker.load_checkpoint() {
                Ok(Some(checkpoint)) => {
                    let Some(next_sequence) = checkpoint.next_sequence() else {
                        continue;
                    };
                    if let Some(replay_source) = self.replay_source() {
                        match replay_source.replay_from(checkpoint.session_id, next_sequence) {
                            Ok(replayed) => {
                                let reply = registered.worker.apply_batch(replayed);
                                registered
                                    .note_applied_batch(reply.applied_events, reply.last_sequence);
                                if let Some(fault) = reply.fault.as_ref() {
                                    self.record_consumer_fault(registered, fault);
                                }
                            }
                            Err(error) => {
                                let fault = Self::replay_fault(&checkpoint, &error);
                                self.record_consumer_fault(registered, &fault);
                            }
                        }
                    } else if checkpoint.session_id != self.inner.session_id {
                        let fault = DerivedStateConsumerFault::new(
                            DerivedStateConsumerFaultKind::ReplayGap,
                            Some(next_sequence),
                            format!(
                                "checkpoint session {:?} does not match current session {:?} and no replay source is configured",
                                checkpoint.session_id, self.inner.session_id
                            ),
                        );
                        self.record_consumer_fault(registered, &fault);
                    }
                }
                Ok(None) => {}
                Err(fault) => {
                    self.record_consumer_fault(registered, &fault);
                }
            }
        }
    }

    /// Attempts replay-based recovery for unhealthy consumers.
    #[must_use]
    pub fn recover_consumers(&self) -> DerivedStateRecoveryReport {
        let mut report = DerivedStateRecoveryReport::default();
        for registered in self.inner.consumers.iter() {
            if !registered.is_unhealthy() {
                continue;
            }
            report.attempted = report.attempted.saturating_add(1);

            let checkpoint = match registered.worker.load_checkpoint() {
                Ok(Some(checkpoint)) => checkpoint,
                Ok(None) => {
                    registered
                        .set_recovery_state(DerivedStateConsumerRecoveryState::RebuildRequired);
                    report.rebuild_required = report.rebuild_required.saturating_add(1);
                    continue;
                }
                Err(fault) => {
                    self.record_consumer_fault(registered, &fault);
                    report.still_pending = report.still_pending.saturating_add(1);
                    continue;
                }
            };
            let Some(next_sequence) = checkpoint.next_sequence() else {
                registered.note_recovered_checkpoint(checkpoint.last_applied_sequence);
                report.recovered = report.recovered.saturating_add(1);
                continue;
            };
            let Some(replay_source) = self.replay_source() else {
                registered.set_recovery_state(DerivedStateConsumerRecoveryState::RebuildRequired);
                report.rebuild_required = report.rebuild_required.saturating_add(1);
                continue;
            };
            match replay_source.replay_from(checkpoint.session_id, next_sequence) {
                Ok(replayed) => {
                    let reply = registered.worker.apply_batch(replayed);
                    registered.note_applied_batch(reply.applied_events, reply.last_sequence);
                    let mut recovered = reply.fault.is_none();
                    if reply.applied_events == 0 && reply.last_sequence.is_none() && recovered {
                        registered.note_recovered_checkpoint(checkpoint.last_applied_sequence);
                    } else {
                        if let Some(fault) = reply.fault.as_ref() {
                            self.record_consumer_fault(registered, fault);
                            recovered = false;
                        }
                        if recovered {
                            registered.mark_live();
                        }
                    }
                    if recovered {
                        report.recovered = report.recovered.saturating_add(1);
                    } else {
                        match registered.recovery_state() {
                            DerivedStateConsumerRecoveryState::RebuildRequired => {
                                report.rebuild_required = report.rebuild_required.saturating_add(1);
                            }
                            DerivedStateConsumerRecoveryState::Live
                            | DerivedStateConsumerRecoveryState::ReplayRecoveryPending => {
                                report.still_pending = report.still_pending.saturating_add(1);
                            }
                        }
                    }
                }
                Err(error) => {
                    let fault = Self::replay_fault(&checkpoint, &error);
                    self.record_consumer_fault(registered, &fault);
                    match registered.recovery_state() {
                        DerivedStateConsumerRecoveryState::RebuildRequired => {
                            report.rebuild_required = report.rebuild_required.saturating_add(1);
                        }
                        DerivedStateConsumerRecoveryState::Live
                        | DerivedStateConsumerRecoveryState::ReplayRecoveryPending => {
                            report.still_pending = report.still_pending.saturating_add(1);
                        }
                    }
                }
            }
        }
        report
    }

    /// Reserves a contiguous per-slot transaction-index range for feed events.
    ///
    /// Returns the starting index for the reserved range. Callers should assign
    /// offsets from that base locally to avoid one mutex round-trip per
    /// transaction on the dataset hot path.
    #[must_use]
    pub fn reserve_slot_tx_indexes(&self, slot: u64, count: u32) -> u32 {
        let mut slot_tx_indexes = self
            .inner
            .slot_tx_indexes
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let next = slot_tx_indexes.entry(slot).or_insert(0);
        let start = *next;
        *next = next.saturating_add(count);
        start
    }

    /// Emits one transaction-applied record into the derived-state feed.
    pub fn on_transaction(&self, tx_index: u32, event: TransactionEvent) {
        if self.is_empty() {
            return;
        }
        self.dispatch(
            FeedWatermarks {
                canonical_tip_slot: None,
                processed_slot: Some(event.slot),
                confirmed_slot: event.confirmed_slot,
                finalized_slot: event.finalized_slot,
            },
            DerivedStateFeedEvent::TransactionApplied((tx_index, event).into()),
        );
    }

    /// Emits one account-touch record into the derived-state feed.
    pub fn on_account_touch(&self, tx_index: u32, event: AccountTouchEvent) {
        if self.is_empty() {
            return;
        }
        self.dispatch(
            FeedWatermarks {
                canonical_tip_slot: None,
                processed_slot: Some(event.slot),
                confirmed_slot: event.confirmed_slot,
                finalized_slot: event.finalized_slot,
            },
            DerivedStateFeedEvent::AccountTouchObserved((tx_index, event).into()),
        );
    }

    /// Emits one transaction-status observation into the derived-state feed.
    pub fn on_transaction_status(&self, event: TransactionStatusEvent) {
        if self.is_empty() {
            return;
        }
        self.dispatch(
            FeedWatermarks {
                canonical_tip_slot: Some(event.slot),
                processed_slot: Some(event.slot),
                confirmed_slot: event.confirmed_slot,
                finalized_slot: event.finalized_slot,
            },
            DerivedStateFeedEvent::TransactionStatusObserved(event.into()),
        );
    }

    /// Emits one block-meta observation into the derived-state feed.
    pub fn on_block_meta(&self, event: BlockMetaEvent) {
        if self.is_empty() {
            return;
        }
        self.dispatch(
            FeedWatermarks {
                canonical_tip_slot: Some(event.slot),
                processed_slot: Some(event.slot),
                confirmed_slot: event.confirmed_slot,
                finalized_slot: event.finalized_slot,
            },
            DerivedStateFeedEvent::BlockMetaObserved(event.into()),
        );
    }

    /// Emits a prebuilt batch of derived-state events using shared watermarks and one dispatch turn.
    pub fn on_events(&self, watermarks: FeedWatermarks, events: Vec<DerivedStateFeedEvent>) {
        if self.is_empty() || events.is_empty() {
            return;
        }
        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let first_sequence = self.reserve_sequence_block(events.len());
        self.dispatch_vec_unlocked(watermarks, dispatch_ticket, first_sequence, events);
    }

    /// Emits one reusable batch of derived-state events and keeps the caller-owned buffer capacity.
    pub fn on_events_drain(
        &self,
        watermarks: FeedWatermarks,
        events: &mut Vec<DerivedStateFeedEvent>,
    ) {
        if self.is_empty() || events.is_empty() {
            return;
        }
        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let first_sequence = self.reserve_sequence_block(events.len());
        let envelopes = self.build_shared_envelopes(
            watermarks,
            events
                .drain(..)
                .enumerate()
                .map(|(index, event)| (sequence_offset(first_sequence, index), event)),
        );
        let last_sequence = envelopes
            .last()
            .map(|envelope| envelope.sequence)
            .unwrap_or(first_sequence);
        self.dispatch_shared_envelopes(&envelopes);
        self.finish_dispatch_turn(dispatch_ticket, last_sequence, watermarks);
    }

    /// Emits one observed recent blockhash record into the derived-state feed.
    pub fn on_recent_blockhash(&self, event: ObservedRecentBlockhashEvent) {
        if self.is_empty() {
            return;
        }
        let slot = event.slot;
        let watermarks = FeedWatermarks {
            canonical_tip_slot: Some(slot),
            processed_slot: Some(slot),
            confirmed_slot: None,
            finalized_slot: None,
        };
        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let mut control_plane_state = self.inner.control_plane_state.clone();
        let mut next_control_plane_state = control_plane_state.shared_get().clone();
        let recent_blockhash_update =
            next_control_plane_state.apply_recent_blockhash(slot, event.recent_blockhash);
        if !recent_blockhash_update.state_changed {
            self.finish_dispatch_turn_without_events(dispatch_ticket, watermarks);
            return;
        }
        let control_plane_event = next_control_plane_state.snapshot(watermarks);
        let invalidation_event = invalidation_from_control_plane_state(
            &mut next_control_plane_state,
            control_plane_event,
        );
        control_plane_state.update(next_control_plane_state);
        let mut events = Vec::with_capacity(3);
        if recent_blockhash_update.hash_changed {
            events.push(DerivedStateFeedEvent::RecentBlockhashObserved(event));
        }
        events.push(DerivedStateFeedEvent::ControlPlaneStateUpdated(
            control_plane_event,
        ));
        if let Some(invalidation_event) = invalidation_event {
            events.push(DerivedStateFeedEvent::StateInvalidated(invalidation_event));
        }
        let first_sequence = self.reserve_sequence_block(events.len());
        self.dispatch_vec_unlocked(watermarks, dispatch_ticket, first_sequence, events);
    }

    /// Emits one cluster topology record into the derived-state feed.
    pub fn on_cluster_topology(&self, event: ClusterTopologyEvent) {
        if self.is_empty() {
            return;
        }
        let slot = event.slot;
        let source = event.source;
        let known_cluster_nodes = if !event.snapshot_nodes.is_empty() {
            event.snapshot_nodes.len()
        } else {
            event.total_nodes
        };
        let watermarks = FeedWatermarks {
            canonical_tip_slot: slot,
            processed_slot: slot,
            confirmed_slot: None,
            finalized_slot: None,
        };
        let wallclock_skew_ms = topology_max_wallclock_skew_ms(&event);
        self.dispatch_with_control_plane_update(
            watermarks,
            DerivedStateFeedEvent::ClusterTopologyChanged(event),
            |state| {
                state.apply_cluster_topology(slot, known_cluster_nodes, source, wallclock_skew_ms)
            },
        );
    }

    /// Emits one leader schedule record into the derived-state feed.
    pub fn on_leader_schedule(&self, event: LeaderScheduleEvent) {
        if self.is_empty() {
            return;
        }
        let slot = event.slot;
        let source = event.source;
        let snapshot_leader_count = event.snapshot_leaders.len();
        let added_leader_count = event.added_leaders.len();
        let removed_slot_count = event.removed_slots.len();
        let watermarks = FeedWatermarks {
            canonical_tip_slot: slot,
            processed_slot: slot,
            confirmed_slot: None,
            finalized_slot: None,
        };
        self.dispatch_with_control_plane_update(
            watermarks,
            DerivedStateFeedEvent::LeaderScheduleUpdated(event),
            |state| {
                state.apply_leader_schedule(
                    slot,
                    snapshot_leader_count,
                    added_leader_count,
                    removed_slot_count,
                    source,
                )
            },
        );
    }

    /// Emits one slot-status change record into the derived-state feed.
    pub fn on_slot_status(&self, event: SlotStatusEvent) {
        if self.is_empty() {
            return;
        }
        if matches!(
            event.status,
            ForkSlotStatus::Finalized | ForkSlotStatus::Orphaned
        ) {
            let mut slot_tx_indexes = self
                .inner
                .slot_tx_indexes
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let _ = slot_tx_indexes.remove(&event.slot);
        }
        let watermarks = FeedWatermarks::from_slot_status(&event);
        self.dispatch_with_control_plane_update(
            watermarks,
            DerivedStateFeedEvent::SlotStatusChanged(event.into()),
            |_| {},
        );
    }

    /// Emits one canonical branch reorg record into the derived-state feed.
    pub fn on_reorg(&self, event: ReorgEvent) {
        if self.is_empty() {
            return;
        }
        let watermarks = FeedWatermarks::from_reorg(&event);
        let detached_slots = event.detached_slots.clone();
        let branch_event = BranchReorgedEvent::from(event);
        self.dispatch_many(
            watermarks,
            [
                DerivedStateFeedEvent::BranchReorged(branch_event),
                DerivedStateFeedEvent::StateInvalidated(DerivedStateInvalidationEvent {
                    reason: DerivedStateInvalidationReason::Reorg,
                    detached_slots,
                    control_plane_quality: None,
                }),
            ],
        );
    }

    /// Emits one externally computed invalidation event.
    pub fn on_state_invalidation(
        &self,
        watermarks: FeedWatermarks,
        event: DerivedStateInvalidationEvent,
    ) {
        if self.is_empty() {
            return;
        }
        self.dispatch(watermarks, DerivedStateFeedEvent::StateInvalidated(event));
    }

    /// Emits one tx outcome event supplied by a higher-level service.
    pub fn on_tx_outcome(&self, watermarks: FeedWatermarks, event: DerivedStateTxOutcomeEvent) {
        if self.is_empty() {
            return;
        }
        self.dispatch(watermarks, DerivedStateFeedEvent::TxOutcomeObserved(event));
    }

    /// Emits a checkpoint barrier and flushes durable checkpoints for all consumers.
    pub fn emit_checkpoint_barrier(
        &self,
        reason: CheckpointBarrierReason,
        watermarks: FeedWatermarks,
    ) {
        if self.is_empty() {
            return;
        }

        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let sequence = self.reserve_sequence_block(1);
        let envelope = DerivedStateFeedEnvelope {
            session_id: self.inner.session_id,
            sequence,
            emitted_at: SystemTime::now(),
            watermarks,
            event: DerivedStateFeedEvent::CheckpointBarrier(CheckpointBarrierEvent {
                barrier_sequence: sequence,
                reason,
            }),
        };
        if let Some(replay_source) = self.replay_source() {
            replay_source.append(envelope.clone());
        }
        let envelope = Arc::new(envelope);

        for registered in self.inner.consumers.iter() {
            if registered.is_unhealthy() {
                continue;
            }
            if !registered.accepts_event(&envelope.event) {
                continue;
            }
            if let Err(fault) = registered.worker.flush_checkpoint(
                envelope.clone(),
                self.inner.session_id,
                watermarks,
            ) {
                self.record_consumer_fault(registered, &fault);
                continue;
            }
            registered.note_applied(sequence);
            registered.note_checkpoint_flush();
        }
        self.finish_dispatch_turn(dispatch_ticket, sequence, watermarks);
    }

    /// Emits a shutdown checkpoint barrier using the latest runtime watermarks.
    pub fn emit_shutdown_checkpoint_barrier(&self, watermarks: FeedWatermarks) {
        self.emit_checkpoint_barrier(CheckpointBarrierReason::ShutdownRequested, watermarks);
    }

    /// Builds one feed envelope and dispatches it to every registered consumer.
    fn dispatch(&self, watermarks: FeedWatermarks, event: DerivedStateFeedEvent) {
        self.dispatch_many(watermarks, [event]);
    }

    /// Emits one primary event plus the current control-plane quality snapshot.
    fn dispatch_with_control_plane_update<F>(
        &self,
        watermarks: FeedWatermarks,
        primary_event: DerivedStateFeedEvent,
        update_state: F,
    ) where
        F: FnOnce(&mut DerivedStateControlPlaneTracker),
    {
        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let mut control_plane_state = self.inner.control_plane_state.clone();
        let mut next_control_plane_state = control_plane_state.shared_get().clone();
        update_state(&mut next_control_plane_state);
        let control_plane_event = next_control_plane_state.snapshot(watermarks);
        let invalidation_event = invalidation_from_control_plane_state(
            &mut next_control_plane_state,
            control_plane_event,
        );
        control_plane_state.update(next_control_plane_state);
        let events = if let Some(invalidation_event) = invalidation_event {
            vec![
                primary_event,
                DerivedStateFeedEvent::ControlPlaneStateUpdated(control_plane_event),
                DerivedStateFeedEvent::StateInvalidated(invalidation_event),
            ]
        } else {
            vec![
                primary_event,
                DerivedStateFeedEvent::ControlPlaneStateUpdated(control_plane_event),
            ]
        };
        let first_sequence = self.reserve_sequence_block(events.len());
        self.dispatch_vec_unlocked(watermarks, dispatch_ticket, first_sequence, events);
    }

    /// Emits a fixed batch of feed events while preserving global sequence order.
    fn dispatch_many<const N: usize>(
        &self,
        watermarks: FeedWatermarks,
        events: [DerivedStateFeedEvent; N],
    ) {
        let dispatch_ticket = self.reserve_dispatch_ticket();
        self.wait_for_dispatch_turn(dispatch_ticket);
        let first_sequence = self.reserve_sequence_block(N);
        self.dispatch_many_unlocked(watermarks, dispatch_ticket, first_sequence, events);
    }

    /// Emits a fixed batch of feed events after the caller acquired dispatch order.
    fn dispatch_many_unlocked<const N: usize>(
        &self,
        watermarks: FeedWatermarks,
        dispatch_ticket: u64,
        first_sequence: FeedSequence,
        events: [DerivedStateFeedEvent; N],
    ) {
        let envelopes = self.build_shared_envelopes(
            watermarks,
            events
                .into_iter()
                .enumerate()
                .map(|(index, event)| (sequence_offset(first_sequence, index), event)),
        );
        let last_sequence = envelopes
            .last()
            .map(|envelope| envelope.sequence)
            .unwrap_or(first_sequence);
        self.dispatch_shared_envelopes(&envelopes);
        self.finish_dispatch_turn(dispatch_ticket, last_sequence, watermarks);
    }

    /// Emits an owned event list after the caller acquired dispatch order.
    fn dispatch_vec_unlocked(
        &self,
        watermarks: FeedWatermarks,
        dispatch_ticket: u64,
        first_sequence: FeedSequence,
        events: Vec<DerivedStateFeedEvent>,
    ) {
        let envelopes = self.build_shared_envelopes(
            watermarks,
            events
                .into_iter()
                .enumerate()
                .map(|(index, event)| (sequence_offset(first_sequence, index), event)),
        );
        let last_sequence = envelopes
            .last()
            .map(|envelope| envelope.sequence)
            .unwrap_or(first_sequence);
        self.dispatch_shared_envelopes(&envelopes);
        self.finish_dispatch_turn(dispatch_ticket, last_sequence, watermarks);
    }

    /// Builds shared feed envelopes for one reserved publish batch.
    fn build_shared_envelopes<I>(
        &self,
        watermarks: FeedWatermarks,
        events: I,
    ) -> Arc<Vec<DerivedStateFeedEnvelope>>
    where
        I: IntoIterator<Item = (FeedSequence, DerivedStateFeedEvent)>,
    {
        let emitted_at = SystemTime::now();
        let mut envelopes = Vec::new();
        for (sequence, event) in events {
            let envelope = DerivedStateFeedEnvelope {
                session_id: self.inner.session_id,
                sequence,
                emitted_at,
                watermarks,
                event,
            };
            envelopes.push(envelope);
        }
        let shared = Arc::new(envelopes);
        if let Some(replay_source) = self.replay_source() {
            replay_source.append_shared_batch(shared.as_slice());
        }
        shared
    }

    /// Dispatches one shared publish batch to every registered consumer.
    fn dispatch_shared_envelopes(&self, envelopes: &Arc<Vec<DerivedStateFeedEnvelope>>) {
        let universally_delivered = envelopes
            .iter()
            .all(|envelope| envelope.event.is_universally_delivered());
        let mut pending = Vec::with_capacity(self.inner.consumers.len());
        for registered in self.inner.consumers.iter() {
            if registered.is_unhealthy() {
                continue;
            }
            let batch = if universally_delivered || registered.accepts_all_events() {
                SharedDerivedStateEnvelopeBatch::Full(Arc::clone(envelopes))
            } else {
                let indexes: Vec<_> = envelopes
                    .iter()
                    .enumerate()
                    .filter_map(|(index, envelope)| {
                        registered.accepts_event(&envelope.event).then_some(index)
                    })
                    .collect();
                if indexes.is_empty() {
                    continue;
                }
                SharedDerivedStateEnvelopeBatch::Indexed {
                    envelopes: Arc::clone(envelopes),
                    indexes,
                }
            };
            let reply = match registered.worker.begin_apply_shared_batch(batch) {
                Ok(last_sequence) => {
                    pending.push((registered, last_sequence));
                    continue;
                }
                Err(reply) => reply,
            };
            registered.note_applied_batch(reply.applied_events, reply.last_sequence);
            if let Some(fault) = reply.fault.as_ref() {
                self.record_consumer_fault(registered, fault);
            }
        }
        for (registered, last_sequence) in pending {
            let reply = registered
                .worker
                .recv_apply_shared_batch_reply(last_sequence);
            registered.note_applied_batch(reply.applied_events, reply.last_sequence);
            if let Some(fault) = reply.fault.as_ref() {
                self.record_consumer_fault(registered, fault);
            }
        }
    }

    /// Records the latest emitted sequence and watermarks for recovery bookkeeping.
    fn note_emitted_sequence(&self, sequence: FeedSequence, watermarks: FeedWatermarks) {
        self.inner
            .last_sequence
            .store(sequence.0, Ordering::Relaxed);
        self.inner.has_last_sequence.store(true, Ordering::Relaxed);
        self.inner.last_watermarks.store(watermarks);
    }

    /// Reserves one global dispatch ticket for one publish batch.
    fn reserve_dispatch_ticket(&self) -> u64 {
        self.inner
            .next_dispatch_ticket
            .fetch_add(1, Ordering::Relaxed)
    }

    /// Reserves one contiguous sequence range for one dispatch batch.
    fn reserve_sequence_block(&self, event_count: usize) -> FeedSequence {
        let event_count = u64::try_from(event_count).unwrap_or(1).max(1);
        FeedSequence(
            self.inner
                .next_sequence
                .fetch_add(event_count, Ordering::Relaxed),
        )
    }

    /// Waits until earlier dispatch batches have published their reserved range.
    fn wait_for_dispatch_turn(&self, dispatch_ticket: u64) {
        let mut spins = 0_u32;
        while self.inner.dispatch_ticket_cursor.load(Ordering::Acquire) != dispatch_ticket {
            std::hint::spin_loop();
            spins = spins.saturating_add(1);
            if spins.is_multiple_of(1_024) {
                std::thread::yield_now();
            }
        }
    }

    /// Marks one reserved dispatch batch as fully published.
    fn finish_dispatch_turn(
        &self,
        dispatch_ticket: u64,
        last_sequence: FeedSequence,
        watermarks: FeedWatermarks,
    ) {
        self.note_emitted_sequence(last_sequence, watermarks);
        self.inner
            .dispatch_ticket_cursor
            .store(dispatch_ticket.saturating_add(1), Ordering::Release);
    }

    /// Marks one reserved dispatch batch as complete when it emitted no feed events.
    fn finish_dispatch_turn_without_events(
        &self,
        dispatch_ticket: u64,
        watermarks: FeedWatermarks,
    ) {
        self.inner.last_watermarks.store(watermarks);
        self.inner
            .dispatch_ticket_cursor
            .store(dispatch_ticket.saturating_add(1), Ordering::Release);
    }

    /// Records one consumer fault for telemetry and structured logs.
    fn record_consumer_fault(
        &self,
        registered: &RegisteredDerivedStateConsumer,
        fault: &DerivedStateConsumerFault,
    ) {
        let _ = self.inner.fault_count.fetch_add(1, Ordering::Relaxed);
        registered.note_fault(fault.sequence);
        registered.note_fault_kind(fault.kind);
        if fault.kind.breaks_live_continuity() {
            registered.set_recovery_state(match fault.kind {
                DerivedStateConsumerFaultKind::ReplayGap => {
                    DerivedStateConsumerRecoveryState::RebuildRequired
                }
                DerivedStateConsumerFaultKind::LagExceeded
                | DerivedStateConsumerFaultKind::QueueOverflow
                | DerivedStateConsumerFaultKind::ConsumerApplyFailed => {
                    DerivedStateConsumerRecoveryState::ReplayRecoveryPending
                }
                DerivedStateConsumerFaultKind::CheckpointWriteFailed => {
                    DerivedStateConsumerRecoveryState::Live
                }
            });
        }
        if fault.kind.breaks_live_continuity() && registered.mark_unhealthy() {
            tracing::warn!(
                consumer = registered.name,
                ?fault.kind,
                sequence = ?fault.sequence,
                recovery_state = ?registered.recovery_state(),
                "derived-state consumer marked unhealthy"
            );
        }
        tracing::warn!(
            consumer = registered.name,
            ?fault.kind,
            sequence = ?fault.sequence,
            message = %fault.message,
            "derived-state consumer fault"
        );
    }
}

/// Shared dispatch state for one immutable derived-state host.
struct DerivedStateHostInner {
    /// Registered consumers in dispatch order.
    consumers: Arc<[RegisteredDerivedStateConsumer]>,
    /// Monotonic session id assigned when the host is built.
    session_id: FeedSessionId,
    /// Optional retained replay source used during checkpoint resume.
    replay_source: Option<Arc<dyn DerivedStateReplaySource>>,
    /// Runtime-installed replay source used when the builder did not configure one.
    runtime_replay_source: OnceLock<Arc<dyn DerivedStateReplaySource>>,
    /// Next dispatch ticket currently allowed to publish into the feed.
    dispatch_ticket_cursor: AtomicU64,
    /// Next dispatch ticket assigned to a publish batch.
    next_dispatch_ticket: AtomicU64,
    /// Next sequence number assigned to emitted feed envelopes.
    next_sequence: AtomicU64,
    /// Highest emitted sequence when one exists.
    last_sequence: AtomicU64,
    /// Whether `last_sequence` is initialized.
    has_last_sequence: AtomicBool,
    /// Latest runtime watermarks observed by the host.
    last_watermarks: AtomicFeedWatermarks,
    /// Control-plane tracker state shared by control-plane update paths.
    control_plane_state: ArcShift<DerivedStateControlPlaneTracker>,
    /// Total number of structured faults recorded across all consumers.
    fault_count: AtomicU64,
    /// Ensures checkpoint loading runs only once per host.
    initialized: AtomicBool,
    /// Per-slot transaction indexes used to stabilize event ordering.
    slot_tx_indexes: Mutex<HashMap<u64, u32>>,
}

/// Atomically published watermarks snapshot shared across dispatch paths.
struct AtomicFeedWatermarks {
    /// Last canonical tip slot, or unset sentinel.
    canonical_tip_slot: AtomicU64,
    /// Last processed slot, or unset sentinel.
    processed_slot: AtomicU64,
    /// Last confirmed slot, or unset sentinel.
    confirmed_slot: AtomicU64,
    /// Last finalized slot, or unset sentinel.
    finalized_slot: AtomicU64,
}

impl AtomicFeedWatermarks {
    /// Sentinel encoding for absent optional watermarks.
    const UNSET: u64 = u64::MAX;

    /// Loads the current atomically published watermark snapshot.
    fn load(&self) -> FeedWatermarks {
        FeedWatermarks {
            canonical_tip_slot: decode_optional_u64(
                self.canonical_tip_slot.load(Ordering::Relaxed),
            ),
            processed_slot: decode_optional_u64(self.processed_slot.load(Ordering::Relaxed)),
            confirmed_slot: decode_optional_u64(self.confirmed_slot.load(Ordering::Relaxed)),
            finalized_slot: decode_optional_u64(self.finalized_slot.load(Ordering::Relaxed)),
        }
    }

    /// Stores a new atomically published watermark snapshot.
    fn store(&self, watermarks: FeedWatermarks) {
        self.canonical_tip_slot.store(
            encode_optional_u64(watermarks.canonical_tip_slot),
            Ordering::Relaxed,
        );
        self.processed_slot.store(
            encode_optional_u64(watermarks.processed_slot),
            Ordering::Relaxed,
        );
        self.confirmed_slot.store(
            encode_optional_u64(watermarks.confirmed_slot),
            Ordering::Relaxed,
        );
        self.finalized_slot.store(
            encode_optional_u64(watermarks.finalized_slot),
            Ordering::Relaxed,
        );
    }
}

impl Default for AtomicFeedWatermarks {
    fn default() -> Self {
        Self {
            canonical_tip_slot: AtomicU64::new(Self::UNSET),
            processed_slot: AtomicU64::new(Self::UNSET),
            confirmed_slot: AtomicU64::new(Self::UNSET),
            finalized_slot: AtomicU64::new(Self::UNSET),
        }
    }
}

/// Encodes optional watermark fields into an atomic-friendly sentinel form.
fn encode_optional_u64(value: Option<u64>) -> u64 {
    value.unwrap_or(AtomicFeedWatermarks::UNSET)
}

/// Decodes optional watermark fields from the atomic sentinel representation.
fn decode_optional_u64(value: u64) -> Option<u64> {
    (value != AtomicFeedWatermarks::UNSET).then_some(value)
}

/// Computes one sequence inside a reserved contiguous dispatch block.
fn sequence_offset(first_sequence: FeedSequence, offset: usize) -> FeedSequence {
    let offset = u64::try_from(offset).unwrap_or(0);
    FeedSequence(first_sequence.0.saturating_add(offset))
}

/// Observer-side control-plane tracker used to classify feed freshness and quality.
#[derive(Debug, Clone, Default)]
struct DerivedStateControlPlaneTracker {
    /// Slot of the most recent recent-blockhash observation.
    recent_blockhash_slot: Option<u64>,
    /// Latest observed recent blockhash bytes when known.
    recent_blockhash: Option<[u8; 32]>,
    /// Slot of the most recent cluster-topology update.
    cluster_topology_slot: Option<u64>,
    /// Slot of the most recent leader-schedule update.
    leader_schedule_slot: Option<u64>,
    /// Number of nodes visible in the latest cluster-topology snapshot.
    known_cluster_nodes: usize,
    /// Number of leader slots visible in the latest leader-schedule snapshot.
    known_leader_slots: usize,
    /// Source of the latest cluster-topology update.
    cluster_topology_source: Option<ControlPlaneSource>,
    /// Source of the latest leader-schedule update.
    leader_schedule_source: Option<ControlPlaneSource>,
    /// Maximum wallclock skew observed across the latest topology payload.
    cluster_topology_max_wallclock_skew_ms: Option<u64>,
    /// Number of source or slot conflicts seen in this host session.
    conflict_count: u64,
    /// Last emitted quality used for invalidation transitions.
    last_quality: Option<DerivedStateControlPlaneQuality>,
}

#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
/// Outcome flags returned after applying one recent-blockhash observation.
struct RecentBlockhashUpdate {
    /// Whether the tracked recent blockhash changed.
    hash_changed: bool,
    /// Whether any tracked control-plane field changed.
    state_changed: bool,
}

impl DerivedStateControlPlaneTracker {
    /// Updates the tracker from one recent-blockhash observation.
    fn apply_recent_blockhash(
        &mut self,
        slot: u64,
        recent_blockhash: [u8; 32],
    ) -> RecentBlockhashUpdate {
        if self
            .recent_blockhash_slot
            .is_some_and(|previous_slot| slot < previous_slot)
        {
            self.conflict_count = self.conflict_count.saturating_add(1);
            return RecentBlockhashUpdate {
                hash_changed: false,
                state_changed: true,
            };
        }
        let slot_changed = self.recent_blockhash_slot != Some(slot);
        let hash_changed = self.recent_blockhash != Some(recent_blockhash);
        self.recent_blockhash_slot = Some(slot);
        self.recent_blockhash = Some(recent_blockhash);
        RecentBlockhashUpdate {
            hash_changed,
            state_changed: slot_changed || hash_changed,
        }
    }

    /// Updates the tracker from one cluster-topology observation.
    fn apply_cluster_topology(
        &mut self,
        slot: Option<u64>,
        known_cluster_nodes: usize,
        source: ControlPlaneSource,
        wallclock_skew_ms: Option<u64>,
    ) {
        if let Some(slot) = slot {
            if self
                .cluster_topology_slot
                .is_some_and(|previous| slot < previous)
            {
                self.conflict_count = self.conflict_count.saturating_add(1);
            }
            self.cluster_topology_slot = Some(slot);
        }
        if self
            .cluster_topology_source
            .is_some_and(|previous| previous != source)
        {
            self.conflict_count = self.conflict_count.saturating_add(1);
        }
        self.known_cluster_nodes = known_cluster_nodes;
        self.cluster_topology_source = Some(source);
        self.cluster_topology_max_wallclock_skew_ms = wallclock_skew_ms;
    }

    /// Updates the tracker from one leader-schedule observation.
    fn apply_leader_schedule(
        &mut self,
        slot: Option<u64>,
        snapshot_leader_count: usize,
        added_leader_count: usize,
        removed_slot_count: usize,
        source: ControlPlaneSource,
    ) {
        if let Some(slot) = slot {
            if self
                .leader_schedule_slot
                .is_some_and(|previous| slot < previous)
            {
                self.conflict_count = self.conflict_count.saturating_add(1);
            }
            self.leader_schedule_slot = Some(slot);
        }
        if self
            .leader_schedule_source
            .is_some_and(|previous| previous != source)
        {
            self.conflict_count = self.conflict_count.saturating_add(1);
        }
        self.known_leader_slots = if snapshot_leader_count > 0 {
            snapshot_leader_count
        } else {
            self.known_leader_slots
                .saturating_add(added_leader_count)
                .saturating_sub(removed_slot_count)
        };
        self.leader_schedule_source = Some(source);
    }

    /// Builds the canonical control-plane state snapshot for one watermark boundary.
    fn snapshot(&self, watermarks: FeedWatermarks) -> DerivedStateControlPlaneStateEvent {
        let tip_slot = watermarks.canonical_tip_slot.or(watermarks.processed_slot);
        let recent_blockhash_freshness = classify_control_plane_freshness(
            self.recent_blockhash_slot,
            tip_slot,
            CONTROL_PLANE_MAX_RECENT_BLOCKHASH_SLOT_LAG,
        );
        let cluster_topology_freshness = classify_control_plane_freshness(
            self.cluster_topology_slot,
            tip_slot,
            CONTROL_PLANE_MAX_CLUSTER_TOPOLOGY_SLOT_LAG,
        );
        let leader_schedule_freshness = classify_control_plane_freshness(
            self.leader_schedule_slot,
            tip_slot,
            CONTROL_PLANE_MAX_LEADER_SCHEDULE_SLOT_LAG,
        );
        let control_plane_slot_spread = control_plane_slot_spread(
            self.recent_blockhash_slot,
            self.cluster_topology_slot,
            self.leader_schedule_slot,
        );
        let inputs_aligned = control_plane_slot_spread
            .map(|spread| spread <= CONTROL_PLANE_MAX_SLOT_SPREAD)
            .unwrap_or(true);
        let quality = classify_control_plane_quality(
            recent_blockhash_freshness,
            cluster_topology_freshness,
            leader_schedule_freshness,
            inputs_aligned,
            tip_slot,
            watermarks,
        );
        let strategy_safe = matches!(quality, DerivedStateControlPlaneQuality::Stable);

        DerivedStateControlPlaneStateEvent {
            recent_blockhash_slot: self.recent_blockhash_slot,
            cluster_topology_slot: self.cluster_topology_slot,
            leader_schedule_slot: self.leader_schedule_slot,
            tip_slot,
            known_cluster_nodes: self.known_cluster_nodes,
            known_leader_slots: self.known_leader_slots,
            cluster_topology_source: self.cluster_topology_source,
            leader_schedule_source: self.leader_schedule_source,
            cluster_topology_max_wallclock_skew_ms: self.cluster_topology_max_wallclock_skew_ms,
            recent_blockhash_freshness,
            cluster_topology_freshness,
            leader_schedule_freshness,
            control_plane_slot_spread,
            inputs_aligned,
            strategy_safe,
            conflicts_detected: self.conflict_count > 0,
            conflict_count: self.conflict_count,
            quality,
        }
    }
}

/// Classifies one observer-side control-plane input against the built-in freshness budget.
const fn classify_control_plane_freshness(
    observed_slot: Option<u64>,
    tip_slot: Option<u64>,
    max_allowed_slot_lag: u64,
) -> DerivedStateInputFreshness {
    let slot_lag = match (observed_slot, tip_slot) {
        (Some(observed), Some(tip)) => Some(tip.saturating_sub(observed)),
        _ => None,
    };
    let state = match (observed_slot, tip_slot, slot_lag) {
        (None, _, _) => DerivedStateFreshnessState::Missing,
        (Some(_), None, _) => DerivedStateFreshnessState::Unknown,
        (Some(_), Some(_), Some(slot_lag)) if slot_lag > max_allowed_slot_lag => {
            DerivedStateFreshnessState::Stale
        }
        (Some(_), Some(_), _) => DerivedStateFreshnessState::Fresh,
    };

    DerivedStateInputFreshness {
        observed_slot,
        tip_slot,
        slot_lag,
        max_allowed_slot_lag: Some(max_allowed_slot_lag),
        state,
    }
}

/// Returns the spread across observed control-plane input slots when at least two inputs exist.
fn control_plane_slot_spread(
    recent_blockhash_slot: Option<u64>,
    cluster_topology_slot: Option<u64>,
    leader_schedule_slot: Option<u64>,
) -> Option<u64> {
    let mut slots = [
        recent_blockhash_slot,
        cluster_topology_slot,
        leader_schedule_slot,
    ]
    .into_iter()
    .flatten();
    let first = slots.next()?;
    let (min_slot, max_slot) = slots.fold((first, first), |(min_slot, max_slot), slot| {
        (min_slot.min(slot), max_slot.max(slot))
    });
    Some(max_slot.saturating_sub(min_slot))
}

/// Classifies the observer-side control plane from per-input freshness and alignment state.
fn classify_control_plane_quality(
    recent_blockhash_freshness: DerivedStateInputFreshness,
    cluster_topology_freshness: DerivedStateInputFreshness,
    leader_schedule_freshness: DerivedStateInputFreshness,
    inputs_aligned: bool,
    tip_slot: Option<u64>,
    watermarks: FeedWatermarks,
) -> DerivedStateControlPlaneQuality {
    if tip_slot.is_none()
        || matches!(
            recent_blockhash_freshness.state,
            DerivedStateFreshnessState::Missing
        )
        || matches!(
            cluster_topology_freshness.state,
            DerivedStateFreshnessState::Missing
        )
        || matches!(
            leader_schedule_freshness.state,
            DerivedStateFreshnessState::Missing
        )
    {
        return DerivedStateControlPlaneQuality::IncompleteControlPlane;
    }

    if matches!(
        recent_blockhash_freshness.state,
        DerivedStateFreshnessState::Stale
    ) || matches!(
        cluster_topology_freshness.state,
        DerivedStateFreshnessState::Stale
    ) || matches!(
        leader_schedule_freshness.state,
        DerivedStateFreshnessState::Stale
    ) {
        return DerivedStateControlPlaneQuality::Stale;
    }

    if !inputs_aligned {
        return DerivedStateControlPlaneQuality::Degraded;
    }

    if watermarks.finalized_slot != tip_slot {
        if watermarks.confirmed_slot == tip_slot {
            return DerivedStateControlPlaneQuality::Provisional;
        }
        return DerivedStateControlPlaneQuality::ReorgRisk;
    }

    DerivedStateControlPlaneQuality::Stable
}

/// Emits an invalidation when control-plane quality transitions into an unsafe state.
fn invalidation_from_control_plane_state(
    tracker: &mut DerivedStateControlPlaneTracker,
    state: DerivedStateControlPlaneStateEvent,
) -> Option<DerivedStateInvalidationEvent> {
    let previous_quality = tracker.last_quality.replace(state.quality);
    let became_unsafe = !state.strategy_safe
        && previous_quality
            .is_none_or(|previous| previous == DerivedStateControlPlaneQuality::Stable);
    if became_unsafe {
        Some(DerivedStateInvalidationEvent {
            reason: DerivedStateInvalidationReason::ControlPlaneUnsafe,
            detached_slots: Vec::new(),
            control_plane_quality: Some(state.quality),
        })
    } else {
        None
    }
}

/// Returns the maximum wallclock skew across topology nodes when present.
fn topology_max_wallclock_skew_ms(event: &ClusterTopologyEvent) -> Option<u64> {
    let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
    event
        .snapshot_nodes
        .iter()
        .chain(event.added_nodes.iter())
        .chain(event.updated_nodes.iter())
        .map(|node| now_secs.abs_diff(node.wallclock).saturating_mul(1_000))
        .max()
}

/// Consumer registration entry stored by the host.
struct RegisteredDerivedStateConsumer {
    /// Stable consumer name used in logs and telemetry.
    name: &'static str,
    /// Dedicated worker that owns the consumer and preserves callback order without a mutex.
    worker: DerivedStateConsumerWorker,
    /// Immutable event-interest bitmap so ignored event classes never lock/apply.
    subscriptions: DerivedStateConsumerSubscriptions,
    /// Whether the consumer has lost live continuity and should stop receiving events.
    unhealthy: AtomicBool,
    /// Current recovery state for this consumer.
    recovery_state: AtomicU8,
    /// Total number of successfully applied envelopes.
    applied_events: AtomicU64,
    /// Total number of successfully flushed checkpoints.
    checkpoint_flushes: AtomicU64,
    /// Total number of structured faults recorded for the consumer.
    fault_count: AtomicU64,
    /// Highest applied sequence number when one exists.
    last_applied_sequence: AtomicU64,
    /// Whether `last_applied_sequence` is initialized.
    has_last_applied_sequence: AtomicBool,
    /// Highest fault-associated sequence number when one exists.
    last_fault_sequence: AtomicU64,
    /// Whether `last_fault_sequence` is initialized.
    has_last_fault_sequence: AtomicBool,
    /// Last structured fault kind when one exists.
    last_fault_kind: AtomicU8,
    /// Whether `last_fault_kind` is initialized.
    has_last_fault_kind: AtomicBool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
/// Per-consumer subscription bitmap for selectively routing derived-state feed events.
struct DerivedStateConsumerSubscriptions {
    /// Whether the consumer wants `TransactionApplied` events.
    transaction_applied: bool,
    /// Whether the consumer wants `TransactionStatusObserved` events.
    transaction_status_observed: bool,
    /// Whether the consumer wants `BlockMetaObserved` events.
    block_meta_observed: bool,
    /// Whether the consumer wants `AccountTouchObserved` events.
    account_touch_observed: bool,
    /// Whether the consumer wants partitioned account-touch key sets.
    account_touch_key_partitions: bool,
    /// Whether the consumer wants control-plane feed events.
    control_plane_observed: bool,
}

impl RegisteredDerivedStateConsumer {
    /// Returns whether the consumer accepts every derived-state event kind.
    #[must_use]
    const fn accepts_all_events(&self) -> bool {
        self.subscriptions.transaction_applied
            && self.subscriptions.transaction_status_observed
            && self.subscriptions.block_meta_observed
            && self.subscriptions.account_touch_observed
            && self.subscriptions.control_plane_observed
    }

    /// Returns whether this consumer has lost live continuity.
    #[must_use]
    fn is_unhealthy(&self) -> bool {
        self.unhealthy.load(Ordering::Acquire)
    }

    /// Returns the current recovery state for this consumer.
    #[must_use]
    fn recovery_state(&self) -> DerivedStateConsumerRecoveryState {
        DerivedStateConsumerRecoveryState::from_u8(self.recovery_state.load(Ordering::Acquire))
    }

    /// Returns whether the consumer should receive the provided feed event.
    #[must_use]
    const fn accepts_event(&self, event: &DerivedStateFeedEvent) -> bool {
        match event {
            DerivedStateFeedEvent::TransactionApplied(_) => self.subscriptions.transaction_applied,
            DerivedStateFeedEvent::TransactionStatusObserved(_) => {
                self.subscriptions.transaction_status_observed
            }
            DerivedStateFeedEvent::BlockMetaObserved(_) => self.subscriptions.block_meta_observed,
            DerivedStateFeedEvent::AccountTouchObserved(_) => {
                self.subscriptions.account_touch_observed
            }
            DerivedStateFeedEvent::RecentBlockhashObserved(_)
            | DerivedStateFeedEvent::ClusterTopologyChanged(_)
            | DerivedStateFeedEvent::LeaderScheduleUpdated(_)
            | DerivedStateFeedEvent::ControlPlaneStateUpdated(_)
            | DerivedStateFeedEvent::StateInvalidated(_)
            | DerivedStateFeedEvent::TxOutcomeObserved(_) => {
                self.subscriptions.control_plane_observed
            }
            DerivedStateFeedEvent::SlotStatusChanged(_)
            | DerivedStateFeedEvent::BranchReorged(_)
            | DerivedStateFeedEvent::CheckpointBarrier(_) => true,
        }
    }

    /// Marks the consumer unhealthy and returns whether the state changed.
    #[must_use]
    fn mark_unhealthy(&self) -> bool {
        !self.unhealthy.swap(true, Ordering::AcqRel)
    }

    /// Marks the consumer healthy after successful recovery.
    fn mark_live(&self) {
        self.unhealthy.store(false, Ordering::Release);
        self.recovery_state.store(
            DerivedStateConsumerRecoveryState::Live.into_u8(),
            Ordering::Release,
        );
    }

    /// Records one recovery state transition.
    fn set_recovery_state(&self, state: DerivedStateConsumerRecoveryState) {
        self.recovery_state
            .store(state.into_u8(), Ordering::Release);
    }

    /// Records one successful envelope application.
    fn note_applied(&self, sequence: FeedSequence) {
        let _ = self.applied_events.fetch_add(1, Ordering::Relaxed);
        self.last_applied_sequence
            .store(sequence.0, Ordering::Release);
        self.has_last_applied_sequence
            .store(true, Ordering::Release);
        if !self.is_unhealthy() {
            self.set_recovery_state(DerivedStateConsumerRecoveryState::Live);
        }
    }

    /// Records a batch of successfully applied envelopes.
    fn note_applied_batch(&self, applied_events: u64, last_sequence: Option<FeedSequence>) {
        let _ = self
            .applied_events
            .fetch_add(applied_events, Ordering::Relaxed);
        if let Some(sequence) = last_sequence {
            self.last_applied_sequence
                .store(sequence.0, Ordering::Release);
            self.has_last_applied_sequence
                .store(true, Ordering::Release);
        }
        if applied_events > 0 && !self.is_unhealthy() {
            self.set_recovery_state(DerivedStateConsumerRecoveryState::Live);
        }
    }

    /// Records one successful recovery to an already-applied checkpoint boundary.
    fn note_recovered_checkpoint(&self, sequence: FeedSequence) {
        self.last_applied_sequence
            .store(sequence.0, Ordering::Release);
        self.has_last_applied_sequence
            .store(true, Ordering::Release);
        self.mark_live();
    }

    /// Records one successful checkpoint flush.
    fn note_checkpoint_flush(&self) {
        let _ = self.checkpoint_flushes.fetch_add(1, Ordering::Relaxed);
    }

    /// Records one structured consumer fault.
    fn note_fault(&self, sequence: Option<FeedSequence>) {
        let _ = self.fault_count.fetch_add(1, Ordering::Relaxed);
        if let Some(sequence) = sequence {
            self.last_fault_sequence
                .store(sequence.0, Ordering::Release);
            self.has_last_fault_sequence.store(true, Ordering::Release);
        }
    }

    /// Records the last fault kind for telemetry.
    fn note_fault_kind(&self, kind: DerivedStateConsumerFaultKind) {
        self.last_fault_kind
            .store(kind.into_u8(), Ordering::Release);
        self.has_last_fault_kind.store(true, Ordering::Release);
    }

    /// Builds a point-in-time telemetry snapshot for this consumer.
    #[must_use]
    fn telemetry(&self) -> DerivedStateConsumerTelemetry {
        DerivedStateConsumerTelemetry {
            name: self.name,
            unhealthy: self.is_unhealthy(),
            recovery_state: self.recovery_state(),
            applied_events: self.applied_events.load(Ordering::Relaxed),
            checkpoint_flushes: self.checkpoint_flushes.load(Ordering::Relaxed),
            fault_count: self.fault_count.load(Ordering::Relaxed),
            last_applied_sequence: self
                .has_last_applied_sequence
                .load(Ordering::Acquire)
                .then(|| FeedSequence(self.last_applied_sequence.load(Ordering::Acquire))),
            last_fault_sequence: self
                .has_last_fault_sequence
                .load(Ordering::Acquire)
                .then(|| FeedSequence(self.last_fault_sequence.load(Ordering::Acquire))),
            last_fault_kind: self.has_last_fault_kind.load(Ordering::Acquire).then(|| {
                DerivedStateConsumerFaultKind::from_u8(self.last_fault_kind.load(Ordering::Acquire))
            }),
        }
    }
}

/// Generates a best-effort unique session id for one process lifetime.
fn generate_session_id() -> FeedSessionId {
    let now_nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0_u128, |duration| duration.as_nanos());
    let pid = u128::from(std::process::id());
    FeedSessionId(now_nanos ^ pid)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::framework::{ClusterNodeInfo, ControlPlaneSource, LeaderScheduleEntry};
    use solana_signature::Signature;
    use std::{
        env, fs,
        net::SocketAddr,
        path::PathBuf,
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering as AtomicOrdering},
        },
        thread,
    };

    fn unique_test_replay_dir(name: &str) -> PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map_or(0_u128, |duration| duration.as_nanos());
        env::temp_dir().join(format!(
            "sof-derived-state-{name}-{}-{unique}",
            std::process::id()
        ))
    }

    fn unique_test_checkpoint_path(name: &str) -> PathBuf {
        unique_test_replay_dir(name).join("checkpoint.json")
    }

    #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
    struct TestCheckpointState {
        latest_slot: Option<u64>,
        item_count: usize,
    }

    #[test]
    fn checkpoint_store_round_trips_persisted_state() {
        let checkpoint_path = unique_test_checkpoint_path("store-roundtrip");
        let store = DerivedStateCheckpointStore::new(&checkpoint_path);
        let checkpoint = DerivedStateCheckpoint {
            session_id: FeedSessionId(77),
            last_applied_sequence: FeedSequence(18),
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(55),
                processed_slot: Some(55),
                confirmed_slot: Some(55),
                finalized_slot: Some(54),
            },
            state_version: 3,
            extension_version: "checkpoint-store-test".to_owned(),
        };
        let state = TestCheckpointState {
            latest_slot: Some(55),
            item_count: 4,
        };

        let store_result = store.store(&checkpoint, &state);
        assert!(store_result.is_ok(), "{store_result:?}");

        let persisted_result = store.load::<TestCheckpointState>();
        assert!(persisted_result.is_ok(), "{persisted_result:?}");
        let persisted = persisted_result.ok().flatten();

        assert_eq!(
            persisted,
            Some(DerivedStatePersistedCheckpoint::new(checkpoint, state))
        );

        drop(fs::remove_file(&checkpoint_path));
        if let Some(parent) = checkpoint_path.parent() {
            drop(fs::remove_dir_all(parent));
        }
    }

    #[test]
    fn checkpoint_store_filters_incompatible_state_contracts() {
        let checkpoint_path = unique_test_checkpoint_path("store-compatible");
        let store = DerivedStateCheckpointStore::new(&checkpoint_path);
        let checkpoint = DerivedStateCheckpoint {
            session_id: FeedSessionId(91),
            last_applied_sequence: FeedSequence(7),
            watermarks: FeedWatermarks::default(),
            state_version: 2,
            extension_version: "compatible-test".to_owned(),
        };

        let store_result = store.store(
            &checkpoint,
            &TestCheckpointState {
                latest_slot: None,
                item_count: 1,
            },
        );
        assert!(store_result.is_ok(), "{store_result:?}");

        let compatible_result = store.load_compatible::<TestCheckpointState>(2, "compatible-test");
        assert!(compatible_result.is_ok(), "{compatible_result:?}");
        let compatible = compatible_result.ok().flatten();

        let incompatible_result =
            store.load_compatible::<TestCheckpointState>(3, "compatible-test");
        assert!(incompatible_result.is_ok(), "{incompatible_result:?}");
        let incompatible = incompatible_result.ok().flatten();

        assert!(compatible.is_some());
        assert_eq!(incompatible, None);

        drop(fs::remove_file(&checkpoint_path));
        if let Some(parent) = checkpoint_path.parent() {
            drop(fs::remove_dir_all(parent));
        }
    }

    #[test]
    fn feed_sequence_next_advances_by_one() {
        assert_eq!(FeedSequence(41).next(), Some(FeedSequence(42)));
    }

    #[test]
    fn watermarks_commitment_prefers_finalized() {
        let watermarks = FeedWatermarks {
            canonical_tip_slot: Some(200),
            processed_slot: Some(200),
            confirmed_slot: Some(150),
            finalized_slot: Some(120),
        };
        assert_eq!(
            watermarks.commitment_for_slot(100),
            TxCommitmentStatus::Finalized
        );
        assert_eq!(
            watermarks.commitment_for_slot(140),
            TxCommitmentStatus::Confirmed
        );
        assert_eq!(
            watermarks.commitment_for_slot(180),
            TxCommitmentStatus::Processed
        );
    }

    #[test]
    fn checkpoint_next_sequence_uses_last_applied_boundary() {
        let checkpoint = DerivedStateCheckpoint {
            session_id: FeedSessionId(7),
            last_applied_sequence: FeedSequence(99),
            watermarks: FeedWatermarks::default(),
            state_version: 1,
            extension_version: "test".to_owned(),
        };
        assert_eq!(checkpoint.next_sequence(), Some(FeedSequence(100)));
    }

    #[test]
    fn replay_backend_parses_case_insensitively() {
        assert_eq!(
            DerivedStateReplayBackend::from_config_value("memory"),
            Some(DerivedStateReplayBackend::Memory)
        );
        assert_eq!(
            DerivedStateReplayBackend::from_config_value("DISK"),
            Some(DerivedStateReplayBackend::Disk)
        );
        assert_eq!(DerivedStateReplayBackend::from_config_value("other"), None);
    }

    #[test]
    fn replay_durability_parses_case_insensitively() {
        assert_eq!(
            DerivedStateReplayDurability::from_config_value("flush"),
            Some(DerivedStateReplayDurability::Flush)
        );
        assert_eq!(
            DerivedStateReplayDurability::from_config_value("FSYNC"),
            Some(DerivedStateReplayDurability::Fsync)
        );
        assert_eq!(
            DerivedStateReplayDurability::from_config_value("other"),
            None
        );
    }

    #[test]
    fn watermarks_from_reorg_use_new_tip_and_commitment_fields() {
        let watermarks = FeedWatermarks::from_reorg(&ReorgEvent {
            old_tip: 100,
            new_tip: 120,
            common_ancestor: Some(95),
            detached_slots: vec![100, 99],
            attached_slots: vec![118, 119, 120],
            confirmed_slot: Some(110),
            finalized_slot: Some(90),
            provider_source: None,
        });

        assert_eq!(watermarks.canonical_tip_slot, Some(120));
        assert_eq!(watermarks.processed_slot, Some(120));
        assert_eq!(watermarks.confirmed_slot, Some(110));
        assert_eq!(watermarks.finalized_slot, Some(90));
    }

    #[derive(Default)]
    struct RecordingState {
        envelopes: Vec<DerivedStateFeedEnvelope>,
        checkpoints: Vec<DerivedStateCheckpoint>,
    }

    struct RecordingConsumer {
        state: Arc<Mutex<RecordingState>>,
    }

    impl RecordingConsumer {
        fn new(state: Arc<Mutex<RecordingState>>) -> Self {
            Self { state }
        }
    }

    impl DerivedStateConsumer for RecordingConsumer {
        fn name(&self) -> &'static str {
            "recording-consumer"
        }

        fn state_version(&self) -> u32 {
            7
        }

        fn extension_version(&self) -> &'static str {
            "test-consumer"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            Ok(None)
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new()
                .with_transaction_applied()
                .with_transaction_status_observed()
                .with_block_meta_observed()
                .with_account_touch_key_partitions()
                .with_control_plane_observed()
        }

        fn apply(
            &mut self,
            envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            self.state
                .lock()
                .map_err(|_poison| {
                    DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                        Some(envelope.sequence),
                        "recording state mutex poisoned during apply",
                    )
                })?
                .envelopes
                .push(envelope.clone());
            Ok(())
        }

        fn flush_checkpoint(
            &mut self,
            checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            self.state
                .lock()
                .map_err(|_poison| {
                    DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                        Some(checkpoint.last_applied_sequence),
                        "recording state mutex poisoned during checkpoint flush",
                    )
                })?
                .checkpoints
                .push(checkpoint);
            Ok(())
        }
    }

    struct LifecycleConsumer {
        starts: Arc<AtomicUsize>,
        stops: Arc<AtomicUsize>,
    }

    impl DerivedStateConsumer for LifecycleConsumer {
        fn name(&self) -> &'static str {
            "lifecycle-consumer"
        }

        fn state_version(&self) -> u32 {
            1
        }

        fn extension_version(&self) -> &'static str {
            "lifecycle-test"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            Ok(None)
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new().with_control_plane_observed()
        }

        fn setup(
            &mut self,
            _ctx: DerivedStateConsumerContext,
        ) -> Result<(), DerivedStateConsumerSetupError> {
            let _ = self.starts.fetch_add(1, AtomicOrdering::Relaxed);
            Ok(())
        }

        fn shutdown(&mut self, _ctx: DerivedStateConsumerContext) {
            let _ = self.stops.fetch_add(1, AtomicOrdering::Relaxed);
        }

        fn apply(
            &mut self,
            _envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            Ok(())
        }

        fn flush_checkpoint(
            &mut self,
            _checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            Ok(())
        }
    }

    #[test]
    fn consumer_lifecycle_hooks_run_once() {
        let starts = Arc::new(AtomicUsize::new(0));
        let stops = Arc::new(AtomicUsize::new(0));
        {
            let host = DerivedStateHost::builder()
                .add_consumer(LifecycleConsumer {
                    starts: Arc::clone(&starts),
                    stops: Arc::clone(&stops),
                })
                .build();
            assert_eq!(host.consumer_names(), vec!["lifecycle-consumer"]);
            assert_eq!(starts.load(AtomicOrdering::Relaxed), 0);
            assert_eq!(stops.load(AtomicOrdering::Relaxed), 0);
            host.initialize();
            host.initialize();
            assert_eq!(starts.load(AtomicOrdering::Relaxed), 1);
            assert_eq!(stops.load(AtomicOrdering::Relaxed), 0);
        }
        assert_eq!(starts.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(stops.load(AtomicOrdering::Relaxed), 1);
    }

    #[test]
    fn host_assigns_monotonic_sequences() {
        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .add_consumer(RecordingConsumer::new(Arc::clone(&state)))
            .build();

        host.on_slot_status(SlotStatusEvent {
            slot: 10,
            parent_slot: Some(9),
            previous_status: None,
            status: ForkSlotStatus::Processed,
            tip_slot: Some(10),
            confirmed_slot: None,
            finalized_slot: None,
            provider_source: None,
        });
        host.on_reorg(ReorgEvent {
            old_tip: 10,
            new_tip: 12,
            common_ancestor: Some(8),
            detached_slots: vec![10],
            attached_slots: vec![11, 12],
            confirmed_slot: Some(7),
            finalized_slot: Some(6),
            provider_source: None,
        });

        let state = state
            .lock()
            .expect("recording state mutex should not be poisoned");
        let sequences = state
            .envelopes
            .iter()
            .map(|envelope| envelope.sequence)
            .collect::<Vec<_>>();
        assert_eq!(
            sequences,
            vec![
                FeedSequence(0),
                FeedSequence(1),
                FeedSequence(2),
                FeedSequence(3),
                FeedSequence(4)
            ]
        );
        assert_eq!(host.last_emitted_sequence(), Some(FeedSequence(4)));
        assert_eq!(
            host.current_watermarks(),
            FeedWatermarks {
                canonical_tip_slot: Some(12),
                processed_slot: Some(12),
                confirmed_slot: Some(7),
                finalized_slot: Some(6),
            }
        );
        assert_eq!(host.fault_count(), 0);
    }

    #[test]
    fn host_dispatches_control_plane_events_into_feed() {
        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .add_consumer(RecordingConsumer::new(Arc::clone(&state)))
            .build();

        host.on_recent_blockhash(ObservedRecentBlockhashEvent {
            slot: 70,
            recent_blockhash: [7_u8; 32],
            dataset_tx_count: 3,
            provider_source: None,
        });
        host.on_cluster_topology(ClusterTopologyEvent {
            source: ControlPlaneSource::GossipBootstrap,
            slot: Some(71),
            epoch: None,
            active_entrypoint: None,
            total_nodes: 1,
            added_nodes: Vec::new(),
            removed_pubkeys: Vec::new(),
            updated_nodes: vec![ClusterNodeInfo {
                pubkey: [1_u8; 32].into(),
                wallclock: 1,
                shred_version: 1,
                gossip: None,
                tpu: Some(SocketAddr::from(([127, 0, 0, 1], 9000))),
                tpu_quic: Some(SocketAddr::from(([127, 0, 0, 1], 9006))),
                tpu_forwards: None,
                tpu_forwards_quic: None,
                tpu_vote: None,
                tvu: None,
                rpc: None,
            }],
            snapshot_nodes: Vec::new(),
            provider_source: None,
        });
        host.on_leader_schedule(LeaderScheduleEvent {
            source: ControlPlaneSource::GossipBootstrap,
            slot: Some(72),
            epoch: None,
            added_leaders: Vec::new(),
            removed_slots: Vec::new(),
            updated_leaders: vec![LeaderScheduleEntry {
                slot: 72,
                leader: [2_u8; 32].into(),
            }],
            snapshot_leaders: Vec::new(),
            provider_source: None,
        });

        let state = state
            .lock()
            .expect("recording state mutex should not be poisoned");
        assert_eq!(state.envelopes.len(), 7);
        assert!(matches!(
            state.envelopes[0].event,
            DerivedStateFeedEvent::RecentBlockhashObserved(_)
        ));
        assert_eq!(state.envelopes[0].watermarks.processed_slot, Some(70));
        assert!(matches!(
            state.envelopes[1].event,
            DerivedStateFeedEvent::ControlPlaneStateUpdated(_)
        ));
        assert!(matches!(
            state.envelopes[2].event,
            DerivedStateFeedEvent::StateInvalidated(_)
        ));
        assert_eq!(state.envelopes[2].watermarks.processed_slot, Some(70));
        assert!(matches!(
            state.envelopes[3].event,
            DerivedStateFeedEvent::ClusterTopologyChanged(_)
        ));
        assert_eq!(state.envelopes[3].watermarks.processed_slot, Some(71));
        assert!(matches!(
            state.envelopes[4].event,
            DerivedStateFeedEvent::ControlPlaneStateUpdated(_)
        ));
        assert!(matches!(
            state.envelopes[5].event,
            DerivedStateFeedEvent::LeaderScheduleUpdated(_)
        ));
        assert_eq!(state.envelopes[5].watermarks.processed_slot, Some(72));
        assert!(matches!(
            state.envelopes[6].event,
            DerivedStateFeedEvent::ControlPlaneStateUpdated(_)
        ));
        assert_eq!(state.envelopes[6].watermarks.processed_slot, Some(72));
        let DerivedStateFeedEvent::ControlPlaneStateUpdated(control_plane) =
            state.envelopes[6].event.clone()
        else {
            panic!("expected control-plane state update");
        };
        assert_eq!(
            control_plane.quality,
            DerivedStateControlPlaneQuality::ReorgRisk
        );
        assert!(control_plane.inputs_aligned);
        assert!(!control_plane.strategy_safe);
        assert_eq!(host.last_emitted_sequence(), Some(FeedSequence(6)));
    }

    #[test]
    fn host_dispatches_provider_observed_events_into_feed() {
        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .add_consumer(RecordingConsumer::new(Arc::clone(&state)))
            .build();

        host.on_transaction_status(TransactionStatusEvent {
            slot: 91,
            commitment_status: TxCommitmentStatus::Confirmed,
            confirmed_slot: Some(91),
            finalized_slot: Some(80),
            signature: SignatureBytes::from_solana(Signature::from([9_u8; 64])),
            is_vote: false,
            index: Some(4),
            err: None,
            provider_source: None,
        });
        host.on_block_meta(BlockMetaEvent {
            slot: 92,
            commitment_status: TxCommitmentStatus::Confirmed,
            confirmed_slot: Some(92),
            finalized_slot: Some(81),
            blockhash: [3_u8; 32],
            parent_slot: 91,
            parent_blockhash: [2_u8; 32],
            block_time: Some(1_700_000_000),
            block_height: Some(123),
            executed_transaction_count: 17,
            entries_count: 5,
            provider_source: None,
        });

        let state = state
            .lock()
            .expect("recording state mutex should not be poisoned");
        assert_eq!(state.envelopes.len(), 2);
        assert!(matches!(
            state.envelopes[0].event,
            DerivedStateFeedEvent::TransactionStatusObserved(_)
        ));
        assert_eq!(state.envelopes[0].watermarks.processed_slot, Some(91));
        assert_eq!(state.envelopes[0].watermarks.confirmed_slot, Some(91));
        assert_eq!(state.envelopes[0].watermarks.finalized_slot, Some(80));
        assert!(matches!(
            state.envelopes[1].event,
            DerivedStateFeedEvent::BlockMetaObserved(_)
        ));
        assert_eq!(state.envelopes[1].watermarks.processed_slot, Some(92));
        assert_eq!(state.envelopes[1].watermarks.confirmed_slot, Some(92));
        assert_eq!(state.envelopes[1].watermarks.finalized_slot, Some(81));
        assert_eq!(host.last_emitted_sequence(), Some(FeedSequence(1)));
    }

    #[test]
    fn host_serializes_sequences_across_concurrent_producers() {
        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .add_consumer(RecordingConsumer::new(Arc::clone(&state)))
            .build();

        thread::scope(|scope| {
            for slot in 0_u64..16 {
                let host = host.clone();
                scope.spawn(move || {
                    host.on_slot_status(SlotStatusEvent {
                        slot,
                        parent_slot: slot.checked_sub(1),
                        previous_status: None,
                        status: ForkSlotStatus::Processed,
                        tip_slot: Some(slot),
                        confirmed_slot: None,
                        finalized_slot: None,
                        provider_source: None,
                    });
                });
            }
        });

        let state = state
            .lock()
            .expect("recording state mutex should not be poisoned");
        let sequences = state
            .envelopes
            .iter()
            .map(|envelope| envelope.sequence.0)
            .collect::<Vec<_>>();
        assert_eq!(sequences.len(), 33);
        assert_eq!(sequences, (0_u64..33).collect::<Vec<_>>());
        assert_eq!(host.last_emitted_sequence(), Some(FeedSequence(32)));
        assert_eq!(host.fault_count(), 0);
    }

    #[test]
    fn checkpoint_barrier_flushes_consumer_checkpoint() {
        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .add_consumer(RecordingConsumer::new(Arc::clone(&state)))
            .build();

        host.on_slot_status(SlotStatusEvent {
            slot: 44,
            parent_slot: Some(43),
            previous_status: None,
            status: ForkSlotStatus::Processed,
            tip_slot: Some(44),
            confirmed_slot: Some(40),
            finalized_slot: Some(39),
            provider_source: None,
        });
        let watermarks = FeedWatermarks {
            canonical_tip_slot: Some(44),
            processed_slot: Some(44),
            confirmed_slot: Some(40),
            finalized_slot: Some(39),
        };
        host.emit_checkpoint_barrier(CheckpointBarrierReason::Periodic, watermarks);

        let state = state
            .lock()
            .expect("recording state mutex should not be poisoned");
        assert_eq!(state.envelopes.len(), 4);
        assert_eq!(state.checkpoints.len(), 1);
        let barrier_envelope = &state.envelopes[3];
        assert_eq!(barrier_envelope.sequence, FeedSequence(3));
        assert_eq!(barrier_envelope.watermarks, watermarks);
        assert!(matches!(
            barrier_envelope.event,
            DerivedStateFeedEvent::CheckpointBarrier(CheckpointBarrierEvent {
                barrier_sequence: FeedSequence(3),
                reason: CheckpointBarrierReason::Periodic,
            })
        ));
        assert_eq!(
            state.checkpoints[0],
            DerivedStateCheckpoint {
                session_id: host.session_id(),
                last_applied_sequence: FeedSequence(3),
                watermarks,
                state_version: 7,
                extension_version: "test-consumer".to_owned(),
            }
        );
        assert_eq!(host.last_emitted_sequence(), Some(FeedSequence(3)));
        assert_eq!(host.current_watermarks(), watermarks);
        assert_eq!(host.fault_count(), 0);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "recording-consumer",
                unhealthy: false,
                recovery_state: DerivedStateConsumerRecoveryState::Live,
                applied_events: 4,
                checkpoint_flushes: 1,
                fault_count: 0,
                last_applied_sequence: Some(FeedSequence(3)),
                last_fault_sequence: None,
                last_fault_kind: None,
            }]
        );
    }

    struct FailingApplyConsumer {
        apply_calls: Arc<AtomicUsize>,
    }

    impl DerivedStateConsumer for FailingApplyConsumer {
        fn name(&self) -> &'static str {
            "failing-apply"
        }

        fn state_version(&self) -> u32 {
            1
        }

        fn extension_version(&self) -> &'static str {
            "failing-apply-test"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            Ok(None)
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new()
                .with_transaction_applied()
                .with_transaction_status_observed()
                .with_block_meta_observed()
                .with_account_touch_key_partitions()
                .with_control_plane_observed()
        }

        fn apply(
            &mut self,
            envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            let _ = self.apply_calls.fetch_add(1, AtomicOrdering::Relaxed);
            Err(DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                Some(envelope.sequence),
                "intentional test failure",
            ))
        }

        fn flush_checkpoint(
            &mut self,
            _checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            Ok(())
        }
    }

    #[test]
    fn continuity_fault_marks_consumer_unhealthy_and_stops_live_apply() {
        let apply_calls = Arc::new(AtomicUsize::new(0));
        let host = DerivedStateHost::builder()
            .add_consumer(FailingApplyConsumer {
                apply_calls: Arc::clone(&apply_calls),
            })
            .build();

        host.on_slot_status(SlotStatusEvent {
            slot: 1,
            parent_slot: None,
            previous_status: None,
            status: ForkSlotStatus::Processed,
            tip_slot: Some(1),
            confirmed_slot: None,
            finalized_slot: None,
            provider_source: None,
        });
        host.on_reorg(ReorgEvent {
            old_tip: 1,
            new_tip: 2,
            common_ancestor: Some(0),
            detached_slots: vec![1],
            attached_slots: vec![2],
            confirmed_slot: None,
            finalized_slot: None,
            provider_source: None,
        });

        assert_eq!(apply_calls.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(host.healthy_consumer_count(), 0);
        assert!(host.has_unhealthy_consumers());
        assert_eq!(host.unhealthy_consumer_names(), vec!["failing-apply"]);
        assert!(host.has_consumers_requiring_resync());
        assert_eq!(host.consumers_requiring_resync(), vec!["failing-apply"]);
        assert_eq!(host.consumers_pending_recovery(), vec!["failing-apply"]);
        assert!(host.consumers_requiring_rebuild().is_empty());
        assert_eq!(host.fault_count(), 1);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "failing-apply",
                unhealthy: true,
                recovery_state: DerivedStateConsumerRecoveryState::ReplayRecoveryPending,
                applied_events: 0,
                checkpoint_flushes: 0,
                fault_count: 1,
                last_applied_sequence: None,
                last_fault_sequence: Some(FeedSequence(0)),
                last_fault_kind: Some(DerivedStateConsumerFaultKind::ConsumerApplyFailed),
            }]
        );
    }

    struct FailingCheckpointConsumer {
        apply_calls: Arc<AtomicUsize>,
        flush_calls: Arc<AtomicUsize>,
    }

    impl DerivedStateConsumer for FailingCheckpointConsumer {
        fn name(&self) -> &'static str {
            "failing-checkpoint"
        }

        fn state_version(&self) -> u32 {
            9
        }

        fn extension_version(&self) -> &'static str {
            "failing-checkpoint-test"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            Ok(None)
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new()
                .with_transaction_applied()
                .with_transaction_status_observed()
                .with_block_meta_observed()
                .with_account_touch_key_partitions()
                .with_control_plane_observed()
        }

        fn apply(
            &mut self,
            _envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            let _ = self.apply_calls.fetch_add(1, AtomicOrdering::Relaxed);
            Ok(())
        }

        fn flush_checkpoint(
            &mut self,
            checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            let _ = self.flush_calls.fetch_add(1, AtomicOrdering::Relaxed);
            Err(DerivedStateConsumerFault::new(
                DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                Some(checkpoint.last_applied_sequence),
                "intentional checkpoint write failure",
            ))
        }
    }

    #[test]
    fn checkpoint_write_fault_does_not_mark_consumer_unhealthy() {
        let apply_calls = Arc::new(AtomicUsize::new(0));
        let flush_calls = Arc::new(AtomicUsize::new(0));
        let host = DerivedStateHost::builder()
            .add_consumer(FailingCheckpointConsumer {
                apply_calls: Arc::clone(&apply_calls),
                flush_calls: Arc::clone(&flush_calls),
            })
            .build();

        host.on_slot_status(SlotStatusEvent {
            slot: 11,
            parent_slot: Some(10),
            previous_status: None,
            status: ForkSlotStatus::Processed,
            tip_slot: Some(11),
            confirmed_slot: Some(9),
            finalized_slot: Some(8),
            provider_source: None,
        });
        host.emit_checkpoint_barrier(
            CheckpointBarrierReason::Periodic,
            FeedWatermarks {
                canonical_tip_slot: Some(11),
                processed_slot: Some(11),
                confirmed_slot: Some(9),
                finalized_slot: Some(8),
            },
        );
        host.on_reorg(ReorgEvent {
            old_tip: 11,
            new_tip: 12,
            common_ancestor: Some(10),
            detached_slots: vec![11],
            attached_slots: vec![12],
            confirmed_slot: Some(9),
            finalized_slot: Some(8),
            provider_source: None,
        });

        assert_eq!(apply_calls.load(AtomicOrdering::Relaxed), 6);
        assert_eq!(flush_calls.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(host.healthy_consumer_count(), 1);
        assert!(!host.has_unhealthy_consumers());
        assert!(host.unhealthy_consumer_names().is_empty());
        assert!(!host.has_consumers_requiring_resync());
        assert!(host.consumers_requiring_resync().is_empty());
        assert_eq!(host.fault_count(), 1);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "failing-checkpoint",
                unhealthy: false,
                recovery_state: DerivedStateConsumerRecoveryState::Live,
                applied_events: 5,
                checkpoint_flushes: 0,
                fault_count: 1,
                last_applied_sequence: Some(FeedSequence(5)),
                last_fault_sequence: Some(FeedSequence(3)),
                last_fault_kind: Some(DerivedStateConsumerFaultKind::CheckpointWriteFailed),
            }]
        );
    }

    struct ReplayCheckpointConsumer {
        state: Arc<Mutex<RecordingState>>,
        checkpoint: Option<DerivedStateCheckpoint>,
    }

    impl DerivedStateConsumer for ReplayCheckpointConsumer {
        fn name(&self) -> &'static str {
            "replay-checkpoint"
        }

        fn state_version(&self) -> u32 {
            3
        }

        fn extension_version(&self) -> &'static str {
            "replay-checkpoint-test"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            Ok(self.checkpoint.take())
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new()
                .with_transaction_applied()
                .with_transaction_status_observed()
                .with_block_meta_observed()
                .with_account_touch_key_partitions()
                .with_control_plane_observed()
        }

        fn apply(
            &mut self,
            envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            self.state
                .lock()
                .map_err(|_poison| {
                    DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                        Some(envelope.sequence),
                        "replay recording state mutex poisoned during apply",
                    )
                })?
                .envelopes
                .push(envelope.clone());
            Ok(())
        }

        fn flush_checkpoint(
            &mut self,
            checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            self.state
                .lock()
                .map_err(|_poison| {
                    DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                        Some(checkpoint.last_applied_sequence),
                        "replay recording state mutex poisoned during checkpoint flush",
                    )
                })?
                .checkpoints
                .push(checkpoint);
            Ok(())
        }
    }

    struct RecoverableConsumerState {
        checkpoint: Option<DerivedStateCheckpoint>,
        fail_sequence_once: Option<FeedSequence>,
        applied_sequences: Vec<FeedSequence>,
    }

    struct RecoverableConsumer {
        state: Arc<Mutex<RecoverableConsumerState>>,
    }

    impl DerivedStateConsumer for RecoverableConsumer {
        fn name(&self) -> &'static str {
            "recoverable-consumer"
        }

        fn state_version(&self) -> u32 {
            5
        }

        fn extension_version(&self) -> &'static str {
            "recoverable-consumer-test"
        }

        fn load_checkpoint(
            &mut self,
        ) -> Result<Option<DerivedStateCheckpoint>, DerivedStateConsumerFault> {
            let state = self.state.lock().map_err(|_poison| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                    None,
                    "recoverable consumer state mutex poisoned while loading checkpoint",
                )
            })?;
            Ok(state.checkpoint.clone())
        }

        fn config(&self) -> DerivedStateConsumerConfig {
            DerivedStateConsumerConfig::new()
                .with_transaction_applied()
                .with_transaction_status_observed()
                .with_block_meta_observed()
                .with_account_touch_key_partitions()
                .with_control_plane_observed()
        }

        fn apply(
            &mut self,
            envelope: &DerivedStateFeedEnvelope,
        ) -> Result<(), DerivedStateConsumerFault> {
            let mut state = self.state.lock().map_err(|_poison| {
                DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                    Some(envelope.sequence),
                    "recoverable consumer state mutex poisoned while applying envelope",
                )
            })?;
            if state.fail_sequence_once == Some(envelope.sequence) {
                state.fail_sequence_once = None;
                return Err(DerivedStateConsumerFault::new(
                    DerivedStateConsumerFaultKind::ConsumerApplyFailed,
                    Some(envelope.sequence),
                    "recoverable consumer injected one-shot apply failure",
                ));
            }
            state.applied_sequences.push(envelope.sequence);
            Ok(())
        }

        fn flush_checkpoint(
            &mut self,
            checkpoint: DerivedStateCheckpoint,
        ) -> Result<(), DerivedStateConsumerFault> {
            let sequence = checkpoint.last_applied_sequence;
            self.state
                .lock()
                .map_err(|_poison| {
                    DerivedStateConsumerFault::new(
                        DerivedStateConsumerFaultKind::CheckpointWriteFailed,
                        Some(sequence),
                        "recoverable consumer state mutex poisoned while flushing checkpoint",
                    )
                })?
                .checkpoint = Some(checkpoint);
            Ok(())
        }
    }

    #[test]
    fn initialize_replays_retained_events_from_checkpoint() {
        let replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let session_id = FeedSessionId(42);

        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(0),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(10),
                processed_slot: Some(10),
                confirmed_slot: Some(9),
                finalized_slot: Some(8),
            },
            event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                slot: 10,
                parent_slot: Some(9),
                previous_status: None,
                status: ForkSlotStatus::Processed,
            }),
        });
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(1),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(11),
                processed_slot: Some(11),
                confirmed_slot: Some(9),
                finalized_slot: Some(8),
            },
            event: DerivedStateFeedEvent::BranchReorged(BranchReorgedEvent {
                old_tip: 10,
                new_tip: 11,
                common_ancestor: Some(9),
                detached_slots: Arc::from([10]),
                attached_slots: Arc::from([11]),
            }),
        });

        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .with_session_id(session_id)
            .with_replay_source(replay_source)
            .add_consumer(ReplayCheckpointConsumer {
                state: Arc::clone(&state),
                checkpoint: Some(DerivedStateCheckpoint {
                    session_id,
                    last_applied_sequence: FeedSequence(0),
                    watermarks: FeedWatermarks {
                        canonical_tip_slot: Some(10),
                        processed_slot: Some(10),
                        confirmed_slot: Some(9),
                        finalized_slot: Some(8),
                    },
                    state_version: 3,
                    extension_version: "replay-checkpoint-test".to_owned(),
                }),
            })
            .build();

        host.initialize();

        let state = state
            .lock()
            .expect("replay recording state mutex should not be poisoned");
        assert_eq!(state.envelopes.len(), 1);
        assert_eq!(state.envelopes[0].sequence, FeedSequence(1));
        assert_eq!(host.healthy_consumer_count(), 1);
        assert_eq!(host.fault_count(), 0);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "replay-checkpoint",
                unhealthy: false,
                recovery_state: DerivedStateConsumerRecoveryState::Live,
                applied_events: 1,
                checkpoint_flushes: 0,
                fault_count: 0,
                last_applied_sequence: Some(FeedSequence(1)),
                last_fault_sequence: None,
                last_fault_kind: None,
            }]
        );
    }

    #[test]
    fn initialize_accepts_checkpoint_already_at_retained_tail() {
        let replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let session_id = FeedSessionId(41);
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(0),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks::default(),
            event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                slot: 5,
                parent_slot: Some(4),
                previous_status: None,
                status: ForkSlotStatus::Processed,
            }),
        });
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(1),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks::default(),
            event: DerivedStateFeedEvent::CheckpointBarrier(CheckpointBarrierEvent {
                barrier_sequence: FeedSequence(1),
                reason: CheckpointBarrierReason::Periodic,
            }),
        });

        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .with_session_id(FeedSessionId(999))
            .with_replay_source(replay_source)
            .add_consumer(ReplayCheckpointConsumer {
                state: Arc::clone(&state),
                checkpoint: Some(DerivedStateCheckpoint {
                    session_id,
                    last_applied_sequence: FeedSequence(1),
                    watermarks: FeedWatermarks::default(),
                    state_version: 3,
                    extension_version: "replay-checkpoint-test".to_owned(),
                }),
            })
            .build();

        host.initialize();

        let state = state
            .lock()
            .expect("replay recording state mutex should not be poisoned");
        assert!(state.envelopes.is_empty());
        assert_eq!(host.healthy_consumer_count(), 1);
        assert!(!host.has_unhealthy_consumers());
    }

    #[test]
    fn runtime_installed_replay_source_replays_checkpoint_tail() {
        let replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let session_id = FeedSessionId(52);
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(1),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(12),
                processed_slot: Some(12),
                confirmed_slot: Some(11),
                finalized_slot: Some(10),
            },
            event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                slot: 12,
                parent_slot: Some(11),
                previous_status: None,
                status: ForkSlotStatus::Processed,
            }),
        });

        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .with_session_id(session_id)
            .add_consumer(ReplayCheckpointConsumer {
                state: Arc::clone(&state),
                checkpoint: Some(DerivedStateCheckpoint {
                    session_id,
                    last_applied_sequence: FeedSequence(0),
                    watermarks: FeedWatermarks {
                        canonical_tip_slot: Some(11),
                        processed_slot: Some(11),
                        confirmed_slot: Some(10),
                        finalized_slot: Some(9),
                    },
                    state_version: 3,
                    extension_version: "replay-checkpoint-test".to_owned(),
                }),
            })
            .build();

        assert!(host.install_runtime_replay_source(replay_source));
        host.initialize();

        let state = state
            .lock()
            .expect("replay recording state mutex should not be poisoned");
        assert_eq!(state.envelopes.len(), 1);
        assert_eq!(state.envelopes[0].sequence, FeedSequence(1));
        assert_eq!(host.healthy_consumer_count(), 1);
    }

    #[test]
    fn initialize_marks_consumer_unhealthy_when_replay_gap_exists() {
        let replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let session_id = FeedSessionId(77);
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(2),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks::default(),
            event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                slot: 20,
                parent_slot: Some(19),
                previous_status: None,
                status: ForkSlotStatus::Processed,
            }),
        });

        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .with_session_id(FeedSessionId(78))
            .with_replay_source(replay_source)
            .add_consumer(ReplayCheckpointConsumer {
                state,
                checkpoint: Some(DerivedStateCheckpoint {
                    session_id,
                    last_applied_sequence: FeedSequence(0),
                    watermarks: FeedWatermarks::default(),
                    state_version: 3,
                    extension_version: "replay-checkpoint-test".to_owned(),
                }),
            })
            .build();

        host.initialize();

        assert!(host.has_unhealthy_consumers());
        assert_eq!(host.unhealthy_consumer_names(), vec!["replay-checkpoint"]);
        assert!(host.has_consumers_requiring_resync());
        assert_eq!(host.consumers_requiring_resync(), vec!["replay-checkpoint"]);
        assert!(host.consumers_pending_recovery().is_empty());
        assert_eq!(
            host.consumers_requiring_rebuild(),
            vec!["replay-checkpoint"]
        );
        assert_eq!(host.fault_count(), 1);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "replay-checkpoint",
                unhealthy: true,
                recovery_state: DerivedStateConsumerRecoveryState::RebuildRequired,
                applied_events: 0,
                checkpoint_flushes: 0,
                fault_count: 1,
                last_applied_sequence: None,
                last_fault_sequence: Some(FeedSequence(1)),
                last_fault_kind: Some(DerivedStateConsumerFaultKind::ReplayGap),
            }]
        );
    }

    #[test]
    fn builder_replay_source_takes_precedence_over_runtime_source() {
        let configured_replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let runtime_replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let host = DerivedStateHost::builder()
            .with_replay_source(configured_replay_source.clone())
            .add_consumer(ReplayCheckpointConsumer {
                state: Arc::new(Mutex::new(RecordingState::default())),
                checkpoint: None,
            })
            .build();

        assert!(!host.install_runtime_replay_source(runtime_replay_source.clone()));

        host.on_slot_status(SlotStatusEvent {
            slot: 40,
            tip_slot: Some(40),
            confirmed_slot: Some(39),
            finalized_slot: Some(38),
            parent_slot: Some(39),
            status: ForkSlotStatus::Processed,
            previous_status: None,
            provider_source: None,
        });

        assert_eq!(
            configured_replay_source.retained_envelopes(host.session_id()),
            3
        );
        assert_eq!(
            runtime_replay_source.retained_envelopes(host.session_id()),
            0
        );
    }

    #[test]
    fn recover_consumers_replays_from_checkpoint_after_live_failure() {
        let replay_source = Arc::new(InMemoryDerivedStateReplaySource::new());
        let state = Arc::new(Mutex::new(RecoverableConsumerState {
            checkpoint: None,
            fail_sequence_once: Some(FeedSequence(4)),
            applied_sequences: Vec::new(),
        }));
        let host = DerivedStateHost::builder()
            .with_replay_source(replay_source)
            .add_consumer(RecoverableConsumer {
                state: Arc::clone(&state),
            })
            .build();

        host.on_slot_status(SlotStatusEvent {
            slot: 10,
            tip_slot: Some(10),
            confirmed_slot: Some(9),
            finalized_slot: Some(8),
            parent_slot: Some(9),
            status: ForkSlotStatus::Processed,
            previous_status: None,
            provider_source: None,
        });
        host.emit_checkpoint_barrier(
            CheckpointBarrierReason::Periodic,
            FeedWatermarks {
                canonical_tip_slot: Some(10),
                processed_slot: Some(10),
                confirmed_slot: Some(9),
                finalized_slot: Some(8),
            },
        );
        host.on_slot_status(SlotStatusEvent {
            slot: 11,
            tip_slot: Some(11),
            confirmed_slot: Some(10),
            finalized_slot: Some(9),
            parent_slot: Some(10),
            status: ForkSlotStatus::Processed,
            previous_status: None,
            provider_source: None,
        });

        assert_eq!(
            host.consumers_pending_recovery(),
            vec!["recoverable-consumer"]
        );
        assert!(host.consumers_requiring_rebuild().is_empty());

        let recovery_report = host.recover_consumers();
        assert_eq!(
            recovery_report,
            DerivedStateRecoveryReport {
                attempted: 1,
                recovered: 1,
                still_pending: 0,
                rebuild_required: 0,
            }
        );
        assert_eq!(host.healthy_consumer_count(), 1);
        assert!(!host.has_unhealthy_consumers());
        assert!(host.consumers_pending_recovery().is_empty());

        let state = state
            .lock()
            .expect("recoverable consumer state mutex should not be poisoned");
        assert_eq!(
            state.applied_sequences,
            vec![
                FeedSequence(0),
                FeedSequence(1),
                FeedSequence(2),
                FeedSequence(3),
                FeedSequence(4),
                FeedSequence(5)
            ]
        );
        assert_eq!(
            state
                .checkpoint
                .as_ref()
                .map(|checkpoint| checkpoint.last_applied_sequence),
            Some(FeedSequence(3))
        );
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "recoverable-consumer",
                unhealthy: false,
                recovery_state: DerivedStateConsumerRecoveryState::Live,
                applied_events: 6,
                checkpoint_flushes: 1,
                fault_count: 1,
                last_applied_sequence: Some(FeedSequence(5)),
                last_fault_sequence: Some(FeedSequence(4)),
                last_fault_kind: Some(DerivedStateConsumerFaultKind::ConsumerApplyFailed),
            }]
        );
    }

    #[test]
    fn disk_replay_source_replays_after_reopen() {
        let replay_dir = unique_test_replay_dir("reopen");
        let session_id = FeedSessionId(1337);
        let replay_source = DiskDerivedStateReplaySource::new(&replay_dir, 4)
            .expect("disk replay source should create its root directory");
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(0),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(60),
                processed_slot: Some(60),
                confirmed_slot: Some(59),
                finalized_slot: Some(58),
            },
            event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                slot: 60,
                parent_slot: Some(59),
                previous_status: None,
                status: ForkSlotStatus::Processed,
            }),
        });
        replay_source.append(DerivedStateFeedEnvelope {
            session_id,
            sequence: FeedSequence(1),
            emitted_at: SystemTime::UNIX_EPOCH,
            watermarks: FeedWatermarks {
                canonical_tip_slot: Some(61),
                processed_slot: Some(61),
                confirmed_slot: Some(60),
                finalized_slot: Some(59),
            },
            event: DerivedStateFeedEvent::CheckpointBarrier(CheckpointBarrierEvent {
                barrier_sequence: FeedSequence(1),
                reason: CheckpointBarrierReason::Periodic,
            }),
        });
        drop(replay_source);

        let reopened = DiskDerivedStateReplaySource::new(&replay_dir, 4)
            .expect("disk replay source should reopen persisted logs");
        let replayed = reopened
            .replay_from(session_id, FeedSequence(0))
            .expect("reopened disk replay source should replay the retained session");
        assert_eq!(replayed.len(), 2);
        assert_eq!(replayed[0].sequence, FeedSequence(0));
        assert_eq!(replayed[1].sequence, FeedSequence(1));

        drop(fs::remove_dir_all(replay_dir));
    }

    #[test]
    fn disk_replay_source_persists_truncation_window() {
        let replay_dir = unique_test_replay_dir("truncate");
        let session_id = FeedSessionId(1440);
        let replay_source = DiskDerivedStateReplaySource::new(&replay_dir, 2)
            .expect("disk replay source should create its root directory");
        for (sequence, slot) in [
            (FeedSequence(0), 70),
            (FeedSequence(1), 71),
            (FeedSequence(2), 72),
        ] {
            replay_source.append(DerivedStateFeedEnvelope {
                session_id,
                sequence,
                emitted_at: SystemTime::UNIX_EPOCH,
                watermarks: FeedWatermarks {
                    canonical_tip_slot: Some(slot),
                    processed_slot: Some(slot),
                    confirmed_slot: Some(slot.saturating_sub(1)),
                    finalized_slot: Some(slot.saturating_sub(2)),
                },
                event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                    slot,
                    parent_slot: slot.checked_sub(1),
                    previous_status: None,
                    status: ForkSlotStatus::Processed,
                }),
            });
        }
        drop(replay_source);

        let reopened = DiskDerivedStateReplaySource::new(&replay_dir, 2)
            .expect("disk replay source should reopen persisted logs");
        assert_eq!(reopened.retained_envelopes(session_id), 2);
        let replay_result = reopened.replay_from(session_id, FeedSequence(0));
        assert!(matches!(
            replay_result,
            Err(DerivedStateReplayError::Truncated {
                session_id: _,
                sequence: FeedSequence(0),
                oldest_retained_sequence: FeedSequence(1),
            })
        ));

        drop(fs::remove_dir_all(replay_dir));
    }

    #[test]
    fn disk_replay_source_evicts_stale_appenders_during_truncation() {
        let replay_dir = unique_test_replay_dir("truncate-appender-eviction");
        let session_id = FeedSessionId(2026);
        let replay_source = DiskDerivedStateReplaySource::new(&replay_dir, 2)
            .expect("disk replay source should create its root directory");

        for sequence in 0..2048_u64 {
            replay_source
                .append_batch_inline(&[DerivedStateFeedEnvelope {
                    session_id,
                    sequence: FeedSequence(sequence),
                    emitted_at: SystemTime::UNIX_EPOCH,
                    watermarks: FeedWatermarks {
                        canonical_tip_slot: Some(500 + sequence),
                        processed_slot: Some(500 + sequence),
                        confirmed_slot: Some(499 + sequence),
                        finalized_slot: Some(498 + sequence),
                    },
                    event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                        slot: 500 + sequence,
                        parent_slot: Some(499 + sequence),
                        previous_status: None,
                        status: ForkSlotStatus::Processed,
                    }),
                }])
                .expect("inline append should not fail while truncating retained segments");
        }

        assert_eq!(replay_source.append_failures(), 0);
        let replayed = replay_source
            .replay_from(session_id, FeedSequence(2046))
            .expect("replay should return the retained tail after repeated truncation");
        assert_eq!(
            replayed
                .iter()
                .map(|envelope| envelope.sequence)
                .collect::<Vec<_>>(),
            vec![FeedSequence(2046), FeedSequence(2047)]
        );

        let cached_appenders = DISK_REPLAY_APPENDERS.with(|appenders| appenders.borrow().len());
        assert!(
            cached_appenders <= 2,
            "expected truncation to keep cached appenders bounded, got {cached_appenders}"
        );

        drop(replay_source);
        DISK_REPLAY_APPENDERS.with(|appenders| appenders.borrow_mut().clear());
        drop(fs::remove_dir_all(replay_dir));
    }

    #[test]
    fn bounded_replay_source_truncates_old_envelopes_and_marks_replay_gap() {
        let replay_source =
            Arc::new(InMemoryDerivedStateReplaySource::with_max_envelopes_per_session(1));
        let session_id = FeedSessionId(91);
        for (sequence, slot) in [
            (FeedSequence(0), 30),
            (FeedSequence(1), 31),
            (FeedSequence(2), 32),
        ] {
            replay_source.append(DerivedStateFeedEnvelope {
                session_id,
                sequence,
                emitted_at: SystemTime::UNIX_EPOCH,
                watermarks: FeedWatermarks {
                    canonical_tip_slot: Some(slot),
                    processed_slot: Some(slot),
                    confirmed_slot: Some(slot.saturating_sub(1)),
                    finalized_slot: Some(slot.saturating_sub(2)),
                },
                event: DerivedStateFeedEvent::SlotStatusChanged(SlotStatusChangedEvent {
                    slot,
                    parent_slot: slot.checked_sub(1),
                    previous_status: None,
                    status: ForkSlotStatus::Processed,
                }),
            });
        }

        assert_eq!(replay_source.retained_envelopes(session_id), 1);
        assert_eq!(replay_source.truncated_envelopes(), 2);
        let replayed = replay_source
            .replay_from(session_id, FeedSequence(2))
            .expect("bounded replay source should retain the requested tail");
        assert_eq!(replayed.len(), 1);
        assert_eq!(replayed[0].sequence, FeedSequence(2));
        assert_eq!(replayed[0].watermarks.canonical_tip_slot, Some(32));

        let state = Arc::new(Mutex::new(RecordingState::default()));
        let host = DerivedStateHost::builder()
            .with_session_id(session_id)
            .with_replay_source(replay_source)
            .add_consumer(ReplayCheckpointConsumer {
                state,
                checkpoint: Some(DerivedStateCheckpoint {
                    session_id,
                    last_applied_sequence: FeedSequence(0),
                    watermarks: FeedWatermarks {
                        canonical_tip_slot: Some(30),
                        processed_slot: Some(30),
                        confirmed_slot: Some(29),
                        finalized_slot: Some(28),
                    },
                    state_version: 3,
                    extension_version: "replay-checkpoint-test".to_owned(),
                }),
            })
            .build();

        host.initialize();

        assert!(host.has_unhealthy_consumers());
        assert_eq!(host.unhealthy_consumer_names(), vec!["replay-checkpoint"]);
        assert!(host.has_consumers_requiring_resync());
        assert_eq!(host.consumers_requiring_resync(), vec!["replay-checkpoint"]);
        assert!(host.consumers_pending_recovery().is_empty());
        assert_eq!(
            host.consumers_requiring_rebuild(),
            vec!["replay-checkpoint"]
        );
        assert_eq!(host.fault_count(), 1);
        assert_eq!(
            host.consumer_telemetry(),
            vec![DerivedStateConsumerTelemetry {
                name: "replay-checkpoint",
                unhealthy: true,
                recovery_state: DerivedStateConsumerRecoveryState::RebuildRequired,
                applied_events: 0,
                checkpoint_flushes: 0,
                fault_count: 1,
                last_applied_sequence: None,
                last_fault_sequence: Some(FeedSequence(1)),
                last_fault_kind: Some(DerivedStateConsumerFaultKind::ReplayGap),
            }]
        );
    }
}