oxide-batch 0.6.0

Rust-native framework for reliable, restartable batch processing, inspired by Spring Batch
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
//! Deterministic single-threaded chunk-step orchestration.

use std::collections::BTreeSet;
use std::fmt;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use futures_util::FutureExt;
use sha2::{Digest, Sha256};
use tokio::sync::Mutex as AsyncMutex;

use crate::runtime::{lower_one_step, one_step_node};
use crate::{
    AdaptiveCompletionPolicy, BackoffOutcome, BoxFuture, BoxedStream, ChunkCommitReceipt,
    ChunkCompletion, ChunkCompletionContext, ChunkCompletionOutcome, ChunkComponentRevisions,
    ChunkCount, ChunkCounts, ChunkFaultProgress, ChunkSize, ChunkTransaction,
    ChunkTransactionContext, ChunkTransactionError, ChunkTransactionManager, CompiledExecutionPlan,
    CompletionPolicy, ComponentRevision, ComponentStateEnvelope, ComponentStreamIdentity,
    DefinitionError, DefinitionIdentity, DefinitionRevision, ExecutionCorrelation, FailureCategory,
    FailureId, FailureSummary, FaultDecision, FaultDescriptor, FaultEvidence, FaultPhase,
    FaultProgress, FaultRuntime, InFlightPolicy, InheritedStepProgress, ItemListenerContext,
    ItemListenerFailure, ItemListenerSet, ItemProcessor, ItemReader, ItemStream, ItemWriter,
    JobExecutionListener, JobLauncher, JobName, JobParameters, LaunchError, LaunchReport,
    LifecycleEventKind, ListenerFailureKind, ProcessContext, ProcessOutcome, ProcessorError,
    ReadContext, ReadOutcome, ReaderError, RestartabilityDeclaration, RetryCounts, RetryKey,
    RetryOrdinal, RetryOutcome, RetryReservation, RollbackDisposition, SkipCounts, StepComponents,
    StepExecutionListener, StepName, StopToken, StreamCloseContext, StreamOpenContext,
    StreamRuntimeOutcome, StreamStateContract, StreamUpdateContext, Tasklet, TaskletContext,
    TaskletError, TaskletJob, TaskletOutcome, TaskletStep, WriteContext, WriteOutcome, WriterError,
};

/// Distinguishes who registered one runtime [`ItemStream`] entry, so a
/// completion-policy replacement can remove exactly the registrations it
/// itself installed and never one a caller registered directly.
///
/// Ownership is tracked explicitly per entry rather than inferred from
/// [`ComponentStreamIdentity`] equality: two entries can legitimately share
/// one identity for a moment while a `ChunkStep` is still being built (a
/// manual registration and a policy's own registration, installed in either
/// order), and removing "whatever this policy reports" must never remove
/// the wrong one just because the values match.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StreamOwner {
    /// Registered directly via [`ChunkStep::with_item_stream`].
    Manual,
    /// Registered by [`ChunkStep::with_completion_policy`] on behalf of the
    /// installed [`CompletionPolicy`]'s own [`CompletionPolicy::stream_registrations`].
    Policy,
}

/// One runtime [`ItemStream`] registration and its explicit provenance.
type StreamRegistration = (
    ComponentStreamIdentity,
    Arc<BoxedStream>,
    StreamStateContract,
    StreamOwner,
);

/// A validated one-step chunk definition.
pub struct ChunkStep<I, O, R, P, W> {
    name: StepName,
    size: ChunkSize,
    reader: R,
    processor: P,
    writer: W,
    transactions: Arc<dyn ChunkTransactionManager>,
    completion: Arc<dyn ChunkCompletion>,
    completion_policy: Option<Arc<dyn CompletionPolicy>>,
    listeners: Vec<Arc<dyn ChunkListener>>,
    step_listeners: Vec<Arc<dyn StepExecutionListener>>,
    item_listeners: ItemListenerSet<I, O>,
    fault: Option<FaultRuntime>,
    streams: Vec<StreamRegistration>,
    in_flight_policy: InFlightPolicy,
    definition_digest: [u8; 32],
}

impl<I, O, R, P, W> ChunkStep<I, O, R, P, W>
where
    R: ItemReader<I>,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    /// Constructs a chunk step from facade-owned component and transaction
    /// ports.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        name: StepName,
        size: ChunkSize,
        reader: R,
        processor: P,
        writer: W,
        transactions: Arc<dyn ChunkTransactionManager>,
        completion: Arc<dyn ChunkCompletion>,
    ) -> Self {
        Self {
            name,
            size,
            reader,
            processor,
            writer,
            transactions,
            completion,
            completion_policy: None,
            listeners: Vec::new(),
            step_listeners: Vec::new(),
            item_listeners: ItemListenerSet::new(),
            fault: None,
            streams: Vec::new(),
            in_flight_policy: InFlightPolicy::FinishChunk,
            definition_digest: [0; 32],
        }
    }

    /// Replaces the post-commit completion observer installed by [`Self::new`].
    ///
    /// Additive parity with the other post-construction `with_*` methods:
    /// [`Self::new`] requires a [`ChunkCompletion`] up front because it is a
    /// required construction port, not because every caller has an opinion
    /// about it. [`crate::ChunkPipelineBuilder`] installs a no-op default and
    /// uses this method to let a caller override it without hand-rolling a
    /// [`ChunkCompletion`] implementation for the common case that does not
    /// need one.
    #[must_use]
    pub fn with_completion(mut self, completion: Arc<dyn ChunkCompletion>) -> Self {
        self.completion = completion;
        self
    }

    /// Installs an additional early-completion policy.
    ///
    /// The configured [`ChunkSize`] passed to [`Self::new`] always remains
    /// the hard resource-safety ceiling for buffered items; installing a
    /// policy here only allows a chunk to stop *earlier* than that ceiling,
    /// per `REPEAT-POLICY-001`. Without a policy, completion is exactly the
    /// pre-#151 `ChunkSize`-only behavior.
    ///
    /// Also registers every [`ItemStream`] that `policy` (or, for a
    /// [`crate::CompositeCompletionPolicy`], any of its members at any
    /// nesting depth) reports through
    /// [`CompletionPolicy::stream_registrations`], bound to that exact
    /// instance. This is the only place that registration happens, so an
    /// [`AdaptiveCompletionPolicy`] gets its persisted decision wired
    /// correctly whether it is installed directly here or nested anywhere
    /// inside a composite -- there is no second, composite-blind path that
    /// could silently drop it.
    ///
    /// Calling this again to replace a previously installed policy first
    /// removes exactly the previous policy's own registered streams --
    /// every entry this method itself tagged as policy-owned, never a
    /// manually registered [`Self::with_item_stream`] entry that happens
    /// to coexist, even under the identical [`ComponentStreamIdentity`]: a
    /// policy replacement is a full replacement of what *this method*
    /// installed, not an accumulation of every policy this step ever
    /// installed, and ownership is tracked per entry rather than inferred
    /// from identity equality, so a coincidental identity collision with a
    /// manual registration can never cause that manual entry to be removed.
    #[must_use]
    pub fn with_completion_policy(mut self, policy: Arc<dyn CompletionPolicy>) -> Self {
        if self.completion_policy.is_some() {
            self.streams
                .retain(|(_, _, _, owner)| *owner != StreamOwner::Policy);
        }
        for (identity, stream, contract) in policy.stream_registrations() {
            self.streams
                .push((identity, stream, contract, StreamOwner::Policy));
        }
        self.completion_policy = Some(policy);
        self
    }

    /// Registers one [`AdaptiveCompletionPolicy`] instance as this step's
    /// completion policy.
    ///
    /// A thin, discoverable alias for [`Self::with_completion_policy`]:
    /// [`CompletionPolicy::stream_registrations`] already binds this exact
    /// instance's persisted decision to the step, so there is exactly one
    /// registration mechanism regardless of which method installs it --
    /// never a second path that could drift onto a different instance.
    #[must_use]
    pub fn with_adaptive_completion_policy(self, policy: Arc<AdaptiveCompletionPolicy>) -> Self {
        self.with_completion_policy(policy)
    }

    /// Registers a chunk listener in deterministic before-order.
    #[must_use]
    pub fn with_chunk_listener(mut self, listener: Arc<dyn ChunkListener>) -> Self {
        self.listeners.push(listener);
        self
    }

    /// Installs the authoritative item, retry, and skip listener families.
    ///
    /// The set replaces any previously installed families.
    #[must_use]
    pub fn with_item_listeners(mut self, listeners: ItemListenerSet<I, O>) -> Self {
        self.item_listeners = listeners;
        self
    }

    /// Installs bounded retry, backoff, skip, and rollback behavior.
    ///
    /// Without a fault runtime every component failure fails the step after a
    /// known rollback, which is the M2 behavior.
    #[must_use]
    pub fn with_fault_runtime(mut self, fault: FaultRuntime) -> Self {
        self.fault = Some(fault);
        self
    }

    /// Registers a step listener in deterministic before-order.
    #[must_use]
    pub fn with_listener(mut self, listener: Arc<dyn StepExecutionListener>) -> Self {
        self.step_listeners.push(listener);
        self
    }

    /// Registers one namespaced `ItemStream` in deterministic registration
    /// order.
    ///
    /// `identity` must match the namespace registered for this stream in the
    /// [`ChunkComponentRevisions`] this step's definition declares (see
    /// [`ChunkComponentRevisions::with_stream_revision`]): it is both the
    /// restart-relevant fingerprint token and the runtime key used to
    /// associate this stream with its committed durable state.
    /// [`ChunkJob::new`]/[`FlowJob::with_chunk_step`](crate::FlowJob::with_chunk_step)
    /// reject a definition where the runtime registrations and declared
    /// revisions are not the same set.
    ///
    /// `contract` binds this stream's expected schema/codec identity,
    /// version, and restartability declaration so the runtime can validate
    /// and migrate an inherited envelope -- and enforce restartability at
    /// binding time -- before `open` ever runs, without introspecting this
    /// stream's opaque internal state.
    #[must_use]
    pub fn with_item_stream(
        mut self,
        identity: ComponentStreamIdentity,
        stream: impl ItemStream + 'static,
        contract: StreamStateContract,
    ) -> Self {
        self.streams.push((
            identity,
            Arc::new(BoxedStream::new(stream)),
            contract,
            StreamOwner::Manual,
        ));
        self
    }

    /// Borrows the step name.
    #[must_use]
    pub const fn name(&self) -> &StepName {
        &self.name
    }

    /// Returns the configured chunk size.
    #[must_use]
    pub const fn size(&self) -> ChunkSize {
        self.size
    }

    /// Executes this step deterministically on the caller's async runtime.
    ///
    /// The reader is stateful, so the definition is mutably borrowed for the
    /// duration of the run. Only counts returned by successful transaction
    /// commits appear in the report. `correlation` identifies the execution for
    /// item, retry, and skip listeners; it never reaches a component.
    pub async fn execute(
        &mut self,
        correlation: &ExecutionCorrelation,
        stop: &StopToken,
    ) -> ChunkExecutionReport
    where
        I: Send + Sync,
        O: Send + Sync,
    {
        execute_chunk_step(self, correlation, stop, None, |_| {}).await
    }
}

/// Validates the bijection between a step's runtime `ItemStream`
/// registrations and its definition's declared stream revisions, and
/// enforces that no registered stream's contract blocks the plan from
/// claiming restartability.
///
/// Restart-relevant stream revisions are declared through
/// [`ChunkComponentRevisions::with_stream_revision`] independently of the
/// runtime registrations a step assembles through
/// [`ChunkStep::with_item_stream`]. Nothing else in the framework proves
/// these two sets describe the same streams, so a mismatch here would
/// otherwise surface only as an opaque runtime `open`/`update` failure (or,
/// worse, silent misbinding) instead of failing before execution begins.
///
/// A chunk definition always carries a checkpoint/restart contract (Gate C),
/// so it implicitly claims restartability; a registered stream whose
/// contract declares [`RestartabilityDeclaration::NotRestartable`] must
/// therefore prevent binding unconditionally -- independent of whether the
/// step's own reader checkpoint exists or is itself restartable.
fn validate_stream_registrations<I, O, R, P, W>(
    step: &ChunkStep<I, O, R, P, W>,
    components: &ChunkComponentRevisions,
) -> Result<(), DefinitionError> {
    let mut seen: BTreeSet<&ComponentStreamIdentity> = BTreeSet::new();
    for (identity, _, contract, _owner) in &step.streams {
        if !seen.insert(identity) {
            return Err(DefinitionError::DuplicateRuntimeStream {
                namespace: identity.clone(),
            });
        }
        if components
            .stream_revisions()
            .all(|(declared, _)| declared != identity)
        {
            return Err(DefinitionError::RuntimeStreamNotDeclared {
                namespace: identity.clone(),
            });
        }
        if contract.restartability() == RestartabilityDeclaration::NotRestartable {
            return Err(DefinitionError::NonRestartableStream {
                namespace: identity.clone(),
            });
        }
    }
    for (declared, _) in components.stream_revisions() {
        if !step
            .streams
            .iter()
            .any(|(identity, _, _, _)| identity == declared)
        {
            return Err(DefinitionError::DeclaredStreamMissingRuntime {
                namespace: declared.clone(),
            });
        }
    }
    Ok(())
}

/// Computes the [`ChunkComponentRevisions`] completion-policy revision token
/// for `policy`: the restart-relevant hash of its live
/// [`CompletionPolicy::fingerprint`], the same one [`ChunkJob::new`] folds
/// in automatically.
///
/// [`ChunkJob::new`] builds its compiled plan and its runtime step from the
/// same call, so it can call this for you. [`FlowJob::with_chunk_step`](crate::FlowJob::with_chunk_step)
/// cannot: a flow node is compiled from bare [`ChunkComponentRevisions`]
/// before any concrete [`ChunkStep`] (or the completion policy it installs)
/// exists, so nothing at compile time can fold a not-yet-installed policy's
/// fingerprint in. Call this explicitly instead, fold the result into the
/// [`ChunkComponentRevisions`] used for *both*
/// [`crate::FlowGraph`](crate::FlowGraph) compilation and the later
/// [`FlowJob::with_chunk_step`](crate::FlowJob::with_chunk_step) call (via
/// [`ChunkComponentRevisions::with_completion_policy_revision`]) -- the same
/// pattern already used to declare a stream revision up front, rather than
/// relying on the automatic folding only a single-call constructor can do.
///
/// The configuration is hashed (rather than embedded verbatim) so an
/// arbitrarily large composite tree still yields a bounded-length revision
/// token.
///
/// # Errors
///
/// Returns [`DefinitionError::CompletionPolicyFingerprintPanic`] if the
/// application-supplied [`CompletionPolicy::fingerprint`] panics, and
/// [`DefinitionError`] if the computed digest somehow failed
/// [`ComponentRevision`]'s token validation, which cannot happen for a fixed
/// hex-digest shape.
pub fn completion_policy_revision(
    policy: &dyn CompletionPolicy,
) -> Result<ComponentRevision, DefinitionError> {
    let fingerprint = catch_unwind(AssertUnwindSafe(|| policy.fingerprint()))
        .map_err(|_| DefinitionError::CompletionPolicyFingerprintPanic)?;
    let digest: [u8; 32] = Sha256::digest(fingerprint.as_bytes()).into();
    let hex = digest.iter().fold(String::new(), |mut hex, byte| {
        use std::fmt::Write as _;
        let _ = write!(hex, "{byte:02x}");
        hex
    });
    ComponentRevision::new(format!("completion:{hex}"))
}

/// Folds an installed completion policy's configuration into the
/// restart-relevant component revisions used to compute a standalone
/// [`ChunkJob`]'s definition fingerprint.
///
/// Computed automatically from the live [`CompletionPolicy::fingerprint`] of
/// whatever policy [`ChunkStep::with_completion_policy`] (or
/// [`ChunkStep::with_adaptive_completion_policy`]) installed, never from an
/// application-supplied token: an application cannot forget to bump a
/// revision it never has to declare, and a configuration change that alters
/// completion semantics always changes the resulting definition fingerprint.
/// A step with no completion policy installed folds in nothing, so its
/// fingerprint stays byte-for-byte identical to one built before this
/// function existed.
///
/// This automatic folding is only sound for [`ChunkJob::new`], which builds
/// the compiled plan and the runtime step together in one call; see
/// [`completion_policy_revision`] for why [`FlowJob::with_chunk_step`](crate::FlowJob::with_chunk_step)
/// cannot do the same and must validate a declared revision instead.
///
/// # Errors
///
/// Returns [`DefinitionError::CompletionPolicyFingerprintPanic`] if the
/// installed policy's application-supplied [`CompletionPolicy::fingerprint`]
/// panics, and [`DefinitionError`] if the computed digest somehow failed
/// [`ComponentRevision`]'s token validation, which cannot happen for a fixed
/// hex-digest shape.
pub(crate) fn completion_policy_component_revisions<I, O, R, P, W>(
    step: &ChunkStep<I, O, R, P, W>,
    components: &ChunkComponentRevisions,
) -> Result<ChunkComponentRevisions, DefinitionError> {
    let Some(policy) = step.completion_policy.as_ref() else {
        return Ok(components.clone());
    };
    let revision = completion_policy_revision(policy.as_ref())?;
    Ok(components.clone().with_completion_policy_revision(revision))
}

/// Validates that a step's live completion-policy fingerprint (if any)
/// matches the completion-policy revision already declared in `revisions`.
///
/// Unlike [`ChunkJob::new`], [`FlowJob::with_chunk_step`](crate::FlowJob::with_chunk_step) binds a runtime
/// step to a plan compiled earlier from bare [`ChunkComponentRevisions`], so
/// it cannot compute this fingerprint for the caller -- it can only check
/// that whatever the caller declared (via [`completion_policy_revision`],
/// folded in before compiling the graph) still matches the step's actual,
/// live policy. A step with no completion policy installed must declare
/// none either.
///
/// # Errors
///
/// Returns [`DefinitionError::CompletionPolicyFingerprintPanic`] if the
/// installed policy's [`CompletionPolicy::fingerprint`] panics, and
/// [`DefinitionError::CompletionPolicyRevisionMismatch`] if the declared and
/// live revisions disagree.
fn validate_completion_policy_revision<I, O, R, P, W>(
    step: &ChunkStep<I, O, R, P, W>,
    revisions: &ChunkComponentRevisions,
) -> Result<(), DefinitionError> {
    let expected = step
        .completion_policy
        .as_ref()
        .map(|policy| completion_policy_revision(policy.as_ref()))
        .transpose()?;
    if expected.as_ref() == revisions.completion_policy_revision() {
        Ok(())
    } else {
        Err(DefinitionError::CompletionPolicyRevisionMismatch)
    }
}

impl<I, O, R, P, W> fmt::Debug for ChunkStep<I, O, R, P, W> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ChunkStep")
            .field("name", &self.name)
            .field("size", &self.size)
            .field("chunk_listener_count", &self.listeners.len())
            .field("step_listener_count", &self.step_listeners.len())
            .field("stream_count", &self.streams.len())
            .finish_non_exhaustive()
    }
}

/// A validated single-step chunk job definition.
pub struct ChunkJob<I, O, R, P, W> {
    name: JobName,
    step_name: StepName,
    plan: CompiledExecutionPlan,
    tasklet: Arc<ChunkTasklet<I, O, R, P, W>>,
    step_listeners: Vec<Arc<dyn StepExecutionListener>>,
    listeners: Vec<Arc<dyn JobExecutionListener>>,
}

impl<I, O, R, P, W> ChunkJob<I, O, R, P, W> {
    /// Constructs a chunk job with explicit restart-relevant revisions.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError::ManifestEncoding`] if the bounded canonical
    /// manifest cannot be encoded, and
    /// [`DefinitionError::DeliveryModeMismatch`] when an installed fault
    /// runtime declares a different delivery mode than the restart contract.
    pub fn new(
        name: JobName,
        mut step: ChunkStep<I, O, R, P, W>,
        revision: DefinitionRevision,
        components: &ChunkComponentRevisions,
    ) -> Result<Self, DefinitionError>
    where
        R: ItemReader<I> + Send + 'static,
        P: ItemProcessor<I, O> + Send + 'static,
        W: ItemWriter<O> + Send + 'static,
    {
        if let Some(fault) = step.fault.as_ref()
            && fault.delivery_mode() != components.delivery_mode()
        {
            return Err(DefinitionError::DeliveryModeMismatch);
        }
        validate_stream_registrations(&step, components)?;
        let components = completion_policy_component_revisions(&step, components)?;
        let components = &components;
        let step_name = step.name.clone();
        let definition =
            DefinitionIdentity::chunk(&name, &step_name, step.size, revision, components)?;
        step.in_flight_policy = components.in_flight_policy();
        step.definition_digest = *definition.manifest_digest();
        let mut node = one_step_node(
            &step_name,
            StepComponents::Chunk {
                size: step.size,
                revisions: Box::new(components.clone()),
            },
        )?;
        if let Some(fault) = step.fault.as_ref() {
            node = node.with_fault_policy(fault.policy().clone());
        }
        let plan = lower_one_step(definition, node)?;
        let step_listeners = step.step_listeners.clone();
        Ok(Self {
            name,
            step_name,
            plan,
            tasklet: Arc::new(ChunkTasklet::new(step)),
            step_listeners,
            listeners: Vec::new(),
        })
    }

    /// Borrows the in-memory compatibility plan this wrapper lowers into.
    ///
    /// The plan retains the wrapper's original manifest bytes, format, and
    /// fingerprint and records no durable flow decision.
    #[must_use]
    pub const fn compiled_plan(&self) -> &CompiledExecutionPlan {
        &self.plan
    }

    /// Borrows the exact restart-relevant definition identity.
    #[must_use]
    pub const fn definition_identity(&self) -> &DefinitionIdentity {
        self.plan.definition_identity()
    }

    /// Registers a job listener in deterministic before-order.
    #[must_use]
    pub fn with_listener(mut self, listener: Arc<dyn JobExecutionListener>) -> Self {
        self.listeners.push(listener);
        self
    }

    /// Borrows the job name.
    #[must_use]
    pub const fn name(&self) -> &JobName {
        &self.name
    }

    /// Borrows the chunk-step name.
    #[must_use]
    pub const fn step_name(&self) -> &StepName {
        &self.step_name
    }
}

impl<I, O, R, P, W> fmt::Debug for ChunkJob<I, O, R, P, W> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ChunkJob")
            .field("name", &self.name)
            .field("step_name", &self.step_name)
            .field("definition", self.plan.definition_identity())
            .field("listener_count", &self.listeners.len())
            .field("step_listener_count", &self.step_listeners.len())
            .finish_non_exhaustive()
    }
}

impl crate::FlowJob {
    /// Binds a stateful chunk step to one compiled flow node.
    ///
    /// The chunk's size, component revisions, delivery mode, and fault policy
    /// must exactly match the immutable plan. The component is erased only at
    /// the existing tasklet composition boundary; the reader, processor, and
    /// writer keep their concrete types (ADR-0008) all the way through, with
    /// [`BoxedReader`](crate::BoxedReader), [`BoxedProcessor`](crate::BoxedProcessor),
    /// and [`BoxedWriter`](crate::BoxedWriter) available if a caller wants
    /// item-level erasure too.
    ///
    /// If `step` installs a [`CompletionPolicy`], `revisions` must already
    /// declare the matching completion-policy revision -- computed via
    /// [`completion_policy_revision`] and folded in with
    /// [`ChunkComponentRevisions::with_completion_policy_revision`] *before*
    /// the enclosing [`crate::FlowGraph`] was compiled, the same way a
    /// stream revision is declared up front rather than derived here.
    /// Unlike [`ChunkJob::new`], this method cannot compute it for you: the
    /// plan was already compiled from bare `ChunkComponentRevisions` before
    /// this step (or the policy it installs) existed.
    ///
    /// # Errors
    ///
    /// Returns [`crate::FlowJobError::ComponentMismatch`] when executable and
    /// manifest declarations differ (including a missing or stale declared
    /// completion-policy revision), or the ordinary binding errors for an
    /// unknown, wrong-kind, duplicate, or differently named node.
    pub fn with_chunk_step<I, O, R, P, W>(
        mut self,
        node_id: crate::NodeId,
        mut step: ChunkStep<I, O, R, P, W>,
        revisions: &ChunkComponentRevisions,
    ) -> Result<Self, crate::FlowJobError>
    where
        I: Send + Sync + 'static,
        O: Send + Sync + 'static,
        R: ItemReader<I> + Send + 'static,
        P: ItemProcessor<I, O> + Send + 'static,
        W: ItemWriter<O> + Send + 'static,
    {
        let Some(crate::FlowNode::Step(compiled)) = self.compiled_plan().node(&node_id) else {
            return Err(crate::FlowJobError::WrongNodeKind { node: node_id });
        };
        if validate_completion_policy_revision(&step, revisions).is_err() {
            return Err(crate::FlowJobError::ComponentMismatch { node: node_id });
        }
        let expected = StepComponents::Chunk {
            size: step.size,
            revisions: Box::new(revisions.clone()),
        };
        if compiled.step_name() != step.name()
            || compiled.components() != &expected
            || compiled.fault_policy() != step.fault.as_ref().map(FaultRuntime::policy)
        {
            return Err(crate::FlowJobError::ComponentMismatch { node: node_id });
        }
        if validate_stream_registrations(&step, revisions).is_err() {
            return Err(crate::FlowJobError::ComponentMismatch { node: node_id });
        }
        step.definition_digest = *self.compiled_plan().fingerprint();
        step.in_flight_policy = revisions.in_flight_policy();
        let listeners = step.step_listeners.clone();
        let tasklet: Arc<dyn Tasklet> = Arc::new(ChunkTasklet::new(step));
        let mut tasklet_step = TaskletStep::new(compiled.step_name().clone(), tasklet);
        for listener in listeners {
            tasklet_step = tasklet_step.with_listener(listener);
        }
        self.bind_chunk_tasklet(node_id, tasklet_step)?;
        Ok(self)
    }
}

struct ChunkTasklet<I, O, R, P, W> {
    step: AsyncMutex<ChunkStep<I, O, R, P, W>>,
    last_report: Mutex<Option<ChunkExecutionReport>>,
}

impl<I, O, R, P, W> ChunkTasklet<I, O, R, P, W>
where
    R: ItemReader<I>,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    fn new(step: ChunkStep<I, O, R, P, W>) -> Self {
        Self {
            step: AsyncMutex::new(step),
            last_report: Mutex::new(None),
        }
    }

    fn take_last_report(&self) -> Option<ChunkExecutionReport> {
        self.last_report
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
    }

    fn clear_last_report(&self) {
        *self
            .last_report
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
    }
}

impl<I, O, R, P, W> Tasklet for ChunkTasklet<I, O, R, P, W>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
    R: ItemReader<I> + Send + 'static,
    P: ItemProcessor<I, O> + Send + 'static,
    W: ItemWriter<O> + Send + 'static,
{
    fn execute<'a>(
        &'a self,
        context: TaskletContext<'a>,
    ) -> BoxFuture<'a, Result<TaskletOutcome, TaskletError>> {
        Box::pin(async move {
            let mut step = self.step.lock().await;
            let transaction_context = ChunkTransactionContext::new(
                context.job_execution_id(),
                context.step_execution_id(),
            );
            let report = execute_chunk_step(
                &mut step,
                context.correlation(),
                context.stop_token(),
                Some(transaction_context),
                |event| match event {
                    ChunkRuntimeEvent::Started(sequence) => {
                        context.emit_chunk_event(LifecycleEventKind::ChunkStarted, sequence);
                    }
                    ChunkRuntimeEvent::Committed(sequence) => {
                        context.emit_chunk_event(LifecycleEventKind::ChunkCommitted, sequence);
                    }
                    ChunkRuntimeEvent::RolledBack(sequence) => {
                        context.emit_chunk_event(LifecycleEventKind::ChunkRolledBack, sequence);
                    }
                    ChunkRuntimeEvent::Unknown(sequence) => {
                        context.emit_chunk_event(LifecycleEventKind::ChunkUnknown, sequence);
                    }
                    ChunkRuntimeEvent::Fault(fault) => context.emit_fault_event(&fault),
                },
            )
            .await;
            let outcome = match report.outcome() {
                ChunkExecutionOutcome::Completed => Ok(TaskletOutcome::Completed),
                ChunkExecutionOutcome::Stopped => Ok(TaskletOutcome::Stopped),
                ChunkExecutionOutcome::Failed(_) => Err(TaskletError::new()),
                ChunkExecutionOutcome::Unknown => Ok(TaskletOutcome::CommitOutcomeUnknown),
            };
            if report.terminal_rollback {
                context.acknowledge_terminal_rollback();
            }
            *self
                .last_report
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(report);
            outcome
        })
    }
}

/// Combined repository lifecycle and chunk-orchestration result.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChunkLaunchReport {
    launch: LaunchReport,
    chunk: Option<ChunkExecutionReport>,
}

impl ChunkLaunchReport {
    /// Borrows the persisted job/step lifecycle result.
    #[must_use]
    pub const fn launch(&self) -> &LaunchReport {
        &self.launch
    }

    /// Borrows chunk evidence when user work reached the chunk step.
    ///
    /// A stop or before-listener failure can finish the launch without
    /// invoking the chunk body.
    #[must_use]
    pub const fn chunk(&self) -> Option<&ChunkExecutionReport> {
        self.chunk.as_ref()
    }
}

impl JobLauncher<'_> {
    /// Launches a stateful one-step chunk job through the existing repository,
    /// lifecycle-listener, and event contracts.
    ///
    /// The mutable job borrow prevents concurrent use of one stateful reader.
    ///
    /// # Errors
    ///
    /// Returns [`LaunchError`] when repository metadata cannot reach a final
    /// state. Component failures are persisted and returned in the reports.
    pub async fn launch_chunk<I, O, R, P, W>(
        &self,
        job: &mut ChunkJob<I, O, R, P, W>,
        parameters: &JobParameters,
        stop: &StopToken,
    ) -> Result<ChunkLaunchReport, LaunchError>
    where
        I: Send + Sync + 'static,
        O: Send + Sync + 'static,
        R: ItemReader<I> + Send + 'static,
        P: ItemProcessor<I, O> + Send + 'static,
        W: ItemWriter<O> + Send + 'static,
    {
        job.tasklet.clear_last_report();
        let tasklet: Arc<dyn Tasklet> = job.tasklet.clone();
        let mut tasklet_step = TaskletStep::new(job.step_name.clone(), tasklet);
        for listener in &job.step_listeners {
            tasklet_step = tasklet_step.with_listener(Arc::clone(listener));
        }
        let mut tasklet_job =
            TaskletJob::from_lowered_plan(job.name.clone(), tasklet_step, job.plan.clone());
        for listener in &job.listeners {
            tasklet_job = tasklet_job.with_listener(Arc::clone(listener));
        }

        let launch = self.launch(&tasklet_job, parameters, stop).await?;
        let chunk = job.tasklet.take_last_report();
        Ok(ChunkLaunchReport { launch, chunk })
    }
}

/// Read-only state supplied at a chunk-listener boundary.
#[derive(Clone, Copy, Debug)]
pub struct ChunkListenerContext<'a> {
    sequence: ChunkCount,
    committed_counts: ChunkCounts,
    stop: &'a StopToken,
}

impl<'a> ChunkListenerContext<'a> {
    const fn new(sequence: ChunkCount, committed_counts: ChunkCounts, stop: &'a StopToken) -> Self {
        Self {
            sequence,
            committed_counts,
            stop,
        }
    }

    /// Returns the nonzero chunk-attempt sequence.
    #[must_use]
    pub const fn sequence(self) -> ChunkCount {
        self.sequence
    }

    /// Returns counts from chunks committed before this attempt.
    #[must_use]
    pub const fn committed_counts(self) -> ChunkCounts {
        self.committed_counts
    }

    /// Borrows the cooperative stop token.
    #[must_use]
    pub const fn stop_token(self) -> &'a StopToken {
        self.stop
    }
}

/// The result visible to an after-chunk listener.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkAttemptOutcome {
    /// The chunk transaction committed.
    Committed,
    /// The transaction rolled back after a failure.
    RolledBack,
    /// Cooperative stop rolled back the open attempt.
    Stopped,
    /// The commit result is unknown and must not be guessed.
    Unknown,
}

/// A value-redacted chunk-listener failure.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ChunkListenerError;

impl ChunkListenerError {
    /// Constructs a listener error without retaining application data.
    #[must_use]
    pub const fn new() -> Self {
        Self
    }
}

impl fmt::Display for ChunkListenerError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("chunk listener failed")
    }
}

impl std::error::Error for ChunkListenerError {}

/// Observes a chunk attempt around its transaction body.
pub trait ChunkListener: Send + Sync {
    /// Runs before the transaction begins.
    fn before_chunk<'a>(
        &'a self,
        context: ChunkListenerContext<'a>,
    ) -> BoxFuture<'a, Result<(), ChunkListenerError>>;

    /// Runs after commit, rollback, stop, or an unknown commit result.
    fn after_chunk<'a>(
        &'a self,
        context: ChunkListenerContext<'a>,
        outcome: ChunkAttemptOutcome,
    ) -> BoxFuture<'a, Result<(), ChunkListenerError>>;
}

/// Whether a chunk listener returned an error or panicked.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkListenerFailureKind {
    /// The listener returned a classified error.
    Error,
    /// The listener panicked before or while its future was polled.
    Panic,
}

/// The listener callback phase.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkListenerPhase {
    /// Before the transaction body.
    BeforeChunk,
    /// After the transaction outcome.
    AfterChunk,
}

/// One redacted chunk-listener failure in callback execution order.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ChunkListenerFailure {
    phase: ChunkListenerPhase,
    registration_index: usize,
    kind: ChunkListenerFailureKind,
}

impl ChunkListenerFailure {
    const fn new(
        phase: ChunkListenerPhase,
        registration_index: usize,
        kind: ChunkListenerFailureKind,
    ) -> Self {
        Self {
            phase,
            registration_index,
            kind,
        }
    }

    /// Returns the callback phase.
    #[must_use]
    pub const fn phase(self) -> ChunkListenerPhase {
        self.phase
    }

    /// Returns the zero-based registration index.
    #[must_use]
    pub const fn registration_index(self) -> usize {
        self.registration_index
    }

    /// Returns whether the listener errored or panicked.
    #[must_use]
    pub const fn kind(self) -> ChunkListenerFailureKind {
        self.kind
    }
}

/// Stable phase classification for a failed chunk step.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkFailure {
    /// Checked count arithmetic rejected the attempted update.
    Count,
    /// The reader returned an error.
    Reader,
    /// The reader panicked.
    ReaderPanic,
    /// The processor returned an error.
    Processor,
    /// The processor panicked.
    ProcessorPanic,
    /// The writer returned an error.
    Writer,
    /// The writer panicked.
    WriterPanic,
    /// A chunk transaction could not begin.
    TransactionBegin,
    /// A chunk transaction was known not to commit.
    TransactionCommit,
    /// Rollback itself failed.
    TransactionRollback,
    /// The post-commit completion callback returned an error.
    Completion,
    /// The post-commit completion callback panicked.
    CompletionPanic,
    /// A chunk listener returned an error.
    Listener,
    /// A chunk listener panicked.
    ListenerPanic,
    /// An item, retry, or skip listener returned an error.
    ItemListener,
    /// An item, retry, or skip listener panicked.
    ItemListenerPanic,
    /// A retry ordinal could not be reserved durably.
    RetryReservation,
    /// Durable fault state was unusable, so no component work began.
    FaultState,
    /// The step already retains its maximum unresolved retry keys.
    RetryStateExhausted,
    /// The selected resource cannot honour the declared policy.
    UnsupportedCapability,
    /// Restoring a required `ItemStream` failed before any component work
    /// began.
    StreamOpen,
    /// An `ItemStream` could not prepare its candidate state for the
    /// committing chunk.
    StreamUpdate,
    /// An `ItemStream` failed to close.
    StreamClose,
    /// A completion policy panicked in `begin_chunk`, `is_complete`, or
    /// `end_chunk`.
    CompletionPolicyPanic,
}

/// Final result of deterministic chunk orchestration.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkExecutionOutcome {
    /// End of input was reached and every open chunk committed.
    Completed,
    /// Cooperative stop was observed at a safe chunk boundary.
    Stopped,
    /// A typed component, listener, count, or transaction failure occurred.
    Failed(ChunkFailure),
    /// Commit outcome is unknown; replay requires durable recovery evidence.
    Unknown,
}

/// In-memory execution evidence returned by a chunk step.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChunkExecutionReport {
    outcome: ChunkExecutionOutcome,
    original_outcome: Option<ChunkExecutionOutcome>,
    committed_counts: ChunkCounts,
    committed_chunks: ChunkCount,
    rolled_back_chunks: ChunkCount,
    listener_failures: Vec<ChunkListenerFailure>,
    item_listener_failures: Vec<ItemListenerFailure>,
    skip_counts: SkipCounts,
    retry_counts: RetryCounts,
    rollback_count: u64,
    no_rollback_count: u64,
    terminal_rollback: bool,
    stream_close_failed: bool,
}

impl ChunkExecutionReport {
    /// Returns the final chunk-step result.
    #[must_use]
    pub const fn outcome(&self) -> ChunkExecutionOutcome {
        self.outcome
    }

    /// Returns whether closing a registered `ItemStream` failed.
    ///
    /// A close failure never erases an earlier primary failure or
    /// already-committed chunks: when the step would otherwise have
    /// completed cleanly, [`Self::outcome`] becomes
    /// `Failed(ChunkFailure::StreamClose)` and [`Self::original_outcome`]
    /// records the superseded `Completed` result; when the step already had
    /// a failure, stop, or unknown outcome, that outcome is unchanged and
    /// this flag is the only signal of the additional close failure.
    #[must_use]
    pub const fn stream_close_failed(&self) -> bool {
        self.stream_close_failed
    }

    /// Merges a stream-close failure into this report without erasing an
    /// earlier primary failure or already-committed chunks.
    fn with_stream_close_failure(mut self) -> Self {
        if matches!(self.outcome, ChunkExecutionOutcome::Completed) {
            self.original_outcome = Some(self.outcome);
            self.outcome = ChunkExecutionOutcome::Failed(ChunkFailure::StreamClose);
        }
        self.stream_close_failed = true;
        self
    }

    /// Returns the result superseded by an after-listener failure.
    #[must_use]
    pub const fn original_outcome(&self) -> Option<ChunkExecutionOutcome> {
        self.original_outcome
    }

    /// Returns aggregate counts from committed chunks only.
    #[must_use]
    pub const fn committed_counts(&self) -> ChunkCounts {
        self.committed_counts
    }

    /// Returns the number of committed chunk transactions.
    #[must_use]
    pub const fn committed_chunks(&self) -> ChunkCount {
        self.committed_chunks
    }

    /// Returns the number of rolled-back chunk transactions.
    #[must_use]
    pub const fn rolled_back_chunks(&self) -> ChunkCount {
        self.rolled_back_chunks
    }

    /// Borrows listener failures in callback execution order.
    #[must_use]
    pub fn listener_failures(&self) -> &[ChunkListenerFailure] {
        &self.listener_failures
    }

    /// Borrows item, retry, and skip listener failures in execution order.
    #[must_use]
    pub fn item_listener_failures(&self) -> &[ItemListenerFailure] {
        &self.item_listener_failures
    }

    /// Returns committed per-phase skip counts.
    ///
    /// A skip appears here only after the chunk that accepted it committed. On
    /// a repository-backed run the totals include the counts this attempt
    /// inherited, because the aggregate skip limit spans every attempt of one
    /// job instance.
    #[must_use]
    pub const fn skip_counts(&self) -> SkipCounts {
        self.skip_counts
    }

    /// Returns per-phase counts of durably reserved retry ordinals.
    ///
    /// The counts include the ordinals this attempt inherited.
    #[must_use]
    pub const fn retry_counts(&self) -> RetryCounts {
        self.retry_counts
    }

    /// Returns framework rollback decisions with a durable acknowledgement.
    ///
    /// A retry reservation and a terminal known rollback each add one. A
    /// database abort caused by process death is not counted. Unlike the skip
    /// and retry counts this value is scoped to the current attempt.
    #[must_use]
    pub const fn rollback_count(&self) -> u64 {
        self.rollback_count
    }

    /// Returns commits that accepted a
    /// [`RollbackDisposition::CommitSafeSkip`], including inherited ones.
    #[must_use]
    pub const fn no_rollback_count(&self) -> u64 {
        self.no_rollback_count
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ChunkRuntimeEvent {
    Started(ChunkCount),
    Committed(ChunkCount),
    RolledBack(ChunkCount),
    Unknown(ChunkCount),
    Fault(FaultRuntimeEvent),
}

/// A post-decision fault observation with only reviewed bounded fields.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct FaultRuntimeEvent {
    pub(crate) kind: LifecycleEventKind,
    pub(crate) sequence: ChunkCount,
    pub(crate) phase: FaultPhase,
    pub(crate) summary: Option<FailureSummary>,
    pub(crate) ordinal: Option<RetryOrdinal>,
    pub(crate) backoff: Option<Duration>,
}

impl FaultRuntimeEvent {
    const fn new(kind: LifecycleEventKind, sequence: ChunkCount, phase: FaultPhase) -> Self {
        Self {
            kind,
            sequence,
            phase,
            summary: None,
            ordinal: None,
            backoff: None,
        }
    }

    const fn with_summary(mut self, summary: FailureSummary) -> Self {
        self.summary = Some(summary);
        self
    }

    const fn with_ordinal(mut self, ordinal: RetryOrdinal) -> Self {
        self.ordinal = Some(ordinal);
        self
    }

    const fn with_backoff(mut self, backoff: Duration) -> Self {
        self.backoff = Some(backoff);
        self
    }
}

struct ExecutionState {
    committed_counts: ChunkCounts,
    committed_chunks: ChunkCount,
    rolled_back_chunks: ChunkCount,
    listener_failures: Vec<ChunkListenerFailure>,
    item_listener_failures: Vec<ItemListenerFailure>,
    skip_counts: SkipCounts,
    retry_counts: RetryCounts,
    rollback_count: u64,
    no_rollback_count: u64,
    terminal_rollback: bool,
    next_failure_id: u64,
}

impl ExecutionState {
    fn new() -> Self {
        Self::inheriting(FaultProgress::NONE)
    }

    /// Starts an attempt from the totals its durable predecessor committed.
    fn inheriting(inherited: FaultProgress) -> Self {
        Self {
            committed_counts: ChunkCounts::default(),
            committed_chunks: ChunkCount::ZERO,
            rolled_back_chunks: ChunkCount::ZERO,
            listener_failures: Vec::new(),
            item_listener_failures: Vec::new(),
            skip_counts: inherited.skips(),
            retry_counts: inherited.retries(),
            rollback_count: 0,
            no_rollback_count: inherited.no_rollbacks(),
            terminal_rollback: false,
            next_failure_id: 0,
        }
    }

    /// Preserves step-scoped fault evidence while resetting per-attempt state.
    fn drain(&mut self) -> Self {
        let mut replacement = Self::new();
        replacement.skip_counts = self.skip_counts;
        replacement.retry_counts = self.retry_counts;
        replacement.rollback_count = self.rollback_count;
        replacement.no_rollback_count = self.no_rollback_count;
        replacement.terminal_rollback = self.terminal_rollback;
        replacement.next_failure_id = self.next_failure_id;
        std::mem::replace(self, replacement)
    }

    fn report(
        self,
        outcome: ChunkExecutionOutcome,
        original_outcome: Option<ChunkExecutionOutcome>,
    ) -> ChunkExecutionReport {
        ChunkExecutionReport {
            outcome,
            original_outcome,
            committed_counts: self.committed_counts,
            committed_chunks: self.committed_chunks,
            rolled_back_chunks: self.rolled_back_chunks,
            listener_failures: self.listener_failures,
            item_listener_failures: self.item_listener_failures,
            skip_counts: self.skip_counts,
            retry_counts: self.retry_counts,
            rollback_count: self.rollback_count,
            no_rollback_count: self.no_rollback_count,
            terminal_rollback: self.terminal_rollback,
            stream_close_failed: false,
        }
    }
}

/// One buffered input retained across the retry replays of a chunk.
struct ItemSlot<I> {
    item: I,
    ordinal: u64,
    skipped: bool,
}

/// One accepted skip awaiting the commit that makes it authoritative.
struct PendingSkip<O> {
    phase: FaultPhase,
    fault: FaultDescriptor,
    disposition: RollbackDisposition,
    slot: Option<usize>,
    output: Option<O>,
}

/// The in-flight retry scope for one key.
struct PendingRetry {
    key: RetryKey,
    fault: FaultDescriptor,
    entered: usize,
}

/// Chunk-scoped work that survives a rollback and its replay.
///
/// A retry rolls the open transaction back and replays the chunk. The reader is
/// stateful and cannot rewind in process, so already-read inputs stay buffered
/// and the replay re-invokes only the components that have not yet succeeded.
struct ChunkBuffer<I, O> {
    slots: Vec<ItemSlot<I>>,
    skips: Vec<PendingSkip<O>>,
    retry: Option<PendingRetry>,
    end_of_input: bool,
    base_ordinal: u64,
    read_ordinal: u64,
    checkpoint_digest: [u8; 32],
}

impl<I, O> ChunkBuffer<I, O> {
    const fn new(base_ordinal: u64, checkpoint_digest: [u8; 32]) -> Self {
        Self {
            slots: Vec::new(),
            skips: Vec::new(),
            retry: None,
            end_of_input: false,
            base_ordinal,
            read_ordinal: base_ordinal,
            checkpoint_digest,
        }
    }
}

/// Returns the fault-tolerance deltas one chunk commit makes authoritative.
fn accepted_fault_progress<O>(skips: &[PendingSkip<O>]) -> Option<ChunkFaultProgress> {
    let mut counts = SkipCounts::ZERO;
    let mut no_rollbacks = 0_u64;
    for skip in skips {
        counts = counts.checked_increment(skip.phase).ok()?;
        if skip.disposition == RollbackDisposition::CommitSafeSkip {
            no_rollbacks = no_rollbacks.checked_add(1)?;
        }
    }
    Some(ChunkFaultProgress::new(counts, no_rollbacks))
}

/// Returns durable skips plus the skips one chunk has not yet committed.
fn projected_skips<O>(committed: SkipCounts, skips: &[PendingSkip<O>]) -> Option<SkipCounts> {
    skips.iter().try_fold(committed, |counts, skip| {
        counts.checked_increment(skip.phase).ok()
    })
}

/// The verdict of one chunk attempt body, before rollback or commit.
enum Verdict {
    /// Every buffered input is classified; the attempt may commit.
    Commit,
    /// A retryable fault ends the attempt, reserves an ordinal, and replays.
    Retry(RetryRequest),
    /// An accepted rollback skip ends the attempt and replays the chunk.
    Replay,
    /// The attempt is terminal.
    Terminal(ChunkExecutionOutcome),
}

/// One retry, reserved after rollback and before backoff.
struct RetryRequest {
    key: RetryKey,
    phase: FaultPhase,
    fault: FaultDescriptor,
    ordinal: RetryOrdinal,
    delay: Duration,
}

/// The result of one complete chunk attempt.
enum AttemptResult {
    /// The chunk transaction committed.
    Committed {
        counts: ChunkCounts,
        receipt: ChunkCommitReceipt,
    },
    /// The attempt rolled back and the chunk replays.
    Replay,
    /// The attempt rolled back and the step is finished.
    RolledBack(ChunkExecutionOutcome),
    /// Rollback itself failed after an earlier outcome.
    RollbackFailed(Option<ChunkExecutionOutcome>),
    /// The commit outcome is unknown and must never be guessed.
    Unknown,
}

/// Borrowed components and policy for one chunk step.
struct Components<'a, I, O, P, W> {
    processor: &'a P,
    writer: &'a W,
    item_listeners: &'a ItemListenerSet<I, O>,
    fault: Option<&'a FaultRuntime>,
    streams: &'a [StreamRegistration],
    step_name: &'a StepName,
    definition_digest: [u8; 32],
    size: ChunkSize,
    completion_policy: Option<&'a dyn CompletionPolicy>,
}

/// Borrowed call state for one chunk attempt.
#[derive(Clone, Copy)]
struct AttemptScope<'a> {
    correlation: &'a ExecutionCorrelation,
    stop: &'a StopToken,
    sequence: ChunkCount,
}

impl<'a> AttemptScope<'a> {
    const fn listener_context(self) -> ItemListenerContext<'a> {
        ItemListenerContext::new(self.correlation, self.sequence, self.stop)
    }
}

/// Provisional writer input for one attempt.
struct AttemptOutputs<O> {
    values: Vec<O>,
    slots: Vec<usize>,
    filtered: u64,
}

impl<O> AttemptOutputs<O> {
    const fn new() -> Self {
        Self {
            values: Vec::new(),
            slots: Vec::new(),
            filtered: 0,
        }
    }

    fn reset(&mut self) {
        self.values.clear();
        self.slots.clear();
        self.filtered = 0;
    }
}

/// One component invocation classified without inspecting its payload.
enum Invoked<T, E> {
    Completed(T),
    Failed(E),
    Panicked,
}

#[allow(
    clippy::similar_names,
    clippy::too_many_lines,
    reason = "the chunk loop keeps the canonical attempt, commit, and stop order visible"
)]
pub(crate) async fn execute_chunk_step<I, O, R, P, W>(
    step: &mut ChunkStep<I, O, R, P, W>,
    correlation: &ExecutionCorrelation,
    stop: &StopToken,
    transaction_context: Option<ChunkTransactionContext>,
    emit: impl FnMut(ChunkRuntimeEvent),
) -> ChunkExecutionReport
where
    I: Send + Sync,
    O: Send + Sync,
    R: ItemReader<I>,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let ChunkStep {
        name,
        size,
        reader,
        processor,
        writer,
        transactions,
        completion,
        completion_policy,
        listeners,
        item_listeners,
        fault,
        streams,
        in_flight_policy,
        definition_digest,
        ..
    } = step;
    let components = Components {
        processor,
        writer,
        item_listeners,
        fault: fault.as_ref(),
        streams,
        step_name: name,
        definition_digest: *definition_digest,
        size: *size,
        completion_policy: completion_policy.as_deref(),
    };

    let (inherited, opened) = match inherited_progress(
        transactions.as_ref(),
        fault.as_ref(),
        transaction_context,
        streams,
        stop,
    )
    .await
    {
        StreamOpenPhaseResult::Opened { progress, streams } => (progress, streams),
        StreamOpenPhaseResult::Failed {
            outcome,
            close_failed,
        } => {
            let report = ExecutionState::new().report(outcome, None);
            return if close_failed {
                report.with_stream_close_failure()
            } else {
                report
            };
        }
    };
    let base_ordinal = inherited.read_ordinal();
    let state = ExecutionState::inheriting(inherited.fault());
    let buffer = ChunkBuffer::new(base_ordinal, inherited.checkpoint_digest());

    let report = run_chunk_loop(
        &components,
        reader,
        correlation,
        stop,
        listeners,
        transactions.as_ref(),
        transaction_context,
        *in_flight_policy,
        completion.as_ref(),
        base_ordinal,
        buffer,
        state,
        emit,
    )
    .await;

    close_opened_streams(&opened, stop, report).await
}

/// Runs [`ItemStream::close`] for every stream that opened successfully, in
/// reverse registration order, and merges any close failure into `report`
/// without erasing an earlier primary failure or already-committed chunks.
async fn close_opened_streams(
    opened: &[Arc<BoxedStream>],
    stop: &StopToken,
    report: ChunkExecutionReport,
) -> ChunkExecutionReport {
    if opened.is_empty() {
        return report;
    }
    let runtime_outcome = match report.outcome() {
        ChunkExecutionOutcome::Completed => StreamRuntimeOutcome::Committed,
        ChunkExecutionOutcome::Stopped => StreamRuntimeOutcome::Stopped,
        ChunkExecutionOutcome::Unknown => StreamRuntimeOutcome::Unknown,
        ChunkExecutionOutcome::Failed(_) => StreamRuntimeOutcome::Failed,
    };
    let context = StreamCloseContext::new(stop, runtime_outcome);
    let close_failed = close_streams(opened, context).await;
    if close_failed {
        report.with_stream_close_failure()
    } else {
        report
    }
}

/// Closes already-opened streams in reverse successful-open order, continuing
/// after an individual close failure so every cleanup call is attempted.
async fn close_streams(streams: &[Arc<BoxedStream>], context: StreamCloseContext<'_>) -> bool {
    let mut close_failed = false;
    for stream in streams.iter().rev() {
        if stream.close(context).await.is_err() {
            close_failed = true;
        }
    }
    close_failed
}

/// Drives one step attempt's per-chunk loop to its terminal
/// [`ChunkExecutionReport`].
///
/// Extracted from [`execute_chunk_step`] as a pure, behavior-preserving
/// refactor so a future "always run before returning" funnel (stream close)
/// can wrap this call without touching the loop's many existing exit points.
#[allow(
    clippy::similar_names,
    clippy::too_many_arguments,
    clippy::too_many_lines,
    reason = "the chunk loop keeps the canonical attempt, commit, and stop order visible"
)]
async fn run_chunk_loop<I, O, E, P, W, R>(
    components: &Components<'_, I, O, P, W>,
    reader: &mut R,
    correlation: &ExecutionCorrelation,
    stop: &StopToken,
    listeners: &[Arc<dyn ChunkListener>],
    transactions: &dyn ChunkTransactionManager,
    transaction_context: Option<ChunkTransactionContext>,
    in_flight_policy: InFlightPolicy,
    completion: &dyn ChunkCompletion,
    base_ordinal: u64,
    mut buffer: ChunkBuffer<I, O>,
    mut state: ExecutionState,
    mut emit: E,
) -> ChunkExecutionReport
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
    R: ItemReader<I>,
{
    let mut sequence = ChunkCount::ZERO;
    loop {
        if stop.is_stop_requested() {
            return state.report(ChunkExecutionOutcome::Stopped, None);
        }
        sequence = match sequence.checked_increment() {
            Ok(value) => value,
            Err(_) => {
                return state.report(ChunkExecutionOutcome::Failed(ChunkFailure::Count), None);
            }
        };
        let listener_context = ChunkListenerContext::new(sequence, state.committed_counts, stop);

        if let Some(failure) = run_before_listeners(listeners, listener_context).await {
            let outcome = listener_failure_outcome(failure.kind());
            state.listener_failures.push(failure);
            return state.report(outcome, None);
        }
        if stop.is_stop_requested() {
            return state.report(ChunkExecutionOutcome::Stopped, None);
        }

        let begun = match transaction_context {
            Some(context) => transactions.begin_for(context).await,
            None => transactions.begin().await,
        };
        let mut transaction = match begun {
            Ok(transaction) => transaction,
            Err(
                ChunkTransactionError::NotCommitted
                | ChunkTransactionError::ComponentStateUnsupported,
            ) => {
                // No transaction ever began this attempt, so its
                // `begin_chunk` never ran either -- `not_begun` reports this
                // truthfully rather than invoking `end_chunk` for a `begin`
                // that never happened.
                return finish_failed_attempt(
                    listeners,
                    CompletionPolicyAttempt::not_begun(components.completion_policy),
                    listener_context,
                    ChunkAttemptOutcome::RolledBack,
                    ChunkExecutionOutcome::Failed(ChunkFailure::TransactionBegin),
                    &mut state,
                )
                .await;
            }
            Err(ChunkTransactionError::CommitOutcomeUnknown) => {
                return finish_failed_attempt(
                    listeners,
                    CompletionPolicyAttempt::not_begun(components.completion_policy),
                    listener_context,
                    ChunkAttemptOutcome::Unknown,
                    ChunkExecutionOutcome::Unknown,
                    &mut state,
                )
                .await;
            }
        };
        emit(ChunkRuntimeEvent::Started(sequence));

        // Once a chunk is open, the definition decides whether a shutdown
        // request remains visible to component calls. The masked token is
        // scoped to this attempt; the real token is consulted immediately
        // after commit so `FinishChunk` never starts another chunk.
        let masked_stop;
        let attempt_stop = match in_flight_policy {
            InFlightPolicy::FinishChunk => {
                let (_, token) = crate::StopSource::new();
                masked_stop = token;
                &masked_stop
            }
            // `InFlightPolicy::RollbackChunk`, and any policy this build does
            // not know: `InFlightPolicy` is `#[non_exhaustive]`, and an
            // unrecognized policy never masks a shutdown request.
            _ => stop,
        };
        let scope = AttemptScope {
            correlation,
            stop: attempt_stop,
            sequence,
        };

        let (result, policy_attempt) = run_attempt(
            components,
            reader,
            scope,
            &mut buffer,
            &mut state,
            transaction.as_mut(),
            &mut emit,
        )
        .await;
        drop(transaction);

        match result {
            AttemptResult::Committed { counts, receipt } => {
                let Ok(next_counts) = state.committed_counts.checked_add(counts) else {
                    return finish_failed_attempt(
                        listeners,
                        policy_attempt,
                        listener_context,
                        ChunkAttemptOutcome::Committed,
                        ChunkExecutionOutcome::Failed(ChunkFailure::Count),
                        &mut state,
                    )
                    .await;
                };
                let Ok(next_chunks) = state.committed_chunks.checked_increment() else {
                    return finish_failed_attempt(
                        listeners,
                        policy_attempt,
                        listener_context,
                        ChunkAttemptOutcome::Committed,
                        ChunkExecutionOutcome::Failed(ChunkFailure::Count),
                        &mut state,
                    )
                    .await;
                };
                state.committed_counts = next_counts;
                state.committed_chunks = next_chunks;
                emit(ChunkRuntimeEvent::Committed(sequence));
                emit_committed_skips(&buffer, sequence, &mut emit);

                let end_of_input = buffer.end_of_input;
                let checkpoint_digest = checkpoint_digest(receipt.checkpoint());
                let Some(next_ordinal) =
                    base_ordinal.checked_add(state.committed_counts.read().get())
                else {
                    return finish_failed_attempt(
                        listeners,
                        policy_attempt,
                        listener_context,
                        ChunkAttemptOutcome::Committed,
                        ChunkExecutionOutcome::Failed(ChunkFailure::Count),
                        &mut state,
                    )
                    .await;
                };
                buffer = ChunkBuffer::new(next_ordinal, checkpoint_digest);

                let completion_context = ChunkCompletionContext::new(
                    receipt.checkpoint(),
                    receipt.execution_context(),
                    counts,
                    stop,
                );
                let terminal_outcome = match invoke_completion(completion, completion_context).await
                {
                    Ok(ChunkCompletionOutcome::Acknowledged) => {
                        if stop.is_stop_requested() {
                            Some(ChunkExecutionOutcome::Stopped)
                        } else if end_of_input {
                            Some(ChunkExecutionOutcome::Completed)
                        } else {
                            None
                        }
                    }
                    Ok(ChunkCompletionOutcome::StoppedAfterCommit) => {
                        Some(ChunkExecutionOutcome::Stopped)
                    }
                    Err(failure) => Some(ChunkExecutionOutcome::Failed(failure)),
                };

                let after_context =
                    ChunkListenerContext::new(sequence, state.committed_counts, stop);
                let after_failures =
                    run_after_listeners(listeners, after_context, ChunkAttemptOutcome::Committed)
                        .await;
                // `end_chunk` observes this attempt's transaction outcome
                // (already committed by this point), never a listener's
                // outcome, so it always runs here -- even when an
                // `after_chunk` listener below fails -- or an
                // AdaptiveCompletionPolicy's pending candidate would never
                // promote to confirmed for a chunk that in fact committed,
                // leaving durable and in-memory state disagreeing about the
                // authoritative target for the rest of this process.
                let completion_policy_panicked = policy_attempt
                    .finish(ChunkAttemptOutcome::Committed)
                    .is_err();
                if let Some(first) = after_failures.first().copied() {
                    state.listener_failures.extend(after_failures);
                    let original = terminal_outcome.or(Some(ChunkExecutionOutcome::Completed));
                    return state.report(listener_failure_outcome(first.kind()), original);
                }
                if completion_policy_panicked {
                    let original = terminal_outcome.or(Some(ChunkExecutionOutcome::Completed));
                    return state.report(
                        ChunkExecutionOutcome::Failed(ChunkFailure::CompletionPolicyPanic),
                        original,
                    );
                }
                if let Some(outcome) = terminal_outcome {
                    return state.report(outcome, None);
                }
            }
            AttemptResult::Replay => {
                if let Err(report) = record_rolled_back_attempt(
                    listeners,
                    policy_attempt,
                    listener_context,
                    &mut state,
                    &mut emit,
                )
                .await
                {
                    return report;
                }
            }
            AttemptResult::RolledBack(ChunkExecutionOutcome::Completed) => {
                // The final chunk read nothing, so its unused transaction rolls
                // back without counting as a rolled-back attempt.
                emit(ChunkRuntimeEvent::RolledBack(sequence));
                let failures = run_after_listeners(
                    listeners,
                    listener_context,
                    ChunkAttemptOutcome::RolledBack,
                )
                .await;
                let completion_policy_panicked = policy_attempt
                    .finish(ChunkAttemptOutcome::RolledBack)
                    .is_err();
                if let Some(first) = failures.first().copied() {
                    state.listener_failures.extend(failures);
                    return state
                        .drain()
                        .report(listener_failure_outcome(first.kind()), None);
                }
                if completion_policy_panicked {
                    return state.drain().report(
                        ChunkExecutionOutcome::Failed(ChunkFailure::CompletionPolicyPanic),
                        None,
                    );
                }
                return state.report(ChunkExecutionOutcome::Completed, None);
            }
            AttemptResult::RolledBack(outcome) => {
                state.rollback_count = state.rollback_count.saturating_add(1);
                state.terminal_rollback = true;
                state.rolled_back_chunks = match state.rolled_back_chunks.checked_increment() {
                    Ok(count) => count,
                    Err(_) => {
                        return state.drain().report(
                            ChunkExecutionOutcome::Failed(ChunkFailure::Count),
                            Some(outcome),
                        );
                    }
                };
                emit(ChunkRuntimeEvent::RolledBack(sequence));
                let attempt_outcome = match outcome {
                    ChunkExecutionOutcome::Stopped => ChunkAttemptOutcome::Stopped,
                    _ => ChunkAttemptOutcome::RolledBack,
                };
                return finish_failed_attempt(
                    listeners,
                    policy_attempt,
                    listener_context,
                    attempt_outcome,
                    outcome,
                    &mut state,
                )
                .await;
            }
            AttemptResult::RollbackFailed(original) => {
                // Rollback failure must never suppress a policy lifecycle
                // this attempt already began: the transaction's fate is no
                // longer knowable, so `end_chunk` observes `Unknown` rather
                // than being skipped -- see `CompletionPolicy::end_chunk`.
                let completion_policy_panicked =
                    policy_attempt.finish(ChunkAttemptOutcome::Unknown).is_err();
                if completion_policy_panicked {
                    return state.drain().report(
                        ChunkExecutionOutcome::Failed(ChunkFailure::CompletionPolicyPanic),
                        Some(ChunkExecutionOutcome::Failed(
                            ChunkFailure::TransactionRollback,
                        )),
                    );
                }
                return state.drain().report(
                    ChunkExecutionOutcome::Failed(ChunkFailure::TransactionRollback),
                    original,
                );
            }
            AttemptResult::Unknown => {
                emit(ChunkRuntimeEvent::Unknown(sequence));
                return finish_failed_attempt(
                    listeners,
                    policy_attempt,
                    listener_context,
                    ChunkAttemptOutcome::Unknown,
                    ChunkExecutionOutcome::Unknown,
                    &mut state,
                )
                .await;
            }
        }
    }
}

/// Loads the durable progress this attempt inherits and binds durable state.
///
/// A standalone chunk step has no repository execution and inherits nothing. A
/// repository-backed step fails closed rather than restarting a bounded policy
/// limit from zero or deriving retry keys from the wrong checkpoint.
enum StreamOpenPhaseResult {
    Opened {
        progress: InheritedStepProgress,
        streams: Vec<Arc<BoxedStream>>,
    },
    Failed {
        outcome: ChunkExecutionOutcome,
        close_failed: bool,
    },
}

async fn inherited_progress(
    transactions: &dyn ChunkTransactionManager,
    fault: Option<&FaultRuntime>,
    context: Option<ChunkTransactionContext>,
    streams: &[StreamRegistration],
    stop: &StopToken,
) -> StreamOpenPhaseResult {
    let inherited_state = match context {
        None => Vec::new(),
        Some(_) if streams.is_empty() => Vec::new(),
        Some(context) => match transactions.inherited_component_state(context).await {
            Ok(state) => state,
            Err(_) => {
                return StreamOpenPhaseResult::Failed {
                    outcome: ChunkExecutionOutcome::Failed(ChunkFailure::StreamOpen),
                    close_failed: false,
                };
            }
        },
    };

    let progress = match context {
        None => InheritedStepProgress::NONE,
        Some(context) => {
            if let Some(fault) = fault
                && fault.state().bind(context).await.is_err()
            {
                return StreamOpenPhaseResult::Failed {
                    outcome: ChunkExecutionOutcome::Failed(ChunkFailure::FaultState),
                    close_failed: false,
                };
            }
            match transactions.inherited_progress(context).await {
                Ok(inherited) => inherited,
                Err(ChunkTransactionError::CommitOutcomeUnknown) => {
                    return StreamOpenPhaseResult::Failed {
                        outcome: ChunkExecutionOutcome::Unknown,
                        close_failed: false,
                    };
                }
                Err(
                    ChunkTransactionError::NotCommitted
                    | ChunkTransactionError::ComponentStateUnsupported,
                ) => {
                    return StreamOpenPhaseResult::Failed {
                        outcome: ChunkExecutionOutcome::Failed(ChunkFailure::FaultState),
                        close_failed: false,
                    };
                }
            }
        }
    };

    let mut opened: Vec<Arc<BoxedStream>> = Vec::with_capacity(streams.len());
    for (identity, stream, contract, _owner) in streams {
        let envelope = inherited_state
            .iter()
            .find(|envelope| envelope.namespace() == identity);
        // Gate C: an inherited envelope is validated against this stream's
        // declared schema/codec contract and migrated to its current
        // versions -- rejecting an unknown/newer schema or codec, or a
        // migration failure -- before `open` ever runs. `open` never
        // observes an envelope this contract has not already accepted.
        let validated = match envelope.map(|envelope| contract.validate_for_open(envelope)) {
            None => None,
            Some(Ok(migrated)) => Some(migrated),
            Some(Err(_)) => {
                let close_context = StreamCloseContext::new(stop, StreamRuntimeOutcome::Failed);
                let close_failed = close_streams(&opened, close_context).await;
                return StreamOpenPhaseResult::Failed {
                    outcome: ChunkExecutionOutcome::Failed(ChunkFailure::StreamOpen),
                    close_failed,
                };
            }
        };
        let open_context = StreamOpenContext::new(validated.as_ref(), stop);
        if stream.open(open_context).await.is_ok() {
            opened.push(Arc::clone(stream));
        } else {
            let close_context = StreamCloseContext::new(stop, StreamRuntimeOutcome::Failed);
            let close_failed = close_streams(&opened, close_context).await;
            return StreamOpenPhaseResult::Failed {
                outcome: ChunkExecutionOutcome::Failed(ChunkFailure::StreamOpen),
                close_failed,
            };
        }
    }
    StreamOpenPhaseResult::Opened {
        progress,
        streams: opened,
    }
}

/// Counts one rolled-back attempt and runs its after-chunk listeners.
async fn record_rolled_back_attempt<E>(
    listeners: &[Arc<dyn ChunkListener>],
    policy_attempt: CompletionPolicyAttempt<'_>,
    context: ChunkListenerContext<'_>,
    state: &mut ExecutionState,
    emit: &mut E,
) -> Result<(), ChunkExecutionReport>
where
    E: FnMut(ChunkRuntimeEvent),
{
    state.rolled_back_chunks = match state.rolled_back_chunks.checked_increment() {
        Ok(count) => count,
        Err(_) => {
            return Err(state
                .drain()
                .report(ChunkExecutionOutcome::Failed(ChunkFailure::Count), None));
        }
    };
    emit(ChunkRuntimeEvent::RolledBack(context.sequence()));
    let failures = run_after_listeners(listeners, context, ChunkAttemptOutcome::RolledBack).await;
    let completion_policy_panicked = policy_attempt
        .finish(ChunkAttemptOutcome::RolledBack)
        .is_err();
    if let Some(first) = failures.first().copied() {
        state.listener_failures.extend(failures);
        return Err(state
            .drain()
            .report(listener_failure_outcome(first.kind()), None));
    }
    if completion_policy_panicked {
        return Err(state.drain().report(
            ChunkExecutionOutcome::Failed(ChunkFailure::CompletionPolicyPanic),
            None,
        ));
    }
    Ok(())
}

async fn run_attempt<'c, I, O, E, P, W, R>(
    components: &Components<'c, I, O, P, W>,
    reader: &mut R,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    transaction: &mut dyn ChunkTransaction,
    emit: &mut E,
) -> (AttemptResult, CompletionPolicyAttempt<'c>)
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
    R: ItemReader<I>,
{
    let mut outputs = AttemptOutputs::new();
    let mut component_state = Vec::new();
    // Constructed first, before any other phase of this attempt: every
    // attempt whose transaction has already begun (this function only runs
    // once one has) owes exactly one `begin_chunk`/`end_chunk` pair,
    // regardless of what happens afterward in this attempt -- see the
    // lifecycle contract on `CompletionPolicy::begin_chunk`.
    let policy_attempt = CompletionPolicyAttempt::begin(components.completion_policy);

    let verdict = 'body: {
        if policy_attempt.begin_panicked() {
            break 'body Verdict::Terminal(ChunkExecutionOutcome::Failed(
                ChunkFailure::CompletionPolicyPanic,
            ));
        }
        if let Some(fault) = components.fault
            && fault.policy().requires_commit_safe_skip()
            && transaction.business_transaction().is_none()
        {
            break 'body Verdict::Terminal(ChunkExecutionOutcome::Failed(
                ChunkFailure::UnsupportedCapability,
            ));
        }

        match read_phase(components, reader, scope, buffer, state, emit).await {
            Verdict::Commit => {}
            other => break 'body other,
        }

        if buffer.slots.is_empty() && buffer.end_of_input && buffer.skips.is_empty() {
            break 'body Verdict::Terminal(ChunkExecutionOutcome::Completed);
        }

        match process_phase(components, scope, buffer, state, &mut outputs, emit).await {
            Verdict::Commit => {}
            other => break 'body other,
        }

        write_phase(
            components,
            scope,
            buffer,
            state,
            &mut outputs,
            transaction,
            &mut component_state,
            emit,
        )
        .await
    };

    let result = match verdict {
        Verdict::Commit => {
            commit_attempt(
                components,
                scope,
                buffer,
                state,
                transaction,
                &outputs,
                &component_state,
            )
            .await
        }
        Verdict::Retry(request) => {
            schedule_retry(components, scope, buffer, state, transaction, request, emit).await
        }
        Verdict::Replay => {
            if transaction.rollback().await.is_err() {
                AttemptResult::RollbackFailed(None)
            } else {
                AttemptResult::Replay
            }
        }
        Verdict::Terminal(ChunkExecutionOutcome::Unknown) => AttemptResult::Unknown,
        Verdict::Terminal(outcome) => {
            if transaction.rollback().await.is_err() {
                AttemptResult::RollbackFailed(Some(outcome))
            } else {
                AttemptResult::RolledBack(outcome)
            }
        }
    };
    (result, policy_attempt)
}

/// Reads until the chunk is full or the input ends.
#[allow(
    clippy::too_many_lines,
    reason = "one phase keeps its listener, classification, and skip order visible"
)]
async fn read_phase<I, O, E, P, W, R>(
    components: &Components<'_, I, O, P, W>,
    reader: &mut R,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    emit: &mut E,
) -> Verdict
where
    I: Send + Sync,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
    R: ItemReader<I>,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
{
    let listener_context = scope.listener_context();
    loop {
        if buffer.end_of_input || buffer.slots.len() >= components.size.get() as usize {
            break;
        }
        // Forward-progress invariant (`REPEAT-POLICY-001` livelock guard):
        // consult the completion policy only once this attempt has actually
        // accepted at least one item. A policy that reports
        // `is_complete(0) == true` can therefore never stop this attempt
        // before it has read (or exhausted) at least one input, so the step
        // can never repeatedly commit an all-empty chunk purely on the
        // policy's say-so -- see `CompletionPolicy::is_complete`.
        if !buffer.slots.is_empty()
            && let Some(policy) = components.completion_policy
        {
            match invoke_completion_policy_is_complete(
                policy,
                ChunkCount::new(buffer.slots.len() as u64),
            ) {
                Ok(true) => break,
                Ok(false) => {}
                Err(()) => {
                    return Verdict::Terminal(ChunkExecutionOutcome::Failed(
                        ChunkFailure::CompletionPolicyPanic,
                    ));
                }
            }
        }
        if scope.stop.is_stop_requested() {
            return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
        }
        let ordinal = buffer.read_ordinal;
        let key = retry_key(
            components,
            buffer.checkpoint_digest,
            FaultPhase::Read,
            ordinal,
        );

        let before = components
            .item_listeners
            .before_read(listener_context)
            .await;
        if let Some(failure) = before.failure() {
            state.item_listener_failures.push(failure);
            return Verdict::Terminal(item_listener_outcome(failure.kind()));
        }

        match invoke_reader(reader, ReadContext::new(scope.stop)).await {
            Invoked::Completed(ReadOutcome::Item(item)) => {
                let failures = components
                    .item_listeners
                    .after_read(before.entered(), &item, listener_context)
                    .await;
                if let Some(first) = failures.first().copied() {
                    state.item_listener_failures.extend(failures);
                    return Verdict::Terminal(item_listener_outcome(first.kind()));
                }
                if let Some(outcome) = complete_retry(
                    components,
                    listener_context,
                    &mut buffer.retry,
                    state,
                    key,
                    RetryOutcome::Recovered,
                )
                .await
                {
                    return Verdict::Terminal(outcome);
                }
                resolve_key(components, key).await;
                buffer.slots.push(ItemSlot {
                    item,
                    ordinal,
                    skipped: false,
                });
                buffer.read_ordinal = buffer.read_ordinal.saturating_add(1);
            }
            Invoked::Completed(ReadOutcome::EndOfInput) => buffer.end_of_input = true,
            Invoked::Completed(ReadOutcome::Stopped) => {
                return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
            }
            invoked => {
                let (error, panicked) = match invoked {
                    Invoked::Failed(error) => (error, false),
                    _ => (ReaderError::new(), true),
                };
                let terminal = if panicked {
                    ChunkFailure::ReaderPanic
                } else {
                    ChunkFailure::Reader
                };
                let advanced = !panicked && error.has_checkpoint_advanced();
                let Some(fault) = descriptor(
                    components,
                    state,
                    &buffer.skips,
                    FaultPhase::Read,
                    error.category(),
                ) else {
                    return Verdict::Terminal(ChunkExecutionOutcome::Failed(ChunkFailure::Count));
                };
                let fault = with_reserved_ordinal(components, key, fault).await;

                let failures = components
                    .item_listeners
                    .on_read_error(before.entered(), fault, listener_context)
                    .await;
                if let Some(first) = failures.first().copied() {
                    state.item_listener_failures.extend(failures);
                    return Verdict::Terminal(item_listener_outcome(first.kind()));
                }

                let evidence = FaultEvidence::new(advanced, true, advanced);
                let decision = match classify(
                    components,
                    listener_context,
                    &mut buffer.retry,
                    state,
                    key,
                    fault,
                    evidence,
                    scope.sequence,
                    emit,
                )
                .await
                {
                    Ok(decision) => decision,
                    Err(outcome) => return Verdict::Terminal(outcome),
                };
                match decision {
                    FaultDecision::Retry { ordinal, delay } => {
                        return Verdict::Retry(RetryRequest {
                            key,
                            phase: FaultPhase::Read,
                            fault,
                            ordinal,
                            delay,
                        });
                    }
                    FaultDecision::Skip { disposition } => {
                        resolve_key(components, key).await;
                        buffer.read_ordinal = buffer.read_ordinal.saturating_add(1);
                        buffer.skips.push(PendingSkip {
                            phase: FaultPhase::Read,
                            fault,
                            disposition,
                            slot: None,
                            output: None,
                        });
                        if disposition == RollbackDisposition::Rollback {
                            return Verdict::Replay;
                        }
                    }
                    FaultDecision::Unknown => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Unknown);
                    }
                    FaultDecision::Stop => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
                    }
                    // `FaultDecision::FailAndRollback`, and any decision this
                    // build does not know: `FaultDecision` is
                    // `#[non_exhaustive]`, and an unrecognized decision rolls
                    // back and fails rather than committing work or claiming an
                    // unknown commit.
                    _ => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Failed(terminal));
                    }
                }
            }
        }
    }
    Verdict::Commit
}

/// Processes every buffered input that is not already skipped.
#[allow(
    clippy::too_many_lines,
    reason = "one phase keeps its listener, classification, and skip order visible"
)]
async fn process_phase<I, O, E, P, W>(
    components: &Components<'_, I, O, P, W>,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    outputs: &mut AttemptOutputs<O>,
    emit: &mut E,
) -> Verdict
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let listener_context = scope.listener_context();
    outputs.reset();
    for index in 0..buffer.slots.len() {
        if buffer.slots[index].skipped {
            continue;
        }
        if scope.stop.is_stop_requested() {
            return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
        }
        let ordinal = buffer.slots[index].ordinal;
        let key = retry_key(
            components,
            buffer.checkpoint_digest,
            FaultPhase::Process,
            ordinal,
        );

        let before = components
            .item_listeners
            .before_process(&buffer.slots[index].item, listener_context)
            .await;
        if let Some(failure) = before.failure() {
            state.item_listener_failures.push(failure);
            return Verdict::Terminal(item_listener_outcome(failure.kind()));
        }

        let invoked = invoke_processor(
            components.processor,
            &buffer.slots[index].item,
            ProcessContext::new(scope.stop),
        )
        .await;
        match invoked {
            Invoked::Completed(ProcessOutcome::Item(output)) => {
                let failures = components
                    .item_listeners
                    .after_process(
                        before.entered(),
                        &buffer.slots[index].item,
                        Some(&output),
                        listener_context,
                    )
                    .await;
                if let Some(first) = failures.first().copied() {
                    state.item_listener_failures.extend(failures);
                    return Verdict::Terminal(item_listener_outcome(first.kind()));
                }
                if let Some(outcome) = complete_retry(
                    components,
                    listener_context,
                    &mut buffer.retry,
                    state,
                    key,
                    RetryOutcome::Recovered,
                )
                .await
                {
                    return Verdict::Terminal(outcome);
                }
                resolve_key(components, key).await;
                outputs.values.push(output);
                outputs.slots.push(index);
            }
            Invoked::Completed(ProcessOutcome::Filtered) => {
                let failures = components
                    .item_listeners
                    .after_process(
                        before.entered(),
                        &buffer.slots[index].item,
                        None,
                        listener_context,
                    )
                    .await;
                if let Some(first) = failures.first().copied() {
                    state.item_listener_failures.extend(failures);
                    return Verdict::Terminal(item_listener_outcome(first.kind()));
                }
                if let Some(outcome) = complete_retry(
                    components,
                    listener_context,
                    &mut buffer.retry,
                    state,
                    key,
                    RetryOutcome::Recovered,
                )
                .await
                {
                    return Verdict::Terminal(outcome);
                }
                resolve_key(components, key).await;
                outputs.filtered = outputs.filtered.saturating_add(1);
            }
            Invoked::Completed(ProcessOutcome::Stopped) => {
                return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
            }
            invoked => {
                let (error, panicked) = match invoked {
                    Invoked::Failed(error) => (error, false),
                    _ => (ProcessorError::new(), true),
                };
                let terminal = if panicked {
                    ChunkFailure::ProcessorPanic
                } else {
                    ChunkFailure::Processor
                };
                let Some(fault) = descriptor(
                    components,
                    state,
                    &buffer.skips,
                    FaultPhase::Process,
                    error.category(),
                ) else {
                    return Verdict::Terminal(ChunkExecutionOutcome::Failed(ChunkFailure::Count));
                };
                let fault = with_reserved_ordinal(components, key, fault).await;

                let failures = components
                    .item_listeners
                    .on_process_error(
                        before.entered(),
                        &buffer.slots[index].item,
                        fault,
                        listener_context,
                    )
                    .await;
                if let Some(first) = failures.first().copied() {
                    state.item_listener_failures.extend(failures);
                    return Verdict::Terminal(item_listener_outcome(first.kind()));
                }

                // The input is located and no writer effect has started, so the
                // framework owns every piece of process-skip evidence.
                let evidence = FaultEvidence::new(true, true, true);
                let decision = match classify(
                    components,
                    listener_context,
                    &mut buffer.retry,
                    state,
                    key,
                    fault,
                    evidence,
                    scope.sequence,
                    emit,
                )
                .await
                {
                    Ok(decision) => decision,
                    Err(outcome) => return Verdict::Terminal(outcome),
                };
                match decision {
                    FaultDecision::Retry { ordinal, delay } => {
                        return Verdict::Retry(RetryRequest {
                            key,
                            phase: FaultPhase::Process,
                            fault,
                            ordinal,
                            delay,
                        });
                    }
                    FaultDecision::Skip { disposition } => {
                        resolve_key(components, key).await;
                        buffer.slots[index].skipped = true;
                        buffer.skips.push(PendingSkip {
                            phase: FaultPhase::Process,
                            fault,
                            disposition,
                            slot: Some(index),
                            output: None,
                        });
                        if disposition == RollbackDisposition::Rollback {
                            return Verdict::Replay;
                        }
                    }
                    FaultDecision::Unknown => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Unknown);
                    }
                    FaultDecision::Stop => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
                    }
                    // `FaultDecision::FailAndRollback`, and any decision this
                    // build does not know: `FaultDecision` is
                    // `#[non_exhaustive]`, and an unrecognized decision rolls
                    // back and fails rather than committing work or claiming an
                    // unknown commit.
                    _ => {
                        return Verdict::Terminal(ChunkExecutionOutcome::Failed(terminal));
                    }
                }
            }
        }
    }
    Verdict::Commit
}

/// Writes the provisional output batch inside the open transaction.
#[allow(
    clippy::too_many_lines,
    reason = "one phase keeps its listener, classification, and skip order visible"
)]
#[allow(
    clippy::too_many_arguments,
    reason = "the write boundary needs components, scope, buffer, state, outputs, and the transaction"
)]
async fn write_phase<I, O, E, P, W>(
    components: &Components<'_, I, O, P, W>,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    outputs: &mut AttemptOutputs<O>,
    transaction: &mut dyn ChunkTransaction,
    component_state: &mut Vec<ComponentStateEnvelope>,
    emit: &mut E,
) -> Verdict
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    if outputs.values.is_empty() {
        return update_streams(components, scope, component_state).await;
    }
    if scope.stop.is_stop_requested() {
        return Verdict::Terminal(ChunkExecutionOutcome::Stopped);
    }
    let listener_context = scope.listener_context();
    let key = retry_key(
        components,
        buffer.checkpoint_digest,
        FaultPhase::Write,
        buffer.base_ordinal,
    );

    let before = components
        .item_listeners
        .before_write(&outputs.values, listener_context)
        .await;
    if let Some(failure) = before.failure() {
        state.item_listener_failures.push(failure);
        return Verdict::Terminal(item_listener_outcome(failure.kind()));
    }

    let write_context = match transaction.business_transaction() {
        Some(business) => WriteContext::enlisted(scope.stop, business),
        None => WriteContext::non_transactional(scope.stop),
    };
    match invoke_writer(components.writer, &outputs.values, write_context).await {
        Invoked::Completed(WriteOutcome::Written) => {
            let failures = components
                .item_listeners
                .after_write(before.entered(), &outputs.values, listener_context)
                .await;
            if let Some(first) = failures.first().copied() {
                state.item_listener_failures.extend(failures);
                return Verdict::Terminal(item_listener_outcome(first.kind()));
            }
            if let Some(outcome) = complete_retry(
                components,
                listener_context,
                &mut buffer.retry,
                state,
                key,
                RetryOutcome::Recovered,
            )
            .await
            {
                return Verdict::Terminal(outcome);
            }
            resolve_key(components, key).await;
            update_streams(components, scope, component_state).await
        }
        Invoked::Completed(WriteOutcome::Stopped) => {
            Verdict::Terminal(ChunkExecutionOutcome::Stopped)
        }
        invoked => {
            let (error, panicked) = match invoked {
                Invoked::Failed(error) => (error, false),
                _ => (WriterError::new(), true),
            };
            let terminal = if panicked {
                ChunkFailure::WriterPanic
            } else {
                ChunkFailure::Writer
            };
            let located = if panicked {
                None
            } else {
                error
                    .rolled_back_output()
                    .filter(|index| *index < outputs.values.len())
            };
            let Some(fault) = descriptor(
                components,
                state,
                &buffer.skips,
                FaultPhase::Write,
                error.category(),
            ) else {
                return Verdict::Terminal(ChunkExecutionOutcome::Failed(ChunkFailure::Count));
            };
            let fault = with_reserved_ordinal(components, key, fault).await;

            let failures = components
                .item_listeners
                .on_write_error(before.entered(), &outputs.values, fault, listener_context)
                .await;
            if let Some(first) = failures.first().copied() {
                state.item_listener_failures.extend(failures);
                return Verdict::Terminal(item_listener_outcome(first.kind()));
            }

            let evidence = FaultEvidence::new(located.is_some(), located.is_some(), false);
            let decision = match classify(
                components,
                listener_context,
                &mut buffer.retry,
                state,
                key,
                fault,
                evidence,
                scope.sequence,
                emit,
            )
            .await
            {
                Ok(decision) => decision,
                Err(outcome) => return Verdict::Terminal(outcome),
            };
            match decision {
                FaultDecision::Retry { ordinal, delay } => Verdict::Retry(RetryRequest {
                    key,
                    phase: FaultPhase::Write,
                    fault,
                    ordinal,
                    delay,
                }),
                FaultDecision::Skip { disposition } => {
                    let Some(index) = located else {
                        return Verdict::Terminal(ChunkExecutionOutcome::Failed(terminal));
                    };
                    resolve_key(components, key).await;
                    let slot = outputs.slots[index];
                    buffer.slots[slot].skipped = true;
                    buffer.skips.push(PendingSkip {
                        phase: FaultPhase::Write,
                        fault,
                        disposition,
                        slot: Some(slot),
                        output: Some(outputs.values.remove(index)),
                    });
                    outputs.slots.remove(index);
                    Verdict::Replay
                }
                FaultDecision::Unknown => Verdict::Terminal(ChunkExecutionOutcome::Unknown),
                FaultDecision::Stop => Verdict::Terminal(ChunkExecutionOutcome::Stopped),
                // `FaultDecision::FailAndRollback`, and any decision this build
                // does not know: `FaultDecision` is `#[non_exhaustive]`, and an
                // unrecognized decision rolls back and fails rather than
                // committing work or claiming an unknown commit.
                _ => Verdict::Terminal(ChunkExecutionOutcome::Failed(terminal)),
            }
        }
    }
}

/// Prepares each registered `ItemStream`'s candidate state for the
/// committing chunk, in registration order.
///
/// Runs once per committing attempt, after the writer has accepted the
/// chunk and before the durable commit -- never per item. A failure here
/// prevents the candidate commit, matching process/write-error handling: no
/// partial commit. A stream that returns an envelope carrying a namespace
/// other than its own registered identity is rejected here, before the
/// candidate ever reaches the durable UPSERT: an unregistered or mismatched
/// namespace on the persisted side would let one stream silently overwrite
/// another's committed state.
async fn update_streams<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    scope: AttemptScope<'_>,
    component_state: &mut Vec<ComponentStateEnvelope>,
) -> Verdict {
    component_state.clear();
    let context = StreamUpdateContext::new(scope.stop);
    for (identity, stream, _, _owner) in components.streams {
        match stream.update(context).await {
            Ok(envelope) if envelope.namespace() == identity => component_state.push(envelope),
            Ok(_) | Err(_) => {
                component_state.clear();
                return Verdict::Terminal(ChunkExecutionOutcome::Failed(
                    ChunkFailure::StreamUpdate,
                ));
            }
        }
    }
    Verdict::Commit
}

/// Runs skip callbacks, clears resolved keys, and commits the chunk.
async fn commit_attempt<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    transaction: &mut dyn ChunkTransaction,
    outputs: &AttemptOutputs<O>,
    component_state: &[ComponentStateEnvelope],
) -> AttemptResult
where
    I: Send + Sync,
    O: Send + Sync,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let listener_context = scope.listener_context();
    for skip in &buffer.skips {
        let failures = match (skip.phase, skip.slot, skip.output.as_ref()) {
            (FaultPhase::Process, Some(index), _) => {
                components
                    .item_listeners
                    .on_skip_in_process(&buffer.slots[index].item, skip.fault, listener_context)
                    .await
            }
            (FaultPhase::Write, _, Some(output)) => {
                components
                    .item_listeners
                    .on_skip_in_write(output, skip.fault, listener_context)
                    .await
            }
            _ => {
                components
                    .item_listeners
                    .on_skip_in_read(skip.fault, listener_context)
                    .await
            }
        };
        if let Some(first) = failures.first().copied() {
            state.item_listener_failures.extend(failures);
            let outcome = item_listener_outcome(first.kind());
            if transaction.rollback().await.is_err() {
                return AttemptResult::RollbackFailed(Some(outcome));
            }
            return AttemptResult::RolledBack(outcome);
        }
    }

    let read = ChunkCount::new(buffer.slots.len() as u64);
    let processed = ChunkCount::new(outputs.values.len() as u64);
    let Ok(counts) = ChunkCounts::new(
        read,
        processed,
        processed,
        ChunkCount::new(outputs.filtered),
    ) else {
        let outcome = ChunkExecutionOutcome::Failed(ChunkFailure::Count);
        if transaction.rollback().await.is_err() {
            return AttemptResult::RollbackFailed(Some(outcome));
        }
        return AttemptResult::RolledBack(outcome);
    };

    let Some(accepted) = accepted_fault_progress(&buffer.skips) else {
        let outcome = ChunkExecutionOutcome::Failed(ChunkFailure::Count);
        if transaction.rollback().await.is_err() {
            return AttemptResult::RollbackFailed(Some(outcome));
        }
        return AttemptResult::RolledBack(outcome);
    };

    match transaction
        .commit_with_component_state(counts, accepted, component_state)
        .await
    {
        Ok(receipt) => {
            let Ok(next_skips) = state.skip_counts.checked_add(accepted.skips()) else {
                return AttemptResult::RolledBack(ChunkExecutionOutcome::Failed(
                    ChunkFailure::Count,
                ));
            };
            state.skip_counts = next_skips;
            state.no_rollback_count = state
                .no_rollback_count
                .saturating_add(accepted.no_rollbacks());
            // The commit that advanced the checkpoint superseded every retry
            // key of the previous generation, so the durable clear is already
            // authoritative and this only prunes process-local bookkeeping.
            if let Some(fault) = components.fault {
                let _ = fault.state().clear_resolved().await;
            }
            AttemptResult::Committed { counts, receipt }
        }
        Err(
            ChunkTransactionError::NotCommitted | ChunkTransactionError::ComponentStateUnsupported,
        ) => {
            let outcome = ChunkExecutionOutcome::Failed(ChunkFailure::TransactionCommit);
            if transaction.rollback().await.is_err() {
                return AttemptResult::RollbackFailed(Some(outcome));
            }
            AttemptResult::RolledBack(outcome)
        }
        Err(ChunkTransactionError::CommitOutcomeUnknown) => AttemptResult::Unknown,
    }
}

/// Rolls back, reserves the retry ordinal durably, then waits for backoff.
#[allow(
    clippy::too_many_arguments,
    reason = "the retry scope needs components, scope, buffer, state, transaction, request, and events"
)]
async fn schedule_retry<I, O, E, P, W>(
    components: &Components<'_, I, O, P, W>,
    scope: AttemptScope<'_>,
    buffer: &mut ChunkBuffer<I, O>,
    state: &mut ExecutionState,
    transaction: &mut dyn ChunkTransaction,
    request: RetryRequest,
    emit: &mut E,
) -> AttemptResult
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let Some(fault_runtime) = components.fault else {
        return AttemptResult::RolledBack(ChunkExecutionOutcome::Failed(
            ChunkFailure::RetryReservation,
        ));
    };
    if transaction.rollback().await.is_err() {
        return AttemptResult::RollbackFailed(None);
    }
    if scope.stop.is_stop_requested() {
        return AttemptResult::RolledBack(ChunkExecutionOutcome::Stopped);
    }

    let reservation = RetryReservation::new(
        request.key,
        request.phase,
        request.fault.category(),
        request.ordinal,
    );
    match fault_runtime.state().reserve(reservation).await {
        Ok(()) => {}
        Err(crate::FaultStateError::CapacityExhausted { .. }) => {
            return AttemptResult::RolledBack(ChunkExecutionOutcome::Failed(
                ChunkFailure::RetryStateExhausted,
            ));
        }
        Err(_) => {
            return AttemptResult::RolledBack(ChunkExecutionOutcome::Failed(
                ChunkFailure::RetryReservation,
            ));
        }
    }
    state.rollback_count = state.rollback_count.saturating_add(1);
    state.retry_counts = state.retry_counts.increment(request.phase);
    emit(ChunkRuntimeEvent::Fault(
        FaultRuntimeEvent::new(
            LifecycleEventKind::RetryReserved,
            scope.sequence,
            request.phase,
        )
        .with_summary(request.fault.summary())
        .with_ordinal(request.ordinal),
    ));
    emit(ChunkRuntimeEvent::Fault(
        FaultRuntimeEvent::new(
            LifecycleEventKind::FaultRollbackCommitted,
            scope.sequence,
            request.phase,
        )
        .with_summary(request.fault.summary()),
    ));

    let listener_context = scope.listener_context();
    let before = components
        .item_listeners
        .before_retry(request.fault, listener_context)
        .await;
    if let Some(failure) = before.failure() {
        state.item_listener_failures.push(failure);
        return AttemptResult::RolledBack(item_listener_outcome(failure.kind()));
    }
    buffer.retry = Some(PendingRetry {
        key: request.key,
        fault: request.fault,
        entered: before.entered(),
    });

    if scope.stop.is_stop_requested() {
        return AttemptResult::RolledBack(ChunkExecutionOutcome::Stopped);
    }
    emit(ChunkRuntimeEvent::Fault(
        FaultRuntimeEvent::new(
            LifecycleEventKind::RetryBackoffStarted,
            scope.sequence,
            request.phase,
        )
        .with_ordinal(request.ordinal)
        .with_backoff(request.delay),
    ));
    if fault_runtime
        .sleeper()
        .sleep(request.delay, scope.stop)
        .await
        == BackoffOutcome::Stopped
    {
        emit(ChunkRuntimeEvent::Fault(
            FaultRuntimeEvent::new(
                LifecycleEventKind::RetryBackoffCancelled,
                scope.sequence,
                request.phase,
            )
            .with_ordinal(request.ordinal)
            .with_backoff(request.delay),
        ));
        return AttemptResult::RolledBack(ChunkExecutionOutcome::Stopped);
    }
    if scope.stop.is_stop_requested() {
        return AttemptResult::RolledBack(ChunkExecutionOutcome::Stopped);
    }
    AttemptResult::Replay
}

/// Runs the retry-completion callback when `key` had a reserved retry.
async fn complete_retry<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    listener_context: ItemListenerContext<'_>,
    retry: &mut Option<PendingRetry>,
    state: &mut ExecutionState,
    key: RetryKey,
    outcome: RetryOutcome,
) -> Option<ChunkExecutionOutcome>
where
    I: Send + Sync,
    O: Send + Sync,
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let pending = retry.take_if(|pending| pending.key == key)?;
    let failures = components
        .item_listeners
        .after_retry(pending.entered, pending.fault, outcome, listener_context)
        .await;
    let first = failures.first().copied()?;
    state.item_listener_failures.extend(failures);
    Some(item_listener_outcome(first.kind()))
}

/// Decides one fault and runs the exhaustion callback when the budget is spent.
#[allow(
    clippy::too_many_arguments,
    reason = "classification needs components, listeners, retry state, and the fault inputs"
)]
async fn classify<I, O, E, P, W>(
    components: &Components<'_, I, O, P, W>,
    listener_context: ItemListenerContext<'_>,
    retry: &mut Option<PendingRetry>,
    state: &mut ExecutionState,
    key: RetryKey,
    fault: FaultDescriptor,
    evidence: FaultEvidence,
    sequence: ChunkCount,
    emit: &mut E,
) -> Result<FaultDecision, ChunkExecutionOutcome>
where
    I: Send + Sync,
    O: Send + Sync,
    E: FnMut(ChunkRuntimeEvent),
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let entered = retry
        .as_ref()
        .filter(|pending| pending.key == key)
        .map(|pending| pending.entered);
    if entered.is_some()
        && let Some(outcome) = complete_retry(
            components,
            listener_context,
            retry,
            state,
            key,
            RetryOutcome::Failed,
        )
        .await
    {
        return Err(outcome);
    }

    let Some(fault_runtime) = components.fault else {
        return Ok(FaultDecision::FailAndRollback);
    };
    let decision = fault_runtime.policy().decide(&fault, evidence);

    if !decision.is_retry()
        && let Some(entered) = entered
    {
        emit(ChunkRuntimeEvent::Fault(
            FaultRuntimeEvent::new(LifecycleEventKind::RetryExhausted, sequence, fault.phase())
                .with_summary(fault.summary())
                .with_ordinal(fault.retry_ordinal()),
        ));
        let failures = components
            .item_listeners
            .on_retry_exhausted(entered, fault, listener_context)
            .await;
        if let Some(first) = failures.first().copied() {
            state.item_listener_failures.extend(failures);
            return Err(item_listener_outcome(first.kind()));
        }
    }
    Ok(decision)
}

/// Builds the framework-owned classification input for one fault.
fn descriptor<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    state: &mut ExecutionState,
    skips: &[PendingSkip<O>],
    phase: FaultPhase,
    category: FailureCategory,
) -> Option<FaultDescriptor>
where
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let delivery_mode = components.fault.map_or(
        crate::ChunkDeliveryMode::AtLeastOnce,
        FaultRuntime::delivery_mode,
    );
    let committed = projected_skips(state.skip_counts, skips)?;
    state.next_failure_id = state.next_failure_id.saturating_add(1);
    let failure_id = FailureId::new(state.next_failure_id).ok()?;
    Some(FaultDescriptor::new(
        phase,
        FailureSummary::new(category, failure_id),
        RetryOrdinal::INITIAL,
        committed,
        true,
        delivery_mode,
    ))
}

/// Replaces the descriptor ordinal with the durably reserved one.
async fn with_reserved_ordinal<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    key: RetryKey,
    fault: FaultDescriptor,
) -> FaultDescriptor
where
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    let Some(fault_runtime) = components.fault else {
        return fault;
    };
    let ordinal = fault_runtime
        .state()
        .reserved_ordinal(key)
        .await
        .ok()
        .flatten()
        .unwrap_or(RetryOrdinal::INITIAL);
    FaultDescriptor::new(
        fault.phase(),
        fault.summary(),
        ordinal,
        fault.committed_skips(),
        fault.is_transaction_open(),
        fault.delivery_mode(),
    )
}

/// Marks one retry key resolved because its unit of work finished.
async fn resolve_key<I, O, P, W>(components: &Components<'_, I, O, P, W>, key: RetryKey)
where
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    if let Some(fault_runtime) = components.fault {
        let _ = fault_runtime.state().resolve(key).await;
    }
}

fn retry_key<I, O, P, W>(
    components: &Components<'_, I, O, P, W>,
    checkpoint_digest: [u8; 32],
    phase: FaultPhase,
    ordinal: u64,
) -> RetryKey
where
    P: ItemProcessor<I, O>,
    W: ItemWriter<O>,
{
    RetryKey::derive(
        &components.definition_digest,
        components.step_name,
        phase,
        &checkpoint_digest,
        ordinal,
    )
}

fn checkpoint_digest(checkpoint: &crate::Checkpoint) -> [u8; 32] {
    checkpoint.generation_digest()
}

fn emit_committed_skips<I, O, E>(buffer: &ChunkBuffer<I, O>, sequence: ChunkCount, emit: &mut E)
where
    E: FnMut(ChunkRuntimeEvent),
{
    for skip in &buffer.skips {
        emit(ChunkRuntimeEvent::Fault(
            FaultRuntimeEvent::new(LifecycleEventKind::ItemSkipped, sequence, skip.phase)
                .with_summary(skip.fault.summary()),
        ));
        if skip.disposition == RollbackDisposition::CommitSafeSkip {
            emit(ChunkRuntimeEvent::Fault(
                FaultRuntimeEvent::new(
                    LifecycleEventKind::FaultNoRollbackCommitted,
                    sequence,
                    skip.phase,
                )
                .with_summary(skip.fault.summary()),
            ));
        }
    }
}

const fn item_listener_outcome(kind: ListenerFailureKind) -> ChunkExecutionOutcome {
    match kind {
        ListenerFailureKind::Error => ChunkExecutionOutcome::Failed(ChunkFailure::ItemListener),
        ListenerFailureKind::Panic => {
            ChunkExecutionOutcome::Failed(ChunkFailure::ItemListenerPanic)
        }
    }
}

async fn finish_failed_attempt(
    listeners: &[Arc<dyn ChunkListener>],
    policy_attempt: CompletionPolicyAttempt<'_>,
    context: ChunkListenerContext<'_>,
    attempt_outcome: ChunkAttemptOutcome,
    outcome: ChunkExecutionOutcome,
    state: &mut ExecutionState,
) -> ChunkExecutionReport {
    let failures = run_after_listeners(listeners, context, attempt_outcome).await;
    // Always observed, regardless of listener outcome: `attempt_outcome` may
    // be `Committed` (for example this attempt's transaction committed but
    // bookkeeping afterward overflowed a counter), and `end_chunk` must see
    // that commit exactly once to keep a policy's durable and in-memory
    // state from disagreeing. A no-op when this attempt's `begin_chunk`
    // never ran (for example its transaction never began).
    let completion_policy_panicked = policy_attempt.finish(attempt_outcome).is_err();
    if let Some(first) = failures.first().copied() {
        state.listener_failures.extend(failures);
        if outcome == ChunkExecutionOutcome::Unknown {
            return state.drain().report(outcome, None);
        }
        return state
            .drain()
            .report(listener_failure_outcome(first.kind()), Some(outcome));
    }
    if completion_policy_panicked {
        if outcome == ChunkExecutionOutcome::Unknown {
            return state.drain().report(outcome, None);
        }
        return state.drain().report(
            ChunkExecutionOutcome::Failed(ChunkFailure::CompletionPolicyPanic),
            Some(outcome),
        );
    }
    state.drain().report(outcome, None)
}

async fn run_before_listeners(
    listeners: &[Arc<dyn ChunkListener>],
    context: ChunkListenerContext<'_>,
) -> Option<ChunkListenerFailure> {
    for (index, listener) in listeners.iter().enumerate() {
        if let Err(kind) = invoke_before_listener(listener.as_ref(), context).await {
            return Some(ChunkListenerFailure::new(
                ChunkListenerPhase::BeforeChunk,
                index,
                kind,
            ));
        }
    }
    None
}

async fn run_after_listeners(
    listeners: &[Arc<dyn ChunkListener>],
    context: ChunkListenerContext<'_>,
    outcome: ChunkAttemptOutcome,
) -> Vec<ChunkListenerFailure> {
    let mut failures = Vec::new();
    for (index, listener) in listeners.iter().enumerate().rev() {
        if let Err(kind) = invoke_after_listener(listener.as_ref(), context, outcome).await {
            failures.push(ChunkListenerFailure::new(
                ChunkListenerPhase::AfterChunk,
                index,
                kind,
            ));
        }
    }
    failures
}

const fn listener_failure_outcome(kind: ChunkListenerFailureKind) -> ChunkExecutionOutcome {
    match kind {
        ChunkListenerFailureKind::Error => ChunkExecutionOutcome::Failed(ChunkFailure::Listener),
        ChunkListenerFailureKind::Panic => {
            ChunkExecutionOutcome::Failed(ChunkFailure::ListenerPanic)
        }
    }
}

async fn invoke_before_listener(
    listener: &dyn ChunkListener,
    context: ChunkListenerContext<'_>,
) -> Result<(), ChunkListenerFailureKind> {
    let future = catch_unwind(AssertUnwindSafe(|| listener.before_chunk(context)))
        .map_err(|_| ChunkListenerFailureKind::Panic)?;
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(())) => Ok(()),
        Ok(Err(_)) => Err(ChunkListenerFailureKind::Error),
        Err(_) => Err(ChunkListenerFailureKind::Panic),
    }
}

async fn invoke_after_listener(
    listener: &dyn ChunkListener,
    context: ChunkListenerContext<'_>,
    outcome: ChunkAttemptOutcome,
) -> Result<(), ChunkListenerFailureKind> {
    let future = catch_unwind(AssertUnwindSafe(|| listener.after_chunk(context, outcome)))
        .map_err(|_| ChunkListenerFailureKind::Panic)?;
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(())) => Ok(()),
        Ok(Err(_)) => Err(ChunkListenerFailureKind::Error),
        Err(_) => Err(ChunkListenerFailureKind::Panic),
    }
}

/// Guards construction of the reader's call future against a synchronous
/// panic, without allocating.
///
/// Each `invoke_*` helper below drives its component call inside one `async`
/// block wrapped by [`FutureExt::catch_unwind`], rather than constructing the
/// call future in a plain closure passed to [`catch_unwind`]. An `async`
/// block is not desugared through the `Fn` family of traits, so it does not
/// hit the borrow-checker limitation where a closure that captures a `&mut`
/// receiver by move and returns its borrowed, opaque call future is rejected
/// as escaping a `FnMut` body — even though the closure is only ever called
/// once (rust-lang/rust#89976 and similar). Because the component call sits
/// before the block's only `await` point, a synchronous panic during call
/// construction happens during the block's first poll, which
/// `FutureExt::catch_unwind` already guards; polling panics are guarded the
/// same way. Neither step allocates: the block compiles to a plain state
/// machine borrowing the receiver for the call's lifetime, not a boxed future.
async fn invoke_reader<'a, I, R>(
    reader: &'a mut R,
    context: ReadContext<'a>,
) -> Invoked<ReadOutcome<I>, ReaderError>
where
    R: ItemReader<I>,
{
    let future = async move { reader.read(context).await };
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(outcome)) => Invoked::Completed(outcome),
        Ok(Err(error)) => Invoked::Failed(error),
        Err(_) => Invoked::Panicked,
    }
}

async fn invoke_processor<I, O, P>(
    processor: &P,
    item: &I,
    context: ProcessContext<'_>,
) -> Invoked<ProcessOutcome<O>, ProcessorError>
where
    P: ItemProcessor<I, O>,
{
    let future = async move { processor.process(item, context).await };
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(outcome)) => Invoked::Completed(outcome),
        Ok(Err(error)) => Invoked::Failed(error),
        Err(_) => Invoked::Panicked,
    }
}

async fn invoke_writer<'a, O, W>(
    writer: &'a W,
    items: &'a [O],
    context: WriteContext<'a>,
) -> Invoked<WriteOutcome, WriterError>
where
    W: ItemWriter<O>,
{
    let future = async move { writer.write(items, context).await };
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(outcome)) => Invoked::Completed(outcome),
        Ok(Err(error)) => Invoked::Failed(error),
        Err(_) => Invoked::Panicked,
    }
}

async fn invoke_completion(
    completion: &dyn ChunkCompletion,
    context: ChunkCompletionContext<'_>,
) -> Result<ChunkCompletionOutcome, ChunkFailure> {
    let future = catch_unwind(AssertUnwindSafe(|| completion.after_commit(context)))
        .map_err(|_| ChunkFailure::CompletionPanic)?;
    match AssertUnwindSafe(future).catch_unwind().await {
        Ok(Ok(outcome)) => Ok(outcome),
        Ok(Err(_)) => Err(ChunkFailure::Completion),
        Err(_) => Err(ChunkFailure::CompletionPanic),
    }
}

/// Calls a completion policy's synchronous `begin_chunk` inside the same
/// panic-containment boundary every other user-supplied component call in
/// this module already uses. A public [`CompletionPolicy`] implementation
/// panicking must fail this attempt through the ordinary typed-failure path,
/// never unwind through the chunk runtime.
fn invoke_completion_policy_begin(policy: &dyn CompletionPolicy) -> Result<(), ()> {
    catch_unwind(AssertUnwindSafe(|| policy.begin_chunk())).map_err(|_| ())
}

/// Calls a completion policy's synchronous `is_complete` under the same
/// panic containment as [`invoke_completion_policy_begin`].
fn invoke_completion_policy_is_complete(
    policy: &dyn CompletionPolicy,
    items_read: ChunkCount,
) -> Result<bool, ()> {
    catch_unwind(AssertUnwindSafe(|| policy.is_complete(items_read))).map_err(|_| ())
}

/// Calls a completion policy's synchronous `end_chunk` under the same panic
/// containment as [`invoke_completion_policy_begin`]. Called for every
/// terminal chunk-attempt outcome (committed, rolled back, stopped, or
/// unknown) so an [`AdaptiveCompletionPolicy`] can promote or discard its
/// speculative candidate; a no-op default for every other policy.
fn invoke_completion_policy_end(
    policy: Option<&dyn CompletionPolicy>,
    outcome: ChunkAttemptOutcome,
) -> Result<(), ()> {
    let Some(policy) = policy else {
        return Ok(());
    };
    catch_unwind(AssertUnwindSafe(|| policy.end_chunk(outcome))).map_err(|_| ())
}

/// Structurally enforces the [`CompletionPolicy`] begin/end lifecycle
/// contract documented on [`CompletionPolicy::begin_chunk`]:
/// [`Self::begin`] performs an attempt's one `begin_chunk` call, and
/// [`Self::finish`] performs its one matching `end_chunk` call -- so no call
/// site in this module can invoke `end_chunk` without a preceding
/// `begin_chunk` for the same attempt, and none can invoke `begin_chunk`
/// without the runtime later owing a matching `end_chunk`.
///
/// Dropping an attempt that began successfully but was never explicitly
/// [`finish`](Self::finish)ed -- reachable only by a future bug in this
/// module, never by any call path today -- still invokes `end_chunk`, with
/// [`ChunkAttemptOutcome::Unknown`] standing in for whatever outcome was
/// never reported. A missed call site therefore fails safe (a possibly
/// imprecise outcome) rather than silently leaking the lifecycle.
struct CompletionPolicyAttempt<'a> {
    policy: Option<&'a dyn CompletionPolicy>,
    began: bool,
    finished: bool,
}

impl<'a> CompletionPolicyAttempt<'a> {
    /// Calls `begin_chunk` exactly once, if a policy is installed.
    ///
    /// [`Self::begin_panicked`] distinguishes a panic there from simply
    /// having no policy installed; either way, [`Self::finish`] becomes a
    /// deliberate no-op for this attempt.
    fn begin(policy: Option<&'a dyn CompletionPolicy>) -> Self {
        let began = match policy {
            Some(policy) => invoke_completion_policy_begin(policy).is_ok(),
            None => false,
        };
        Self {
            policy,
            began,
            finished: false,
        }
    }

    /// Represents an attempt whose transaction never began, so this
    /// attempt's `begin_chunk` was never called at all -- never even
    /// attempted. [`Self::finish`] on this value is always a no-op: no
    /// `begin_chunk` ran, so no `end_chunk` is owed.
    const fn not_begun(policy: Option<&'a dyn CompletionPolicy>) -> Self {
        Self {
            policy,
            began: false,
            finished: false,
        }
    }

    /// Reports whether a policy is installed and its `begin_chunk` panicked
    /// this attempt -- distinct from simply having no policy installed at
    /// all, which also leaves nothing owed but is not a failure.
    const fn begin_panicked(&self) -> bool {
        self.policy.is_some() && !self.began
    }

    /// Calls `end_chunk` with `outcome`, exactly once, only when this
    /// attempt's `begin_chunk` actually ran without panicking. A `begin`
    /// that never ran (or panicked) owes no matching `end`, so this is a
    /// deliberate no-op in that case (never an error): a panicked `begin` is
    /// instead surfaced by the caller checking [`Self::begin_panicked`]
    /// immediately after construction.
    fn finish(mut self, outcome: ChunkAttemptOutcome) -> Result<(), ()> {
        self.finished = true;
        if !self.began {
            return Ok(());
        }
        invoke_completion_policy_end(self.policy, outcome)
    }
}

impl Drop for CompletionPolicyAttempt<'_> {
    fn drop(&mut self) {
        if self.finished || !self.began {
            return;
        }
        let _ = invoke_completion_policy_end(self.policy, ChunkAttemptOutcome::Unknown);
    }
}