aws-durable-execution-sdk 0.2.0

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

use std::future::Future;
use std::sync::Arc;

use aws_sdk_lambda::types::{OperationAction, OperationType, OperationUpdate};
use tracing::Instrument as _;

use crate::BoxError;
use crate::Serdes;
use crate::checkpoint_coalescer::ScopeClose;
use crate::child::CHECKPOINT_SIZE_LIMIT_BYTES;
use crate::context::{DurableContext, SubmittedWrite, run_body};
use crate::engine::{CheckpointStatus, OperationId};
use crate::error::{
    ChildContextError, ChildContextErrorKind, ChildFnError, OperationError, OperationErrorKind,
};
use crate::plugin::UserBody;
use crate::serdes::SerdesContext;
use crate::start::StartStep;
use crate::task::{NoRuntime, TaskOutcome, TrackedJoinSet};
use serde_json::value::RawValue;

/// Wire sub-type for map operations.
pub(crate) const MAP_SUB_TYPE: &str = "Map";
/// Wire sub-type for map iteration children.
pub(crate) const MAP_ITERATION_SUB_TYPE: &str = "MapIteration";
/// Wire sub-type for parallel operations.
pub(crate) const PARALLEL_SUB_TYPE: &str = "Parallel";
/// Wire sub-type for parallel branch children.
pub(crate) const PARALLEL_BRANCH_SUB_TYPE: &str = "ParallelBranch";

/// Sentinel error message returned by `replay_terminal_batch` when the
/// batch has `replay_children` set, signalling the caller should fall
/// through to normal re-execution instead of short-circuiting.
const REPLAY_CHILDREN_SENTINEL: &str = "__replay_children_reexecute__";

/// The status of one item or branch in a batch operation.
///
/// Each item in a [`BatchResult`] has a status indicating whether it
/// completed successfully, failed, or had started but not yet reached a
/// terminal state when the batch completed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BatchItemStatus {
    /// The item completed successfully.
    Succeeded,
    /// The item failed.
    Failed,
    /// The item was dispatched and was not terminal when the batch
    /// completed.
    ///
    /// It appears live and on replay. A completion rule that ends the batch
    /// early leaves running and parked items in this status. The SDK
    /// cancels a running item at its next `.await`, and none of its later
    /// checkpoints is written. Its child context can still show
    /// `Succeeded` or `Failed` in history when its outcome was recorded
    /// before the batch completed. The item carries no result and no
    /// error.
    Started,
}

/// The outcome of one item or branch in a batch operation.
///
/// Contains the index, optional display name, status, and either the
/// result value or the item's complete recorded failure record (type
/// identifier, message, opaque `error_data` payload, and stack trace). A
/// [`BatchItemStatus::Started`] item carries neither.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{BatchItemStatus, BatchItem};
///
/// let item: BatchItem<i32> = BatchItem::new(
///     0,
///     String::new(),
///     BatchItemStatus::Succeeded,
///     Some(42),
///     None,
///     None,
/// );
/// assert_eq!(item.status, BatchItemStatus::Succeeded);
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct BatchItem<O> {
    /// Zero-based position in the original input.
    pub index: usize,
    /// The name history records for the item: the map item namer's result
    /// or the branch name, or `map-item-{index}` or
    /// `parallel-branch-{index}` when that name is missing or empty.
    pub name: String,
    /// Status: `Succeeded` or `Failed` for a terminal item, or `Started`
    /// for an item that was not terminal when the batch completed.
    pub status: BatchItemStatus,
    /// Result value (only meaningful when status is Succeeded).
    pub result: Option<O>,
    /// Error message (only meaningful when status is Failed).
    pub error_message: Option<String>,
    /// Error type identifier (only meaningful when status is Failed).
    ///
    /// Carries the type recorded in the batch checkpoint payload (the
    /// item error's `Cause.ErrorType`): the recorded type of the error the
    /// item body returned (`"Error"` for an untyped error), so error
    /// identity survives checkpoint replay alongside the message. `None`
    /// when the payload recorded no type.
    pub error_type: Option<String>,
    /// Opaque wire `ErrorData` payload recorded with the failure (only
    /// meaningful when status is Failed).
    ///
    /// Passed through verbatim from the failing item's recorded wire
    /// record, never interpreted by the SDK. `None` when the failure
    /// recorded no payload.
    pub error_data: Option<String>,
    /// Recorded wire `StackTrace` frames from the failure (only
    /// meaningful when status is Failed).
    ///
    /// Store-and-expose only, exactly like
    /// [`WireError::stack_trace`](crate::WireError::stack_trace). Empty
    /// when the failure recorded no frames.
    pub stack_trace: Vec<String>,
}

impl<O> BatchItem<O> {
    /// Creates a new batch item.
    ///
    /// The failure payload fields ([`error_data`](Self::error_data) and
    /// [`stack_trace`](Self::stack_trace)) start empty; set them directly
    /// when constructing a failed item that carries them.
    #[must_use]
    pub fn new(
        index: usize,
        name: String,
        status: BatchItemStatus,
        result: Option<O>,
        error_message: Option<String>,
        error_type: Option<String>,
    ) -> Self {
        Self {
            index,
            name,
            status,
            result,
            error_message,
            error_type,
            error_data: None,
            stack_trace: Vec::new(),
        }
    }

    /// Creates a failed item carrying the complete recorded wire failure
    /// record: all four wire fields survive into the item, so live and
    /// replayed batches expose the same failure identity.
    pub(crate) fn failed_from_wire(
        index: usize,
        name: String,
        wire: &crate::error::WireError,
    ) -> Self {
        Self {
            index,
            name,
            status: BatchItemStatus::Failed,
            result: None,
            error_message: wire.error_message().map(str::to_owned),
            error_type: wire.error_type().map(str::to_owned),
            error_data: wire.error_data().map(str::to_owned),
            stack_trace: wire.stack_trace().to_vec(),
        }
    }

    /// Rebuilds the item's recorded failure as a wire record (all four
    /// fields), for surfacing the failure as an operation error.
    pub(crate) fn failure_wire(&self) -> crate::error::WireError {
        crate::error::WireError::new(
            self.error_type.as_deref(),
            Some(
                self.error_message
                    .as_deref()
                    .unwrap_or("branch failed")
                    .to_owned(),
            ),
        )
        .with_error_data(self.error_data.as_deref())
        .with_stack_trace(self.stack_trace.clone())
    }
}

/// The overall status of a completed batch.
///
/// Returned by [`BatchResult::status`]. A custom completion decides the
/// status on its own: [`CompletionReason::CustomCompletionSucceeded`] gives
/// [`BatchStatus::Succeeded`] even when an item failed, and
/// [`CompletionReason::CustomCompletionFailed`] gives [`BatchStatus::Failed`]
/// even when no item failed. For every other reason the status is
/// [`BatchStatus::Failed`] exactly when a started item failed. The `Display`
/// implementation renders the wire strings `"SUCCEEDED"` and `"FAILED"`.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::BatchStatus;
///
/// assert_eq!(BatchStatus::Succeeded.as_str(), "SUCCEEDED");
/// assert_eq!(BatchStatus::Failed.to_string(), "FAILED");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BatchStatus {
    /// The predicate completed the batch as succeeded, or, for any other
    /// reason, no started item failed.
    Succeeded,
    /// The predicate completed the batch as failed, or, for any other
    /// reason, at least one started item failed.
    Failed,
}

impl BatchStatus {
    /// Wire representation of the batch status.
    ///
    /// Returns the string used in checkpoint payloads and conformance
    /// assertions.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Succeeded => "SUCCEEDED",
            Self::Failed => "FAILED",
        }
    }
}

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

/// A failed item's error, tied to the item that produced it.
///
/// Returned by [`BatchResult::errors`]. Each entry borrows from the
/// [`BatchItem`] it describes and carries the item's position, display
/// name, error type identifier, and error message, so callers can
/// associate a failure with the input that caused it rather than
/// receiving a bare message string.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{BatchResult, BatchItem, BatchItemStatus, CompletionReason};
///
/// let result: BatchResult<i32> = BatchResult::new(
///     vec![BatchItem::new(
///         2,
///         "branch-c".to_owned(),
///         BatchItemStatus::Failed,
///         None,
///         Some("boom".into()),
///         Some("Error".into()),
///     )],
///     CompletionReason::AllCompleted,
/// );
/// let error = result.errors().next().expect("one item failed");
/// assert_eq!(error.index, 2);
/// assert_eq!(error.name, "branch-c");
/// assert_eq!(error.message, "boom");
/// assert_eq!(error.error_type, Some("Error"));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct BatchError<'a> {
    /// Zero-based position of the failed item in the original input.
    pub index: usize,
    /// The recorded name of the failed item: the map item namer's result or
    /// the branch name, or `map-item-{index}` or `parallel-branch-{index}`
    /// when that name is missing or empty.
    pub name: &'a str,
    /// The error message the item failed with.
    pub message: &'a str,
    /// The error type identifier the item failed with, as recorded in the
    /// batch checkpoint payload: the recorded type of the error the item
    /// body returned (`"Error"` for an untyped error).
    /// `None` when the payload recorded no type.
    pub error_type: Option<&'a str>,
}

/// Why the batch completed.
///
/// Records the reason a [`BatchResult`] finished: all items ran, the
/// success threshold was met, the failure tolerance was exceeded, or a
/// custom completion predicate completed the batch as a success or a
/// failure.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::CompletionReason;
///
/// let reason = CompletionReason::AllCompleted;
/// assert_eq!(reason.as_str(), "ALL_COMPLETED");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompletionReason {
    /// Every item ran to completion.
    AllCompleted,
    /// The `min_successful` threshold was met.
    MinSuccessfulReached,
    /// The failure tolerance was exceeded.
    FailureToleranceExceeded,
    /// The custom completion predicate returned
    /// `CompletionDecision::complete(CompletionOutcome::Succeeded)`.
    ///
    /// The predicate is configured through
    /// [`crate::builders::map_parallel::CompletionConfig::with_completion_predicate`] or
    /// [`crate::builders::map_parallel::CompletionConfigBuilder::completion_predicate`]. Like
    /// [`CompletionReason::MinSuccessfulReached`], a batch completed this
    /// way is a successful early completion: item failures inside it are
    /// tolerated rather than propagated as errors.
    CustomCompletionSucceeded,
    /// The custom completion predicate returned
    /// `CompletionDecision::complete(CompletionOutcome::Failed)`.
    ///
    /// [`BatchResult::status`] is [`BatchStatus::Failed`] even when no item
    /// failed, and awaiting the batch returns an error.
    CustomCompletionFailed,
}

impl CompletionReason {
    /// Wire representation of the completion reason.
    ///
    /// Returns the string used in checkpoint payloads and conformance
    /// assertions.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AllCompleted => "ALL_COMPLETED",
            Self::MinSuccessfulReached => "MIN_SUCCESSFUL_REACHED",
            Self::FailureToleranceExceeded => "FAILURE_TOLERANCE_EXCEEDED",
            Self::CustomCompletionSucceeded => "CUSTOM_COMPLETION_SUCCEEDED",
            Self::CustomCompletionFailed => "CUSTOM_COMPLETION_FAILED",
        }
    }

    /// Parses the wire representation back into a completion reason.
    ///
    /// Unrecognized strings map to [`CompletionReason::AllCompleted`],
    /// matching the checkpoint replay path's tolerance for payloads written
    /// by newer SDK versions.
    pub(crate) fn from_wire(s: &str) -> Self {
        match s {
            "MIN_SUCCESSFUL_REACHED" => Self::MinSuccessfulReached,
            "FAILURE_TOLERANCE_EXCEEDED" => Self::FailureToleranceExceeded,
            "CUSTOM_COMPLETION_SUCCEEDED" => Self::CustomCompletionSucceeded,
            "CUSTOM_COMPLETION_FAILED" => Self::CustomCompletionFailed,
            _ => Self::AllCompleted,
        }
    }

    /// Strictly parses the wire representation, returning `None` for a
    /// string this SDK never writes.
    ///
    /// The batch decision record uses this instead of [`Self::from_wire`]:
    /// a decision record is SDK-owned bookkeeping whose reason replay
    /// reports verbatim, so an unrecognized value there is corruption to
    /// reject, not a future variant to tolerate.
    pub(crate) fn try_from_wire(s: &str) -> Option<Self> {
        match s {
            "ALL_COMPLETED" => Some(Self::AllCompleted),
            "MIN_SUCCESSFUL_REACHED" => Some(Self::MinSuccessfulReached),
            "FAILURE_TOLERANCE_EXCEEDED" => Some(Self::FailureToleranceExceeded),
            "CUSTOM_COMPLETION_SUCCEEDED" => Some(Self::CustomCompletionSucceeded),
            "CUSTOM_COMPLETION_FAILED" => Some(Self::CustomCompletionFailed),
            _ => None,
        }
    }
}

/// What a completion predicate decides before an item starts or after an item settles.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{
///     CompletionDecision, CompletionOutcome,
/// };
///
/// let decision = CompletionDecision::complete(CompletionOutcome::Failed);
/// assert_ne!(decision, CompletionDecision::Continue);
/// ```
///
/// The enum and its `Complete` variant are `#[non_exhaustive]`. Build a
/// completion with [`CompletionDecision::complete`], and match it with
/// `..`. Rust does not accept a tuple pattern for a `#[non_exhaustive]`
/// tuple variant outside its crate, so use the field syntax, as in
/// `CompletionDecision::Complete { 0: outcome, .. }`. A caller cannot build
/// the variant directly:
///
/// ```rust,compile_fail
/// use aws_durable_execution_sdk::builders::map_parallel::{
///     CompletionDecision, CompletionOutcome,
/// };
///
/// let _ = CompletionDecision::Complete(CompletionOutcome::Succeeded);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompletionDecision {
    /// Keep starting and awaiting items.
    Continue,
    /// Complete the batch now with this outcome.
    #[non_exhaustive]
    Complete(CompletionOutcome),
}

impl CompletionDecision {
    /// A [`Complete`](Self::Complete) decision with the given outcome.
    #[must_use]
    pub fn complete(outcome: CompletionOutcome) -> Self {
        Self::Complete(outcome)
    }
}

/// Whether a custom completion counts as a success or a failure of the batch.
///
/// `Succeeded` records [`CompletionReason::CustomCompletionSucceeded`], and
/// `Failed` records [`CompletionReason::CustomCompletionFailed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompletionOutcome {
    /// The batch completed as a success.
    Succeeded,
    /// The batch completed as a failure.
    Failed,
}

/// One input item as a completion predicate sees it.
///
/// [`BatchStats::items`] holds one entry per input item, by index. The SDK
/// asks the predicate before each item starts and after each item settles,
/// so an entry can be not started, running, or settled. The live settle
/// order is not recorded, and on resume the recorded items settle first, in
/// index order; so a predicate must be pure and monotonic (see
/// [`CompletionConfigBuilder::completion_predicate`](crate::builders::map_parallel::CompletionConfigBuilder::completion_predicate)).
///
/// The public constructor exists so a completion predicate can be unit
/// tested against hand-built statistics without running a batch.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{BatchItemStatus, CompletionItem};
///
/// let item = CompletionItem::new(3, Some("charge".to_owned()), Some(BatchItemStatus::Started));
/// assert_eq!(item.index, 3);
/// assert_eq!(item.name.as_deref(), Some("charge"));
/// assert_eq!(item.status, Some(BatchItemStatus::Started));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CompletionItem {
    /// Zero-based position in the input.
    pub index: usize,
    /// The name the caller gave the item: the item namer's result, or the
    /// branch name. `None` when the caller gave no name. An empty string is
    /// `Some("")`. The recorded name is independent and falls back to
    /// `map-item-{index}` or `parallel-branch-{index}`.
    pub name: Option<String>,
    /// `None`: not started. `Some(Started)`: running or waiting.
    /// `Some(Succeeded)` or `Some(Failed)`: settled.
    pub status: Option<BatchItemStatus>,
}

impl CompletionItem {
    /// Builds an item (public so a predicate can be unit tested).
    #[must_use]
    pub fn new(index: usize, name: Option<String>, status: Option<BatchItemStatus>) -> Self {
        Self {
            index,
            name,
            status,
        }
    }
}

/// A snapshot of a map/parallel batch, passed to a custom completion
/// predicate.
///
/// The SDK builds a snapshot before each item starts and after each item
/// settles. The counts follow the settle order, and
/// [`items`](Self::items) holds every input item by index, with its name
/// and its status. The live settle order is not recorded, and on resume the
/// recorded items settle first, in index order. So the sequence of
/// snapshots can differ between runs, and a predicate must be a pure and
/// monotonic function of the snapshot: see
/// [`CompletionConfigBuilder::completion_predicate`](crate::builders::map_parallel::CompletionConfigBuilder::completion_predicate).
///
/// The public constructor exists so a completion predicate can be unit
/// tested against hand-built statistics without running a batch.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{
///     BatchItemStatus, BatchStats, CompletionItem,
/// };
///
/// let items = [
///     CompletionItem::new(0, None, Some(BatchItemStatus::Failed)),
///     CompletionItem::new(1, None, Some(BatchItemStatus::Succeeded)),
///     CompletionItem::new(2, None, Some(BatchItemStatus::Started)),
///     CompletionItem::new(3, None, None),
/// ];
/// let stats = BatchStats::new(&items);
/// assert_eq!(stats.succeeded(), 1);
/// assert_eq!(stats.failed(), 1);
/// assert_eq!(stats.settled(), 2);
/// assert_eq!(stats.total_items(), 4);
/// assert_eq!(stats.items()[2].status, Some(BatchItemStatus::Started));
/// ```
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct BatchStats<'a> {
    /// Count of items that have succeeded so far.
    succeeded: usize,
    /// Count of items that have failed so far.
    failed: usize,
    /// Every input item, by index.
    items: &'a [CompletionItem],
}

impl<'a> BatchStats<'a> {
    /// Builds a snapshot, counting the settled items (public for unit tests).
    #[must_use]
    pub fn new(items: &'a [CompletionItem]) -> Self {
        let count = |status| {
            items
                .iter()
                .filter(|item| item.status == Some(status))
                .count()
        };
        Self {
            succeeded: count(BatchItemStatus::Succeeded),
            failed: count(BatchItemStatus::Failed),
            items,
        }
    }

    /// Builds a snapshot from the coordinator's running counts.
    pub(crate) fn from_counts(
        succeeded: usize,
        failed: usize,
        items: &'a [CompletionItem],
    ) -> Self {
        Self {
            succeeded,
            failed,
            items,
        }
    }

    /// Items that succeeded so far.
    pub fn succeeded(&self) -> usize {
        self.succeeded
    }

    /// Items that failed so far.
    pub fn failed(&self) -> usize {
        self.failed
    }

    /// `succeeded() + failed()`.
    pub fn settled(&self) -> usize {
        self.succeeded + self.failed
    }

    /// `items().len()`, the number of input items.
    pub fn total_items(&self) -> usize {
        self.items.len()
    }

    /// Every input item, by index: `items()[i].index == i`.
    pub fn items(&self) -> &'a [CompletionItem] {
        self.items
    }
}

/// The collected outcome of a map/parallel operation.
///
/// Contains per-item outcomes and the reason the batch completed. Provides
/// accessor methods for building conformance projections.
///
/// Only items that were actually started are included: items that never
/// started due to early completion are omitted. An item that was still
/// running or parked when the completion rule ended the batch appears as
/// [`BatchItemStatus::Started`], live and on replay.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{
///     BatchResult, BatchItem, BatchItemStatus, BatchStatus, CompletionReason,
/// };
///
/// let result: BatchResult<i32> = BatchResult::new(
///     vec![
///         BatchItem::new(0, String::new(), BatchItemStatus::Succeeded, Some(10), None, None),
///         BatchItem::new(
///             1,
///             String::new(),
///             BatchItemStatus::Failed,
///             None,
///             Some("oops".into()),
///             Some("Error".into()),
///         ),
///     ],
///     CompletionReason::FailureToleranceExceeded,
/// );
/// assert!(result.has_failure());
/// assert_eq!(result.success_count(), 1);
/// assert_eq!(result.failure_count(), 1);
/// assert_eq!(result.status(), BatchStatus::Failed);
/// let error = result.errors().next().expect("one item failed");
/// assert_eq!(error.index, 1);
/// assert_eq!(error.message, "oops");
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct BatchResult<O> {
    /// Per-item outcomes in input order (only started items, including
    /// [`BatchItemStatus::Started`] ones).
    pub items: Vec<BatchItem<O>>,
    /// Why the batch completed.
    pub reason: CompletionReason,
}

impl<O> BatchResult<O> {
    /// Creates a new batch result.
    #[must_use]
    pub fn new(items: Vec<BatchItem<O>>, reason: CompletionReason) -> Self {
        Self { items, reason }
    }

    /// Iterates over the values of the succeeded items, in input order.
    ///
    /// Failed items, `Started` items, and items that never started are
    /// omitted.
    pub fn results(&self) -> impl Iterator<Item = &O> + '_ {
        self.succeeded().filter_map(|item| item.result.as_ref())
    }

    /// Returns the count of successes.
    pub fn success_count(&self) -> usize {
        self.items
            .iter()
            .filter(|i| i.status == BatchItemStatus::Succeeded)
            .count()
    }

    /// Returns the count of failures.
    pub fn failure_count(&self) -> usize {
        self.items
            .iter()
            .filter(|i| i.status == BatchItemStatus::Failed)
            .count()
    }

    /// Reports whether any item failed.
    pub fn has_failure(&self) -> bool {
        self.items
            .iter()
            .any(|i| i.status == BatchItemStatus::Failed)
    }

    /// Returns the batch status.
    ///
    /// [`CompletionReason::CustomCompletionFailed`] gives
    /// [`BatchStatus::Failed`], and
    /// [`CompletionReason::CustomCompletionSucceeded`] gives
    /// [`BatchStatus::Succeeded`], whatever the items did. Any other reason
    /// gives [`BatchStatus::Failed`] exactly when an item failed.
    pub fn status(&self) -> BatchStatus {
        match self.reason {
            CompletionReason::CustomCompletionFailed => BatchStatus::Failed,
            CompletionReason::CustomCompletionSucceeded => BatchStatus::Succeeded,
            _ if self.has_failure() => BatchStatus::Failed,
            _ => BatchStatus::Succeeded,
        }
    }

    /// Returns the total number of items that were started.
    ///
    /// The count includes [`BatchItemStatus::Started`] items, which can
    /// appear live when the completion rule ends the batch early.
    pub fn total_count(&self) -> usize {
        self.items.len()
    }

    /// Iterates over the errors of the failed items, in input order.
    ///
    /// Each [`BatchError`] carries the failed item's index, display name,
    /// error type identifier, and error message, so a caller can tell
    /// which input produced which failure and what kind of error it was.
    pub fn errors(&self) -> impl Iterator<Item = BatchError<'_>> + '_ {
        self.failed().map(|item| BatchError {
            index: item.index,
            name: &item.name,
            message: item.error_message.as_deref().unwrap_or_default(),
            error_type: item.error_type.as_deref(),
        })
    }

    /// Returns the items with status [`BatchItemStatus::Succeeded`], in
    /// input order.
    pub fn succeeded(&self) -> impl Iterator<Item = &BatchItem<O>> + '_ {
        self.with_status(BatchItemStatus::Succeeded)
    }

    /// Returns the items with status [`BatchItemStatus::Failed`], in input
    /// order.
    pub fn failed(&self) -> impl Iterator<Item = &BatchItem<O>> + '_ {
        self.with_status(BatchItemStatus::Failed)
    }

    /// Returns the items with status [`BatchItemStatus::Started`], in input
    /// order: the items that were still running when the completion rule
    /// ended the batch.
    pub fn started(&self) -> impl Iterator<Item = &BatchItem<O>> + '_ {
        self.with_status(BatchItemStatus::Started)
    }

    /// Returns the number of [`BatchItemStatus::Started`] items.
    pub fn started_count(&self) -> usize {
        self.started().count()
    }

    /// Returns `Ok(self)` unless an item failed or the batch status is
    /// [`BatchStatus::Failed`].
    ///
    /// This is JS `throwIfError()`. It returns an error for a failure
    /// within the configured tolerance too. `.await` on the builder differs:
    /// it returns an error only when the batch failed.
    ///
    /// # Errors
    ///
    /// The first failed item's error, in input order: the error `.await`
    /// returns for that item, of kind
    /// [`ChildContextErrorKind::ChildFailed`](crate::ChildContextErrorKind::ChildFailed)
    /// with the item's recorded failure. When no item failed and the
    /// status is [`BatchStatus::Failed`], the batch completion error, of
    /// kind
    /// [`ChildContextErrorKind::BatchCompletionFailed`](crate::ChildContextErrorKind::BatchCompletionFailed).
    pub fn into_result(self) -> Result<Self, OperationError> {
        if let Some(item) = self.failed().next() {
            return Err(item_failure_error(item.failure_wire()));
        }
        if self.status() == BatchStatus::Failed {
            return Err(batch_completion_failed_error());
        }
        Ok(self)
    }

    fn with_status(&self, status: BatchItemStatus) -> impl Iterator<Item = &BatchItem<O>> + '_ {
        self.items.iter().filter(move |item| item.status == status)
    }
}

impl BatchResult<crate::future::BranchValue> {
    /// Returns the value of the branch that `key` names, when that branch
    /// succeeded.
    ///
    /// This is how the summary of
    /// [`ParallelMixedBuilder::summary`](crate::builders::ParallelMixedBuilder::summary)
    /// reads a branch's typed value: take the key with
    /// [`BranchHandle::key`](crate::BranchHandle::key) before the set goes
    /// to [`DurableContext::parallel_mixed`](crate::DurableContext::parallel_mixed),
    /// and pass it here. The value is what the branch's serdes decoded, as
    /// [`BranchHandle::into_result`](crate::BranchHandle::into_result)
    /// returns it.
    ///
    /// Returns `None` when the branch failed, was still running when the
    /// batch completed, or never started, and for a key from another
    /// [`BranchSet`](crate::BranchSet).
    ///
    /// The key's type fixes the type of the value, so a key of one type
    /// cannot read a value of another:
    ///
    /// ```compile_fail
    /// use aws_durable_execution_sdk as durable;
    /// use durable::builders::map_parallel::{BatchResult, CompletionReason};
    /// use durable::{BranchSet, BranchValue};
    ///
    /// let mut branches = BranchSet::new();
    /// let count = branches.add("count", |_ctx| async { Ok(7_u32) });
    /// let key = count.key();
    /// let batch: BatchResult<BranchValue> =
    ///     BatchResult::new(Vec::new(), CompletionReason::AllCompleted);
    /// let _value: Option<&String> = batch.value(&key);
    /// ```
    pub fn value<T: 'static>(&self, key: &crate::BranchKey<T>) -> Option<&T> {
        self.items
            .iter()
            .find(|item| item.index == key.index())?
            .result
            .as_ref()?
            .of_branch(key)
    }
}

/// Controls whether batch items run in real or virtual child contexts.
///
/// [`NestingMode::Normal`] (the default) runs each item in its own child
/// context, producing per-item `ContextStarted`/`ContextSucceeded` events.
/// [`NestingMode::Flat`] runs items in a virtual context: operations inside
/// each item are checkpointed directly under the parent batch context, with
/// no per-item context events.
///
/// In both modes, item `i` of the batch with ID `b` has the ID `b-{i+1}`,
/// in the batch's own namespace, and the operations inside it have the IDs
/// `b-{i+1}-{n}`. A Normal item records a child context at its ID, with the
/// batch as its parent. A Flat item records nothing at its ID, and its
/// operations name the batch as their parent.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::NestingMode;
///
/// let mode = NestingMode::Flat;
/// assert_ne!(mode, NestingMode::Normal);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum NestingMode {
    /// Each item runs in its own child context with full context events.
    #[default]
    Normal,
    /// Items run in a virtual context under the parent, no per-item
    /// context events are emitted.
    Flat,
}

/// A map item namer: receives the item and its index, and returns the name
/// the caller gives the item.
pub(crate) type ItemNamer<I> = Box<dyn Fn(&I, usize) -> String + Send + Sync>;

/// The caller's summary of an oversized batch result (see
/// [`MapBuilder::summary`](crate::builders::MapBuilder::summary)).
pub(crate) type BatchSummary<O> = Arc<dyn Fn(&BatchResult<O>) -> String + Send + Sync>;

/// Internal state for a map execution passed from the builder.
///
/// Holds the user's map closure as `Arc<F>`: shared rather than boxed,
/// because the same closure runs once per item, concurrently. Each item
/// call produces a **concrete** future from `Arc<F>`, so the
/// [`JoinSet`](tokio::task::JoinSet) inside [`execute_batch`] holds
/// concrete futures with no per-item box; the one erasure point is the
/// builder's `.future()` / `into_future`, which boxes the whole execution
/// future once inside [`DurableFuture`](crate::DurableFuture).
pub(crate) struct MapExecution<I, O, F, IS, RS> {
    pub(crate) ctx: DurableContext,
    pub(crate) op_id: OperationId,
    pub(crate) name: Option<String>,
    pub(crate) max_concurrency: Option<usize>,
    pub(crate) completion: Option<crate::builders::map_parallel::CompletionConfig>,
    pub(crate) serdes: IS,
    pub(crate) encoding: ItemEncoding,
    pub(crate) result_serdes: RS,
    pub(crate) nesting: NestingMode,
    pub(crate) item_namer: Option<ItemNamer<I>>,
    pub(crate) summary: Option<BatchSummary<O>>,
    pub(crate) items: Vec<I>,
    pub(crate) closure: Arc<F>,
    pub(crate) _marker: std::marker::PhantomData<fn() -> O>,
}

impl<I, O, F, Fut, IS, RS> MapExecution<I, O, F, IS, RS>
where
    I: Send + 'static,
    O: Send + 'static,
    F: Fn(DurableContext, I, usize) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
    IS: Serdes<O>,
    RS: Serdes<String>,
{
    /// Executes the map operation and returns the full `BatchResult`.
    ///
    /// The user closure enters the batch engine only through the
    /// [`ItemDispatch`] object, so [`execute_batch`], the checkpoint state
    /// machine, compiles once per result type while every item still runs
    /// as a concrete, unboxed future. The `Vec<O>` view of `.await` is
    /// projected by [`collect_successful`].
    ///
    /// Runs the batch's start step now, on the caller's task, and returns
    /// the future of the rest of the operation (see [`crate::start`]).
    pub(crate) fn execute_batch_result_started(
        self,
    ) -> impl Future<Output = Result<BatchResult<O>, OperationError>> + Send + 'static {
        let started = self.start();
        self.run(started)
    }

    /// The start step of the batch parent (see [`batch_start`]).
    fn start(&self) -> Result<StartStep, OperationError> {
        batch_start(
            &self.ctx,
            &self.op_id,
            self.name.as_deref(),
            MAP_SUB_TYPE,
            self.max_concurrency,
        )
    }

    /// The rest of the map after its start step `started`.
    async fn run(
        self,
        started: Result<StartStep, OperationError>,
    ) -> Result<BatchResult<O>, OperationError> {
        let started = started?;
        let total_items = self.items.len();
        // Every name is computed here, once per input item, while the items
        // are still readable: after `into_item_slots` they sit behind
        // take-once slots. So the namer runs exactly once per input item,
        // including items that never start, and sees the item itself.
        let user_names: Vec<Option<String>> = self
            .items
            .iter()
            .enumerate()
            .map(|(i, item)| self.item_namer.as_ref().map(|namer| namer(item, i)))
            .collect();
        drop(self.item_namer);
        let record_names = record_names_of(&user_names, "map-item");
        let items = into_item_slots(self.items);
        let closure = self.closure;
        let items_ref = Arc::clone(&items);
        let item_ids = ItemIds::new(&self.op_id, total_items);

        let dispatch = MapDispatch {
            run_item: Arc::new(move |child_ctx: DurableContext, index: usize| {
                let items = Arc::clone(&items_ref);
                let closure = Arc::clone(&closure);
                async move {
                    let item = take_item(&items, index).map_err(ChildFnError::from)?;
                    (closure)(child_ctx, item, index).await.map_err(Into::into)
                }
            }),
        };

        execute_batch(
            self.ctx,
            self.op_id,
            self.name,
            self.max_concurrency,
            self.completion,
            self.serdes,
            self.encoding,
            self.result_serdes,
            self.nesting,
            user_names,
            record_names,
            self.summary,
            total_items,
            MAP_SUB_TYPE,
            MAP_ITERATION_SUB_TYPE,
            &dispatch,
            &item_ids,
            started,
        )
        .await
    }
}

/// Internal state for a parallel execution passed from the builder.
pub(crate) struct ParallelExecution<O, IS, RS> {
    pub(crate) ctx: DurableContext,
    pub(crate) op_id: OperationId,
    pub(crate) name: Option<String>,
    pub(crate) max_concurrency: Option<usize>,
    pub(crate) completion: Option<crate::builders::map_parallel::CompletionConfig>,
    pub(crate) serdes: IS,
    pub(crate) encoding: ItemEncoding,
    pub(crate) result_serdes: RS,
    pub(crate) nesting: NestingMode,
    pub(crate) branches: Vec<(Option<String>, crate::future::BranchBody<O>)>,
    pub(crate) summary: Option<BatchSummary<O>>,
    /// The IDs of the branches (see [`ItemIds`]). `parallel_mixed` builds
    /// its item serdes from the same table.
    pub(crate) item_ids: ItemIds,
}

impl<O, IS, RS> ParallelExecution<O, IS, RS>
where
    O: Send + 'static,
    IS: Serdes<O>,
    RS: Serdes<String>,
{
    /// Executes the parallel operation and returns the full `BatchResult`.
    ///
    /// Branch bodies are heterogeneous, so each carries exactly one erased
    /// future ([`crate::future::BranchBody`], built at `Branch::new`); the
    /// batch engine and its per-item state machine are shared, non-generic
    /// code. The `Vec<O>` view of `.await` is projected by
    /// [`collect_successful`], as for map: failed branches within
    /// tolerance are skipped, and the batch errors when the failure
    /// tolerance was exceeded or the predicate completed it as failed.
    ///
    /// Runs the batch's start step now, on the caller's task, and returns
    /// the future of the rest of the operation (see [`crate::start`]).
    pub(crate) fn execute_batch_result_started(
        self,
    ) -> impl Future<Output = Result<BatchResult<O>, OperationError>> + Send + 'static {
        let started = self.start();
        self.run(started)
    }

    /// The start step of the batch parent (see [`batch_start`]).
    fn start(&self) -> Result<StartStep, OperationError> {
        batch_start(
            &self.ctx,
            &self.op_id,
            self.name.as_deref(),
            PARALLEL_SUB_TYPE,
            self.max_concurrency,
        )
    }

    /// The rest of the parallel after its start step `started`.
    async fn run(
        self,
        started: Result<StartStep, OperationError>,
    ) -> Result<BatchResult<O>, OperationError> {
        let started = started?;
        let total = self.branches.len();
        // Split each branch into the name the caller gave (`None` for
        // `Branch::unnamed`) and its erased body (kept in a take-once slot
        // since it runs at most once). The recorded names default a
        // missing or empty name.
        let mut user_names: Vec<Option<String>> = Vec::with_capacity(total);
        let mut slots: Vec<std::sync::Mutex<Option<crate::future::BranchBody<O>>>> =
            Vec::with_capacity(total);
        for (name, body) in self.branches {
            user_names.push(name);
            slots.push(std::sync::Mutex::new(Some(body)));
        }
        let record_names = record_names_of(&user_names, "parallel-branch");

        let dispatch = BranchDispatch {
            slots: Arc::new(slots),
        };

        execute_batch(
            self.ctx,
            self.op_id,
            self.name,
            self.max_concurrency,
            self.completion,
            self.serdes,
            self.encoding,
            self.result_serdes,
            self.nesting,
            user_names,
            record_names,
            self.summary,
            total,
            PARALLEL_SUB_TYPE,
            PARALLEL_BRANCH_SUB_TYPE,
            &dispatch,
            &self.item_ids,
            started,
        )
        .await
    }
}

/// The name history records for each batch item: the caller's name when it
/// is present and not empty, else `{prefix}-{index}`, as JS records
/// `item.name || item.id`.
fn record_names_of(user_names: &[Option<String>], prefix: &str) -> Vec<String> {
    user_names
        .iter()
        .enumerate()
        .map(|(i, name)| match name.as_deref() {
            Some(name) if !name.is_empty() => name.to_owned(),
            _ => format!("{prefix}-{i}"),
        })
        .collect()
}

/// Projects a full [`BatchResult`] onto the plain `Vec<O>` success view
/// shared by `map` and `parallel` `.await`.
///
/// If the batch completed within tolerance (`AllCompleted`) or ended early
/// on a success trigger (`MinSuccessfulReached` or
/// `CustomCompletionSucceeded`), failed items are expected and NOT
/// propagated as errors: they are simply skipped. A batch that ended because
/// the failure tolerance was exceeded (including the default fail-fast case)
/// or because the predicate completed it as failed (`CustomCompletionFailed`)
/// becomes an `Err`: a `ChildFailed`-kinded error carrying the first failed
/// item's recorded wire record (`error_type`, message). A
/// `CustomCompletionFailed` batch with no failed item becomes a
/// `BatchCompletionFailed` error instead.
pub(crate) fn collect_successful<O>(
    batch_result: BatchResult<O>,
) -> Result<Vec<O>, OperationError> {
    if let Some(err) = await_error(&batch_result) {
        return Err(err);
    }
    // Failed items within tolerance and items still started at batch
    // completion carry no value, so the `Vec<O>` view skips them.
    Ok(batch_result
        .items
        .into_iter()
        .filter(|item| item.status == BatchItemStatus::Succeeded)
        .filter_map(|item| item.result)
        .collect())
}

/// The error the `.await` of a map or parallel returns for `batch`, or
/// `None` when it returns the values.
///
/// A batch that ended because the failure tolerance was exceeded
/// (including the default fail-fast case) or because the predicate
/// completed it as failed returns the first failed item's error: a
/// `ChildFailed` error that carries the item's recorded wire record (type,
/// message, `error_data`, `stack_trace`), reserving `Internal` for
/// coordinator defects. When no item failed, the first case returns a
/// batch error and the second a `BatchCompletionFailed` error. Every other
/// batch returns `None`. `collect_successful` and `publish_outcome` both
/// call it, so `parallel` and `parallel_mixed` fail on the same batches
/// with the same error.
fn await_error<O>(batch: &BatchResult<O>) -> Option<OperationError> {
    if !matches!(
        batch.reason,
        CompletionReason::FailureToleranceExceeded | CompletionReason::CustomCompletionFailed
    ) {
        return None;
    }
    if let Some(item) = batch
        .items
        .iter()
        .find(|item| item.status == BatchItemStatus::Failed)
    {
        return Some(item_failure_error(item.failure_wire()));
    }
    Some(match batch.reason {
        CompletionReason::FailureToleranceExceeded => batch_error("failure tolerance exceeded"),
        _ => batch_completion_failed_error(),
    })
}

/// The operation IDs of a batch's items, in the batch's own namespace.
///
/// Item `i` of the batch at the positional ID `b` has the positional ID
/// `b-{i+1}`, as in JS. The table is built from the batch's ID and the item
/// count before anything runs. So an item's ID depends only on its index,
/// not on the polling order, the concurrency, the admission order, an early
/// completion or a replay. The live run, sequential admission, every replay
/// path and the `parallel_mixed` item serdes read item IDs from it.
#[derive(Clone)]
pub(crate) struct ItemIds(Arc<[OperationId]>);

impl ItemIds {
    /// Builds the table of the `count` items of the batch `batch`.
    pub(crate) fn new(batch: &OperationId, count: usize) -> Self {
        Self(
            (1..=count)
                .map(|n| OperationId::new(format!("{}-{n}", batch.positional())))
                .collect(),
        )
    }

    /// The ID of item `index`.
    ///
    /// Every caller passes an index below the item count: the batch engine
    /// iterates `0..total_items`, and the table has `total_items` entries,
    /// and the record readers check each index against `total_items`
    /// before they look it up. So the lookup cannot miss.
    #[expect(clippy::expect_used)]
    // reason: every caller passes an index below the item count the table was built with
    fn id(&self, index: usize) -> &OperationId {
        self.0
            .get(index)
            .expect("every caller passes an index below the item count")
    }
}

/// The item serdes of `parallel_mixed`: each branch's serdes, found from
/// the operation ID of the item that is being encoded or decoded.
///
/// `Serdes::deserialize` receives no item index, but its `SerdesContext`
/// names the item. So `by_op_id` maps the wire ID of each item of the
/// batch's [`ItemIds`] table to the branch index. It is built before the
/// batch runs and never changes. A value encodes itself: it carries its
/// own branch's serdes.
pub(crate) struct MixedItemSerdes {
    by_op_id: std::collections::HashMap<String, usize>,
    decoders: Arc<Vec<Arc<dyn crate::future::BranchDecoder>>>,
}

impl MixedItemSerdes {
    /// Builds the item serdes of the batch whose items have the IDs
    /// `item_ids`, one per decoder.
    pub(crate) fn new(
        item_ids: &ItemIds,
        decoders: Arc<Vec<Arc<dyn crate::future::BranchDecoder>>>,
    ) -> Self {
        let mut by_op_id = std::collections::HashMap::new();
        for index in 0..decoders.len() {
            by_op_id.insert(item_ids.id(index).wire().to_owned(), index);
        }
        Self { by_op_id, decoders }
    }
}

impl Serdes<crate::future::BranchValue> for MixedItemSerdes {
    async fn serialize(
        &self,
        value: crate::future::BranchValue,
        context: SerdesContext,
    ) -> Result<String, BoxError> {
        value.encode(context).await
    }

    async fn deserialize(
        &self,
        wire: String,
        context: SerdesContext,
    ) -> Result<crate::future::BranchValue, BoxError> {
        let decoder = self
            .by_op_id
            .get(context.operation_id())
            .and_then(|index| self.decoders.get(*index))
            .ok_or_else(|| {
                format!(
                    "parallel_mixed: no branch has operation ID \"{}\"",
                    context.operation_id()
                )
            })?;
        decoder.decode(wire, context).await
    }
}

/// Publishes each settled branch of a `parallel_mixed` batch to its handle,
/// and returns what the `.await` of `parallel_mixed` returns.
///
/// An `Err` from the batch publishes nothing. For an `Ok` batch, every
/// settled item is published, whatever [`await_error`] returns: a
/// succeeded item with a value fills its handle with the value, and a
/// failed item fills its handle with the error `parallel(...).await`
/// returns for it. Every other item publishes nothing, so a handle has a
/// result exactly when its branch settled. A failed item whose index names
/// no branch is skipped, because the item indexes of a recorded batch are
/// not checked against the branch count.
pub(crate) fn publish_outcome(
    result: Result<BatchResult<crate::future::BranchValue>, OperationError>,
    decoders: &[Arc<dyn crate::future::BranchDecoder>],
) -> Result<CompletionReason, OperationError> {
    let batch = result?;
    let error = await_error(&batch);
    let reason = batch.reason;
    for item in batch.items {
        match item.status {
            BatchItemStatus::Succeeded => {
                if let Some(value) = item.result {
                    value.publish();
                }
            }
            BatchItemStatus::Failed => {
                if let Some(decoder) = decoders.get(item.index) {
                    decoder.publish_error(item_failure_error(item.failure_wire()));
                }
            }
            BatchItemStatus::Started => {}
        }
    }
    error.map_or(Ok(reason), Err)
}

/// A pre-claimed child operation with its metadata.
struct PreClaimed {
    index: usize,
    op_id: OperationId,
    is_terminal: bool,
    /// Whether the checkpoint log holds ANY record for this child: a
    /// terminal record or a `Started` one from a prior invocation. Drives
    /// two decisions at dispatch: a child with a record never gets a second
    /// `Start` write, and a recorded child counts as "ever started" in the
    /// batch decision record.
    has_record: bool,
}

/// The payload a branch task delivers through the coordinator's join set:
/// the item index plus the item's terminal outcome. A branch that waits on
/// a durable operation stays pending in the join set and keeps its
/// concurrency slot until it finishes.
type ItemJoin<O> = (usize, Result<ItemOutcome<O>, OperationError>);

/// One item's terminal outcome, plus the wire string its child produced
/// when it succeeded: the string the child serialized for its record or its
/// size check, or the string replay read from its record. The batch record
/// takes the item value from it, so it needs no second serdes call.
type ItemOutcome<O> = (BatchItem<O>, Option<String>);

/// Everything one item body needs, owned and free of generic parameters.
///
/// A dispatcher moves one of these into each spawned task, which is what
/// lets the whole checkpoint state machine around the user closure
/// ([`item_before`], [`item_after`], [`execute_batch`]) compile once per
/// result type instead of once per user call site.
struct ItemRequest<IS> {
    ctx: DurableContext,
    child_op_id: OperationId,
    index: usize,
    is_terminal: bool,
    parent_wire: String,
    child_sub_type: String,
    item_name: String,
    nesting: NestingMode,
    /// The info the item's `on_operation_start` received; a live body's
    /// user-function hooks receive it with the item context's replay flag
    /// (`user_function_info`).
    start_info: Arc<crate::plugin::OperationInfo>,
    /// The item serdes, shared across items behind one `Arc` (the
    /// forwarding `impl Serdes for Arc<S>` makes the handle itself a
    /// serdes).
    serdes: Arc<IS>,
    /// The item's `START` write, queued at dispatch and still in flight.
    /// The outcome write takes it and waits for it. `None` for a flat
    /// item, and for an item whose record already existed. A mutex keeps
    /// the request `Sync`, so the item future can hold a reference to it.
    start: std::sync::Mutex<Option<SubmittedWrite>>,
}

impl<IS> ItemRequest<IS> {
    /// Waits for the item's retained `START` write before the item writes
    /// its outcome `action` (see [`DurableContext::await_retained_start`]).
    async fn await_start(&self, action: OperationAction) -> Result<(), OperationError> {
        let start = self
            .start
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        self.ctx
            .await_retained_start(self.child_op_id.wire(), start, action)
            .await
    }
}

/// What [`item_before`] decided: the item is already resolved from the
/// checkpoint log, or the body must run in the prepared child context.
enum ItemPrelude<O> {
    /// Recorded terminal outcome decoded from the checkpoint log.
    Done(ItemOutcome<O>),
    /// The body must run; the child context is ready.
    Run {
        /// The child context the item body receives.
        child_ctx: DurableContext,
    },
}

/// Pre-closure half of one batch item: replay decode, child START
/// checkpoint, child-context creation. Generic only over the result type
/// `O`, no user closure reaches this code.
async fn item_before<O, IS>(req: &ItemRequest<IS>) -> Result<ItemPrelude<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    let child_positional = req.child_op_id.positional().to_owned();
    let child_wire = req.child_op_id.wire().to_owned();
    // Per-item serdes context: the child's wire ID is stable across replays,
    // so a context-sensitive serdes resolves the same location every time.
    let serdes_ctx = SerdesContext::new(child_wire.clone(), req.ctx.execution_arn());

    // Replay path: child already terminal.
    if req.is_terminal {
        match replay_terminal_child(
            &req.ctx,
            &child_positional,
            req.index,
            &req.item_name,
            &req.serdes,
            &serdes_ctx,
        )
        .await
        {
            Ok(item) => return Ok(ItemPrelude::Done(item)),
            Err(e) => {
                // ReplayChildren sentinel: fall through to re-execution.
                let is_replay_children =
                    crate::error::chain_string(&e).contains(REPLAY_CHILDREN_SENTINEL);
                if !is_replay_children {
                    return Err(e);
                }
                // Fall through: re-execute the child to reconstruct result.
            }
        }
    }

    // FLAT nesting: skip child context events; run item directly under
    // parent. Operations inside the flat branch checkpoint with ParentId
    // pointing to the batch parent (not the virtual child).
    if req.nesting == NestingMode::Flat {
        let child_ctx =
            req.ctx
                .new_flat_child(&child_positional, &req.parent_wire, Some(&req.item_name));
        return Ok(ItemPrelude::Run { child_ctx });
    }

    // Create the child context. The child's `Start` was already
    // checkpointed by the coordinator at dispatch (the coordinator is the
    // sole writer of child starts; see `execute_batch`), or exists from a
    // prior invocation.
    Ok(ItemPrelude::Run {
        child_ctx: req.ctx.new_child(&child_positional, Some(&req.item_name)),
    })
}

/// Post-closure half of one batch item: outcome checkpointing and
/// [`BatchItem`] assembly. Generic only over the result type `O`, no user
/// closure reaches this code.
#[expect(clippy::too_many_lines)] // reason: FLAT/NORMAL outcome checkpointing reads better in one flow
async fn item_after<O, IS>(
    req: &ItemRequest<IS>,
    outcome: ItemBody<O>,
    replaying: bool,
) -> Result<ItemOutcome<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    // A live run's failure keeps the one wire its end hooks saw.
    let outcome = match outcome {
        ItemBody::Ran(ran) => ran.into_parts(),
        ItemBody::Unhooked(result) => result.map_err(|error| {
            let wire = error.failure_wire();
            (error, wire)
        }),
    };
    let child_wire = req.child_op_id.wire().to_owned();
    let serdes_ctx = SerdesContext::new(child_wire.clone(), req.ctx.execution_arn());
    let serdes = &req.serdes;
    // The item's own terminal update is written through the batch's
    // context, as a child context's is written through its parent. The
    // item's scope already closed when its body returned, so the item's
    // owners would reject it. The batch scope closes at early completion,
    // so a running item's terminal update is rejected from then on.
    let writer = &req.ctx;

    // FLAT nesting emits no child-context events: only the value transform
    // (round-trip for live == replay consistency) happens here. A terminal
    // item re-runs only to rebuild a `ReplayChildren` result (see
    // `item_before`). Its record is already closed, and a checkpoint backend
    // rejects a second close of a CONTEXT. So it takes the same path and
    // writes nothing.
    if req.nesting == NestingMode::Flat || req.is_terminal {
        let settled = match outcome {
            Ok(value) => {
                // A result serialization failure is LOCAL and
                // deterministic: the item closure already ran, so the item
                // settles as a failed `BatchItem` instead of yielding a
                // catchable coordinator error with no record (issue #43).
                // FLAT items have no per-child record: the failure is
                // recorded inside the parent batch's record when
                // the parent checkpoints, and replay reconstructs the same
                // failed item from it, so live and replayed batches agree.
                let round_trip = async {
                    let name = item_fault_name(&req.item_name);
                    let serialized =
                        serialize_value(&req.ctx, name, value, serdes, serdes_ctx.clone()).await?;
                    let deserialized: O =
                        deserialize_value(&req.ctx, name, serialized.clone(), serdes, serdes_ctx)
                            .await?;
                    Ok::<_, OperationError>((deserialized, serialized))
                };
                match round_trip.await {
                    Ok((deserialized, serialized)) => Ok((
                        BatchItem {
                            index: req.index,
                            name: req.item_name.clone(),
                            status: BatchItemStatus::Succeeded,
                            result: Some(deserialized),
                            error_message: None,
                            error_type: None,
                            error_data: None,
                            stack_trace: Vec::new(),
                        },
                        Some(serialized),
                    )),
                    Err(op_err) => {
                        let wire = crate::error::serialization_failure_wire(&op_err);
                        Ok((
                            BatchItem::failed_from_wire(req.index, req.item_name.clone(), &wire),
                            None,
                        ))
                    }
                }
            }
            Err((_error, wire)) => {
                // The wire record is derived from the error the body
                // returned: its recorded type, and its recorded message
                // (see `wire_message`).
                Ok((
                    BatchItem::failed_from_wire(req.index, req.item_name.clone(), &wire),
                    None,
                ))
            }
        };
        // A flat item reports its end as a virtual child. A terminal
        // Normal item that re-ran to rebuild its result fires nothing.
        if req.nesting == NestingMode::Flat
            && let Ok((item, _)) = &settled
        {
            // A settled flat item either succeeded or failed.
            if matches!(item.status, BatchItemStatus::Succeeded) {
                item_ended(
                    req,
                    crate::OperationStatus::Succeeded,
                    None,
                    None,
                    replaying,
                );
            } else {
                let wire = item.failure_wire();
                item_ended(
                    req,
                    crate::OperationStatus::Failed,
                    None,
                    Some(&wire),
                    replaying,
                );
            }
        }
        return settled;
    }

    match outcome {
        Ok(value) => {
            // Serialize and checkpoint success.
            //
            // A result serialization failure is LOCAL and deterministic:
            // the item closure already ran, so a terminal FAIL is
            // persisted for the child FIRST, and the item settles as a
            // failed `BatchItem` (issue #43). That is exactly the shape a
            // replay of the FAIL record produces (see
            // [`replay_terminal_child`]), so live and replayed batches
            // agree, and the closure never re-runs for this failure.
            let serialized = match serialize_value(
                &req.ctx,
                item_fault_name(&req.item_name),
                value,
                serdes,
                serdes_ctx.clone(),
            )
            .await
            {
                Ok(serialized) => serialized,
                Err(op_err) => {
                    req.await_start(OperationAction::Fail).await?;
                    let wire = crate::error::serialization_failure_wire(&op_err);
                    let update = build_child_fail_update(
                        &child_wire,
                        &req.item_name,
                        &req.child_sub_type,
                        &req.parent_wire,
                        &wire,
                        req.ctx.preserves_children(1),
                    );
                    if let Err(client_err) = writer.checkpoint_updates(vec![update]).await {
                        return writer.checkpoint_failure_unrecoverable(client_err).await;
                    }
                    item_ended(
                        req,
                        crate::OperationStatus::Failed,
                        None,
                        Some(&wire),
                        replaying,
                    );
                    return Ok((
                        BatchItem::failed_from_wire(req.index, req.item_name.clone(), &wire),
                        None,
                    ));
                }
            };
            let mut builder = OperationUpdate::builder()
                .id(child_wire.clone())
                .r#type(OperationType::Context)
                .sub_type(req.child_sub_type.clone())
                .action(OperationAction::Succeed)
                .parent_id(req.parent_wire.clone())
                .name(req.item_name.clone());

            if serialized.len() > CHECKPOINT_SIZE_LIMIT_BYTES {
                builder = builder.context_options(
                    aws_sdk_lambda::types::ContextOptions::builder()
                        .replay_children(true)
                        .build(),
                );
            } else {
                builder = builder.payload(serialized.clone());
                // Within the plugin child operations depth, the item
                // record keeps its children for later invocations.
                if req.ctx.preserves_children(1) {
                    builder = builder.context_options(
                        aws_sdk_lambda::types::ContextOptions::builder()
                            .replay_children(true)
                            .build(),
                    );
                }
            }

            #[expect(clippy::expect_used)] // reason: all required fields are set above
            let update = builder
                .build()
                .expect("all required OperationUpdate fields set");
            // The end hook reports the payload the update carries: none for
            // a `ReplayChildren` result.
            let result = update.payload().map(str::to_owned);

            req.await_start(OperationAction::Succeed).await?;
            if let Err(err) = writer.checkpoint_updates(vec![update]).await {
                return writer.checkpoint_failure_unrecoverable(err).await;
            }
            item_ended(
                req,
                crate::OperationStatus::Succeeded,
                result,
                None,
                replaying,
            );

            // Round-trip deserialize for live == replay consistency.
            let deserialized: O = deserialize_value(
                &req.ctx,
                item_fault_name(&req.item_name),
                serialized.clone(),
                serdes,
                serdes_ctx,
            )
            .await?;

            Ok((
                BatchItem {
                    index: req.index,
                    name: req.item_name.clone(),
                    status: BatchItemStatus::Succeeded,
                    result: Some(deserialized),
                    error_message: None,
                    error_type: None,
                    error_data: None,
                    stack_trace: Vec::new(),
                },
                Some(serialized),
            ))
        }
        Err((_error, wire)) => {
            // The item failed: checkpoint its failure. The wire record is
            // derived from the error the body returned, so the type is the
            // body error's recorded type, the message is its recorded
            // message (see `wire_message`), and `error_data`/`stack_trace` pass through the
            // boundary.
            let mut builder = OperationUpdate::builder()
                .id(child_wire.clone())
                .r#type(OperationType::Context)
                .sub_type(req.child_sub_type.clone())
                .action(OperationAction::Fail)
                .parent_id(req.parent_wire.clone())
                .name(req.item_name.clone())
                .error(wire.to_error_object());
            // Within the plugin child operations depth, the item record
            // keeps its children for later invocations.
            if req.ctx.preserves_children(1) {
                builder = builder.context_options(
                    aws_sdk_lambda::types::ContextOptions::builder()
                        .replay_children(true)
                        .build(),
                );
            }

            #[expect(clippy::expect_used)] // reason: all required fields are set above
            let update = builder
                .build()
                .expect("all required OperationUpdate fields set");

            req.await_start(OperationAction::Fail).await?;
            if let Err(client_err) = writer.checkpoint_updates(vec![update]).await {
                return writer.checkpoint_failure_unrecoverable(client_err).await;
            }
            item_ended(
                req,
                crate::OperationStatus::Failed,
                None,
                Some(&wire),
                replaying,
            );

            Ok((
                BatchItem::failed_from_wire(req.index, req.item_name.clone(), &wire),
                None,
            ))
        }
    }
}

/// The body result [`item_after`] writes: a live run through the
/// user-function runner, or a result that ran no hook (a `ReplayChildren`
/// rebuild, or a branch body that could not be taken).
enum ItemBody<O> {
    Ran(crate::plugin::Ran<O, ChildFnError>),
    Unhooked(Result<O, ChildFnError>),
}

/// Thin generic wrapper around one map item: the ONLY code monomorphized
/// per map call site. Everything before and after the user closure is the
/// non-generic [`item_before`] / [`item_after`] pair; this wrapper just
/// polls the user's concrete future between them under the branch driver.
async fn run_single_item<O, F, Fut, IS>(
    req: ItemRequest<IS>,
    run_item: Arc<F>,
) -> Result<ItemOutcome<O>, OperationError>
where
    O: Send + 'static,
    F: Fn(DurableContext, usize) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, ChildFnError>> + Send + 'static,
    IS: Serdes<O>,
{
    match item_before(&req).await? {
        ItemPrelude::Done(item) => Ok(item),
        ItemPrelude::Run { child_ctx } => {
            // Run the item body inside the item namespace's replay-aware
            // span: a resumed item's pre-wait log lines are suppressed
            // while its own operations replay, independently of the root
            // handler span and of sibling items. A live body's `Runner`
            // owns the span and enters it outside its hooks and wraps; a
            // terminal item's rebuild runs no user function, so its body
            // is instrumented with the span instead.
            let span = child_ctx.replay_span();
            let index = req.index;
            // The active-body scope encloses the closure call, so code the
            // closure runs before it returns its future is checked too. A
            // wait inside the body keeps this task pending in the join set.
            let body = UserBody::Context(child_ctx.prefix().to_owned());
            let item_ctx = child_ctx.clone();
            // The item's scope closes when the body returns, and also when
            // this future is dropped before that (see `item_scope`).
            let scope = item_scope(&req);
            let outcome = if req.is_terminal {
                // A terminal item re-runs only to rebuild a `ReplayChildren`
                // result: no frame and no user-function hook.
                let outcome =
                    run_body(body.into(), async move { run_item(child_ctx, index).await })
                        .instrument(span)
                        .await;
                drop(scope);
                ItemBody::Unhooked(outcome)
            } else {
                let info = user_function_info(&req, &item_ctx);
                ItemBody::Ran(
                    // The runner enters the span outside the hooks and
                    // wraps, and polls the body inside them. The scope
                    // closes inside the body future, so it is closed
                    // before the end hooks, as for a child context.
                    crate::plugin::run_user_function(
                        item_ctx.shared_plugins(),
                        info,
                        body,
                        span,
                        move || async move {
                            let outcome = run_item(child_ctx, index).await;
                            drop(scope);
                            outcome
                        },
                        ChildFnError::failure_wire,
                    )
                    .await,
                )
            };
            item_after(&req, outcome, item_ctx.is_replaying()).await
        }
    }
}

/// The info a map item's or parallel branch's user-function hooks receive:
/// the value `on_operation_start` received, with the replay flag set to the
/// item context's `is_replaying()` when the body starts, as JS sets
/// `isReplay: childReplayMode !== ExecutionMode`. The start hook keeps its
/// record-based flag.
fn user_function_info<IS>(
    req: &ItemRequest<IS>,
    item_ctx: &DurableContext,
) -> Arc<crate::plugin::OperationInfo> {
    let is_replay = item_ctx.is_replaying();
    if req.start_info.is_replay() == is_replay {
        Arc::clone(&req.start_info)
    } else {
        Arc::new((*req.start_info).clone().with_replay(is_replay))
    }
}

/// Non-generic branch runner for `parallel`: the branch body is already the
/// single erased future carried by [`crate::future::BranchBody`], so
/// nothing here monomorphizes per user call site.
async fn run_branch_item<O, IS>(
    req: ItemRequest<IS>,
    slots: Arc<Vec<std::sync::Mutex<Option<crate::future::BranchBody<O>>>>>,
) -> Result<ItemOutcome<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    match item_before(&req).await? {
        ItemPrelude::Done(item) => Ok(item),
        ItemPrelude::Run { child_ctx } => {
            let span = child_ctx.replay_span();
            let item_ctx = child_ctx.clone();
            let scope = item_scope(&req);
            let outcome = match take_branch_body(&slots, req.index) {
                Ok(body) => {
                    // `start` injects the child context and returns the
                    // branch's single erased future, awaited here exactly
                    // like a map item's body. The factory closure runs
                    // inside the erased future, so wrapping the future
                    // encloses the closure call.
                    let active = UserBody::Context(child_ctx.prefix().to_owned());
                    if req.is_terminal {
                        // Rebuilding a `ReplayChildren` result: no frame
                        // and no user-function hook.
                        let outcome = run_body(active.into(), body.start(child_ctx))
                            .instrument(span)
                            .await;
                        drop(scope);
                        ItemBody::Unhooked(outcome)
                    } else {
                        let info = user_function_info(&req, &item_ctx);
                        ItemBody::Ran(
                            // The runner enters the span outside the hooks
                            // and wraps, as for a map item. The scope
                            // closes inside the body future, so it is
                            // closed before the end hooks, as for a map
                            // item.
                            crate::plugin::run_user_function(
                                item_ctx.shared_plugins(),
                                info,
                                active,
                                span,
                                move || async move {
                                    let outcome = body.start(child_ctx).await;
                                    drop(scope);
                                    outcome
                                },
                                ChildFnError::failure_wire,
                            )
                            .await,
                        )
                    }
                }
                Err(err) => {
                    drop(scope);
                    ItemBody::Unhooked(Err(err))
                }
            };
            item_after(&req, outcome, item_ctx.is_replaying()).await
        }
    }
}

/// The scope of one item, normal or flat: it closes when the item's body
/// returns, and when the item's future is dropped before that because the
/// batch aborted the item (see `Admission`). An operation the body started
/// and did not await then writes no further checkpoint, and its task
/// stops. The item's own terminal update is written through the batch's
/// context, so it is admitted.
fn item_scope<IS>(req: &ItemRequest<IS>) -> ScopeClose {
    ScopeClose::new(req.ctx.admission(), req.child_op_id.wire())
}

/// Takes one branch body out of its take-once slot.
fn take_branch_body<O>(
    slots: &[std::sync::Mutex<Option<crate::future::BranchBody<O>>>],
    index: usize,
) -> Result<crate::future::BranchBody<O>, ChildFnError> {
    let guard = slots
        .get(index)
        .ok_or_else(|| ChildFnError::new("branch index out of bounds"))?;
    let mut lock = guard
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    lock.take()
        .ok_or_else(|| ChildFnError::new("branch already consumed (concurrent access bug)"))
}

/// Object-safe item dispatcher: spawns one item body onto the coordinator's
/// [`TrackedJoinSet`] as a CONCRETE (unboxed) future.
///
/// This boundary is what keeps [`execute_batch`], the batch checkpoint
/// state machine, non-generic over the user's closure: only the dispatcher
/// and the thin wrapper it spawns ([`run_single_item`]) monomorphize per
/// call site, while the futures inside the join set stay unboxed.
trait ItemDispatch<O, IS>: Send + Sync {
    /// Spawns the item body for `req` and returns the task's ID, or `None`
    /// when the coordinator refused the spawn. The join set blesses the
    /// task before the body's first poll.
    fn spawn_item(
        &self,
        set: &mut TrackedJoinSet<ItemJoin<O>>,
        req: ItemRequest<IS>,
    ) -> Result<Option<tokio::task::Id>, NoRuntime>;
}

/// Map dispatcher: shares the user closure as `Arc<F>` and produces one
/// concrete future per item: the join set holds no per-item box.
struct MapDispatch<F> {
    run_item: Arc<F>,
}

impl<O, F, Fut, IS> ItemDispatch<O, IS> for MapDispatch<F>
where
    O: Send + 'static,
    F: Fn(DurableContext, usize) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, ChildFnError>> + Send + 'static,
    IS: Serdes<O>,
{
    fn spawn_item(
        &self,
        set: &mut TrackedJoinSet<ItemJoin<O>>,
        req: ItemRequest<IS>,
    ) -> Result<Option<tokio::task::Id>, NoRuntime> {
        let run_item = Arc::clone(&self.run_item);
        let ownership = Arc::clone(req.ctx.task_ownership());
        // The item runs inside the batch context's frames.
        set.spawn(
            crate::task::TaskContext::current(),
            &ownership,
            async move {
                let index = req.index;
                (index, run_single_item(req, run_item).await)
            },
        )
    }
}

/// Parallel dispatcher: hands each spawned task the shared take-once slots
/// holding the single-erasure branch bodies. Non-generic: the erased
/// branch body already carries the user's closure and future.
struct BranchDispatch<O> {
    slots: Arc<Vec<std::sync::Mutex<Option<crate::future::BranchBody<O>>>>>,
}

impl<O, IS> ItemDispatch<O, IS> for BranchDispatch<O>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    fn spawn_item(
        &self,
        set: &mut TrackedJoinSet<ItemJoin<O>>,
        req: ItemRequest<IS>,
    ) -> Result<Option<tokio::task::Id>, NoRuntime> {
        let slots = Arc::clone(&self.slots);
        let ownership = Arc::clone(req.ctx.task_ownership());
        // The branch runs inside the batch context's frames.
        set.spawn(
            crate::task::TaskContext::current(),
            &ownership,
            async move {
                let index = req.index;
                (index, run_branch_item(req, slots).await)
            },
        )
    }
}

/// Mutable coordinator bookkeeping shared by the join-drain paths.
struct BatchProgress<O> {
    /// Running completion statistics plus the first trigger to fire.
    tracker: CompletionTracker,
    /// Terminal outcomes, positional by item index.
    results: Vec<Option<BatchItem<O>>>,
    /// The wire string each succeeded item's child produced, positional by
    /// item index. The batch record takes each item value from it.
    wires: Vec<Option<String>>,
    /// Which items were EVER admitted: dispatched live this invocation, or
    /// holding a checkpoint record from a prior one. Ordered admission makes
    /// this a contiguous prefix of the input, and its length is the
    /// `totalCount` the batch decision record carries: the number of items
    /// ever started, NOT the input length.
    started: Vec<bool>,
}

impl<O> BatchProgress<O> {
    /// Builds the bookkeeping for one batch. `names` holds the caller name
    /// of each input item (see [`CompletionItem::name`]); its length is the
    /// input length.
    fn new(names: Vec<Option<String>>) -> Self {
        let total_items = names.len();
        Self {
            tracker: CompletionTracker::new(names),
            results: (0..total_items).map(|_| None).collect(),
            wires: vec![None; total_items],
            started: vec![false; total_items],
        }
    }

    /// Marks one item as ever admitted (see [`Self::started`]).
    fn mark_started(&mut self, index: usize) {
        if let Some(slot) = self.started.get_mut(index) {
            *slot = true;
        }
    }

    /// Records a live dispatch of one item, for the decision record and for
    /// the completion predicate's view.
    fn mark_dispatched(&mut self, index: usize) {
        self.mark_started(index);
        self.tracker.mark_dispatched(index);
    }

    /// Records one terminal item outcome: it feeds the completion
    /// statistics, its result slot and its wire slot.
    fn settle_outcome(
        &mut self,
        completion_cfg: &crate::builders::map_parallel::CompletionConfig,
        total_items: usize,
        index: usize,
        (item, wire): ItemOutcome<O>,
    ) {
        self.tracker
            .settle(completion_cfg, total_items, index, item.status);
        if let Some(slot) = self.results.get_mut(index) {
            *slot = Some(item);
        }
        if let Some(slot) = self.wires.get_mut(index) {
            *slot = wire;
        }
    }
}

/// Borrowed coordinator context shared by the join-drain helpers, so the
/// helpers stay non-generic functions with manageable signatures.
struct BatchEnv<'a, O, IS> {
    ctx: &'a DurableContext,
    dispatch: &'a dyn ItemDispatch<O, IS>,
    completion_cfg: &'a crate::builders::map_parallel::CompletionConfig,
    total_items: usize,
    nesting: NestingMode,
    parent_wire: &'a str,
    child_sub_type: &'a str,
    serdes: &'a Arc<IS>,
}

impl<O, IS> BatchEnv<'_, O, IS>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    /// Processes one joined branch task: its outcome feeds the progress
    /// accounting, and an error of the task itself, not of its body (for
    /// example the error `.spawn()` returns without a Tokio runtime), is
    /// returned. A failed checkpoint write never reaches here: it fails
    /// the invocation, and the task does not resolve. A panic of the task resumes unwinding here, with
    /// its original payload, and nothing is recorded for it: a panic fails
    /// the invocation, not the item.
    fn settle_joined(
        &self,
        joined: TaskOutcome<ItemJoin<O>>,
        progress: &mut BatchProgress<O>,
    ) -> Result<(), OperationError> {
        let (index, outcome) = joined.into_value();
        // An error of the task itself surfaces; the caller's join set drop
        // aborts the remaining branches.
        let item = outcome?;
        progress.settle_outcome(self.completion_cfg, self.total_items, index, item);
        Ok(())
    }

    /// Resolves a recorded-terminal child inline on the coordinator, in
    /// input order. The common case decodes the recorded outcome without
    /// touching the item body; a `ReplayChildren` child (result too large to
    /// checkpoint) is re-executed through the dispatcher and drained
    /// immediately, so input order is preserved and the join set still
    /// holds only concrete futures.
    ///
    /// A panic during that re-execution resumes unwinding (through
    /// [`Self::settle_joined`]) and checkpoints nothing, as every panic
    /// does: the child's durable record stays a terminal SUCCESS for the
    /// next attempt to reconstruct.
    async fn resolve_terminal_inline(
        &self,
        op_id: &OperationId,
        index: usize,
        item_name: &str,
        join_set: &mut TrackedJoinSet<ItemJoin<O>>,
        progress: &mut BatchProgress<O>,
    ) -> Result<(), OperationError> {
        let child_positional = op_id.positional().to_owned();
        let serdes_ctx = SerdesContext::new(op_id.wire().to_owned(), self.ctx.execution_arn());
        match replay_terminal_child(
            self.ctx,
            &child_positional,
            index,
            item_name,
            self.serdes,
            &serdes_ctx,
        )
        .await
        {
            Ok(item) => {
                progress.settle_outcome(self.completion_cfg, self.total_items, index, item);
                Ok(())
            }
            Err(e) => {
                let is_replay_children =
                    crate::error::chain_string(&e).contains(REPLAY_CHILDREN_SENTINEL);
                if !is_replay_children {
                    return Err(e);
                }
                // ReplayChildren: re-execute the body to reconstruct the
                // oversized result. The join set is quiescent at every
                // inline call site (the replay pass runs before live
                // dispatch; the sequential cursor has nothing in flight), so
                // the immediate drain below joins exactly this item.
                let req = ItemRequest {
                    ctx: self.ctx.clone(),
                    child_op_id: op_id.clone(),
                    index,
                    is_terminal: true,
                    parent_wire: self.parent_wire.to_owned(),
                    child_sub_type: self.child_sub_type.to_owned(),
                    item_name: item_name.to_owned(),
                    nesting: self.nesting,
                    // A reconstruction fires no hook, so nothing reads it.
                    start_info: Arc::new(item_info(
                        self.ctx,
                        op_id.wire(),
                        self.child_sub_type,
                        item_name,
                    )),
                    serdes: Arc::clone(self.serdes),
                    start: std::sync::Mutex::new(None),
                };
                let reconstruction_id = self
                    .dispatch
                    .spawn_item(join_set, req)
                    .map_err(NoRuntime::operation_error)?;
                let Some((joined_id, joined)) = join_set.join_next_with_id().await else {
                    return Err(batch_error(
                        "re-executed replay child produced no join event",
                    ));
                };
                // Verify (rather than assume) the quiescence invariant: the
                // join event must belong to the reconstruction task spawned
                // above.
                if Some(joined_id) != reconstruction_id {
                    return Err(batch_error(
                        "re-executed replay child joined an unexpected task",
                    ));
                }
                self.settle_joined(joined, progress)
            }
        }
    }
}

/// Core batch execution: schedule items with bounded concurrency and
/// completion checking.
///
/// Non-generic over the user closure: item bodies enter only through the
/// [`ItemDispatch`] object, so this coordinator, the batch's checkpoint
/// state machine, monomorphizes once per result type `O`.
#[expect(clippy::too_many_lines)]
// reason: batch coordination has distinct phases (claim, schedule, collect, checkpoint) that read better as one flow
#[expect(clippy::too_many_arguments)] // reason: batch execution requires all these parameters
async fn execute_batch<O, IS, RS>(
    ctx: DurableContext,
    parent_op_id: OperationId,
    parent_name: Option<String>,
    max_concurrency: Option<usize>,
    completion: Option<crate::builders::map_parallel::CompletionConfig>,
    serdes: IS,
    encoding: ItemEncoding,
    result_serdes: RS,
    nesting: NestingMode,
    user_names: Vec<Option<String>>,
    record_names: Vec<String>,
    summary: Option<BatchSummary<O>>,
    total_items: usize,
    parent_sub_type: &str,
    child_sub_type: &str,
    dispatch: &dyn ItemDispatch<O, IS>,
    item_ids: &ItemIds,
    started: StartStep,
) -> Result<BatchResult<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
    RS: Serdes<String>,
{
    // Share the item serdes across items behind one `Arc`: the forwarding
    // `impl Serdes for Arc<S>` makes the handle itself a serdes, so no
    // `Clone` bound is required of the user's implementation.
    let serdes = Arc::new(serdes);

    // 1. The start step ran (see `batch_start`): admission, task
    // ownership, the `max_concurrency` check, the replay identity check,
    // and the parent START with its start hook. The items do not wait for
    // a queued START: the parent's outcome write does.
    let (recorded, parent_start) = match started {
        StartStep::Refused => return std::future::pending().await,
        StartStep::Recorded(view) => (Some(view), None),
        StartStep::Queued(write) => (None, Some(write)),
    };
    // A fresh `START` is a live start; a record resumes the batch.
    let resumed = recorded.is_some();

    // The caller computed both name lists once per input item, before the
    // items moved. `user_names` holds the name the caller gave, which only
    // the completion predicate sees. `record_names` holds the name history
    // records, which replay identity validation, the child checkpoints and
    // the result use.
    //
    // `record_names` has one entry per input item, and every caller of
    // this closure passes an index below `total_items`. So the lookup
    // cannot miss.
    #[expect(clippy::expect_used)]
    // reason: `record_names` has one entry per input item and every index is below `total_items`
    let item_name_of = |i: usize| -> String {
        record_names
            .get(i)
            .expect("record_names has one entry per input item")
            .clone()
    };

    let parent_positional = parent_op_id.positional().to_owned();
    let parent_wire = parent_op_id.wire().to_owned();

    // The batch's own namespace. The batch's START, SUCCEED and FAIL writes
    // and the whole-batch serdes stay on the caller's context `ctx`,
    // because they name the caller's parent. Item replay, item serdes
    // faults and the item contexts use `batch_ctx`, and item IDs come from
    // `item_ids`, so the batch never claims an ID from the caller.
    let batch_ctx = ctx.new_child(&parent_positional, parent_name.as_deref());

    // 2. Check if the parent batch is already terminal in the checkpoint log.
    // Identity validation and the status read happen in one read-guard pass;
    // the terminal payload/error projection is cloned only when the batch is
    // actually terminal and must be replayed.
    // When the parent is terminal with `replay_children` and its payload
    // parses as a batch decision record, replay OBEYS the record instead of
    // re-deriving the outcome. `Some` constrains the re-execution below to
    // the recorded admission set and completion reason.
    let mut replay_plan: Option<ReplayPlan> = None;

    // A non-terminal record (Started/Pending) continues from where it left
    // off. The start step fired its replay start hook.
    if let Some(view) = recorded
        && view.status.is_terminal()
    {
        let snapshot = ctx
            .checkpoint_terminal_replay(&parent_positional)
            .ok_or_else(|| batch_error("terminal batch has no checkpoint record"))?;
        let serdes_ctx = SerdesContext::new(&parent_wire, ctx.execution_arn());

        // A successful batch too large to checkpoint inline recorded a
        // decision record (`totalCount`, `completionReason`, index set)
        // instead of its payload. A payload that fails to parse is
        // corrupt and fails the replay.
        // A batch within the plugin child operations depth recorded its
        // own result instead, and its plan is read from that result.
        let decision =
            if matches!(snapshot.status, CheckpointStatus::Succeeded) && snapshot.replay_children {
                match parse_replay_children_payload(snapshot.result.as_deref())? {
                    Some(record) => Some(record),
                    None => Some(
                        full_result_decision(
                            &ctx,
                            parent_name.as_deref(),
                            snapshot.result.clone().unwrap_or_default(),
                            &result_serdes,
                            &serdes_ctx,
                        )
                        .await?,
                    ),
                }
            } else {
                None
            };

        if let Some(record) = decision {
            let plan = ReplayPlan::from_record(&record, total_items)?;
            // Fast path (Normal nesting): decode every completed item
            // straight from its child record (after validating each
            // child's replay identity), report items in the started
            // set as STARTED without consulting their child
            // checkpoints, and omit every index at or beyond
            // `totalCount`. Flat items have no
            // child records, so Flat always reconstructs through the
            // plan-constrained re-execution below.
            if nesting != NestingMode::Flat {
                match replay_batch_from_record(
                    &batch_ctx,
                    &plan,
                    &record_names,
                    &serdes,
                    child_sub_type,
                    item_ids,
                )
                .await
                {
                    Ok(result) => {
                        // Recorded terminal batch returned without
                        // re-running the batch.
                        ctx.emit_operation_replayed(
                            &parent_wire,
                            parent_name.as_deref(),
                            "Context",
                            Some(parent_sub_type),
                            view.attempt,
                        );
                        return Ok(result);
                    }
                    Err(e) => {
                        let is_replay_children =
                            crate::error::chain_string(&e).contains(REPLAY_CHILDREN_SENTINEL);
                        if !is_replay_children {
                            return Err(e);
                        }
                        // A completed CHILD whose own result was too
                        // large to checkpoint inline: reconstruct it by
                        // re-execution, still constrained by the plan.
                    }
                }
            }
            replay_plan = Some(plan);
            // Fall through: re-execute ONLY the recorded admission set.
        } else {
            match replay_terminal_batch(
                &ctx,
                parent_name.as_deref(),
                &snapshot,
                &serdes,
                encoding.clone(),
                total_items,
                &result_serdes,
                &serdes_ctx,
                item_ids,
            )
            .await
            {
                Ok(result) => {
                    // Recorded terminal batch record returned without
                    // re-running the batch (see `crate::observability`).
                    ctx.emit_operation_replayed(
                        &parent_wire,
                        parent_name.as_deref(),
                        "Context",
                        Some(parent_sub_type),
                        view.attempt,
                    );
                    return Ok(result);
                }
                Err(e) => {
                    // ReplayChildren sentinel: fall through to
                    // re-execution. The children's operations are still
                    // in the checkpoint log, so re-executing the batch
                    // will replay each child from its terminal record.
                    let is_replay_children =
                        crate::error::chain_string(&e).contains(REPLAY_CHILDREN_SENTINEL);
                    if !is_replay_children {
                        // A recorded batch FAILURE replays as this
                        // error; an internal replay problem
                        // (missing/corrupt payload) is not a replayed
                        // outcome and emits nothing.
                        if matches!(snapshot.status, CheckpointStatus::Failed) {
                            ctx.emit_operation_replayed(
                                &parent_wire,
                                parent_name.as_deref(),
                                "Context",
                                Some(parent_sub_type),
                                view.attempt,
                            );
                        }
                        return Err(e);
                    }
                    // Fall through: the batch parent is terminal but we
                    // need to re-execute children to reconstruct the
                    // result.
                }
            }
        }
    }

    let completion_cfg = completion.unwrap_or_default();

    // 3 to 8: the batch-producing section, from the zero-item result or
    // the first record read to the batch and its completion reason. On a
    // live or resumed batch it is the container's user function: its hooks
    // and wraps run through the runner, under the batch child context's
    // body and span, and its end hooks always see `Ok`, because every item
    // failure is in the batch. A rebuild under a decision record polls it
    // with no frame and no user-function hook.
    let rebuild = replay_plan.is_some();
    let active = UserBody::Context(batch_ctx.prefix().to_owned());
    let span = batch_ctx.replay_span();
    let produce = || {
        produce_batch(BatchSection {
            ctx: &ctx,
            batch_ctx: &batch_ctx,
            max_concurrency,
            completion_cfg: &completion_cfg,
            serdes: &serdes,
            nesting,
            user_names,
            item_name_of: &item_name_of,
            total_items,
            child_sub_type,
            dispatch,
            item_ids,
            parent_wire: &parent_wire,
            replay_plan,
        })
    };
    let produced = if rebuild {
        run_body(active.into(), produce()).instrument(span).await
    } else {
        // The info `on_operation_start` received: a fresh `START` is live,
        // a resumed record a replay. The user-function hooks see the
        // batch child context's replay state when the body starts.
        let info = container_info(&ctx, &parent_wire, parent_sub_type, parent_name.as_deref());
        let info = if resumed {
            info
        } else {
            info.with_status(crate::OperationStatus::Started)
        };
        let info = Arc::new(info.with_replay(batch_ctx.is_replaying()));
        match crate::plugin::run_user_function(
            ctx.shared_plugins(),
            info,
            active,
            span,
            move || async move { Ok::<_, std::convert::Infallible>(produce().await) },
            crate::plugin::never_fails,
        )
        .await
        .into_parts()
        {
            Ok(produced) => produced,
            Err((never, _)) => match never {},
        }
    };
    let Produced {
        result: batch_result,
        wires: final_wires,
    } = produced?;
    // 8b. Under a replay plan, the batch outcome is already durably
    // recorded: NOTHING is re-checkpointed.
    if rebuild {
        return Ok(batch_result);
    }

    // 9. Build the batch record text from the item wire strings (no
    // serdes call), then pass it through the SAME `serialize_value` helper
    // as every other path. `result_serdes` receives the record's JSON text
    // and returns the payload to store.
    let payload = from_batch_result(&batch_result, &final_wires, &encoding);
    // The serialization runs after the container's body ended `Ok`, so its
    // failure keeps its own wire (#126 rule 7.6): the returned error
    // carries `serialization_failure_wire`, as a step's or a child's does.
    // The container writes no outcome record for it.
    let serialized_payload = serialize_value(
        &ctx,
        parent_name.as_deref(),
        payload,
        &result_serdes,
        SerdesContext::new(&parent_wire, ctx.execution_arn()),
    )
    .await
    .map_err(|err| {
        let wire = crate::error::serialization_failure_wire(&err);
        err.with_wire(wire)
    })?;

    // The JS summary travels alongside the payload: when the payload is
    // too large to checkpoint inline, the summary is written in its place
    // so replay can obey the recorded outcome instead of re-deriving it.
    // The caller's summary runs only then, and its output joins the JS
    // summary under the key `summary`.
    let caller_summary = match summary {
        Some(summary) if serialized_payload.len() > CHECKPOINT_SIZE_LIMIT_BYTES => {
            Some(summary(&batch_result))
        }
        _ => None,
    };
    let summary_json =
        oversized_batch_summary(&batch_result, parent_sub_type, caller_summary.as_deref());

    // 10. Checkpoint the parent SUCCEED.
    checkpoint_batch_success_serialized(
        &ctx,
        &parent_wire,
        parent_name.as_deref(),
        parent_sub_type,
        &serialized_payload,
        &summary_json,
        parent_start,
    )
    .await?;

    Ok(batch_result)
}

/// The output of a batch's producing section: the batch, and the wire
/// string each reported item's child produced, in the same order, for the
/// batch record.
struct Produced<O> {
    result: BatchResult<O>,
    wires: Vec<Option<String>>,
}

/// The inputs of [`produce_batch`].
struct BatchSection<'a, O, IS> {
    ctx: &'a DurableContext,
    batch_ctx: &'a DurableContext,
    max_concurrency: Option<usize>,
    completion_cfg: &'a crate::builders::map_parallel::CompletionConfig,
    serdes: &'a Arc<IS>,
    nesting: NestingMode,
    user_names: Vec<Option<String>>,
    item_name_of: &'a (dyn Fn(usize) -> String + Send + Sync),
    total_items: usize,
    child_sub_type: &'a str,
    dispatch: &'a dyn ItemDispatch<O, IS>,
    item_ids: &'a ItemIds,
    parent_wire: &'a str,
    replay_plan: Option<ReplayPlan>,
}

/// The batch-producing section of [`execute_batch`], steps 3 to 8: the
/// zero-item result, or every item's record read, the items' dispatch and
/// settlement, and the batch with its completion reason. It returns `Ok`
/// with every item failure in the batch. The batch's scope closes inside
/// it, when dispatch ends.
#[expect(clippy::too_many_lines)]
// reason: batch coordination has distinct phases (read, schedule, collect) that read better as one flow
async fn produce_batch<O, IS>(
    section: BatchSection<'_, O, IS>,
) -> Result<Produced<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    let BatchSection {
        ctx,
        batch_ctx,
        max_concurrency,
        completion_cfg,
        serdes,
        nesting,
        user_names,
        item_name_of,
        total_items,
        child_sub_type,
        dispatch,
        item_ids,
        parent_wire,
        replay_plan,
    } = section;

    // 3. Empty collection: the batch succeeds at once. As in JS, a
    // zero-item batch asks the predicate once, on an empty view; without a
    // predicate the decision is `Continue`, which records `AllCompleted`.
    if total_items == 0 {
        let reason =
            custom_reason(completion_cfg.predicate_decision(&BatchStats::from_counts(0, 0, &[])))
                .unwrap_or(CompletionReason::AllCompleted);
        return Ok(Produced {
            result: BatchResult {
                items: Vec::new(),
                reason,
            },
            wires: Vec::new(),
        });
    }

    // 4. Determine effective concurrency.
    let concurrency = max_concurrency.unwrap_or(total_items).max(1);

    // 5. Read every item's record up front (concurrent path). Each item's
    // ID comes from `item_ids`, so it depends on its index alone. Reading
    // is LOCAL, no `Start` is checkpointed here; the coordinator writes
    // each child's `Start` at dispatch, so a child is admitted (and
    // recorded) only when a concurrency slot is actually free for it.
    // The sequential path (`concurrency == 1`) reads each item's record at
    // the dispatch cursor instead.
    let mut pre_claimed: Vec<PreClaimed> = Vec::with_capacity(total_items);
    if concurrency > 1 {
        for i in 0..total_items {
            let child_op_id = item_ids.id(i).clone();
            // Under a replay plan, only indexes the record admits as
            // COMPLETED have their child checkpoints consulted. Started-set
            // entries are reconstructed from the record alone and
            // never-started entries are omitted, so reading (and
            // identity-validating) their views here would violate the
            // record's contract and could raise a spurious
            // non-determinism error for a record replay never touches.
            let consult_checkpoint = replay_plan.as_ref().is_none_or(|plan| plan.admits(i));
            let (has_record, is_terminal) = if consult_checkpoint {
                let child_positional = child_op_id.positional().to_owned();
                let child_wire = child_op_id.wire().to_owned();
                // Non-determinism detection on child items happens inside
                // the validated view fetch; only the status is consumed
                // here.
                let view = ctx.checkpoint_view_validated(
                    &child_positional,
                    &child_wire,
                    "Context",
                    Some(child_sub_type),
                    Some(&item_name_of(i)),
                )?;
                (view.is_some(), view.is_some_and(|v| v.status.is_terminal()))
            } else {
                (false, false)
            };
            pre_claimed.push(PreClaimed {
                index: i,
                op_id: child_op_id,
                is_terminal,
                has_record,
            });
        }
    }

    // 6. Execute items with bounded concurrency, branch-local suspension, and
    // slot-holding accounting. Admission is ordered and LAZY: the
    // coordinator, the sole writer of child starts, checkpoints each
    // child's `Start` at the moment it dispatches that child, in index
    // order, as concurrency slots free up. No child `Start` is written
    // before its item is about to run, so an early completion trigger or a
    // failure part-way leaves no starts recorded for children that never
    // ran.

    // Coordinator loop. In-flight items are bounded by `concurrency`. An
    // item that waits on a durable operation stays pending in the join set
    // and counts in `running` until its task ends, so it KEEPS its slot
    // (only terminal completion frees one: the slot-holding invariant). It
    // continues when its wait completes; when nothing else can make
    // progress, the invocation coordinator suspends the invocation.
    let child_sub_type_owned = child_sub_type.to_owned();
    // Coordinator-owned task set. Dropping it (on error return OR when the
    // driver drops this coordinator on invocation teardown) aborts every
    // still-running branch task, and the invocation driver waits for each
    // aborted task to unwind, so no branch task outlives the invocation.
    // Every task delivers its outcome through the set, including a panic,
    // which `settle_joined` resumes.
    let mut join_set: TrackedJoinSet<ItemJoin<O>> =
        TrackedJoinSet::new(Arc::clone(ctx.coordinator()));

    // The completion predicate sees each caller name as
    // `CompletionItem::name`.
    let mut progress = BatchProgress::<O>::new(user_names);
    // A batch rebuilt under its decision record already completed. The
    // record holds its reason, so the rebuild evaluates no completion rule.
    if replay_plan.is_some() {
        progress.tracker.stop_evaluating();
    }
    let mut running: usize = 0;
    // The batch's scope: every item context runs inside it. It closes at
    // early completion, before the running items are aborted, and when
    // this future ends or is dropped (see `Admission`).
    let mut batch_scope = Some(ScopeClose::new(ctx.admission(), parent_wire));
    let mut next_index: usize = 0;

    // A child holding ANY checkpoint record was admitted by a prior
    // invocation: it counts toward the "ever started" prefix the decision
    // record carries even if a completion trigger keeps this invocation
    // from re-dispatching it.
    for pre in &pre_claimed {
        if pre.has_record {
            progress.mark_started(pre.index);
        }
    }

    let env = BatchEnv {
        ctx: batch_ctx,
        dispatch,
        completion_cfg,
        total_items,
        nesting,
        parent_wire,
        child_sub_type: &child_sub_type_owned,
        serdes,
    };

    // 7b. Replay pass (concurrent mode): resolve every recorded-terminal
    // child inline on the coordinator, in input order, BEFORE dispatching
    // any live work, never through the live `JoinSet` schedule. This is
    // what keeps completion triggers deterministic under replay: outcomes
    // already in the checkpoint log feed the statistics in canonical input
    // order before any live settlement joins, so identical recorded state
    // yields identical trigger decisions no matter how the scheduler orders
    // the join events of resumed live branches. Recorded terminals are
    // completed history, real work whose outcome the service persisted,
    // so they are applied unconditionally: a trigger firing mid-pass halts
    // future live dispatch but never drops an already-recorded outcome
    // from the result.
    //
    // The sequential path (`concurrency == 1`) discovers terminality lazily
    // at the dispatch cursor instead, where settlement order and input
    // order already coincide.
    if concurrency > 1 {
        for i in 0..total_items {
            let Some(pre) = pre_claimed.get(i) else {
                return Err(batch_error("pre-claimed index out of range"));
            };
            if !pre.is_terminal {
                continue;
            }
            // Under a replay plan only the recorded admission set
            // contributes to the result (a terminal record outside it
            // cannot exist for a well-formed record; skipping is
            // defensive).
            if let Some(plan) = &replay_plan
                && !plan.admits(i)
            {
                continue;
            }
            let item_name = item_name_of(i);
            env.resolve_terminal_inline(&pre.op_id, i, &item_name, &mut join_set, &mut progress)
                .await?;
        }
    }

    loop {
        // Dispatch while capacity remains and not-started eligible work exists.
        // A completion trigger (`tracker.stop_reason`) halts new dispatch,
        // and the join below abandons the running items. Under a replay
        // plan the trigger check
        // is bypassed: the recorded admission set IS the outcome being
        // reproduced, so every admitted item is dispatched regardless of
        // what the thresholds would re-derive, and the recorded reason is
        // taken verbatim below.
        while (replay_plan.is_some() || progress.tracker.stop_reason.is_none())
            && next_index < total_items
            && running < concurrency
        {
            let i = next_index;
            next_index += 1;

            // Under a replay plan, everything outside the recorded
            // admission set is resolved from the record alone: an index at
            // or beyond `totalCount` never started and is omitted; an
            // index in the started set was non-terminal when the batch
            // completed and is reported as STARTED: with no result and no
            // error, its child checkpoints never consulted.
            if let Some(plan) = &replay_plan
                && !plan.admits(i)
            {
                if i < plan.total_count {
                    let item_name = item_name_of(i);
                    if let Some(slot) = progress.results.get_mut(i) {
                        *slot = Some(BatchItem {
                            index: i,
                            name: item_name,
                            status: BatchItemStatus::Started,
                            result: None,
                            error_message: None,
                            error_type: None,
                            error_data: None,
                            stack_trace: Vec::new(),
                        });
                    }
                }
                continue;
            }

            // Concurrent mode: recorded-terminal children were already
            // applied by the replay pass above: skip them here.
            if concurrency > 1 && pre_claimed.get(i).is_some_and(|pre| pre.is_terminal) {
                continue;
            }

            // Determine the PreClaimed item: for concurrent mode use the
            // pre-claimed vector, which holds only non-terminal items here;
            // for sequential mode, read the record of the item's ID now, so
            // the cursor knows whether the item is recorded-terminal before
            // the dispatch gate runs.
            let pc = if concurrency > 1 {
                let pre = pre_claimed
                    .get(i)
                    .ok_or_else(|| batch_error("pre-claimed index out of range"))?;
                PreClaimed {
                    index: pre.index,
                    op_id: pre.op_id.clone(),
                    is_terminal: pre.is_terminal,
                    has_record: pre.has_record,
                }
            } else {
                let child_op_id = item_ids.id(i).clone();
                // Non-determinism detection on child items happens inside
                // the validated view fetch; only the status is consumed.
                let view = ctx.checkpoint_view_validated(
                    child_op_id.positional(),
                    child_op_id.wire(),
                    "Context",
                    Some(child_sub_type),
                    Some(&item_name_of(i)),
                )?;
                let has_record = view.is_some();
                let is_terminal = view.is_some_and(|v| v.status.is_terminal());
                PreClaimed {
                    index: i,
                    op_id: child_op_id,
                    is_terminal,
                    has_record,
                }
            };

            // Recorded-terminal child (sequential path only: the
            // concurrent path applied its recorded terminals in the replay
            // pass above): resolve it inline on the coordinator, at the
            // dispatch cursor, in input order. This is the replay pass of
            // the sequential path, not a live dispatch, so the dispatch
            // gate does not run for it; its settle evaluates the
            // completion rule, except under a replay plan.
            if pc.is_terminal {
                // The item enters the "ever started" prefix the batch
                // decision record reports. It settles at once, with no
                // evaluation in between, so the predicate never sees its
                // `Started`.
                progress.mark_dispatched(i);
                let item_name = item_name_of(pc.index);
                env.resolve_terminal_inline(
                    &pc.op_id,
                    pc.index,
                    &item_name,
                    &mut join_set,
                    &mut progress,
                )
                .await?;
                continue;
            }

            // Dispatch gate: as JS does before each start, ask the
            // completion predicate on the current view. A `Complete`
            // decision sets the reason and stops dispatch; when nothing
            // runs, the loop below ends the batch at once, and otherwise
            // the next settle ends it through early completion. Under a
            // replay plan the recorded reason is reproduced instead.
            if replay_plan.is_none() && progress.tracker.dispatch_gate(completion_cfg) {
                break;
            }

            // The item is admitted: it enters the "ever started" prefix the
            // batch decision record reports, and the predicate's view reads
            // it as `Started`.
            progress.mark_dispatched(i);

            // Compute the item name in the coordinator: the start checkpoint
            // and the branch body both carry it.
            let item_name = item_name_of(pc.index);
            let branch_index = pc.index;
            let branch_wire = pc.op_id.wire().to_owned();

            // Ordered lazy admission: the coordinator, the sole writer of
            // child starts, checkpoints this child's `Start` NOW, at
            // dispatch, just before spawning its body. Writing on the
            // owning task (never inside the spawned task) keeps every
            // start committed before the child's own writes, and no start
            // exists for a child that never ran. A child holding a record
            // from a prior invocation resumes without a second `Start`.
            //
            // As in JS, the START is queued, then `on_operation_start`
            // fires, then the START is released, and the body starts
            // without waiting for its response. The item's outcome write
            // waits for it (see `ItemRequest::await_start`). A failed
            // START ends the invocation there, rather than as an item
            // failure, so a tolerant completion config cannot absorb a
            // checkpoint failure.
            let reserved = (nesting != NestingMode::Flat && !pc.has_record).then(|| {
                ctx.reserve_checkpoint_updates(vec![build_child_update(
                    &branch_wire,
                    &item_name,
                    &child_sub_type_owned,
                    parent_wire,
                    OperationAction::Start,
                )])
            });
            let info = item_info(batch_ctx, &branch_wire, &child_sub_type_owned, &item_name);
            let info = if nesting == NestingMode::Flat {
                // A flat item writes no record: it reports as a virtual
                // child, with the replay state its context will start
                // with.
                info.with_virtual(true)
                    .with_replay(batch_ctx.namespace_is_replaying(pc.op_id.positional()))
            } else if pc.has_record {
                info.with_replay(true)
            } else {
                info.with_status(crate::OperationStatus::Started)
                    .with_replay(false)
            };
            if let Some(plugins) = ctx.plugins() {
                crate::plugin::operation_started(plugins, &info);
            }
            let start = reserved.map(crate::context::ReservedWrite::release);

            let req = ItemRequest {
                ctx: batch_ctx.clone(),
                child_op_id: pc.op_id,
                index: branch_index,
                is_terminal: pc.is_terminal,
                parent_wire: parent_wire.to_owned(),
                child_sub_type: child_sub_type_owned.clone(),
                item_name: item_name.clone(),
                nesting,
                start_info: Arc::new(info),
                serdes: Arc::clone(serdes),
                start: std::sync::Mutex::new(start),
            };
            dispatch
                .spawn_item(&mut join_set, req)
                .map_err(NoRuntime::operation_error)?;
            running += 1;
        }

        if running == 0 {
            // Nothing in flight: either all dispatched work is terminal, or
            // a threshold stopped dispatch.
            break;
        }

        // Await the next branch task to terminate. A panic in user branch
        // code resumes in `settle_joined`.
        let Some((_, joined)) = join_set.join_next_with_id().await else {
            break; // set is empty: unreachable while running > 0
        };
        running -= 1;
        env.settle_joined(joined, &mut progress)?;

        // Early completion: the completion rule is met, so the batch ends
        // now, without waiting for its running items (as in JS). The batch
        // scope closes first, so a write a running item issues from now on
        // is rejected, and every task started inside the batch, by a
        // running or a settled item, is aborted. Then the item tasks are
        // aborted and never joined: an outcome of an abandoned item is
        // never observed. Each aborted task stays counted until it unwinds.
        // Under a replay plan the recorded outcome is reproduced instead,
        // so nothing is abandoned.
        if replay_plan.is_none() && progress.tracker.stop_reason.is_some() {
            drop(batch_scope.take());
            join_set.abort_all();
            break;
        }
    }

    // Dispatch ended: the batch's scope closes here, inside the body, so it
    // is closed before the end hooks. At early completion it closed
    // before the running items were stopped.
    drop(batch_scope);
    drop(join_set);

    let BatchProgress {
        tracker,
        mut results,
        wires,
        started,
    } = progress;

    // 7. Assemble results in input order. On the live path, every
    // dispatched item that is not terminal (running when the trigger fired,
    // parked, or finished but not joined) is reported as STARTED, as in JS.
    // Never-started items are omitted. Under a replay plan the record's
    // started set already appears as STARTED items.
    if replay_plan.is_none() {
        // `results` and `started` both have one entry per input item.
        for (i, (slot, started)) in results.iter_mut().zip(&started).enumerate() {
            if slot.is_none() && *started {
                *slot = Some(BatchItem {
                    index: i,
                    name: item_name_of(i),
                    status: BatchItemStatus::Started,
                    result: None,
                    error_message: None,
                    error_type: None,
                    error_data: None,
                    stack_trace: Vec::new(),
                });
            }
        }
    }
    // Each reported item keeps the wire string its child produced, in the
    // same order, for the batch record.
    let (final_items, final_wires): (Vec<BatchItem<O>>, Vec<Option<String>>) = results
        .into_iter()
        .zip(wires)
        .filter_map(|(slot, wire)| slot.map(|item| (item, wire)))
        .unzip();

    // 8b. Under a replay plan, the batch outcome is already durably
    // recorded: the reason is taken verbatim from the decision record and
    // NOTHING is re-checkpointed: the record being obeyed is the parent's
    // terminal state. `final_items` holds the recorded admission set's
    // reconstructed outcomes.
    if let Some(plan) = replay_plan {
        return Ok(Produced {
            result: BatchResult {
                items: final_items,
                reason: plan.reason,
            },
            wires: final_wires,
        });
    }

    // 8. Determine completion reason: the first trigger to fire during the
    // run (recorded at the dispatch gate or the settle that fired it: first
    // trigger wins), or `AllCompleted` when no trigger fired. A non-empty
    // batch reaches this point only after a settle or after the dispatch
    // gate set the reason, and the zero-item batch returned at step 3.
    let reason = tracker
        .stop_reason
        .unwrap_or(CompletionReason::AllCompleted);

    // Ordered admission makes the ever-started set a contiguous prefix of
    // the input, and every started item is reported (a non-terminal one as
    // STARTED). So `batch_result.items` is that prefix, and its length is
    // the `totalCount` the oversized summary carries: the number of items
    // ever started, NOT the input length.
    Ok(Produced {
        result: BatchResult {
            items: final_items,
            reason,
        },
        wires: final_wires,
    })
}

/// The start step of a batch parent (see [`crate::start`]).
///
/// It returns [`StartStep::Refused`] when admission refuses the batch. It
/// runs the task-ownership check. A `max_concurrency` of zero is a
/// configuration mistake that fails the same way on every retry, and a
/// catchable error would let the handler record a different outcome. So,
/// as in JS, it fails the execution, queues nothing, and returns
/// [`StartStep::Refused`], whose future never resolves. Then it runs the
/// start step: without a record, the parent `START` is queued, then
/// `on_operation_start` fires, then the `START` is released, as JS orders
/// them. A non-terminal record fires the replay start hook.
fn batch_start(
    ctx: &DurableContext,
    op_id: &OperationId,
    name: Option<&str>,
    sub_type: &'static str,
    max_concurrency: Option<usize>,
) -> Result<StartStep, OperationError> {
    if !ctx.admission().admits(ctx.owners()) {
        return Ok(StartStep::Refused);
    }
    ctx.enforce_task_ownership()?;
    if max_concurrency == Some(0) {
        ctx.coordinator()
            .record_fatal("Error".to_owned(), MAX_CONCURRENCY_ZERO_MESSAGE.to_owned());
        return Ok(StartStep::Refused);
    }
    let wire_id = op_id.wire();
    crate::start::start_step(
        ctx,
        &crate::start::StartSpec {
            op_id,
            operation_type: "Context",
            sub_type,
            name,
            order: crate::start::StartOrder::QueueThenHook,
        },
        |view| {
            if view.status.is_terminal() {
                crate::start::Cycle::Record
            } else {
                crate::start::Cycle::Resume
            }
        },
        || build_parent_update(wire_id, name, sub_type, OperationAction::Start, ctx),
        |plugins, is_replay| {
            let info = container_info(ctx, wire_id, sub_type, name);
            let info = if is_replay {
                info.with_replay(true)
            } else {
                info.with_status(crate::OperationStatus::Started)
                    .with_replay(false)
            };
            crate::plugin::operation_started(plugins, &info);
        },
    )
}

/// Replays a terminal batch (parent already succeeded/failed in the log).
///
/// Takes the targeted [`crate::engine::TerminalReplaySnapshot`] projection
/// rather than the full checkpoint record: the status, `replay_children`,
/// and payload/error strings are all this helper reads.
#[expect(clippy::too_many_arguments)] // reason: the record check needs the input length beside the serdes inputs
async fn replay_terminal_batch<O, IS, RS>(
    ctx: &DurableContext,
    name: Option<&str>,
    snapshot: &crate::engine::TerminalReplaySnapshot,
    serdes: &Arc<IS>,
    encoding: ItemEncoding,
    total_items: usize,
    result_serdes: &RS,
    serdes_ctx: &SerdesContext,
    item_ids: &ItemIds,
) -> Result<BatchResult<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
    RS: Serdes<String>,
{
    match &snapshot.status {
        CheckpointStatus::Succeeded => {
            if snapshot.replay_children {
                // ReplayChildren mode: cannot reconstruct from the payload
                // alone: the caller must fall through to re-execution.
                // Signal this by returning a sentinel error that the caller
                // catches to continue normal execution.
                return Err(batch_error(REPLAY_CHILDREN_SENTINEL));
            }
            // Read the stored batch record.
            let payload_str = snapshot
                .result
                .clone()
                .ok_or_else(|| batch_error("terminal batch has no result payload"))?;
            // Reverse the result serdes transform: through the same helper
            // every other path uses.
            let record_text: String =
                deserialize_value(ctx, name, payload_str, result_serdes, serdes_ctx.clone())
                    .await?;
            to_batch_result(
                ctx,
                &record_text,
                serdes,
                encoding,
                total_items,
                serdes_ctx.durable_execution_arn(),
                item_ids,
            )
            .await
        }
        CheckpointStatus::Failed => {
            let msg = snapshot.error_message.as_deref().unwrap_or("batch failed");
            Err(batch_error(msg))
        }
        _ => {
            // Shouldn't happen: we checked is_terminal() above.
            Err(batch_error("unexpected non-terminal status in replay"))
        }
    }
}

/// Replays a terminal child item from the checkpoint log.
///
/// `item_name` is the validated per-item name the caller derived for this
/// slot (branch name for `parallel`, generated name for `map`); the replayed
/// [`BatchItem`] carries it so structured error access reports the producing
/// item's name even when the item reaches the batch result through replay.
async fn replay_terminal_child<O, S>(
    ctx: &DurableContext,
    child_positional: &str,
    index: usize,
    item_name: &str,
    serdes: &S,
    serdes_ctx: &SerdesContext,
) -> Result<ItemOutcome<O>, OperationError>
where
    O: Send + 'static,
    S: Serdes<O>,
{
    let record = ctx
        .checkpoint_terminal_replay(child_positional)
        .ok_or_else(|| batch_error("replay child has no checkpoint record"))?;

    match &record.status {
        CheckpointStatus::Succeeded => {
            if record.replay_children {
                // ReplayChildren mode: signal re-execution needed.
                return Err(batch_error(REPLAY_CHILDREN_SENTINEL));
            }
            let payload = record
                .result
                .clone()
                .ok_or_else(|| batch_error("succeeded child has no result"))?;
            let value: O = deserialize_value(
                ctx,
                item_fault_name(item_name),
                payload.clone(),
                serdes,
                serdes_ctx.clone(),
            )
            .await?;
            Ok((
                BatchItem {
                    index,
                    name: item_name.to_owned(),
                    status: BatchItemStatus::Succeeded,
                    result: Some(value),
                    error_message: None,
                    error_type: None,
                    error_data: None,
                    stack_trace: Vec::new(),
                },
                Some(payload),
            ))
        }
        CheckpointStatus::Failed => {
            let msg = record.error_message.as_deref().unwrap_or("child failed");
            Ok((
                BatchItem {
                    index,
                    name: item_name.to_owned(),
                    status: BatchItemStatus::Failed,
                    result: None,
                    error_message: Some(msg.to_owned()),
                    error_type: record.error_type.clone(),
                    error_data: record.error_data.clone(),
                    stack_trace: record.stack_trace.clone().unwrap_or_default(),
                },
                None,
            ))
        }
        _ => Err(batch_error(
            "unexpected non-terminal child status in replay",
        )),
    }
}

/// The decision record the Python SDK checkpoints in place of a batch
/// result too large to store inline. This SDK writes the JS summary
/// instead (see [`oversized_batch_summary`]), and reads both.
///
/// `totalCount` is the number of items EVER STARTED, not the input length;
/// ordered admission makes the started set the contiguous prefix
/// `[0, totalCount)`. `completionReason` is the wire form of
/// [`CompletionReason`], and one of `startedIndexes` / `completedIndexes`
/// names the partition of that prefix: `startedIndexes` lists items that
/// began but were not terminal when the batch completed, `completedIndexes`
/// lists the terminal ones. The read side accepts either form and
/// reconstructs the other against the same prefix.
///
/// The JS summary is read into this same shape (see
/// [`parse_replay_children_payload`]), so one [`ReplayPlan`] serves both.
#[derive(Debug, serde::Deserialize)]
struct BatchDecisionRecord {
    /// Number of items ever started (the admitted prefix length).
    #[serde(rename = "totalCount")]
    total_count: usize,
    /// Wire form of the batch's [`CompletionReason`], taken verbatim by
    /// replay.
    #[serde(rename = "completionReason")]
    completion_reason: String,
    /// Indexes (within `[0, totalCount)`) of items that began but were not
    /// terminal when the batch completed.
    #[serde(rename = "startedIndexes", default)]
    started_indexes: Option<Vec<usize>>,
    /// Indexes (within `[0, totalCount)`) of items that reached a terminal
    /// state.
    #[serde(rename = "completedIndexes", default)]
    completed_indexes: Option<Vec<usize>>,
}

/// Reads the payload of a terminal `replay_children` batch parent, in this
/// order:
///
/// 1. An absent or empty payload is corrupt bookkeeping, and replay fails
///    rather than re-executing items the recorded batch may never have
///    started.
/// 2. A JSON object with the key `itemStatuses` is the JS summary. Its
///    `itemStatuses` must be a non-empty string of `S`, `F` and `-`; the
///    started prefix is its length, the terminal indexes are its `S` and
///    `F` positions, and the reason is `completionReason`. As in JS,
///    `itemStatuses` is the only per-item field replay reads.
/// 3. A JSON object with `totalCount` and `startedIndexes` or
///    `completedIndexes` is the decision record the Python SDK writes
///    (see [`parse_decision_record`]).
/// 4. Any other payload is the batch's own result, which a batch within
///    the plugin child operations depth records with `ReplayChildren`.
///    It returns `None`, and the caller reads the plan from that result
///    (see [`full_result_decision`]).
fn parse_replay_children_payload(
    payload: Option<&str>,
) -> Result<Option<BatchDecisionRecord>, OperationError> {
    let payload = payload.unwrap_or_default().trim();
    if payload.is_empty() {
        return Err(batch_error(
            "malformed batch decision record: the payload is empty",
        ));
    }
    let Ok(value) = serde_json::from_str::<serde_json::Value>(payload) else {
        return Ok(None);
    };
    if let Some(statuses) = value.get("itemStatuses") {
        let statuses = statuses
            .as_str()
            .filter(|s| !s.is_empty() && s.chars().all(|c| matches!(c, 'S' | 'F' | '-')))
            .ok_or_else(|| {
                batch_error(
                    "malformed batch decision record: itemStatuses must be a non-empty \
                     string of S, F and -",
                )
            })?;
        let completed = statuses
            .chars()
            .enumerate()
            .filter_map(|(i, c)| (c != '-').then_some(i))
            .collect();
        return Ok(Some(BatchDecisionRecord {
            total_count: statuses.chars().count(),
            completion_reason: value
                .get("completionReason")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
                .to_owned(),
            started_indexes: None,
            completed_indexes: Some(completed),
        }));
    }
    if value.get("totalCount").is_some()
        && (value.get("startedIndexes").is_some() || value.get("completedIndexes").is_some())
    {
        return parse_decision_record(payload).map(Some);
    }
    Ok(None)
}

/// Reads the replay plan of a preserved batch from its own result: the
/// payload a batch within the plugin child operations depth records with
/// `ReplayChildren`. The result serdes decodes `payload` to the batch
/// record text. The plan admits the record's started prefix, marks its
/// succeeded and failed items as completed, and keeps its completion
/// reason, so the re-run items end as the recorded batch ended.
async fn full_result_decision<RS>(
    ctx: &DurableContext,
    name: Option<&str>,
    payload: String,
    result_serdes: &RS,
    serdes_ctx: &SerdesContext,
) -> Result<BatchDecisionRecord, OperationError>
where
    RS: Serdes<String>,
{
    let record_text: String =
        deserialize_value(ctx, name, payload, result_serdes, serdes_ctx.clone()).await?;
    let record = parse_batch_record(&record_text).map_err(|message| batch_error(&message))?;
    check_record_indexes(&record)?;
    let mut completed = Vec::with_capacity(record.all.len());
    for item in &record.all {
        if parse_item_status(&item.status)? != BatchItemStatus::Started {
            completed.push(item.index);
        }
    }
    Ok(BatchDecisionRecord {
        total_count: record.all.len(),
        completion_reason: record.completion_reason,
        started_indexes: None,
        completed_indexes: Some(completed),
    })
}

/// Checks that a batch record's `all` holds the started prefix in index
/// order: the item at position `k` has index `k`. A custom `result_serdes`
/// or a corrupt checkpoint can produce a sparse, duplicate or reordered
/// index, which would name the wrong item, so such a record is an error.
fn check_record_indexes(record: &JsBatchRecord) -> Result<(), OperationError> {
    for (position, item) in record.all.iter().enumerate() {
        if item.index != position {
            return Err(batch_error(&format!(
                "batch record item at position {position} has index {}",
                item.index
            )));
        }
    }
    Ok(())
}

/// Parses a terminal batch's `replay_children` payload as the decision
/// record the Python SDK writes.
///
/// A payload that fails to parse is corrupt bookkeeping: the safe
/// response is an error, never a silent fall-back to unconstrained
/// re-execution that could resurrect items the recorded batch never
/// started.
fn parse_decision_record(payload: &str) -> Result<BatchDecisionRecord, OperationError> {
    serde_json::from_str(payload.trim())
        .map_err(|e| batch_error(&format!("malformed batch decision record: {e}")))
}

/// What a decision record instructs replay to do: which indexes were ever
/// started, which of those completed, and the reason the batch ended.
#[derive(Debug)]
struct ReplayPlan {
    /// Number of items ever started (`totalCount`, validated to be no
    /// larger than the input length).
    total_count: usize,
    /// Per-index completion flag over `[0, total_count)`.
    completed: Vec<bool>,
    /// The recorded completion reason, reported verbatim.
    reason: CompletionReason,
}

impl ReplayPlan {
    /// Derives the plan from a parsed decision record, rejecting any record
    /// this SDK's writer could not have produced. The writer emits exactly
    /// one index form (the shorter set), every index inside
    /// `[0, totalCount)`, a `totalCount` no larger than the input it ran
    /// over, and a known completion-reason wire value, so a record that
    /// violates any of those is corrupt bookkeeping. Silently repairing it
    /// (clamping, ignoring, defaulting) would convert recorded outcomes
    /// into different ones; failing keeps replay deterministic and safe.
    fn from_record(
        record: &BatchDecisionRecord,
        total_items: usize,
    ) -> Result<Self, OperationError> {
        if record.total_count > total_items {
            return Err(batch_error(&format!(
                "invalid batch decision record: totalCount {} exceeds the input length {}",
                record.total_count, total_items
            )));
        }
        let Some(reason) = CompletionReason::try_from_wire(&record.completion_reason) else {
            return Err(batch_error(&format!(
                "invalid batch decision record: unknown completionReason {:?}",
                record.completion_reason
            )));
        };
        let total_count = record.total_count;
        let (indexes, indexes_are_completed) =
            match (&record.completed_indexes, &record.started_indexes) {
                (Some(_), Some(_)) => {
                    return Err(batch_error(
                        "invalid batch decision record: both startedIndexes and \
                         completedIndexes are present",
                    ));
                }
                (None, None) => {
                    return Err(batch_error(
                        "invalid batch decision record: neither startedIndexes nor \
                         completedIndexes is present",
                    ));
                }
                (Some(completed), None) => (completed, true),
                (None, Some(started)) => (started, false),
            };
        let mut completed = vec![!indexes_are_completed; total_count];
        for &i in indexes {
            let Some(slot) = completed.get_mut(i) else {
                return Err(batch_error(&format!(
                    "invalid batch decision record: index {i} is outside [0, {total_count})",
                )));
            };
            *slot = indexes_are_completed;
        }
        Ok(Self {
            total_count,
            completed,
            reason,
        })
    }

    /// Whether replay admits item `index` for terminal reconstruction: it
    /// must be inside the started prefix AND recorded as completed.
    /// Started-but-not-terminal items are reported as
    /// [`BatchItemStatus::Started`] from the record alone, and
    /// never-started items are omitted entirely.
    fn admits(&self, index: usize) -> bool {
        index < self.total_count && self.completed.get(index).copied().unwrap_or(false)
    }
}

/// Fast replay of a large-result batch (Normal nesting): reconstructs the
/// batch result directly from the decision record and the child checkpoint
/// records, without re-running any item body.
///
/// Each child's ID comes from the batch's [`ItemIds`] table. An admitted
/// child whose own result was too large to checkpoint inline surfaces as
/// the `ReplayChildren` sentinel, and the caller falls back to
/// re-execution, which reads the same table. Items in the started set are
/// reported as [`BatchItemStatus::Started`] without consulting their child
/// checkpoints, and indexes at or beyond `totalCount` are omitted entirely.
///
/// Every completed child's replay identity (type, sub-type, name) is
/// validated against its checkpoint record before its terminal payload is
/// read, so a handler change that renames or retypes a child raises
/// `NonDeterministicExecution` here exactly as it does on the re-execution
/// path. Started-set children are exempt: their records are never
/// consulted at all.
async fn replay_batch_from_record<O, IS>(
    ctx: &DurableContext,
    plan: &ReplayPlan,
    record_names: &[String],
    serdes: &Arc<IS>,
    child_sub_type: &str,
    item_ids: &ItemIds,
) -> Result<BatchResult<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    let mut items = Vec::new();
    for i in 0..plan.total_count {
        // `ReplayPlan::from_record` rejects a `totalCount` above the input
        // length, and `record_names` has one entry per input item. So the
        // lookup cannot miss.
        #[expect(clippy::expect_used)]
        // reason: `totalCount` is at most the input length, which is the length of `record_names`
        let item_name = record_names
            .get(i)
            .expect("record_names has one entry per input item")
            .clone();
        if !plan.completed.get(i).copied().unwrap_or(false) {
            // STARTED at batch completion: reported from the record with
            // no result and no error; its child checkpoints are never
            // read.
            items.push(BatchItem {
                index: i,
                name: item_name,
                status: BatchItemStatus::Started,
                result: None,
                error_message: None,
                error_type: None,
                error_data: None,
                stack_trace: Vec::new(),
            });
            continue;
        }
        let op_id = item_ids.id(i);
        // Non-determinism detection: validate the claimed child identity
        // against the record before decoding its terminal payload.
        ctx.checkpoint_view_validated(
            op_id.positional(),
            op_id.wire(),
            "Context",
            Some(child_sub_type),
            Some(&item_name),
        )?;
        let serdes_ctx = SerdesContext::new(op_id.wire().to_owned(), ctx.execution_arn());
        let (item, _wire) =
            replay_terminal_child(ctx, op_id.positional(), i, &item_name, serdes, &serdes_ctx)
                .await?;
        items.push(item);
    }
    Ok(BatchResult {
        items,
        reason: plan.reason,
    })
}

/// Checkpoints the parent batch as SUCCEEDED with the pre-serialized result.
///
/// When the serialized payload exceeds [`CHECKPOINT_SIZE_LIMIT_BYTES`], the
/// record is written with `replay_children(true)` and `summary_json`, the
/// JS summary of [`oversized_batch_summary`], as its payload, so replay can
/// obey the recorded outcome (started prefix, terminal items,
/// `completionReason`) instead of re-deriving it by re-execution. A
/// terminal batch is never written without its summary. If the summary
/// exceeds the limit, the checkpoint is refused because replay requires it
/// to reconstruct the recorded outcome.
async fn checkpoint_batch_success_serialized(
    ctx: &DurableContext,
    parent_wire: &str,
    parent_name: Option<&str>,
    parent_sub_type: &str,
    serialized_payload: &str,
    summary_json: &str,
    start: Option<SubmittedWrite>,
) -> Result<(), OperationError> {
    let mut builder = OperationUpdate::builder()
        .id(parent_wire.to_owned())
        .r#type(OperationType::Context)
        .sub_type(parent_sub_type.to_owned())
        .action(OperationAction::Succeed);

    if let Some(n) = parent_name {
        builder = builder.name(n.to_owned());
    }
    if let Some(parent_wire_id) = ctx.parent_wire_id() {
        builder = builder.parent_id(parent_wire_id);
    }

    if serialized_payload.len() > CHECKPOINT_SIZE_LIMIT_BYTES {
        if summary_json.len() > CHECKPOINT_SIZE_LIMIT_BYTES {
            // Never write a terminal batch without its summary (see the
            // function docs).
            return Err(batch_error(
                "batch summary exceeds the checkpoint size limit; \
                 refusing to record the batch outcome without it",
            ));
        }
        builder = builder
            .context_options(
                aws_sdk_lambda::types::ContextOptions::builder()
                    .replay_children(true)
                    .build(),
            )
            .payload(summary_json.to_owned());
    } else {
        builder = builder.payload(serialized_payload.to_owned());
        // Within the plugin child operations depth of the caller's
        // context, the batch record keeps its items for later invocations.
        if ctx.preserves_children(1) {
            builder = builder.context_options(
                aws_sdk_lambda::types::ContextOptions::builder()
                    .replay_children(true)
                    .build(),
            );
        }
    }

    #[expect(clippy::expect_used)] // reason: all required fields are set above
    let update = builder
        .build()
        .expect("all required OperationUpdate fields set");
    // The end hook reports the payload the update carries.
    let result = update.payload().map(str::to_owned);

    // The outcome waits for the parent's START write, still in flight
    // when this invocation queued it.
    ctx.await_retained_start(parent_wire, start, OperationAction::Succeed)
        .await?;
    if let Err(err) = ctx.checkpoint_updates(vec![update]).await {
        return ctx.checkpoint_failure_unrecoverable(err).await;
    }
    if let Some(plugins) = ctx.plugins() {
        let info = container_info(ctx, parent_wire, parent_sub_type, parent_name)
            .with_status(crate::OperationStatus::Succeeded)
            .with_result(result)
            .with_replay(false);
        crate::plugin::operation_ended(plugins, &info);
    }

    Ok(())
}

/// The plugin info of the `map` or `parallel` container `wire_id`, created
/// in the caller's context `ctx`.
fn container_info(
    ctx: &DurableContext,
    wire_id: &str,
    sub_type: &str,
    name: Option<&str>,
) -> crate::plugin::OperationInfo {
    crate::plugin::OperationInfo::for_operation(
        ctx,
        wire_id,
        crate::OperationKind::Context,
        sub_type,
        name,
    )
}

/// The plugin info of the map item or parallel branch `wire_id`, created
/// in the batch's own context `batch_ctx`. That context's parent is the
/// container, so the info names the container as its parent.
fn item_info(
    batch_ctx: &DurableContext,
    wire_id: &str,
    sub_type: &str,
    name: &str,
) -> crate::plugin::OperationInfo {
    crate::plugin::OperationInfo::for_operation(
        batch_ctx,
        wire_id,
        crate::OperationKind::Context,
        sub_type,
        Some(name),
    )
}

/// Fires `on_operation_end` for the item of `req` once its outcome is
/// known: `status` with `result` and `error`. A flat item reports as a
/// virtual child with the replay state `replaying` of its context.
fn item_ended(
    req: &ItemRequest<impl Sized>,
    status: crate::OperationStatus,
    result: Option<String>,
    error: Option<&crate::error::WireError>,
    replaying: bool,
) {
    if let Some(plugins) = req.ctx.plugins() {
        let info = item_info(
            &req.ctx,
            req.child_op_id.wire(),
            &req.child_sub_type,
            &req.item_name,
        )
        .with_status(status)
        .with_result(result)
        .with_error(error.cloned());
        let info = if req.nesting == NestingMode::Flat {
            info.with_virtual(true).with_replay(replaying)
        } else {
            info.with_replay(false)
        };
        crate::plugin::operation_ended(plugins, &info);
    }
}

/// Builds a parent-level operation update.
fn build_parent_update(
    wire_id: &str,
    name: Option<&str>,
    sub_type: &str,
    action: OperationAction,
    ctx: &DurableContext,
) -> OperationUpdate {
    let mut builder = OperationUpdate::builder()
        .id(wire_id.to_owned())
        .r#type(OperationType::Context)
        .sub_type(sub_type.to_owned())
        .action(action);

    if let Some(n) = name {
        builder = builder.name(n.to_owned());
    }
    if let Some(parent_wire) = ctx.parent_wire_id() {
        builder = builder.parent_id(parent_wire);
    }

    #[expect(clippy::expect_used)] // reason: all required fields are set above
    builder
        .build()
        .expect("all required OperationUpdate fields set")
}

/// Builds a child-level operation update.
fn build_child_update(
    child_wire: &str,
    child_name: &str,
    child_sub_type: &str,
    parent_wire: &str,
    action: OperationAction,
) -> OperationUpdate {
    // The recorded name of the map item or parallel branch, so it appears
    // on the child's history records. It is never empty: a missing or empty
    // caller name defaults to `map-item-{i}` or `parallel-branch-{i}`.
    let builder = OperationUpdate::builder()
        .id(child_wire.to_owned())
        .r#type(OperationType::Context)
        .sub_type(child_sub_type.to_owned())
        .action(action)
        .parent_id(parent_wire.to_owned())
        .name(child_name.to_owned());

    #[expect(clippy::expect_used)] // reason: all required fields are set above
    builder
        .build()
        .expect("all required OperationUpdate fields set")
}

/// Builds a child-level `FAIL` update carrying `wire` as its error: the
/// `FAIL` of an item whose result fails to serialize. `preserve` adds `ReplayChildren`: the batch's own
/// context keeps the item's children within its plugin child operations
/// depth.
fn build_child_fail_update(
    child_wire: &str,
    child_name: &str,
    child_sub_type: &str,
    parent_wire: &str,
    wire: &crate::error::WireError,
    preserve: bool,
) -> OperationUpdate {
    // The recorded name is never empty: a missing or empty caller name
    // defaults to `map-item-{i}` or `parallel-branch-{i}`.
    let mut builder = OperationUpdate::builder()
        .id(child_wire.to_owned())
        .r#type(OperationType::Context)
        .sub_type(child_sub_type.to_owned())
        .action(OperationAction::Fail)
        .parent_id(parent_wire.to_owned())
        .error(wire.to_error_object())
        .name(child_name.to_owned());
    if preserve {
        builder = builder.context_options(
            aws_sdk_lambda::types::ContextOptions::builder()
                .replay_children(true)
                .build(),
        );
    }
    #[expect(clippy::expect_used)] // reason: all required fields are set above
    builder
        .build()
        .expect("all required OperationUpdate fields set")
}

/// Running completion state of one batch coordinator: the settle-order
/// counts, the view of every input item that a completion predicate sees,
/// and the first completion trigger to fire.
///
/// Every settle, a recorded-terminal child applied inline or a live join,
/// flows through [`settle`](Self::settle), and every live dispatch first
/// passes [`dispatch_gate`](Self::dispatch_gate). So the completion rule is
/// evaluated in exactly these two places, as JS evaluates it in `isComplete`
/// and `shouldContinue`.
///
/// The fixed thresholds and the predicate cannot both be configured
/// ([`CompletionConfigBuilder::build`](crate::builders::map_parallel::CompletionConfigBuilder::build)
/// rejects the mix), so their order within one settle does not matter.
/// The live settle order is not recorded, and on resume the recorded items
/// settle first, in index order. The thresholds only grow with the counts,
/// so they reach the same decision in any order. A predicate reaches the
/// same decision only when it is monotonic, which its rustdoc requires.
struct CompletionTracker {
    /// Count of items that have succeeded so far (settle order).
    success_count: usize,
    /// Count of items that have failed so far (settle order).
    failure_count: usize,
    /// One entry per input item, by index: the predicate's view.
    items: Vec<CompletionItem>,
    /// The first completion trigger to fire (first trigger wins). `Some`
    /// halts new dispatch, and nothing changes it afterwards.
    stop_reason: Option<CompletionReason>,
    /// `false` while the coordinator rebuilds a batch that already
    /// completed: its reason is read from the decision record, so neither
    /// the thresholds nor the predicate run.
    evaluating: bool,
}

impl CompletionTracker {
    /// Builds one not-started [`CompletionItem`] per input item, carrying
    /// its caller name.
    fn new(names: Vec<Option<String>>) -> Self {
        Self {
            success_count: 0,
            failure_count: 0,
            items: names
                .into_iter()
                .enumerate()
                .map(|(index, name)| CompletionItem::new(index, name, None))
                .collect(),
            stop_reason: None,
            evaluating: true,
        }
    }

    /// Stops every later evaluation of the completion rule. The
    /// coordinator calls it when it rebuilds a batch that already
    /// completed: the recorded reason is the outcome, and a predicate
    /// called on the rebuilt view could complete or fail differently.
    fn stop_evaluating(&mut self) {
        self.evaluating = false;
    }

    /// The predicate's snapshot of the current view.
    fn stats(&self) -> BatchStats<'_> {
        BatchStats::from_counts(self.success_count, self.failure_count, &self.items)
    }

    /// Marks one item as dispatched live: its view entry reads `Started`.
    fn mark_dispatched(&mut self, index: usize) {
        if let Some(item) = self.items.get_mut(index) {
            item.status = Some(BatchItemStatus::Started);
        }
    }

    /// Evaluates the predicate before a live dispatch, while no trigger has
    /// fired. Returns `true` when a trigger has fired, so the item must not
    /// be dispatched.
    fn dispatch_gate(&mut self, cfg: &crate::builders::map_parallel::CompletionConfig) -> bool {
        if self.stop_reason.is_none() {
            self.stop_reason = custom_reason(cfg.predicate_decision(&self.stats()));
        }
        self.stop_reason.is_some()
    }

    /// Applies one settled outcome to the counts and the view and, while no
    /// trigger has fired yet, evaluates the thresholds, then the predicate
    /// (first trigger wins: once `stop_reason` is set it never changes).
    fn settle(
        &mut self,
        cfg: &crate::builders::map_parallel::CompletionConfig,
        total_items: usize,
        index: usize,
        status: BatchItemStatus,
    ) {
        match status {
            BatchItemStatus::Succeeded => self.success_count += 1,
            BatchItemStatus::Failed => self.failure_count += 1,
            // Not a terminal outcome: never fed to the tracker (a Started
            // item exists only in replayed results, and the replay path
            // does not consult the tracker).
            BatchItemStatus::Started => return,
        }
        if let Some(item) = self.items.get_mut(index) {
            item.status = Some(status);
        }
        if !self.evaluating {
            return;
        }
        if self.stop_reason.is_none() {
            self.stop_reason =
                evaluate_thresholds(cfg, self.success_count, self.failure_count, total_items);
        }
        if self.stop_reason.is_none() {
            self.stop_reason = custom_reason(cfg.predicate_decision(&self.stats()));
        }
    }
}

/// Maps a predicate decision to the reason it records: `None` for
/// `Continue`.
fn custom_reason(decision: CompletionDecision) -> Option<CompletionReason> {
    match decision {
        CompletionDecision::Continue => None,
        CompletionDecision::Complete(CompletionOutcome::Succeeded) => {
            Some(CompletionReason::CustomCompletionSucceeded)
        }
        CompletionDecision::Complete(CompletionOutcome::Failed) => {
            Some(CompletionReason::CustomCompletionFailed)
        }
    }
}

/// Evaluates the fixed completion thresholds against the running batch
/// counts, returning the first that fires (or `None`).
///
/// Called after each settled item. The order follows JS: the failure
/// tolerance first, then "every item finished" (which leaves the reason
/// `AllCompleted`), then `min_successful`.
fn evaluate_thresholds(
    cfg: &crate::builders::map_parallel::CompletionConfig,
    success_count: usize,
    failure_count: usize,
    total_items: usize,
) -> Option<CompletionReason> {
    if should_stop_failure(cfg, failure_count, total_items) {
        return Some(CompletionReason::FailureToleranceExceeded);
    }
    if success_count + failure_count < total_items && should_stop_min(cfg, success_count) {
        return Some(CompletionReason::MinSuccessfulReached);
    }
    None
}

/// Checks if the `min_successful` threshold has been met. A minimum of `0`
/// is a configured minimum that any count meets, as in JS.
fn should_stop_min(
    cfg: &crate::builders::map_parallel::CompletionConfig,
    success_count: usize,
) -> bool {
    cfg.min_successful().is_some_and(|min| success_count >= min)
}

/// Checks if the failure tolerance has been exceeded.
fn should_stop_failure(
    cfg: &crate::builders::map_parallel::CompletionConfig,
    failure_count: usize,
    total_items: usize,
) -> bool {
    // Empty config: fail fast. When NO completion criterion is configured
    // (no thresholds and no predicate, which is also what an absent
    // config becomes), a single failure exceeds tolerance, matching the
    // Python and JS SDKs (issue #52). Configuring any criterion opts out
    // of this implicit fail-fast and hands the decision to that criterion.
    if !cfg.has_criteria() {
        return failure_count > 0;
    }

    // Count-based tolerance.
    if let Some(tolerated) = cfg.tolerated_failure_count()
        && failure_count > tolerated
    {
        return true;
    }

    // Percentage-based tolerance.
    // Uses cross-multiplication (failure_count * 100 > pct * total_items)
    // rather than JS's division: it is exact for integer percentages and
    // totals below 2^53, so 7 failures of 50 do not exceed 14.0, where JS's
    // `7 / 50 * 100` gives 14.000000000000002. A true failure rate of 33.3%
    // still exceeds a 33.0% threshold (100 > 99). When pct == 0.0, any
    // failure exceeds the threshold (fail-fast).
    #[expect(clippy::cast_precision_loss)]
    // reason: item counts stay far below 2^53, where the cast is exact
    let exceeds = |pct: f64| failure_count as f64 * 100.0 > pct * total_items as f64;
    if let Some(pct) = cfg.tolerated_failure_percentage()
        && total_items > 0
        && exceeds(pct)
    {
        return true;
    }

    false
}

/// Serializes a value through the configured serdes (ownership transfers;
/// the serdes decides where its work runs).
///
/// This is the same boundary every other operation (step, invoke, callback,
/// child, batch result) uses, and, since the item paths call this helper
/// too, the same one map/parallel ITEM results use. There is no separate
/// item rule.
///
/// A marked error ends the invocation
/// ([`DurableContext::route_serdes_error`]); any other error becomes a
/// batch error.
async fn serialize_value<T, S: Serdes<T>>(
    ctx: &DurableContext,
    name: Option<&str>,
    value: T,
    serdes: &S,
    serdes_ctx: SerdesContext,
) -> Result<String, OperationError> {
    let operation_id = serdes_ctx.operation_id().to_owned();
    match ctx.hold_activity(serdes.serialize(value, serdes_ctx)).await {
        Ok(serialized) => Ok(serialized),
        Err(err) => {
            let e = ctx
                .route_serdes_error("serialize", &operation_id, name, err)
                .await;
            Err(batch_error(&format!(
                "serialize result: {}",
                crate::error::wire_message(&*e)
            )))
        }
    }
}

/// Deserializes a value through the configured serdes.
///
/// Reverses [`serialize_value`]: the serdes turns the wire payload directly
/// back into the typed value, no intermediate representation and no
/// runtime downcast.
///
/// A marked error ends the invocation
/// ([`DurableContext::route_serdes_error`]); any other error becomes a
/// batch error.
async fn deserialize_value<T, S: Serdes<T>>(
    ctx: &DurableContext,
    name: Option<&str>,
    payload: String,
    serdes: &S,
    serdes_ctx: SerdesContext,
) -> Result<T, OperationError> {
    let operation_id = serdes_ctx.operation_id().to_owned();
    match ctx
        .hold_activity(serdes.deserialize(payload, serdes_ctx))
        .await
    {
        Ok(value) => Ok(value),
        Err(err) => {
            let e = ctx
                .route_serdes_error("deserialize", &operation_id, name, err)
                .await;
            Err(batch_error(&format!(
                "deserialize result: {}",
                crate::error::wire_message(&*e)
            )))
        }
    }
}

/// The name a serdes fault reports for a batch item: an empty item name
/// (a map without an item namer) is `None`.
fn item_fault_name(item_name: &str) -> Option<&str> {
    (!item_name.is_empty()).then_some(item_name)
}

/// How the batch record stores the value of a succeeded item.
///
/// JS stores each item value as a JSON value. A custom item serdes writes a
/// string that is not JSON in general, so the record stores that string
/// as it is. The builder knows which serdes it holds: it starts with the
/// default JSON serdes, and `.serdes(..)` replaces it. The record itself
/// has no field for the encoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ItemEncoding {
    /// Every item uses the default JSON serdes. The record embeds each
    /// value as the JSON value of its child wire string.
    AllJson,
    /// Every item uses a custom serdes. The record stores each value as its
    /// child wire string, in a JSON string.
    AllSerdes,
    /// Each item has its own serdes, as in `parallel_mixed`. Entry `i` is
    /// `true` when item `i` uses the default JSON serdes, and `false` when
    /// it uses a custom serdes. There is one entry per item.
    PerItem(Arc<[bool]>),
}

impl ItemEncoding {
    /// Whether the record embeds the value of item `index` as JSON, rather
    /// than as its wire string in a JSON string.
    fn is_json(&self, index: usize) -> bool {
        match self {
            Self::AllJson => true,
            Self::AllSerdes => false,
            // `parallel_mixed` builds one flag per branch, and every item
            // index of a batch is below its item count: the live batch
            // numbers its items, and a recorded batch with more items than
            // the input fails before any item is decoded. So the lookup
            // cannot miss.
            #[expect(clippy::expect_used)]
            // reason: there is one flag per item, and every item index is below the item count
            Self::PerItem(flags) => *flags
                .get(index)
                .expect("parallel_mixed has one encoding flag per branch"),
        }
    }
}

// The batch record a map or parallel operation checkpoints.
//
// It serializes in the shape of the JS SDK's batch result:
//
// ```json
// {"all": [item, ...], "completionReason": "ALL_COMPLETED"}
// ```
//
// `all` holds one item per started index, in index order. Each item has
// `index`, `status` (`"SUCCEEDED"`, `"FAILED"` or `"STARTED"`) and `name`,
// the recorded item name. JS has no `name` field; this record keeps it so
// that per-item errors name the item after replay. A succeeded item has
// `result`: the exact JSON text the default item serdes wrote, or the
// custom item serdes output as a JSON string. A failed item has `error`, a
// one-cause form of JS's recursive error object:
//
// ```json
// {"ErrorType": "ChildContextError", "ErrorMessage": "...",
//  "Cause": {"ErrorType": "<recorded type>", "ErrorMessage": "..."}}
// ```
//
// `ErrorData` and `StackTrace` appear at both levels when the item
// recorded them. A started item has neither `result` nor `error`.
//
// The SDK writes and reads this record with serde_json only. A JSON item
// value is a `RawValue`, which keeps its text only through serde_json's own
// serializer and deserializer. So the result serdes receives the finished
// record text as a `String`, never the record itself (see
// [`from_batch_result`] and [`parse_batch_record`]).

/// The JS-shaped batch record the SDK writes and replays.
#[derive(Debug, serde::Serialize)]
struct JsBatchRecord {
    all: Vec<JsBatchItem>,
    #[serde(rename = "completionReason")]
    completion_reason: String,
}

/// One item of a [`JsBatchRecord`].
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct JsBatchItem {
    index: usize,
    status: String,
    /// Always written. A record without it fails replay, because the
    /// per-item errors name the item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// Present exactly when the item succeeded. The value is the exact JSON
    /// text of the item value. A present `null` is a value (the JSON
    /// encoding of `()`), so it reads as `Some`.
    #[serde(
        default,
        deserialize_with = "present_raw_value",
        skip_serializing_if = "Option::is_none"
    )]
    result: Option<Box<RawValue>>,
    /// Present exactly when the item failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error: Option<JsErrorObject>,
}

/// The error object of a failed [`JsBatchItem`], and its `Cause`.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "PascalCase")]
struct JsErrorObject {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_message: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_data: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    stack_trace: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cause: Option<Box<JsErrorObject>>,
}

/// Reads a field that is present, including a present `null`, as `Some`,
/// and keeps its exact JSON text. With `#[serde(default)]`, an absent
/// field reads as `None`.
fn present_raw_value<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Box<RawValue>>, D::Error> {
    <Box<RawValue> as serde::Deserialize>::deserialize(deserializer).map(Some)
}

/// The top-level fields of a batch record text, read in one pass.
///
/// Each field is optional, and a field whose value is `null` reads as
/// absent. [`parse_batch_record`] then requires both fields. Other fields
/// are ignored.
#[derive(Debug, Default)]
struct BatchRecordFields {
    all: Option<Vec<JsBatchItem>>,
    completion_reason: Option<String>,
}

impl<'de> serde::Deserialize<'de> for BatchRecordFields {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(BatchRecordFieldsVisitor)
    }
}

/// Visits the top-level map of a batch record. It accepts only a map, so a
/// top-level array or scalar fails before the field pairs are checked.
struct BatchRecordFieldsVisitor;

impl<'de> serde::de::Visitor<'de> for BatchRecordFieldsVisitor {
    type Value = BatchRecordFields;

    fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("a batch record object")
    }

    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
        let mut fields = BatchRecordFields::default();
        // A field counts as seen even when its value is `null`, so a
        // duplicate after a `null` still fails.
        let mut seen = [false; 2];
        let [seen_all, seen_completion_reason] = &mut seen;
        while let Some(key) = map.next_key::<String>()? {
            match key.as_str() {
                "all" => read_field_once(&mut map, seen_all, "all", &mut fields.all)?,
                "completionReason" => read_field_once(
                    &mut map,
                    seen_completion_reason,
                    "completionReason",
                    &mut fields.completion_reason,
                )?,
                _ => {
                    map.next_value::<serde::de::IgnoredAny>()?;
                }
            }
        }
        Ok(fields)
    }
}

/// Reads the value of a recognized batch record field into `slot`. A
/// `null` value leaves the field absent. A second occurrence of the field
/// fails, also when the first value was `null`.
fn read_field_once<'de, A, T>(
    map: &mut A,
    seen: &mut bool,
    name: &'static str,
    slot: &mut Option<T>,
) -> Result<(), A::Error>
where
    A: serde::de::MapAccess<'de>,
    T: serde::Deserialize<'de>,
{
    if *seen {
        return Err(<A::Error as serde::de::Error>::duplicate_field(name));
    }
    *seen = true;
    *slot = map.next_value()?;
    Ok(())
}

/// Parses a batch record text in one pass with `serde_json`.
///
/// Both `all` and `completionReason` must be present. A record without
/// one of them fails with an error that names the missing field.
fn parse_batch_record(text: &str) -> Result<JsBatchRecord, String> {
    let fields: BatchRecordFields =
        serde_json::from_str(text).map_err(|err| format!("batch record is not valid: {err}"))?;
    match fields {
        BatchRecordFields {
            all: Some(all),
            completion_reason: Some(completion_reason),
        } => Ok(JsBatchRecord {
            all,
            completion_reason,
        }),
        BatchRecordFields { all: Some(_), .. } => {
            Err("batch record has `all` without `completionReason`".to_owned())
        }
        BatchRecordFields {
            completion_reason: Some(_),
            ..
        } => Err("batch record has `completionReason` without `all`".to_owned()),
        BatchRecordFields { .. } => {
            Err("batch record has neither `all` nor `completionReason`".to_owned())
        }
    }
}

/// The wire form of an item status.
fn item_status_wire(status: BatchItemStatus) -> &'static str {
    match status {
        BatchItemStatus::Succeeded => "SUCCEEDED",
        BatchItemStatus::Failed => "FAILED",
        BatchItemStatus::Started => "STARTED",
    }
}

/// Reads the wire form of an item status.
fn parse_item_status(status: &str) -> Result<BatchItemStatus, OperationError> {
    match status {
        "SUCCEEDED" => Ok(BatchItemStatus::Succeeded),
        "FAILED" => Ok(BatchItemStatus::Failed),
        "STARTED" => Ok(BatchItemStatus::Started),
        other => Err(batch_error(&format!("unknown item status: {other}"))),
    }
}

/// The error object a failed item records: JS's `ChildContextError` with
/// one cause, which carries the item's own recorded type.
fn js_item_error<O>(item: &BatchItem<O>) -> JsErrorObject {
    let message = item.error_message.clone().unwrap_or_default();
    let cause = JsErrorObject {
        error_type: Some(
            item.error_type
                .clone()
                .unwrap_or_else(|| "Error".to_owned()),
        ),
        error_message: Some(message.clone()),
        error_data: item.error_data.clone(),
        stack_trace: item.stack_trace.clone(),
        cause: None,
    };
    JsErrorObject {
        error_type: Some("ChildContextError".to_owned()),
        error_message: Some(message),
        error_data: item.error_data.clone(),
        stack_trace: item.stack_trace.clone(),
        cause: Some(Box::new(cause)),
    }
}

/// Builds the batch record text of a live `BatchResult`.
///
/// `wires` holds, for each item of `result` in the same order, the wire
/// string the item's child produced: the string it serialized for its
/// record or its size check, or the string replay read from its record.
/// Each value comes from that string, so building the record calls no
/// serdes. A JSON item's value is its wire string, unchanged. A
/// custom-serdes item's value is the JSON string encoding of its wire
/// string.
fn from_batch_result<O>(
    result: &BatchResult<O>,
    wires: &[Option<String>],
    encoding: &ItemEncoding,
) -> String {
    let all = result
        .items
        .iter()
        .zip(wires)
        .map(|(item, wire)| {
            // Only a succeeded item has a wire string.
            let value = wire.as_ref().map(|wire| {
                let text = if encoding.is_json(item.index) {
                    wire.clone()
                } else {
                    #[expect(clippy::expect_used)]
                    // reason: serializing a `String` to JSON cannot fail
                    serde_json::to_string(wire).expect("a string serializes to JSON")
                };
                // The default JSON serdes wrote `wire` with
                // `serde_json::to_string`, or read it back with
                // `serde_json::from_str`, so it is valid JSON. A JSON string
                // encoding is valid JSON too.
                #[expect(clippy::expect_used)]
                // reason: the default JSON serdes and a JSON string encoding only produce valid JSON
                RawValue::from_string(text).expect("the item value is valid JSON")
            });
            JsBatchItem {
                index: item.index,
                status: item_status_wire(item.status).to_owned(),
                name: Some(item.name.clone()),
                result: value,
                error: (item.status == BatchItemStatus::Failed).then(|| js_item_error(item)),
            }
        })
        .collect();
    let record = JsBatchRecord {
        all,
        completion_reason: result.reason.as_str().to_owned(),
    };
    #[expect(clippy::expect_used)]
    // reason: the record holds only strings, integers, valid raw JSON and nested records of those, all of which serialize to JSON
    serde_json::to_string(&record).expect("the batch record serializes to JSON")
}

/// The JS summary an oversized batch checkpoints in place of its record.
///
/// A map writes `{"type":"MapResult", totalCount, successCount,
/// failureCount, completionReason, status, itemStatuses}`; a parallel
/// writes `"ParallelResult"` and adds `startedCount`. `totalCount` counts
/// the started items, and `itemStatuses` has one character per started
/// index: `S` succeeded, `F` failed, `-` started and not terminal. The
/// summary is plain JSON: it never goes through `result_serdes`, because
/// it must stay readable even when the result serdes output is what
/// outgrew the limit.
///
/// `caller_summary`, the output of the caller's summary, becomes the last
/// key, `summary`, as JS `composeSummaryGenerator` adds it. Replay never
/// reads it.
fn oversized_batch_summary<O>(
    result: &BatchResult<O>,
    parent_sub_type: &str,
    caller_summary: Option<&str>,
) -> String {
    let total = result.items.len();
    let succeeded = result.success_count();
    let failed = result.failure_count();
    let item_statuses: String = result
        .items
        .iter()
        .map(|item| match item.status {
            BatchItemStatus::Succeeded => 'S',
            BatchItemStatus::Failed => 'F',
            BatchItemStatus::Started => '-',
        })
        .collect();
    let status = match result.status() {
        BatchStatus::Failed => "FAILED",
        BatchStatus::Succeeded => "SUCCEEDED",
    };
    let parallel = parent_sub_type == PARALLEL_SUB_TYPE;
    let summary = OversizedBatchSummary {
        type_name: if parallel {
            "ParallelResult"
        } else {
            "MapResult"
        },
        total_count: total,
        success_count: succeeded,
        failure_count: failed,
        started_count: parallel.then(|| total - succeeded - failed),
        completion_reason: result.reason.as_str(),
        status,
        item_statuses,
        summary: caller_summary,
    };
    #[expect(clippy::expect_used)]
    // reason: the struct holds only JSON-native strings and integers, so serialization cannot fail
    serde_json::to_string(&summary).expect("the oversized batch summary serializes to JSON")
}

/// The JS summary of an oversized batch, with its keys declared in the
/// order JS writes them, so the text does not depend on whether
/// `serde_json` keeps map insertion order.
#[derive(serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct OversizedBatchSummary<'a> {
    #[serde(rename = "type")]
    type_name: &'static str,
    total_count: usize,
    success_count: usize,
    failure_count: usize,
    /// Written for a parallel, omitted for a map.
    #[serde(skip_serializing_if = "Option::is_none")]
    started_count: Option<usize>,
    completion_reason: &'a str,
    status: &'static str,
    item_statuses: String,
    /// The caller's summary, omitted when the caller supplied none.
    #[serde(skip_serializing_if = "Option::is_none")]
    summary: Option<&'a str>,
}

/// Parses a batch record text and converts it back into a `BatchResult`.
///
/// Each item value is decoded with the item serdes and the child's serdes
/// context. `total_items` is the length of the current input.
async fn to_batch_result<O, IS>(
    ctx: &DurableContext,
    record_text: &str,
    serdes: &Arc<IS>,
    encoding: ItemEncoding,
    total_items: usize,
    execution_arn: &str,
    item_ids: &ItemIds,
) -> Result<BatchResult<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    let record = parse_batch_record(record_text).map_err(|message| batch_error(&message))?;
    js_to_batch_result(
        ctx,
        record,
        serdes,
        encoding,
        total_items,
        execution_arn,
        item_ids,
    )
    .await
}

/// Converts a JS-form batch record back into a `BatchResult`.
///
/// The child of item `i` has the ID of item `i` in the batch's
/// [`ItemIds`] table, so its serdes context is derived from that ID. A failed item's type, message and data come from `Cause` when
/// it has them, else from the top level; its frames come from `Cause` when
/// it is present.
///
/// The record is checked before any item is decoded. Its `all` must hold
/// the started prefix of the input in index order: item `k` has index `k`,
/// and there are at most `total_items` items. The SDK writes records in
/// that form, but a custom `result_serdes` or a corrupt checkpoint can
/// produce another one. A sparse, duplicate or reordered index would
/// derive a child serdes context that is not the child's own ID, and an
/// index past the input would name no item of the table. So such a record
/// fails the replay with an error.
async fn js_to_batch_result<O, IS>(
    ctx: &DurableContext,
    record: JsBatchRecord,
    serdes: &Arc<IS>,
    encoding: ItemEncoding,
    total_items: usize,
    execution_arn: &str,
    item_ids: &ItemIds,
) -> Result<BatchResult<O>, OperationError>
where
    O: Send + 'static,
    IS: Serdes<O>,
{
    if record.all.len() > total_items {
        return Err(batch_error(&format!(
            "batch record has {} items but the input has {total_items}",
            record.all.len()
        )));
    }
    check_record_indexes(&record)?;
    let reason = CompletionReason::from_wire(&record.completion_reason);
    let mut items = Vec::with_capacity(record.all.len());
    for item in record.all {
        let index = item.index;
        let status = parse_item_status(&item.status)?;
        let name = item
            .name
            .ok_or_else(|| batch_error(&format!("batch record item {index}: missing name")))?;
        let result = match (status, item.result) {
            (BatchItemStatus::Succeeded, Some(value)) => {
                let wire = if encoding.is_json(index) {
                    // The item serdes reads the exact JSON text it wrote.
                    value.get().to_owned()
                } else {
                    serde_json::from_str::<String>(value.get()).map_err(|_| {
                        batch_error(&format!(
                            "batch record item {index}: expected a string result"
                        ))
                    })?
                };
                let child_op_id = item_ids.id(index);
                let item_ctx = SerdesContext::new(child_op_id.wire().to_owned(), execution_arn);
                Some(
                    deserialize_value::<O, _>(
                        ctx,
                        item_fault_name(&name),
                        wire,
                        serdes.as_ref(),
                        item_ctx,
                    )
                    .await?,
                )
            }
            _ => None,
        };
        let error = item.error.map(|top| match top.cause {
            Some(cause) => (
                cause.error_type.or(top.error_type),
                cause.error_message.or(top.error_message),
                cause.error_data.or(top.error_data),
                cause.stack_trace,
            ),
            None => (
                top.error_type,
                top.error_message,
                top.error_data,
                top.stack_trace,
            ),
        });
        let (error_type, error_message, error_data, stack_trace) =
            error.unwrap_or((None, None, None, Vec::new()));
        items.push(BatchItem {
            index,
            name,
            status,
            result,
            error_message,
            error_type,
            error_data,
            stack_trace,
        });
    }
    Ok(BatchResult { items, reason })
}

/// The execution error `max_concurrency(0)` records: JS's wording, with the
/// Rust setter's name.
const MAX_CONCURRENCY_ZERO_MESSAGE: &str =
    "Invalid max_concurrency: 0. Must be a positive number or unset for unlimited concurrency.";

/// Constructs a batch operation error for a coordinator defect: an
/// internal invariant breach or a malformed record, never a user item's
/// failure (those route through [`item_failure_error`], which classifies
/// as `ChildFailed`).
fn batch_error(message: &str) -> OperationError {
    OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
        ChildContextErrorKind::Internal,
        Some(message.to_owned().into()),
    )))
}

/// Constructs the operation error a batch surfaces when a USER item body
/// failed (the failure tolerance was exceeded): classified as
/// `ChildFailed`, carrying the failing item's COMPLETE recorded wire
/// record so the error's identity (`error_type`, message, `error_data`,
/// `stack_trace`) stays programmatically recoverable and identical live
/// and on replay (both paths read the same recorded per-item fields).
fn item_failure_error(wire: crate::error::WireError) -> OperationError {
    OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
        ChildContextErrorKind::ChildFailed,
        Some(crate::error::ReplayedFailure::source_from(wire.clone())),
    )))
    .with_wire(wire)
}

/// Constructs the operation error a batch surfaces when its completion
/// predicate completed it as failed (`CUSTOM_COMPLETION_FAILED`) and no item
/// failed. It carries a wire record of type `BatchCompletionError`, the type
/// JS throws in the same case.
fn batch_completion_failed_error() -> OperationError {
    let wire = crate::error::WireError::new(
        Some("BatchCompletionError"),
        Some("batch completed as failed by the completion predicate (CUSTOM_COMPLETION_FAILED)"),
    );
    OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
        ChildContextErrorKind::BatchCompletionFailed,
        Some(crate::error::ReplayedFailure::source_from(wire.clone())),
    )))
    .with_wire(wire)
}

/// Wraps owned map inputs in indexed take-once slots shareable across
/// branch tasks. Each item is MOVED out exactly once by [`take_item`],
/// no `Clone` bound and no serde round-trip (which would reject or mutate
/// valid serde types that are not JSON-round-trippable).
fn into_item_slots<I>(items: Vec<I>) -> Arc<Vec<std::sync::Mutex<Option<I>>>> {
    Arc::new(
        items
            .into_iter()
            .map(|item| std::sync::Mutex::new(Some(item)))
            .collect(),
    )
}

/// Moves the item at `index` out of its slot. Each index is dispatched at
/// most once per invocation, so a second take indicates a coordinator bug.
fn take_item<I>(items: &[std::sync::Mutex<Option<I>>], index: usize) -> Result<I, OperationError> {
    let slot = items
        .get(index)
        .ok_or_else(|| batch_error("item index out of bounds"))?;
    let mut lock = slot
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    lock.take()
        .ok_or_else(|| batch_error("map item already consumed (concurrent access bug)"))
}

#[cfg(test)]
#[expect(clippy::indexing_slicing)]
// Tests deliberately spawn foreign (unblessed) tasks to exercise runtime
// behavior; production spawning is confined to the src/task.rs gateway.
#[expect(clippy::disallowed_methods)]
mod tests {
    use super::*;
    use crate::context::DurableContext;
    use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use tokio::sync::Semaphore;

    /// `CompletionDecision::complete` builds the `Complete` variant with
    /// the given outcome.
    #[test]
    fn completion_decision_constructor_builds_complete() {
        for expected in [CompletionOutcome::Succeeded, CompletionOutcome::Failed] {
            assert!(matches!(
                CompletionDecision::complete(expected),
                CompletionDecision::Complete(outcome) if outcome == expected
            ));
        }
    }

    /// `results()` and `errors()` are iterators over the succeeded values
    /// and the failed items' errors, in input order.
    #[test]
    fn results_and_errors_are_iterators() {
        let batch = BatchResult::new(
            vec![
                BatchItem::new(
                    0,
                    "a".to_owned(),
                    BatchItemStatus::Succeeded,
                    Some(1),
                    None,
                    None,
                ),
                BatchItem::new(
                    1,
                    "b".to_owned(),
                    BatchItemStatus::Failed,
                    None,
                    Some("first".to_owned()),
                    Some("Error".to_owned()),
                ),
                BatchItem::new(
                    2,
                    "c".to_owned(),
                    BatchItemStatus::Started,
                    None,
                    None,
                    None,
                ),
                BatchItem::new(
                    3,
                    "d".to_owned(),
                    BatchItemStatus::Succeeded,
                    Some(4),
                    None,
                    None,
                ),
                BatchItem::new(
                    4,
                    "e".to_owned(),
                    BatchItemStatus::Failed,
                    None,
                    Some("second".to_owned()),
                    Some("TimeoutError".to_owned()),
                ),
            ],
            CompletionReason::AllCompleted,
        );

        assert_eq!(batch.results().next(), Some(&1));
        assert_eq!(batch.results().copied().collect::<Vec<_>>(), [1, 4]);
        let errors = batch
            .errors()
            .map(|e| (e.index, e.name, e.message, e.error_type))
            .collect::<Vec<_>>();
        assert_eq!(
            errors,
            [
                (1, "b", "first", Some("Error")),
                (4, "e", "second", Some("TimeoutError")),
            ]
        );
    }

    /// Helper to create a test context with the given checkpoint log.
    fn test_ctx(log: CheckpointLog) -> DurableContext {
        DurableContext::new_root(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(log),
        )
    }

    /// A user item body's failure surfaces as `ChildFailed` carrying the
    /// item's COMPLETE recorded wire record — all four wire fields, not
    /// just type and message (finding: item-body failures and coordinator
    /// defects must not share a classification, and the recorded
    /// `error_data`/`stack_trace` must not be discarded).
    #[test]
    fn collect_successful_classifies_item_failure_as_child_failed() {
        let batch = BatchResult {
            items: vec![BatchItem::<i32> {
                index: 0,
                name: "item-0".to_owned(),
                status: BatchItemStatus::Failed,
                result: None,
                error_message: Some("boom-item".to_owned()),
                error_type: Some("MyItemError".to_owned()),
                error_data: Some(r#"{"detail":42}"#.to_owned()),
                stack_trace: vec!["frame-0".to_owned(), "frame-1".to_owned()],
            }],
            reason: CompletionReason::FailureToleranceExceeded,
        };
        let err = collect_successful(batch).expect_err("tolerance exceeded must error");
        let OperationErrorKind::ChildContext(child_err) = err.kind() else {
            unreachable!("expected a child-context error, got {:?}", err.kind());
        };
        assert!(
            matches!(child_err.kind(), ChildContextErrorKind::ChildFailed),
            "item failures classify as ChildFailed: {:?}",
            child_err.kind()
        );
        let wire = err.wire().expect("the item's wire record is attached");
        assert_eq!(wire.error_type(), Some("MyItemError"));
        assert_eq!(wire.error_message(), Some("boom-item"));
        assert_eq!(wire.error_data(), Some(r#"{"detail":42}"#));
        assert_eq!(
            wire.stack_trace(),
            ["frame-0".to_owned(), "frame-1".to_owned()]
        );
    }

    /// Coordinator defects keep the `Internal` classification.
    #[test]
    fn batch_error_keeps_internal_classification_for_coordinator_defects() {
        let err = batch_error("invariant breached");
        let OperationErrorKind::ChildContext(child_err) = err.kind() else {
            unreachable!("expected a child-context error, got {:?}", err.kind());
        };
        assert!(
            matches!(child_err.kind(), ChildContextErrorKind::Internal),
            "coordinator defects classify as Internal: {:?}",
            child_err.kind()
        );
    }

    /// Helper to create a live test context backed by a recording client.
    fn test_ctx_with_client(
        log: CheckpointLog,
    ) -> (DurableContext, Arc<crate::client::InMemoryExecutionClient>) {
        let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let ctx = DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(log),
            Arc::clone(&client) as Arc<dyn crate::client::ExecutionClient>,
            "token0".to_owned(),
        );
        (ctx, client)
    }

    /// The in-memory client's checkpoint responses return no operations, so
    /// no item record exists when the item hooks fire. The item's infos
    /// still name the map as their parent, because the item is created in
    /// the batch's own context.
    #[tokio::test]
    async fn item_hooks_report_container_without_record() {
        let hooks = crate::plugin::test_support::OpHooks::default();
        let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let ctx = DurableContext::new_root_with_client_and_defaults(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::clone(&client) as Arc<dyn crate::client::ExecutionClient>,
            "token0".to_owned(),
            None,
            0,
            Some(hooks.plugins()),
        );
        let values = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .name("m")
            .await
            .expect("the map succeeds");
        assert_eq!(values, [1]);
        let map_wire = crate::engine::compute_wire_id_public("1");
        let item = hooks.of("map-item-0");
        let shape: Vec<_> = item
            .iter()
            .map(|r| (r.hook, r.parent_id.as_deref()))
            .collect();
        assert_eq!(
            shape,
            [
                ("start", Some(map_wire.as_str())),
                ("end", Some(map_wire.as_str()))
            ]
        );
    }

    /// A record of the operation at `positional_id` with `status` and no
    /// payload.
    fn record_at(positional_id: &str, status: CheckpointStatus) -> (String, CheckpointRecord) {
        let (wire_id, mut record) = succeeded_record(positional_id, "null");
        record.status = status;
        record.result = None;
        (wire_id, record)
    }

    /// Rule 7.3: a STARTED `Normal` item with no inner record reports a
    /// replay to `on_operation_start` and none to its user-function hooks
    /// and wraps. So does a resumed container whose batch child context
    /// has no inner record.
    #[tokio::test]
    async fn normal_item_without_inner_record_replay_flags() {
        use crate::plugin::recorder::{UfHooks, context};
        let map = |ctx: &DurableContext| {
            ctx.map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
                .name("m")
        };

        // Run 1: the map and its item 0 are STARTED.
        let hooks = UfHooks::default();
        let (ctx, _client) = context(
            &hooks,
            vec![
                record_at("1", CheckpointStatus::Started),
                record_at("1-1", CheckpointStatus::Started),
            ],
        );
        assert_eq!(map(&ctx).await.unwrap(), [1]);
        assert!(hooks.find("map-item-0", "start").replay);
        let item = hooks.user_function_of("map-item-0", true);
        assert!(item.iter().all(|r| !r.replay), "{item:?}");

        // Run 2: only the map is STARTED.
        let hooks = UfHooks::default();
        let (ctx, _client) = context(&hooks, vec![record_at("1", CheckpointStatus::Started)]);
        assert_eq!(map(&ctx).await.unwrap(), [1]);
        assert!(hooks.find("m", "start").replay);
        let container = hooks.user_function_of("m", true);
        assert!(container.iter().all(|r| !r.replay), "{container:?}");
    }

    /// Rule 11: each `parallel_mixed` branch and the container are user
    /// functions, in both modes. A branch has the sub-type `ParallelBranch`
    /// and the container as its parent; a flat branch is virtual.
    #[tokio::test]
    async fn parallel_mixed_branches_and_container_both_modes() {
        use crate::plugin::recorder::{UfHooks, context};
        for mode in [NestingMode::Normal, NestingMode::Flat] {
            let hooks = UfHooks::default();
            let (ctx, _client) = context(&hooks, Vec::new());
            let mut set = crate::BranchSet::new();
            let text = set.add("s", |_child| async { Ok("text".to_owned()) });
            let number = set.add("n", |_child| async { Ok(7_u32) });
            ctx.parallel_mixed(set)
                .name("pm")
                .nesting(mode)
                .await
                .unwrap();
            assert_eq!(text.into_result().unwrap(), "text", "{mode:?}");
            assert_eq!(number.into_result().unwrap(), 7, "{mode:?}");

            let container_wire = crate::engine::compute_wire_id_public("1");
            let container = hooks.user_function_of("pm", true);
            assert!(
                container
                    .iter()
                    .all(|r| { r.sub_type.as_deref() == Some(PARALLEL_SUB_TYPE) && !r.is_virtual }),
                "{mode:?}: {container:?}"
            );
            for name in ["s", "n"] {
                let branch = hooks.user_function_of(name, true);
                assert!(
                    branch.iter().all(|r| {
                        r.sub_type.as_deref() == Some(PARALLEL_BRANCH_SUB_TYPE)
                            && r.parent_id.as_deref() == Some(container_wire.as_str())
                            && r.is_virtual == (mode == NestingMode::Flat)
                    }),
                    "{mode:?} {name}: {branch:?}"
                );
                assert_eq!(hooks.find(name, "uf_end").ok, Some(true), "{mode:?}");
            }
            assert_eq!(hooks.find("pm", "uf_end").ok, Some(true), "{mode:?}");
        }
    }

    /// The batch operation [`failing_branches_report_stored_wire`] runs.
    #[derive(Clone, Copy, Debug)]
    enum FailingBatch {
        Map,
        Parallel,
        ParallelMixed,
    }

    /// Rule 11's item and container rows: in a `map`, a `parallel` and a
    /// `parallel_mixed` that tolerate one failure, the failing item's end
    /// hook gets the item's failure wire. A `Normal` item stores it in its
    /// FAIL, a `Flat` item in its `BatchItem`. The container ends `Ok` and
    /// records its SUCCEED.
    #[tokio::test]
    async fn failing_branches_report_stored_wire() {
        use crate::builders::map_parallel::CompletionConfig;
        use crate::plugin::recorder::{
            UfHooks, context, type_and_message, update_error, update_of,
        };
        let tolerate = || CompletionConfig::with_tolerated_failure_count(1);
        let fail = || Err::<u32, BoxError>("boom".into());
        for kind in [
            FailingBatch::Map,
            FailingBatch::Parallel,
            FailingBatch::ParallelMixed,
        ] {
            for mode in [NestingMode::Normal, NestingMode::Flat] {
                let case = format!("{kind:?} {mode:?}");
                let hooks = UfHooks::default();
                let (ctx, client) = context(&hooks, Vec::new());
                // The failing item's name, and the wire the batch keeps
                // for it.
                let (failing, kept) = match kind {
                    FailingBatch::Map => {
                        let batch = ctx
                            .map(vec![0_u32, 1], move |_child, item, _idx| async move {
                                if item == 1 { fail() } else { Ok(item) }
                            })
                            .name("c")
                            .nesting(mode)
                            .completion(tolerate())
                            .await_batch()
                            .await
                            .unwrap();
                        let error = batch.errors().next().expect("item 1 failed");
                        (
                            "map-item-1",
                            (
                                error.error_type.map(str::to_owned),
                                Some(error.message.to_owned()),
                            ),
                        )
                    }
                    FailingBatch::Parallel => {
                        let batch = ctx
                            .parallel(vec![
                                crate::Branch::new("ok", |_child| async { Ok(0_u32) }),
                                crate::Branch::new("bad", move |_child| async move { fail() }),
                            ])
                            .name("c")
                            .nesting(mode)
                            .completion(tolerate())
                            .await_batch()
                            .await
                            .unwrap();
                        let error = batch.errors().next().expect("branch 1 failed");
                        (
                            "bad",
                            (
                                error.error_type.map(str::to_owned),
                                Some(error.message.to_owned()),
                            ),
                        )
                    }
                    FailingBatch::ParallelMixed => {
                        let mut set = crate::BranchSet::new();
                        let _ok = set.add("ok", |_child| async { Ok(0_u32) });
                        let bad = set.add("bad", move |_child| async move { fail() });
                        ctx.parallel_mixed(set)
                            .name("c")
                            .nesting(mode)
                            .completion(tolerate())
                            .await
                            .unwrap();
                        let err = bad.into_result().expect_err("branch 1 failed");
                        ("bad", type_and_message(err.wire().expect("a wire record")))
                    }
                };
                let end = hooks.find(failing, "uf_end");
                assert_eq!(end.ok, Some(false), "{case}");
                let end = type_and_message(end.wire.as_ref().expect("an Err outcome"));
                assert_eq!(end.1.as_deref(), Some("boom"), "{case}");
                assert_eq!(end, kept, "{case}: the batch keeps the end hook's wire");
                let updates = client.recorded_updates();
                let item_fail = update_of(&updates, failing, &OperationAction::Fail);
                match mode {
                    NestingMode::Normal => assert_eq!(
                        update_error(&item_fail.expect("the item's FAIL")),
                        end,
                        "{case}: the FAIL stores the end hook's wire"
                    ),
                    NestingMode::Flat => assert!(item_fail.is_none(), "{case}"),
                }
                assert_eq!(hooks.find("c", "uf_end").ok, Some(true), "{case}");
                assert!(
                    update_of(&updates, "c", &OperationAction::Succeed).is_some(),
                    "{case}: the container's SUCCEED"
                );
            }
        }
    }

    /// A result serdes that fails every serialization with a permanent
    /// error.
    struct FailingResultSerdes;

    impl Serdes<String> for FailingResultSerdes {
        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn serialize(
            &self,
            _value: String,
            _context: SerdesContext,
        ) -> Result<String, BoxError> {
            Err("cannot encode".into())
        }

        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn deserialize(
            &self,
            _wire: String,
            _context: SerdesContext,
        ) -> Result<String, BoxError> {
            Err("cannot decode".into())
        }
    }

    /// An in-memory client that permanently rejects the `SUCCEED` of the
    /// root's first operation.
    #[derive(Debug)]
    struct RejectsParentSucceed(Arc<crate::client::InMemoryExecutionClient>);

    impl crate::client::ExecutionClient for RejectsParentSucceed {
        fn checkpoint(
            &self,
            arn: &str,
            token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::CheckpointOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            let parent = crate::engine::compute_wire_id_public("1");
            if updates
                .iter()
                .any(|u| u.id == parent && u.action() == &OperationAction::Succeed)
            {
                return Box::pin(async {
                    Err(crate::client::ExecutionClientError::new_non_retryable(
                        "rejected",
                    ))
                });
            }
            self.0.checkpoint(arn, token, updates)
        }

        fn get_state(
            &self,
            arn: &str,
            token: &str,
            marker: Option<&str>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::GetStateOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            self.0.get_state(arn, token, marker)
        }
    }

    /// Rule 7.6: a container's body ends `Ok` when its batch is produced. A
    /// failure after it keeps its own wire: a result serdes failure is the
    /// handler's error with `serialization_failure_wire`. A rejected
    /// `SUCCEED` fails the execution, and no `FAIL` is sent, so the
    /// container's record stays at its accepted `START`.
    #[tokio::test]
    async fn container_post_body_failures_keep_own_wire() {
        use crate::plugin::recorder::{UfHooks, context, context_over, update_of};

        // Run 1: the result serdes fails.
        let hooks = UfHooks::default();
        let (ctx, client) = context(&hooks, Vec::new());
        let err = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .name("m")
            .result_serdes(FailingResultSerdes)
            .await
            .expect_err("the batch record cannot be serialized");
        let end = hooks.find("m", "uf_end");
        assert_eq!((end.ok, end.wire), (Some(true), None));
        // The serialization failure is the handler's error, and it keeps
        // its own wire, `serialization_failure_wire`. As on main, a
        // container writes no outcome record for it: the next invocation
        // produces the batch again from its items' records.
        assert_eq!(
            err.wire(),
            Some(&crate::error::WireError::new(
                Some(crate::error::SERIALIZATION_FAILED_ERROR_TYPE),
                Some(
                    "operation error: child_context: internal error: serialize result: cannot encode"
                ),
            ))
        );
        let updates = client.recorded_updates();
        assert!(
            update_of(&updates, "m", &OperationAction::Succeed).is_none()
                && update_of(&updates, "m", &OperationAction::Fail).is_none(),
            "{updates:?}"
        );

        // Run 2: the client rejects the container's SUCCEED.
        let hooks = UfHooks::default();
        let inner = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let ctx = context_over(
            &hooks,
            Vec::new(),
            Arc::new(RejectsParentSucceed(Arc::clone(&inner))),
        );
        let outcome = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            crate::driver::test_support::drive_handler(ctx, None, |ctx| async move {
                ctx.map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
                    .name("m")
                    .await
                    .map_err(crate::driver::test_support::wire_err)?;
                Ok("done".to_owned())
            }),
        )
        .await
        .expect("the invocation ends within 5 s")
        .expect("no panic");
        assert!(
            matches!(outcome, crate::driver::InvocationOutcome::Failed { .. }),
            "{outcome:?}"
        );
        let end = hooks.find("m", "uf_end");
        assert_eq!((end.ok, end.wire), (Some(true), None));
        let updates = inner.recorded_updates();
        assert!(
            update_of(&updates, "m", &OperationAction::Fail).is_none(),
            "no FAIL after the rejected SUCCEED: {updates:?}"
        );
        assert!(
            update_of(&updates, "m", &OperationAction::Start).is_some(),
            "the container's START is its last accepted update: {updates:?}"
        );
    }

    /// Rule 3.4: a branch the batch abandons at its early completion, while
    /// its body runs, gets a start hook and no end hook. The branch that
    /// completed the batch gets both.
    #[tokio::test]
    async fn abandoned_branch_gets_no_end_hook() {
        use crate::builders::map_parallel::CompletionConfig;
        use crate::plugin::recorder::{UfHooks, context};
        let hooks = UfHooks::default();
        let (ctx, _client) = context(&hooks, Vec::new());
        let started = Arc::new(tokio::sync::Notify::new());
        let waits = Arc::clone(&started);
        let batch = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            ctx.parallel(vec![
                crate::Branch::new("done", move |_child| async move {
                    waits.notified().await;
                    Ok(0_u32)
                }),
                crate::Branch::new("abandoned", move |_child| async move {
                    started.notify_one();
                    std::future::pending::<()>().await;
                    Ok(1_u32)
                }),
            ])
            .name("p")
            .completion(CompletionConfig::with_min_successful(1))
            .await_batch(),
        )
        .await
        .expect("the batch completes within 5 s")
        .unwrap();
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        hooks.user_function_of("abandoned", false);
        hooks.user_function_of("done", true);
    }

    /// Builds the request of item 0 of a map named `m` on a root context
    /// that carries the plugin `hooks`, without running the map.
    fn item_request(
        hooks: &crate::plugin::test_support::OpHooks,
        nesting: NestingMode,
    ) -> ItemRequest<crate::serdes::JsonSerdes> {
        let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let ctx = DurableContext::new_root_with_client_and_defaults(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client as Arc<dyn crate::client::ExecutionClient>,
            "token0".to_owned(),
            None,
            0,
            Some(hooks.plugins()),
        );
        ItemRequest {
            ctx,
            child_op_id: OperationId::new("1-1".to_owned()),
            index: 0,
            is_terminal: false,
            parent_wire: crate::engine::compute_wire_id_public("1"),
            child_sub_type: "MapIteration".to_owned(),
            item_name: "map-item-0".to_owned(),
            nesting,
            start_info: Arc::new(crate::plugin::OperationInfo::for_test("1-1")),
            serdes: Arc::new(crate::serdes::JsonSerdes),
            start: std::sync::Mutex::new(None),
        }
    }

    /// The end hook of a flat item reports the `is_replaying()` value that
    /// the caller read from the item's own context, for a success and for
    /// a failure. The test passes both values directly, so it needs no
    /// history that the item body does not follow. A Normal item writes
    /// its own record and ends live, so it reports `false` either way.
    #[tokio::test]
    async fn flat_item_end_reports_item_context_replay_state() {
        for replaying in [true, false] {
            let hooks = crate::plugin::test_support::OpHooks::default();
            let req = item_request(&hooks, NestingMode::Flat);
            item_after(&req, ItemBody::Unhooked(Ok(1_u32)), replaying)
                .await
                .expect("a flat success settles");
            let failed: Result<u32, ChildFnError> = Err(ChildFnError::from(BoxError::from("bad")));
            item_after(&req, ItemBody::Unhooked(failed), replaying)
                .await
                .expect("a flat failure settles");
            let ends: Vec<_> = hooks
                .of("map-item-0")
                .iter()
                .map(|r| (r.hook, r.replay, r.is_virtual, r.status))
                .collect();
            assert_eq!(
                ends,
                [
                    (
                        "end",
                        replaying,
                        true,
                        Some(crate::OperationStatus::Succeeded)
                    ),
                    ("end", replaying, true, Some(crate::OperationStatus::Failed)),
                ],
                "replaying = {replaying}"
            );
        }
        let hooks = crate::plugin::test_support::OpHooks::default();
        let req = item_request(&hooks, NestingMode::Normal);
        item_ended(&req, crate::OperationStatus::Succeeded, None, None, true);
        let normal: Vec<_> = hooks
            .of("map-item-0")
            .iter()
            .map(|r| (r.hook, r.replay, r.is_virtual))
            .collect();
        assert_eq!(normal, [("end", false, false)]);
    }

    /// Map items must be MOVED into the closure, not re-created through a
    /// JSON round-trip: a `HashMap` with tuple keys implements
    /// `Serialize + DeserializeOwned` but `serde_json` rejects non-string
    /// keys, so any round-trip of the ITEM would fail the whole map.
    #[tokio::test]
    async fn map_moves_non_json_round_trippable_items() {
        use std::collections::HashMap;

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        let mut m1: HashMap<(u32, u32), u32> = HashMap::new();
        m1.insert((1, 2), 10);
        let mut m2: HashMap<(u32, u32), u32> = HashMap::new();
        m2.insert((3, 4), 20);
        m2.insert((5, 6), 30);

        let result = ctx
            .map(vec![m1, m2], |_child, item, _idx| async move {
                Ok(item.values().sum::<u32>())
            })
            .await
            .expect("map over non-JSON-round-trippable items must succeed");
        assert_eq!(result, vec![10, 50]);
    }

    /// Collects the names of recorded child START updates (updates that
    /// carry a `ParentId`, distinguishing them from the batch parent).
    fn child_start_names(client: &crate::client::InMemoryExecutionClient) -> Vec<Option<String>> {
        client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Start) && u.parent_id().is_some())
            .map(|u| u.name().map(str::to_owned))
            .collect()
    }

    /// `item_namer` values must appear on the child START history records,
    /// not just in the in-memory batch result.
    #[tokio::test]
    async fn map_item_namer_reaches_child_start_updates() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let result = ctx
            .map(
                vec![1_i32, 2],
                |_child, item, _idx| async move { Ok(item * 10) },
            )
            .item_namer(|_, i| format!("item-{i}"))
            .await
            .expect("map must succeed");
        assert_eq!(result, vec![10, 20]);

        let mut names = child_start_names(&client);
        names.sort();
        assert_eq!(
            names,
            vec![Some("item-0".to_owned()), Some("item-1".to_owned())],
            "item namer values must be checkpointed on child STARTs"
        );
    }

    /// Parallel branch names must appear on the child START history
    /// records: the public naming API must not be silently discarded.
    #[tokio::test]
    async fn parallel_branch_names_reach_child_start_updates() {
        use crate::future::Branch;

        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let result = ctx
            .parallel([
                Branch::new("alpha", |_c| async move { Ok(1_i32) }),
                Branch::new("beta", |_c| async move { Ok(2_i32) }),
            ])
            .await
            .expect("parallel must succeed");
        assert_eq!(result, vec![1, 2]);

        let mut names = child_start_names(&client);
        names.sort();
        assert_eq!(
            names,
            vec![Some("alpha".to_owned()), Some("beta".to_owned())],
            "branch names must be checkpointed on child STARTs"
        );
    }

    /// Collects `(action, name)` of every recorded child update, in write
    /// order. A child update carries a `ParentId`; the batch parent's does
    /// not.
    fn child_update_names(
        client: &crate::client::InMemoryExecutionClient,
    ) -> Vec<(OperationAction, Option<String>)> {
        client
            .recorded_updates()
            .iter()
            .filter(|u| u.parent_id().is_some())
            .map(|u| (u.action().clone(), u.name().map(str::to_owned)))
            .collect()
    }

    /// A child's normal terminal `SUCCEED` and its body-error `FAIL` must
    /// carry the recorded name, as its `START` does. Item 0 has no namer
    /// result, so it records the default `map-item-0`.
    #[tokio::test]
    async fn child_terminal_updates_carry_the_recorded_name() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .map(vec![0_i32, 1], |_child, item, _idx| async move {
                if item == 1 {
                    Err::<i32, BoxError>("intentional".into())
                } else {
                    Ok(item)
                }
            })
            .item_namer(|_, i| {
                if i == 0 {
                    String::new()
                } else {
                    "named".to_owned()
                }
            })
            .max_concurrency(1)
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("a tolerated item failure must not become an operation error");
        assert_eq!(batch.failure_count(), 1);

        let updates = child_update_names(&client);
        let name_of = |action: OperationAction| -> Vec<Option<String>> {
            updates
                .iter()
                .filter(|(a, _)| *a == action)
                .map(|(_, n)| n.clone())
                .collect()
        };
        assert_eq!(
            name_of(OperationAction::Succeed),
            vec![Some("map-item-0".to_owned())],
            "a child SUCCEED must carry the recorded name"
        );
        assert_eq!(
            name_of(OperationAction::Fail),
            vec![Some("named".to_owned())],
            "a child body-error FAIL must carry the recorded name"
        );
    }

    fn succeeded_record(positional_id: &str, result: &str) -> (String, CheckpointRecord) {
        let wire_id = crate::engine::compute_wire_id_public(positional_id);
        (
            wire_id.clone(),
            CheckpointRecord {
                id: wire_id,
                status: CheckpointStatus::Succeeded,
                result: Some(result.to_owned()),
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )
    }

    fn failed_record(positional_id: &str, msg: &str) -> (String, CheckpointRecord) {
        let wire_id = crate::engine::compute_wire_id_public(positional_id);
        (
            wire_id.clone(),
            CheckpointRecord {
                id: wire_id,
                status: CheckpointStatus::Failed,
                result: None,
                error_type: Some("ChildFnError".to_owned()),
                error_message: Some(msg.to_owned()),
                error_data: Some(r#"{"recorded":true}"#.to_owned()),
                stack_trace: Some(vec!["recorded-frame".to_owned()]),
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )
    }

    /// A child recorded as terminal SUCCESS whose result was too large to
    /// checkpoint inline: `replay_children = true`, no payload. Replaying it
    /// requires re-executing the child body to reconstruct the result.
    fn replay_children_success_record(positional_id: &str) -> (String, CheckpointRecord) {
        let wire_id = crate::engine::compute_wire_id_public(positional_id);
        (
            wire_id.clone(),
            CheckpointRecord {
                id: wire_id,
                status: CheckpointStatus::Succeeded,
                result: None,
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: true,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )
    }

    #[tokio::test]
    async fn basic_map_two_items() {
        // A live client: the batch's checkpoint writes must succeed for
        // the items to run to completion. (Pre-#43 this test used a
        // client-less context and asserted the checkpoint failure
        // surfaced as Err; a rejected write now parks the future for the
        // invocation driver instead of yielding.)
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let result = ctx
            .map(vec![10, 20], |_child, item: i32, _idx| async move {
                Ok(item * 2)
            })
            .await;
        assert_eq!(result.unwrap(), vec![20, 40]);
    }

    #[tokio::test]
    async fn basic_parallel_two_branches() {
        use crate::future::Branch;
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let branches = vec![
            Branch::new("a", |_ctx| Box::pin(async { Ok(1) })),
            Branch::new("b", |_ctx| Box::pin(async { Ok(2) })),
        ];
        let result = ctx.parallel(branches).await;
        assert_eq!(result.unwrap(), vec![1, 2]);
    }

    /// `await_batch` on a tolerated mixed batch must report each branch's
    /// terminal status (with names and error messages) and the completion
    /// reason, without converting the tolerated failure into an error.
    #[tokio::test]
    async fn parallel_await_batch_reports_per_branch_status_and_reason() {
        use crate::future::Branch;
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .parallel(vec![
                Branch::new("ok-0", |_ctx| async move { Ok(1_i32) }),
                Branch::new("boom", |_ctx| async move { Err("intentional".into()) }),
                Branch::new("ok-2", |_ctx| async move { Ok(3_i32) }),
            ])
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("a tolerated branch failure must not become an operation error");

        assert_eq!(batch.reason, CompletionReason::AllCompleted);
        assert_eq!(batch.items.len(), 3);
        assert_eq!(batch.success_count(), 2);
        assert_eq!(batch.failure_count(), 1);
        assert_eq!(batch.status(), BatchStatus::Failed);

        let by_index = |idx: usize| {
            batch
                .items
                .iter()
                .find(|i| i.index == idx)
                .expect("batch must contain an item for every started branch")
        };
        assert_eq!(by_index(0).status, BatchItemStatus::Succeeded);
        assert_eq!(by_index(0).result, Some(1));
        assert_eq!(by_index(0).name, "ok-0");
        assert_eq!(by_index(1).status, BatchItemStatus::Failed);
        assert_eq!(by_index(1).result, None);
        assert_eq!(by_index(1).name, "boom");
        assert!(
            by_index(1)
                .error_message
                .as_deref()
                .unwrap_or_default()
                .contains("intentional"),
            "failed branch must carry its error message: {:?}",
            by_index(1).error_message
        );
        assert_eq!(by_index(2).status, BatchItemStatus::Succeeded);
        assert_eq!(by_index(2).result, Some(3));

        // The structured error view must associate the failure with the
        // branch that produced it.
        let errors = batch.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].index, 1);
        assert_eq!(errors[0].name, "boom");
        assert!(
            errors[0].message.contains("intentional"),
            "structured error must carry the branch's message: {:?}",
            errors[0].message
        );
        // Live execution records the body error's type: an untyped body
        // error records "Error", and the structured view exposes that
        // identity alongside the message.
        assert_eq!(errors[0].error_type, Some("Error"));
        assert_eq!(by_index(1).error_type.as_deref(), Some("Error"));
    }

    /// Partial replay must not discard branch names: when a branch reached a
    /// terminal state on a previous invocation (e.g. it failed while a
    /// sibling suspended), the next invocation reconstructs it from the
    /// checkpoint log via `replay_terminal_child`, and the resulting
    /// [`BatchItem`], and the structured error view, must still carry the
    /// producing branch's name. The live branch bodies here return values
    /// that CONTRADICT the recorded outcomes, proving the items came from
    /// replay rather than re-execution.
    #[tokio::test]
    async fn parallel_replayed_terminal_branches_retain_names() {
        use crate::future::Branch;

        // Second-invocation state: the batch parent (positional "1") is not
        // yet terminal, child 0 (positional "1-1") failed, and child 1
        // (positional "1-2") succeeded with 7.
        let log = CheckpointLog::from_records(vec![
            failed_record("1-1", "recorded failure"),
            succeeded_record("1-2", "7"),
        ]);
        let (ctx, _client) = test_ctx_with_client(log);

        let batch = ctx
            .parallel(vec![
                // Would SUCCEED if re-executed: the failure below proves
                // the item was reconstructed from the checkpoint record.
                Branch::new("boom", |_ctx| async move { Ok(999_i32) }),
                // Would return 999 if re-executed: the 7 below proves
                // replay.
                Branch::new("steady", |_ctx| async move { Ok(999_i32) }),
            ])
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("a tolerated replayed failure must not become an operation error");

        assert_eq!(batch.items.len(), 2);
        let by_index = |idx: usize| {
            batch
                .items
                .iter()
                .find(|i| i.index == idx)
                .expect("batch must contain an item for every branch")
        };

        let failed = by_index(0);
        assert_eq!(failed.status, BatchItemStatus::Failed);
        assert_eq!(
            failed.name, "boom",
            "a replayed failed branch must retain its branch name"
        );
        assert_eq!(failed.error_message.as_deref(), Some("recorded failure"));
        // The replayed item carries the child record's COMPLETE wire
        // failure record, not just its type and message.
        assert_eq!(failed.error_type.as_deref(), Some("ChildFnError"));
        assert_eq!(failed.error_data.as_deref(), Some(r#"{"recorded":true}"#));
        assert_eq!(failed.stack_trace, ["recorded-frame".to_owned()]);

        let succeeded = by_index(1);
        assert_eq!(succeeded.status, BatchItemStatus::Succeeded);
        assert_eq!(succeeded.result, Some(7));
        assert_eq!(
            succeeded.name, "steady",
            "a replayed succeeded branch must retain its branch name"
        );

        // The structured error view must associate the replayed failure
        // with the branch that produced it.
        let errors = batch.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].index, 0);
        assert_eq!(
            errors[0].name, "boom",
            "structured errors must name the replayed failed branch"
        );
        assert_eq!(errors[0].message, "recorded failure");
        assert_eq!(errors[0].error_type, Some("ChildFnError"));
    }

    /// The JSON structure of a batch record text, for assertions on its
    /// shape. Exact-text assertions read the text itself instead.
    fn record_json(record_text: &str) -> serde_json::Value {
        serde_json::from_str(record_text).expect("a batch record is JSON")
    }

    /// The batch record text the parent recorded: the first recorded
    /// update payload that parses as a batch record.
    fn recorded_batch_record(client: &crate::client::InMemoryExecutionClient) -> String {
        client
            .recorded_updates()
            .iter()
            .filter(|u| u.parent_id().is_none())
            .filter_map(|u| u.payload())
            .find(|p| parse_batch_record(p).is_ok())
            .map(str::to_owned)
            .expect("the parent records a batch record payload")
    }

    /// A failed map item records the type of the error its body returned
    /// (`"Error"` for an untyped error), and the four views of the failure
    /// agree: the child FAIL record, `BatchItem::error_type`,
    /// `BatchError::error_type` and the summary's `Cause.ErrorType`.
    #[tokio::test]
    async fn map_item_failure_records_body_error_type() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![1_i32], |_child, _item, _idx| async move {
                Err::<i32, BoxError>("plain boom".into())
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(0),
            )
            .await_batch()
            .await
            .expect("await_batch reports a failed item as a batch result");

        let fail = client
            .recorded_updates()
            .into_iter()
            .find(|u| {
                matches!(u.action(), OperationAction::Fail)
                    && matches!(u.r#type(), OperationType::Context)
            })
            .expect("the failed item records a child FAIL update");
        let error = fail
            .error()
            .expect("the FAIL update carries an error object");
        assert_eq!(error.error_type(), Some("Error"));
        assert_eq!(error.error_message(), Some("plain boom"));

        let item = batch
            .items
            .iter()
            .find(|i| i.index == 0)
            .expect("the batch reports the failed item");
        assert_eq!(item.status, BatchItemStatus::Failed);
        assert_eq!(item.error_type.as_deref(), Some("Error"));
        assert_eq!(
            batch.errors().next().map(|e| e.error_type),
            Some(Some("Error"))
        );

        let record = recorded_batch_record(&client);
        assert_eq!(
            record_json(&record).pointer("/all/0/error/Cause/ErrorType"),
            Some(&serde_json::json!("Error"))
        );
    }

    /// The same as [`map_item_failure_records_body_error_type`] for
    /// [`NestingMode::Flat`], which writes no child records.
    #[tokio::test]
    async fn flat_item_failure_records_body_error_type() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![1_i32], |_child, _item, _idx| async move {
                Err::<i32, BoxError>("plain boom".into())
            })
            .nesting(NestingMode::Flat)
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(0),
            )
            .await_batch()
            .await
            .expect("await_batch reports a failed item as a batch result");

        let item = batch
            .items
            .iter()
            .find(|i| i.index == 0)
            .expect("the batch reports the failed item");
        assert_eq!(item.status, BatchItemStatus::Failed);
        assert_eq!(item.error_type.as_deref(), Some("Error"));

        let record = recorded_batch_record(&client);
        assert_eq!(
            record_json(&record).pointer("/all/0/error/Cause/ErrorType"),
            Some(&serde_json::json!("Error"))
        );
    }

    /// `await_batch` surfaces a tolerance-exceeded batch as-is: the reason
    /// says why it ended and the failed branch keeps its status, while the
    /// plain `.await` on the same workload converts it into an error.
    #[tokio::test]
    async fn parallel_await_batch_surfaces_tolerance_exceeded_without_error() {
        use crate::future::Branch;
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .parallel(vec![Branch::new("boom", |_ctx| async move {
                Err::<i32, _>("intentional".into())
            })])
            .completion(
                crate::builders::map_parallel::CompletionConfig::builder()
                    .tolerated_failure_count(0)
                    .build()
                    .expect("valid completion config"),
            )
            .await_batch()
            .await
            .expect("await_batch must return the batch even when tolerance is exceeded");

        assert_eq!(batch.reason, CompletionReason::FailureToleranceExceeded);
        assert_eq!(batch.failure_count(), 1);
        assert_eq!(
            batch.items.first().map(|i| i.status),
            Some(BatchItemStatus::Failed)
        );
    }

    /// Issue #27: `parallel` must honor the failure tolerance a
    /// `CompletionConfig` expresses, exactly as `map` does. A failed branch
    /// within tolerance is omitted from the plain `.await`'s `Vec<O>`
    /// output rather than failing the whole operation.
    #[tokio::test]
    async fn parallel_plain_await_tolerates_failures_within_tolerance() {
        use crate::future::Branch;
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        let results: Vec<i32> = ctx
            .parallel(vec![
                Branch::new("ok-0", |_ctx| async move { Ok(1_i32) }),
                Branch::new("boom", |_ctx| async move { Err("intentional".into()) }),
                Branch::new("ok-2", |_ctx| async move { Ok(3_i32) }),
            ])
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await
            .expect("a tolerated branch failure must not fail the parallel operation");

        assert_eq!(
            results,
            vec![1, 3],
            "successful branch values must be returned in order, tolerated failure omitted"
        );

        // Same workload on map must agree (parity with map's tolerance).
        let (map_ctx, _c) = test_ctx_with_client(CheckpointLog::empty());
        let map_results: Vec<i32> = map_ctx
            .map(vec![1_i32, -1, 3], |_child, item, _idx| async move {
                if item < 0 {
                    Err("intentional".into())
                } else {
                    Ok(item)
                }
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await
            .expect("map must tolerate the failure");
        assert_eq!(
            map_results, results,
            "map and parallel plain `.await` must agree under the same tolerance"
        );
    }

    /// Issue #52: with NO completion config, the first item failure fails
    /// the batch (fail-fast), matching the Python and JS SDKs. Verified
    /// end-to-end on both `map` and `parallel` plain `.await`.
    #[tokio::test]
    async fn absent_completion_config_fails_fast_end_to_end() {
        use crate::future::Branch;

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let err = ctx
            .parallel(vec![
                Branch::new("ok", |_ctx| async move { Ok(1_i32) }),
                Branch::new("boom", |_ctx| async move { Err("intentional".into()) }),
            ])
            .await
            .expect_err("a branch failure without a completion config must fail the batch");
        assert!(
            format!("{err:#}").contains("intentional"),
            "the batch error must carry the failing branch's message, got: {err:#}"
        );

        let (map_ctx, _c) = test_ctx_with_client(CheckpointLog::empty());
        let map_err = map_ctx
            .map(vec![1_i32, -1], |_child, item, _idx| async move {
                if item < 0 {
                    Err("intentional".into())
                } else {
                    Ok(item)
                }
            })
            .await
            .expect_err("an item failure without a completion config must fail the batch");
        assert!(
            format!("{map_err:#}").contains("intentional"),
            "the batch error must carry the failing item's message, got: {map_err:#}"
        );
    }

    /// Issue #52: an EMPTY `CompletionConfig` behaves exactly as no config,
    /// fail-fast, and `await_batch` reports the batch as ended by
    /// `FAILURE_TOLERANCE_EXCEEDED`, the same reason an explicit
    /// `with_tolerated_failure_count(0)` records.
    #[tokio::test]
    async fn empty_completion_config_fails_fast_end_to_end() {
        use crate::future::Branch;

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .parallel(vec![Branch::new("boom", |_ctx| async move {
                Err::<i32, _>("intentional".into())
            })])
            .completion(crate::builders::map_parallel::CompletionConfig::default())
            .await_batch()
            .await
            .expect("await_batch must return the batch even when it fails fast");
        assert_eq!(
            batch.reason,
            CompletionReason::FailureToleranceExceeded,
            "an empty config must record the same reason as explicit fail-fast"
        );
        assert_eq!(batch.failure_count(), 1);

        // Plain `.await` on the same workload converts it into an error.
        let (ctx2, _c2) = test_ctx_with_client(CheckpointLog::empty());
        let err = ctx2
            .parallel(vec![Branch::new("boom", |_ctx| async move {
                Err::<i32, _>("intentional".into())
            })])
            .completion(crate::builders::map_parallel::CompletionConfig::default())
            .await
            .expect_err("a failure under an empty config must fail the batch");
        assert!(
            format!("{err:#}").contains("intentional"),
            "the batch error must carry the branch's message, got: {err:#}"
        );
    }

    /// Parity: `map` and `parallel` `await_batch` must agree on the batch
    /// shape for equivalent workloads: same completion reason, same
    /// per-index statuses, values, counts, and overall status string.
    #[tokio::test]
    async fn map_and_parallel_await_batch_agree_on_shape() {
        use crate::future::Branch;

        // Equivalent workload: 3 slots, the middle one fails, one failure
        // tolerated. `map` derives it from items; `parallel` from branches.
        let (map_ctx, _c1) = test_ctx_with_client(CheckpointLog::empty());
        let map_batch = map_ctx
            .map(vec![0_i32, 1, 2], |_child, item, _idx| async move {
                if item == 1 {
                    Err("intentional".into())
                } else {
                    Ok(item * 10)
                }
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("map await_batch must tolerate the failure");

        let (par_ctx, _c2) = test_ctx_with_client(CheckpointLog::empty());
        let par_batch = par_ctx
            .parallel((0_i32..3).map(|i| {
                Branch::new(format!("branch-{i}"), move |_ctx| async move {
                    if i == 1 {
                        Err("intentional".into())
                    } else {
                        Ok(i * 10)
                    }
                })
            }))
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("parallel await_batch must tolerate the failure");

        assert_eq!(map_batch.reason, par_batch.reason);
        assert_eq!(map_batch.items.len(), par_batch.items.len());
        assert_eq!(map_batch.success_count(), par_batch.success_count());
        assert_eq!(map_batch.failure_count(), par_batch.failure_count());
        assert_eq!(map_batch.status(), par_batch.status());

        let shape = |batch: &BatchResult<i32>| {
            let mut items: Vec<_> = batch
                .items
                .iter()
                .map(|i| (i.index, i.status, i.result))
                .collect();
            items.sort_unstable_by_key(|(idx, _, _)| *idx);
            items
        };
        assert_eq!(
            shape(&map_batch),
            shape(&par_batch),
            "map and parallel batches must report identical per-index outcomes"
        );
    }

    // Compile-level proof that map items and parallel branches accept any
    // `IntoIterator` (array, Vec, lazy iterator) and that closures are plain
    // `async move` bodies using `?`, no manual `Box::pin`, no error
    // conversion. Builders are constructed (type-checking the closures) then
    // dropped without awaiting, so no execution client is required.
    #[tokio::test]
    async fn map_and_parallel_accept_into_iterator_and_plain_async() {
        use crate::future::Branch;
        let ctx = test_ctx(CheckpointLog::empty());

        // map: array literal.
        let _ = ctx.map([1_i32, 2, 3], |c, item, _idx| async move {
            let v = c.step(move |_| async move { Ok(item + 1) }).await?;
            Ok(v)
        });
        // map: Vec.
        let _ = ctx.map(vec![1_i32, 2], |c, item, _idx| async move {
            let v = c.step(move |_| async move { Ok(item) }).await?;
            Ok(v)
        });
        // map: lazy iterator adapter.
        let _ = ctx.map((0_i32..3).map(|x| x * 2), |c, item, _idx| async move {
            let v = c.step(move |_| async move { Ok(item) }).await?;
            Ok(v)
        });

        // parallel: array of branches.
        let _ = ctx.parallel([
            Branch::new("a", |c| async move {
                let v = c.step(|_| async { Ok(1_i32) }).await?;
                Ok(v)
            }),
            Branch::new("b", |c| async move {
                let v = c.step(|_| async { Ok(2_i32) }).await?;
                Ok(v)
            }),
        ]);
        // parallel: Vec of branches.
        let _ = ctx.parallel(vec![Branch::new("x", |_c| async move { Ok(9_i32) })]);
        // parallel: lazy iterator of branches.
        let _ = ctx.parallel(
            (0_i32..2).map(|i| Branch::new(format!("branch-{i}"), move |_c| async move { Ok(i) })),
        );
    }

    #[tokio::test]
    async fn replay_frozen_batch_returns_without_re_execution() {
        // Set up: operation "1" is the parent batch that succeeded.
        // The payload contains two successful items.
        let payload = serde_json::json!({
            "all": [
                {"index": 0, "name": "map-item-0", "status": "SUCCEEDED", "result": "hello"},
                {"index": 1, "name": "map-item-1", "status": "SUCCEEDED", "result": "world"}
            ],
            "completionReason": "ALL_COMPLETED"
        });
        let log = CheckpointLog::from_records(vec![{
            let wire_id = crate::engine::compute_wire_id_public("1");
            (
                wire_id.clone(),
                CheckpointRecord {
                    id: wire_id,
                    status: CheckpointStatus::Succeeded,
                    result: Some(payload.to_string()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            )
        }]);
        let ctx = test_ctx(log);

        let result: Result<Vec<String>, _> = ctx
            .map(
                vec!["a".to_owned(), "b".to_owned()],
                |_child, _item: String, _idx| async move {
                    unreachable!("should not execute during replay");
                },
            )
            .await;

        let values = result.expect("replay should succeed");
        assert_eq!(values, vec!["hello", "world"]);
    }

    #[tokio::test]
    async fn completion_config_min_successful() {
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .min_successful(2)
            .build()
            .expect("valid completion config");
        assert!(should_stop_min(&cfg, 2));
        assert!(should_stop_min(&cfg, 3));
        assert!(!should_stop_min(&cfg, 1));
    }

    #[tokio::test]
    async fn completion_config_tolerated_failure_count() {
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .tolerated_failure_count(0)
            .build()
            .expect("valid completion config");
        // 0 tolerated means fail-fast: first failure exceeds.
        assert!(should_stop_failure(&cfg, 1, 10));
        assert!(!should_stop_failure(&cfg, 0, 10));
    }

    #[tokio::test]
    async fn completion_config_tolerated_failure_percentage() {
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .tolerated_failure_percentage(20.0)
            .build()
            .expect("valid completion config");
        // 3/10 = 30% > 20%: should stop.
        assert!(should_stop_failure(&cfg, 3, 10));
        // 2/10 = 20% == 20%: should NOT stop (strictly exceeds).
        assert!(!should_stop_failure(&cfg, 2, 10));
    }

    #[tokio::test]
    async fn tolerated_failure_percentage_boundary_cross_multiplication() {
        // The original integer-division bug: 1 failure of 3 items with
        // pct=33.  True rate is 33.3% which exceeds 33%, but old code
        // computed (1*100)/3 == 33, and 33 > 33 is false.
        // Cross-multiplication: 1*100=100 > 33*3=99 → true (correctly stops).
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .tolerated_failure_percentage(33.0)
            .build()
            .expect("valid completion config");
        assert!(
            should_stop_failure(&cfg, 1, 3),
            "1/3 = 33.3% should exceed 33% threshold"
        );

        // One item below the boundary: 0 failures of 3 must NOT stop.
        assert!(
            !should_stop_failure(&cfg, 0, 3),
            "0/3 = 0% should not exceed 33%"
        );

        // Exactly at threshold when the division is exact: 1/3 with pct=34
        // means 33.3% < 34%, should NOT stop.
        let cfg34 = crate::builders::map_parallel::CompletionConfig::builder()
            .tolerated_failure_percentage(34.0)
            .build()
            .expect("valid completion config");
        assert!(
            !should_stop_failure(&cfg34, 1, 3),
            "1/3 = 33.3% should not exceed 34%"
        );
    }

    #[tokio::test]
    async fn tolerated_failure_percentage_zero_means_fail_fast() {
        // pct=0 means fail on first failure (fail-fast).
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .tolerated_failure_percentage(0.0)
            .build()
            .expect("valid completion config");
        // First failure must stop the batch.
        assert!(
            should_stop_failure(&cfg, 1, 10),
            "pct=0 should stop on first failure"
        );
        // Zero failures should NOT stop.
        assert!(
            !should_stop_failure(&cfg, 0, 10),
            "pct=0 with no failures should not stop"
        );
    }

    /// Issue #52: an EMPTY config (no threshold, no predicate, which is
    /// also what an absent config becomes) fails fast on the first failure,
    /// matching the Python and JS SDKs.
    #[tokio::test]
    async fn empty_completion_config_fails_fast() {
        let cfg = crate::builders::map_parallel::CompletionConfig::default();
        assert!(
            should_stop_failure(&cfg, 1, 10),
            "an empty config must fail fast on the first failure"
        );
        assert!(
            !should_stop_failure(&cfg, 0, 10),
            "an empty config with no failures must not stop"
        );
    }

    /// Issue #52: configuring ANY criterion opts out of the implicit
    /// fail-fast: a min_successful-only or predicate-only config tolerates
    /// failures and lets its own criterion drive completion.
    #[tokio::test]
    async fn any_configured_criterion_disables_implicit_fail_fast() {
        // min_successful only: failures are tolerated (Python parity:
        // has_criteria is true, and no failure tolerance is configured).
        let min_only = crate::builders::map_parallel::CompletionConfig::with_min_successful(2);
        assert!(
            !should_stop_failure(&min_only, 1, 10),
            "a min_successful-only config must tolerate failures"
        );

        // predicate only: the predicate owns the completion decision
        // (JS parity).
        let predicate_only =
            crate::builders::map_parallel::CompletionConfig::with_completion_predicate(|_stats| {
                CompletionDecision::Continue
            });
        assert!(
            !should_stop_failure(&predicate_only, 1, 10),
            "a predicate-only config must tolerate failures"
        );

        // pct=100: the tolerate-all recipe: the failure rate can never
        // strictly exceed 100%.
        let tolerate_all =
            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_percentage(
                100.0,
            )
            .expect("a valid percentage");
        assert!(
            !should_stop_failure(&tolerate_all, 10, 10),
            "pct=100 must tolerate even a fully failed batch"
        );
    }

    #[tokio::test]
    async fn max_concurrency_bounds_peak() {
        // Track peak concurrent executions using an atomic counter.
        let active = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));

        let active_clone = Arc::clone(&active);
        let peak_clone = Arc::clone(&peak);

        // We can't run the full execution without a client, but we can
        // test the semaphore logic by observing that the concurrency
        // coordinator limits in-flight items.
        //
        // Direct semaphore test:
        let sem = Arc::new(Semaphore::new(2));
        let mut handles = Vec::new();
        for _ in 0..5 {
            let sem = Arc::clone(&sem);
            let active = Arc::clone(&active_clone);
            let peak = Arc::clone(&peak_clone);
            handles.push(tokio::spawn(async move {
                let _permit = sem.acquire().await.unwrap();
                let current = active.fetch_add(1, Ordering::SeqCst) + 1;
                loop {
                    let old = peak.load(Ordering::SeqCst);
                    if current <= old
                        || peak
                            .compare_exchange(old, current, Ordering::SeqCst, Ordering::SeqCst)
                            .is_ok()
                    {
                        break;
                    }
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                active.fetch_sub(1, Ordering::SeqCst);
            }));
        }
        for h in handles {
            h.await.unwrap();
        }
        assert!(
            peak_clone.load(Ordering::SeqCst) <= 2,
            "peak should not exceed max_concurrency=2"
        );
    }

    #[tokio::test]
    async fn deterministic_ids_under_concurrent_scheduling() {
        // IDs must be claimed in creation order regardless of execution.
        let ctx = test_ctx(CheckpointLog::empty());

        // Mint 3 IDs (simulating what map does internally).
        let id1 = ctx.mint_id();
        let id2 = ctx.mint_id();
        let id3 = ctx.mint_id();

        assert_eq!(id1.positional(), "1");
        assert_eq!(id2.positional(), "2");
        assert_eq!(id3.positional(), "3");
    }

    #[tokio::test]
    async fn never_started_branches_omitted_from_results() {
        // A batch with min_successful=1 should omit branches that never started.
        // We test the completion logic directly.
        let cfg = crate::builders::map_parallel::CompletionConfig::builder()
            .min_successful(1)
            .build()
            .expect("valid completion config");
        // After 1 success, should stop.
        assert!(should_stop_min(&cfg, 1));
    }

    /// The completion types the tests below use. `CompletionConfig` gets the
    /// short alias `Config`, because the older tests in this module spell out
    /// its full path.
    use crate::builders::map_parallel::{
        CompletionConfig as Config, CompletionDecision, CompletionItem, CompletionOutcome,
    };

    /// `Complete(Succeeded)` when `done`, else `Continue`.
    fn succeed_when(done: bool) -> CompletionDecision {
        if done {
            CompletionDecision::complete(CompletionOutcome::Succeeded)
        } else {
            CompletionDecision::Continue
        }
    }

    /// `Complete(Failed)` when `done`, else `Continue`.
    fn fail_when(done: bool) -> CompletionDecision {
        if done {
            CompletionDecision::complete(CompletionOutcome::Failed)
        } else {
            CompletionDecision::Continue
        }
    }

    /// Reports whether item `index` of the view has the given status.
    fn item_is(view: &BatchStats<'_>, index: usize, status: BatchItemStatus) -> bool {
        view.items()
            .get(index)
            .is_some_and(|item| item.status == Some(status))
    }

    /// The payload of the batch parent's `SUCCEED` update.
    fn parent_payload(client: &crate::client::InMemoryExecutionClient) -> String {
        parent_succeed_update(client)
            .payload()
            .map(str::to_owned)
            .expect("the batch parent SUCCEED carries a payload")
    }

    /// Runs `map(items)` twice on fresh contexts: once through
    /// `await_batch()` and once through `.await`. An item `Some(v)` returns
    /// `v`, and `None` returns `Err("boom")`. Returns the batch, the parent
    /// `SUCCEED` payload of the `await_batch()` run, and the `.await` result.
    async fn run_map(
        items: Vec<Option<u32>>,
        completion: Config,
        max_concurrency: usize,
    ) -> (BatchResult<u32>, String, Result<Vec<u32>, OperationError>) {
        let body = |_child: DurableContext, item: Option<u32>, _idx: usize| async move {
            item.ok_or_else(|| BoxError::from("boom"))
        };
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(items.clone(), body)
            .max_concurrency(max_concurrency)
            .completion(completion.clone())
            .await_batch()
            .await
            .expect("await_batch never fails for a completed batch");
        let payload = parent_payload(&client);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let awaited = ctx
            .map(items, body)
            .max_concurrency(max_concurrency)
            .completion(completion)
            .await;
        (batch, payload, awaited)
    }

    /// Asserts the reason, the recorded reason string and the status of one
    /// row of the batch table.
    fn assert_row(
        batch: &BatchResult<u32>,
        payload: &str,
        reason: CompletionReason,
        status: BatchStatus,
    ) {
        assert_eq!(batch.reason, reason);
        assert!(
            payload.contains(reason.as_str()),
            "the parent SUCCEED payload must carry {}, got: {payload}",
            reason.as_str()
        );
        assert_eq!(batch.status(), status);
    }

    /// The message of an error's attached wire record.
    fn wire_message(err: &OperationError) -> Option<String> {
        err.wire()
            .and_then(crate::error::WireError::error_message)
            .map(str::to_owned)
    }

    /// The child-context kind of an error.
    fn child_kind(err: &OperationError) -> &ChildContextErrorKind {
        let OperationErrorKind::ChildContext(child) = err.kind() else {
            unreachable!("expected a child-context error, got {:?}", err.kind());
        };
        child.kind()
    }

    /// JS checks "every item finished" before `minSuccessful`, so a
    /// minimum equal to the item count records `ALL_COMPLETED`.
    #[tokio::test]
    async fn min_successful_equal_to_total_records_all_completed() {
        let (batch, payload, awaited) =
            run_map(vec![Some(1), Some(2)], Config::with_min_successful(2), 1).await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::AllCompleted,
            BatchStatus::Succeeded,
        );
        assert_eq!(awaited.expect("Ok"), vec![1, 2]);
    }

    #[tokio::test]
    async fn min_successful_before_last_item_records_min_successful() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), Some(2), Some(3)],
            Config::with_min_successful(1),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::MinSuccessfulReached,
            BatchStatus::Succeeded,
        );
        assert_eq!(batch.items.len(), 1);
        assert_eq!(awaited.expect("Ok"), vec![1]);
    }

    /// JS checks the failure tolerance before "every item finished".
    #[tokio::test]
    async fn tolerance_exceeded_on_last_item_records_failure() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), None],
            Config::with_tolerated_failure_count(0),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::FailureToleranceExceeded,
            BatchStatus::Failed,
        );
        let err = awaited.expect_err("the tolerance is exceeded");
        assert!(matches!(
            child_kind(&err),
            ChildContextErrorKind::ChildFailed
        ));
        assert_eq!(wire_message(&err).as_deref(), Some("boom"));
    }

    #[tokio::test]
    async fn min_not_reached_records_all_completed() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), None, Some(3)],
            Config::with_min_successful(3),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::AllCompleted,
            BatchStatus::Failed,
        );
        assert_eq!(awaited.expect("Ok"), vec![1, 3]);
    }

    #[tokio::test]
    async fn predicate_complete_succeeded() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), Some(2), Some(3)],
            Config::with_completion_predicate(|s| succeed_when(s.succeeded() >= 1)),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::CustomCompletionSucceeded,
            BatchStatus::Succeeded,
        );
        assert_eq!(batch.items.len(), 1);
        assert_eq!(awaited.expect("Ok"), vec![1]);
    }

    /// As JS's `throwIfError`, a batch the predicate completed as failed
    /// with no failed item raises a `BatchCompletionError`.
    #[tokio::test]
    async fn predicate_complete_failed_without_failed_item() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), Some(2)],
            Config::with_completion_predicate(|s| fail_when(s.settled() >= 1)),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::CustomCompletionFailed,
            BatchStatus::Failed,
        );
        assert_eq!(batch.items.len(), 1);
        let err = awaited.expect_err("the predicate failed the batch");
        assert!(matches!(
            child_kind(&err),
            ChildContextErrorKind::BatchCompletionFailed
        ));
        let wire = err.wire().expect("a wire record is attached");
        assert_eq!(wire.error_type(), Some("BatchCompletionError"));
        assert_eq!(
            wire.error_message(),
            Some(
                "batch completed as failed by the completion predicate (CUSTOM_COMPLETION_FAILED)"
            )
        );
        assert_eq!(child_kind(&err).to_string(), "batch completed as failed");
    }

    /// As JS's `throwIfError`, a batch the predicate completed as failed
    /// raises the first failed item's error.
    #[tokio::test]
    async fn predicate_complete_failed_with_failed_item() {
        let (batch, payload, awaited) = run_map(
            vec![None, Some(2)],
            Config::with_completion_predicate(|s| fail_when(s.failed() >= 1)),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::CustomCompletionFailed,
            BatchStatus::Failed,
        );
        assert_eq!(batch.items.len(), 1);
        let err = awaited.expect_err("the predicate failed the batch");
        assert!(matches!(
            child_kind(&err),
            ChildContextErrorKind::ChildFailed
        ));
        assert_eq!(wire_message(&err).as_deref(), Some("boom"));
    }

    #[tokio::test]
    async fn predicate_continue_records_all_completed() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), None],
            Config::with_completion_predicate(|_| CompletionDecision::Continue),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::AllCompleted,
            BatchStatus::Failed,
        );
        assert_eq!(awaited.expect("Ok"), vec![1]);
    }

    /// Item 0 fails and exceeds the tolerance while item 1 still runs. The
    /// batch records that first trigger; item 1's later success would meet
    /// `min_successful(1)`, but it never replaces the reason.
    #[tokio::test(start_paused = true)]
    async fn first_trigger_reason_wins_while_a_later_item_runs() {
        let body = |_child: DurableContext, item: Option<u32>, _idx: usize| async move {
            match item {
                Some(v) => {
                    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                    Ok(v)
                }
                None => Err(BoxError::from("boom")),
            }
        };
        let completion = Config::builder()
            .min_successful(1)
            .tolerated_failure_count(0)
            .build()
            .expect("valid completion config");
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![None, Some(2)], body)
            .max_concurrency(2)
            .completion(completion.clone())
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_row(
            &batch,
            &parent_payload(&client),
            CompletionReason::FailureToleranceExceeded,
            BatchStatus::Failed,
        );
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let err = ctx
            .map(vec![None, Some(2)], body)
            .max_concurrency(2)
            .completion(completion)
            .await
            .expect_err("the tolerance is exceeded");
        assert!(matches!(
            child_kind(&err),
            ChildContextErrorKind::ChildFailed
        ));
        assert_eq!(wire_message(&err).as_deref(), Some("boom"));
    }

    /// JS checks the predicate before "every item finished", so a predicate
    /// that completes at the last settle records the custom reason.
    #[tokio::test]
    async fn predicate_complete_on_last_settle_records_custom() {
        let (batch, payload, awaited) = run_map(
            vec![Some(1), Some(2)],
            Config::with_completion_predicate(|s| succeed_when(s.settled() == s.total_items())),
            1,
        )
        .await;
        assert_row(
            &batch,
            &payload,
            CompletionReason::CustomCompletionSucceeded,
            BatchStatus::Succeeded,
        );
        assert_eq!(awaited.expect("Ok"), vec![1, 2]);
    }

    /// Counts how many bodies of `map([0, 1, ..])` ran, per item.
    fn counting_body(
        counters: Arc<Vec<AtomicUsize>>,
    ) -> impl Fn(DurableContext, usize, usize) -> std::future::Ready<Result<usize, BoxError>>
    + Send
    + Sync
    + 'static {
        move |_child, item, _idx| {
            if let Some(counter) = counters.get(item) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
            std::future::ready(Ok(item))
        }
    }

    fn counters(n: usize) -> Arc<Vec<AtomicUsize>> {
        Arc::new((0..n).map(|_| AtomicUsize::new(0)).collect())
    }

    fn counts(counters: &[AtomicUsize]) -> Vec<usize> {
        counters.iter().map(|c| c.load(Ordering::SeqCst)).collect()
    }

    /// As JS, a predicate that completes before any item starts resolves the
    /// batch at once with no item.
    #[tokio::test]
    async fn predicate_complete_before_first_dispatch_runs_no_body() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let ran = counters(2);
        let batch = ctx
            .map(vec![0_usize, 1], counting_body(Arc::clone(&ran)))
            .completion(Config::with_completion_predicate(|_| succeed_when(true)))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(counts(&ran), [0, 0]);
        assert!(batch.items.is_empty());
        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
        let parent_succeeds = client
            .recorded_updates()
            .iter()
            .filter(|u| u.parent_id().is_none() && matches!(u.action(), OperationAction::Succeed))
            .count();
        assert_eq!(parent_succeeds, 1);
    }

    #[tokio::test]
    async fn predicate_complete_at_dispatch_gate_stops_later_starts() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let ran = counters(3);
        let batch = ctx
            .map(vec![0_usize, 1, 2], counting_body(Arc::clone(&ran)))
            .max_concurrency(1)
            .completion(Config::with_completion_predicate(|s| {
                succeed_when(item_is(s, 0, BatchItemStatus::Succeeded))
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(counts(&ran), [1, 0, 0]);
        assert_eq!(statuses(&batch), [(0, BatchItemStatus::Succeeded)]);
        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
    }

    /// A zero-item batch asks the predicate once (as JS does), and a
    /// `Complete(Failed)` decision fails `.await`.
    #[tokio::test]
    async fn empty_batch_predicate_failed_records_custom_failed() {
        let completion = Config::with_completion_predicate(|_| fail_when(true));
        let body = |_child: DurableContext, item: u32, _idx: usize| async move { Ok(item) };
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(Vec::<u32>::new(), body)
            .completion(completion.clone())
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(batch.reason, CompletionReason::CustomCompletionFailed);
        assert_eq!(batch.status(), BatchStatus::Failed);
        assert!(parent_payload(&client).contains("CUSTOM_COMPLETION_FAILED"));
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let err = ctx
            .map(Vec::<u32>::new(), body)
            .completion(completion)
            .await
            .expect_err("the predicate failed the empty batch");
        assert!(matches!(
            child_kind(&err),
            ChildContextErrorKind::BatchCompletionFailed
        ));
    }

    #[tokio::test]
    async fn empty_batch_predicate_continue_records_all_completed() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let calls = Arc::new(AtomicUsize::new(0));
        let seen = Arc::clone(&calls);
        let batch = ctx
            .map(
                Vec::<u32>::new(),
                |_child, item, _idx| async move { Ok(item) },
            )
            .completion(Config::with_completion_predicate(move |s| {
                seen.fetch_add(1, Ordering::SeqCst);
                assert_eq!(s.total_items(), 0);
                CompletionDecision::Continue
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(batch.reason, CompletionReason::AllCompleted);
        assert_eq!(calls.load(Ordering::SeqCst), 1, "asked exactly once");
    }

    #[tokio::test]
    async fn min_successful_zero_one_item_records_all_completed() {
        let (batch, _payload, awaited) =
            run_map(vec![None], Config::with_min_successful(0), 1).await;
        assert_eq!(batch.reason, CompletionReason::AllCompleted);
        assert_eq!(batch.status(), BatchStatus::Failed);
        assert_eq!(awaited.expect("Ok"), Vec::<u32>::new());
    }

    #[tokio::test]
    async fn min_successful_zero_completes_at_first_settle() {
        let ran = Arc::new(AtomicUsize::new(0));
        let item_one_ran = Arc::clone(&ran);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![None, Some(1_u32)], move |_child, item, _idx| {
                let item_one_ran = Arc::clone(&item_one_ran);
                async move {
                    match item {
                        Some(v) => {
                            item_one_ran.fetch_add(1, Ordering::SeqCst);
                            Ok(v)
                        }
                        None => Err(BoxError::from("boom")),
                    }
                }
            })
            .max_concurrency(1)
            .completion(Config::with_min_successful(0))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(statuses(&batch), [(0, BatchItemStatus::Failed)]);
        assert_eq!(ran.load(Ordering::SeqCst), 0);
    }

    /// Runs 50-or-fewer items of which the first `failures` fail, under a
    /// failure percentage, and returns the reason.
    async fn percentage_reason(total: usize, failures: usize, pct: f64) -> CompletionReason {
        let items: Vec<Option<u32>> = (0..total)
            .map(|i| if i < failures { None } else { Some(1) })
            .collect();
        let (batch, _payload, _awaited) = run_map(
            items,
            Config::with_tolerated_failure_percentage(pct).expect("a valid percentage"),
            1,
        )
        .await;
        batch.reason
    }

    /// Cross-multiplication keeps 7 failures of 50 at 14.0 within the
    /// tolerance, where JS's division exceeds it.
    #[tokio::test]
    async fn percentage_boundary_is_exact() {
        assert_ne!(
            percentage_reason(50, 7, 14.0).await,
            CompletionReason::FailureToleranceExceeded
        );
        assert_eq!(
            percentage_reason(50, 8, 14.0).await,
            CompletionReason::FailureToleranceExceeded
        );
    }

    #[tokio::test]
    async fn fractional_percentage() {
        assert_ne!(
            percentage_reason(8, 1, 12.5).await,
            CompletionReason::FailureToleranceExceeded
        );
        assert_eq!(
            percentage_reason(8, 2, 12.5).await,
            CompletionReason::FailureToleranceExceeded
        );
    }

    /// The statuses of a predicate's view, as `(name, status)` pairs.
    type ViewLog = Arc<std::sync::Mutex<Vec<Vec<(Option<String>, Option<BatchItemStatus>)>>>>;

    fn view_of(stats: &BatchStats<'_>) -> Vec<(Option<String>, Option<BatchItemStatus>)> {
        stats
            .items()
            .iter()
            .map(|i| (i.name.clone(), i.status))
            .collect()
    }

    fn named(
        entries: &[(&str, Option<BatchItemStatus>)],
    ) -> Vec<(Option<String>, Option<BatchItemStatus>)> {
        entries
            .iter()
            .map(|(name, status)| (Some((*name).to_owned()), *status))
            .collect()
    }

    /// A branch that settles at once with `value`.
    fn ok_branch(name: &str, value: u32) -> crate::future::Branch<u32> {
        crate::future::Branch::new(name, move |_ctx| async move { Ok(value) })
    }

    /// A branch whose step never returns, so the branch stays running.
    fn pending_branch(name: &str) -> crate::future::Branch<u32> {
        crate::future::Branch::new(name, |ctx| async move {
            Ok(ctx
                .step(|_| std::future::pending::<Result<u32, BoxError>>())
                .name("forever")
                .await?)
        })
    }

    /// As JS, a predicate can complete on items 1 and 2 without waiting for
    /// a slower item 0.
    #[tokio::test]
    async fn predicate_completes_on_later_items_before_a_slow_earlier_item() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.parallel(vec![
                pending_branch("slow"),
                ok_branch("b", 2),
                ok_branch("c", 3),
            ])
            .completion(Config::with_completion_predicate(|s| {
                succeed_when(
                    item_is(s, 1, BatchItemStatus::Succeeded)
                        && item_is(s, 2, BatchItemStatus::Succeeded),
                )
            }))
            .await_batch(),
        )
        .await
        .expect("the predicate does not wait for item 0")
        .expect("await_batch returns the batch");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Started),
                (1, BatchItemStatus::Succeeded),
                (2, BatchItemStatus::Succeeded)
            ]
        );
        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
    }

    /// The predicate sees every item by index with its caller name, and is
    /// asked at each dispatch gate and after each settle.
    #[tokio::test]
    async fn predicate_sees_names_and_not_started_items() {
        let log: ViewLog = Arc::default();
        let writer = Arc::clone(&log);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.parallel(vec![
            ok_branch("a", 1),
            ok_branch("b", 2),
            ok_branch("c", 3),
        ])
        .max_concurrency(1)
        .completion(Config::with_completion_predicate(move |s| {
            writer.lock().expect("no poisoned lock").push(view_of(s));
            CompletionDecision::Continue
        }))
        .await_batch()
        .await
        .expect("await_batch returns the batch");
        let ok = Some(BatchItemStatus::Succeeded);
        let first = named(&[("a", None), ("b", None), ("c", None)]);
        let after_a = named(&[("a", ok), ("b", None), ("c", None)]);
        let after_b = named(&[("a", ok), ("b", ok), ("c", None)]);
        let after_c = named(&[("a", ok), ("b", ok), ("c", ok)]);
        assert_eq!(
            *log.lock().expect("no poisoned lock"),
            vec![
                first,
                after_a.clone(),
                after_a,
                after_b.clone(),
                after_b,
                after_c
            ]
        );
    }

    #[tokio::test]
    async fn predicate_sees_a_running_item_as_started() {
        let log: ViewLog = Arc::default();
        let writer = Arc::clone(&log);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.parallel(vec![ok_branch("a", 1), pending_branch("b")])
                .completion(Config::with_completion_predicate(move |s| {
                    writer.lock().expect("no poisoned lock").push(view_of(s));
                    succeed_when(s.succeeded() >= 1)
                }))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for item b")
        .expect("await_batch returns the batch");
        assert_eq!(
            log.lock().expect("no poisoned lock").last().cloned(),
            Some(named(&[
                ("a", Some(BatchItemStatus::Succeeded)),
                ("b", Some(BatchItemStatus::Started))
            ]))
        );
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
    }

    #[tokio::test]
    async fn predicate_counts_follow_settle_order() {
        type CountLog = Arc<std::sync::Mutex<Vec<(usize, usize, usize)>>>;
        let log: CountLog = Arc::default();
        let writer = Arc::clone(&log);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        tokio::time::timeout(
            EARLY_BOUND,
            ctx.parallel(vec![
                pending_branch("slow"),
                ok_branch("b", 2),
                ok_branch("c", 3),
            ])
            .completion(Config::with_completion_predicate(move |s| {
                if s.settled() > 0 {
                    writer.lock().expect("no poisoned lock").push((
                        s.succeeded(),
                        s.failed(),
                        s.settled(),
                    ));
                }
                succeed_when(s.settled() == 2)
            }))
            .await_batch(),
        )
        .await
        .expect("the counts do not wait for item 0")
        .expect("await_batch returns the batch");
        assert_eq!(
            *log.lock().expect("no poisoned lock"),
            vec![(1, 0, 1), (2, 0, 2)]
        );
    }

    /// As JS on resume, recorded items settle first, in index order, and
    /// every recorded outcome is kept even after the predicate completed.
    #[tokio::test]
    async fn resumed_batch_keeps_recorded_outcomes() {
        let log = CheckpointLog::from_records(vec![
            succeeded_record("1-1", "1"),
            succeeded_record("1-2", "2"),
            failed_record("1-3", "recorded failure"),
        ]);
        let (ctx, _client) = test_ctx_with_client(log);
        let ran = Arc::new(AtomicUsize::new(0));
        let body_ran = Arc::clone(&ran);
        let batch = ctx
            .map(vec![0_u32, 1, 2], move |_child, _item, _idx| {
                body_ran.fetch_add(1, Ordering::SeqCst);
                async move { Ok(999_u32) }
            })
            .max_concurrency(2)
            .completion(Config::with_completion_predicate(|s| {
                succeed_when(s.succeeded() >= 1)
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Succeeded),
                (2, BatchItemStatus::Failed)
            ]
        );
        assert_eq!(batch.results().collect::<Vec<_>>(), [&1, &2]);
        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
        assert_eq!(ran.load(Ordering::SeqCst), 0, "no body ran");
    }

    /// Once a threshold fired, a later settle that meets another threshold
    /// leaves the reason unchanged.
    #[test]
    fn first_threshold_trigger_wins_across_settles() {
        let cfg = Config::builder()
            .min_successful(1)
            .tolerated_failure_count(0)
            .build()
            .expect("valid completion config");

        let mut tracker = CompletionTracker::new(vec![None; 3]);
        tracker.settle(&cfg, 3, 0, BatchItemStatus::Failed);
        assert_eq!(
            tracker.stop_reason,
            Some(CompletionReason::FailureToleranceExceeded)
        );
        tracker.settle(&cfg, 3, 1, BatchItemStatus::Succeeded);
        assert_eq!(
            tracker.stop_reason,
            Some(CompletionReason::FailureToleranceExceeded)
        );

        let mut tracker = CompletionTracker::new(vec![None; 3]);
        tracker.settle(&cfg, 3, 0, BatchItemStatus::Succeeded);
        assert_eq!(
            tracker.stop_reason,
            Some(CompletionReason::MinSuccessfulReached)
        );
        tracker.settle(&cfg, 3, 1, BatchItemStatus::Failed);
        assert_eq!(
            tracker.stop_reason,
            Some(CompletionReason::MinSuccessfulReached)
        );
    }

    /// A tracker that stopped evaluating, as on a rebuild of a completed
    /// batch, updates its counts and view but runs no threshold and never
    /// calls the predicate.
    #[test]
    fn stopped_tracker_settles_without_evaluating() {
        let calls = Arc::new(AtomicUsize::new(0));
        let seen = Arc::clone(&calls);
        let predicate = Config::with_completion_predicate(move |_| {
            seen.fetch_add(1, Ordering::SeqCst);
            CompletionDecision::complete(CompletionOutcome::Failed)
        });
        let threshold = Config::with_tolerated_failure_count(0);

        for cfg in [&predicate, &threshold] {
            let mut tracker = CompletionTracker::new(vec![None; 2]);
            tracker.stop_evaluating();
            tracker.settle(cfg, 2, 0, BatchItemStatus::Failed);
            tracker.settle(cfg, 2, 1, BatchItemStatus::Succeeded);
            assert_eq!(tracker.stop_reason, None);
            assert_eq!((tracker.success_count, tracker.failure_count), (1, 1));
            assert_eq!(
                tracker
                    .items
                    .iter()
                    .map(|item| item.status)
                    .collect::<Vec<_>>(),
                [
                    Some(BatchItemStatus::Failed),
                    Some(BatchItemStatus::Succeeded)
                ]
            );
        }
        assert_eq!(
            calls.load(Ordering::SeqCst),
            0,
            "the predicate is never called"
        );
    }

    /// Once the predicate completed the batch, the SDK does not ask it
    /// again, so a later decision never replaces the first.
    #[test]
    fn first_predicate_decision_wins_across_settles() {
        let calls = Arc::new(AtomicUsize::new(0));
        let seen = Arc::clone(&calls);
        let cfg = Config::with_completion_predicate(move |s| {
            seen.fetch_add(1, Ordering::SeqCst);
            match s.settled() {
                1 => CompletionDecision::complete(CompletionOutcome::Succeeded),
                2 => CompletionDecision::complete(CompletionOutcome::Failed),
                _ => CompletionDecision::Continue,
            }
        });
        let mut tracker = CompletionTracker::new(vec![None; 3]);
        tracker.settle(&cfg, 3, 0, BatchItemStatus::Succeeded);
        tracker.settle(&cfg, 3, 1, BatchItemStatus::Succeeded);
        assert_eq!(
            tracker.stop_reason,
            Some(CompletionReason::CustomCompletionSucceeded)
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1, "the predicate ran once");
        // A dispatch gate after the trigger asks nothing either.
        assert!(tracker.dispatch_gate(&cfg));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn batch_stats_new_counts_items() {
        let items = [
            CompletionItem::new(0, None, Some(BatchItemStatus::Succeeded)),
            CompletionItem::new(1, None, Some(BatchItemStatus::Failed)),
            CompletionItem::new(2, None, Some(BatchItemStatus::Started)),
            CompletionItem::new(3, None, None),
        ];
        let stats = BatchStats::new(&items);
        assert_eq!(stats.succeeded(), 1);
        assert_eq!(stats.failed(), 1);
        assert_eq!(stats.settled(), 2);
        assert_eq!(stats.total_items(), 4);
        assert_eq!(stats.items().len(), 4);
    }

    /// All six orders of settling items 0, 1 and 2.
    const SETTLE_ORDERS: [[usize; 3]; 6] = [
        [0, 1, 2],
        [0, 2, 1],
        [1, 0, 2],
        [1, 2, 0],
        [2, 0, 1],
        [2, 1, 0],
    ];

    fn abc() -> Vec<Option<String>> {
        vec![Some("a".into()), Some("b".into()), Some("c".into())]
    }

    /// A monotonic predicate records the same reason in every settle order.
    #[test]
    fn monotonic_predicate_records_the_same_outcome_in_every_settle_order() {
        for order in SETTLE_ORDERS {
            let completes = Arc::new(AtomicUsize::new(0));
            let seen = Arc::clone(&completes);
            let cfg = Config::with_completion_predicate(move |s| {
                let decision = succeed_when(
                    item_is(s, 1, BatchItemStatus::Succeeded)
                        && item_is(s, 2, BatchItemStatus::Succeeded),
                );
                if decision != CompletionDecision::Continue {
                    seen.fetch_add(1, Ordering::SeqCst);
                }
                decision
            });
            let mut tracker = CompletionTracker::new(abc());
            for index in order {
                tracker.settle(&cfg, 3, index, BatchItemStatus::Succeeded);
            }
            assert_eq!(
                tracker.stop_reason,
                Some(CompletionReason::CustomCompletionSucceeded),
                "order {order:?}"
            );
            assert_eq!(completes.load(Ordering::SeqCst), 1, "order {order:?}");
        }
    }

    /// The JS counterexample: a predicate that is not monotonic can complete
    /// in one settle order and never in another. The SDK does not reject it.
    #[test]
    fn non_monotonic_predicate_depends_on_settle_order() {
        let cfg = Config::with_completion_predicate(|s| {
            succeed_when(s.succeeded() == 1 && s.failed() == 0)
        });

        let mut order_a = CompletionTracker::new(abc());
        order_a.settle(&cfg, 3, 0, BatchItemStatus::Succeeded);
        order_a.settle(&cfg, 3, 1, BatchItemStatus::Failed);
        assert_eq!(
            order_a.stop_reason,
            Some(CompletionReason::CustomCompletionSucceeded)
        );

        let mut order_b = CompletionTracker::new(abc());
        order_b.settle(&cfg, 3, 1, BatchItemStatus::Failed);
        order_b.settle(&cfg, 3, 0, BatchItemStatus::Succeeded);
        assert_eq!(order_b.stop_reason, None);
    }

    #[test]
    fn tracker_marks_dispatched_items_started() {
        let cfg = Config::default();
        let mut tracker = CompletionTracker::new(vec![Some("a".into()), Some("b".into())]);
        let view = |tracker: &CompletionTracker| -> Vec<Option<BatchItemStatus>> {
            tracker.items.iter().map(|i| i.status).collect()
        };
        assert_eq!(view(&tracker), [None, None]);
        tracker.mark_dispatched(0);
        assert_eq!(view(&tracker), [Some(BatchItemStatus::Started), None]);
        tracker.settle(&cfg, 2, 0, BatchItemStatus::Succeeded);
        assert_eq!(view(&tracker), [Some(BatchItemStatus::Succeeded), None]);
        tracker.mark_dispatched(1);
        assert_eq!(
            view(&tracker),
            [
                Some(BatchItemStatus::Succeeded),
                Some(BatchItemStatus::Started)
            ]
        );
        assert_eq!(
            tracker.items[1].name.as_deref(),
            Some("b"),
            "the view keeps the caller name"
        );
    }

    /// A `map` item has a caller name only when a namer is set, and an
    /// empty name is `Some("")`.
    #[tokio::test]
    async fn predicate_sees_map_namer_names() {
        let log: ViewLog = Arc::default();
        let writer = Arc::clone(&log);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.map(vec![0_u32, 1], |_child, item, _idx| async move { Ok(item) })
            .item_namer(|_, i| {
                if i == 0 {
                    String::new()
                } else {
                    format!("n{i}")
                }
            })
            .completion(Config::with_completion_predicate(move |s| {
                writer.lock().expect("no poisoned lock").push(view_of(s));
                CompletionDecision::Continue
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names: Vec<Option<String>> = log.lock().expect("no poisoned lock")[0]
            .iter()
            .map(|(name, _)| name.clone())
            .collect();
        assert_eq!(names, [Some(String::new()), Some("n1".to_owned())]);

        let log: ViewLog = Arc::default();
        let writer = Arc::clone(&log);
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.map(vec![0_u32], |_child, item, _idx| async move { Ok(item) })
            .completion(Config::with_completion_predicate(move |s| {
                writer.lock().expect("no poisoned lock").push(view_of(s));
                CompletionDecision::Continue
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        assert_eq!(log.lock().expect("no poisoned lock")[0], [(None, None)]);
    }

    /// The item namer runs once per input item, on the sequential and the
    /// concurrent path. A stateful namer gives a different name on each
    /// call, so the predicate view, the child START records and the result
    /// agree only when every consumer reads the one computed name.
    #[tokio::test]
    async fn item_namer_runs_once_per_item_and_names_agree() {
        for concurrency in [1, 3] {
            let calls = Arc::new(AtomicUsize::new(0));
            let counter = Arc::clone(&calls);
            let log: ViewLog = Arc::default();
            let writer = Arc::clone(&log);
            let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
            let batch = ctx
                .map(
                    vec![0_u32, 1, 2],
                    |_child, item, _idx| async move { Ok(item) },
                )
                .item_namer(move |_, i| {
                    let call = counter.fetch_add(1, Ordering::SeqCst);
                    format!("n{i}-call{call}")
                })
                .max_concurrency(concurrency)
                .completion(Config::with_completion_predicate(move |s| {
                    writer.lock().expect("no poisoned lock").push(view_of(s));
                    CompletionDecision::Continue
                }))
                .await_batch()
                .await
                .expect("await_batch returns the batch");

            assert_eq!(
                calls.load(Ordering::SeqCst),
                3,
                "the namer runs once per item (concurrency {concurrency})"
            );
            let result_names: Vec<Option<String>> =
                batch.items.iter().map(|i| Some(i.name.clone())).collect();
            let view_names: Vec<Option<String>> = log
                .lock()
                .expect("no poisoned lock")
                .last()
                .expect("the predicate ran")
                .iter()
                .map(|(name, _)| name.clone())
                .collect();
            let mut start_names = child_start_names(&client);
            start_names.sort();
            assert_eq!(view_names, result_names, "concurrency {concurrency}");
            assert_eq!(start_names, result_names, "concurrency {concurrency}");
        }
    }

    /// The names one batch exposes: the child START names in record order,
    /// the result's item names, and the caller names of the predicate's
    /// first view, in index order.
    struct BatchNames {
        starts: Vec<Option<String>>,
        results: Vec<String>,
        predicate: Vec<Option<String>>,
    }

    impl BatchNames {
        fn of<O>(
            client: &crate::client::InMemoryExecutionClient,
            batch: &BatchResult<O>,
            log: &ViewLog,
        ) -> Self {
            Self {
                starts: child_start_names(client),
                results: batch.items.iter().map(|i| i.name.clone()).collect(),
                predicate: log.lock().expect("no poisoned lock")[0]
                    .iter()
                    .map(|(name, _)| name.clone())
                    .collect(),
            }
        }
    }

    /// A completion predicate that records every view it sees and never
    /// completes the batch.
    fn logging_predicate(log: &ViewLog) -> Config {
        let writer = Arc::clone(log);
        Config::with_completion_predicate(move |s| {
            writer.lock().expect("no poisoned lock").push(view_of(s));
            CompletionDecision::Continue
        })
    }

    fn some(names: &[&str]) -> Vec<Option<String>> {
        names.iter().map(|n| Some((*n).to_owned())).collect()
    }

    fn owned(names: &[&str]) -> Vec<String> {
        names.iter().map(|n| (*n).to_owned()).collect()
    }

    /// The namer reads the item itself, so an item type that is not `Clone`
    /// can be named after its content.
    #[tokio::test]
    async fn map_item_namer_reads_the_item() {
        struct Order {
            id: String,
        }
        let log: ViewLog = Arc::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let orders = vec![
            Order {
                id: "o-1".to_owned(),
            },
            Order {
                id: "o-2".to_owned(),
            },
        ];
        let batch = ctx
            .map(orders, |_child, order: Order, _idx| async move {
                Ok(order.id.len())
            })
            .item_namer(|o, _| o.id.clone())
            .max_concurrency(1)
            .completion(logging_predicate(&log))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names = BatchNames::of(&client, &batch, &log);
        assert_eq!(names.starts, some(&["o-1", "o-2"]));
        assert_eq!(names.results, owned(&["o-1", "o-2"]));
        assert_eq!(names.predicate, some(&["o-1", "o-2"]));
    }

    /// A map item without a namer records `map-item-{index}`, and the
    /// predicate sees `None`.
    #[tokio::test]
    async fn unnamed_map_items_record_default_names() {
        let log: ViewLog = Arc::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![1_u32, 2], |_child, item, _idx| async move { Ok(item) })
            .max_concurrency(1)
            .completion(logging_predicate(&log))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names = BatchNames::of(&client, &batch, &log);
        assert_eq!(names.starts, some(&["map-item-0", "map-item-1"]));
        assert_eq!(names.results, owned(&["map-item-0", "map-item-1"]));
        assert_eq!(names.predicate, [None, None]);
    }

    /// An empty namer result records `map-item-{index}`, and the predicate
    /// sees `Some("")`.
    #[tokio::test]
    async fn empty_namer_result_records_default_name() {
        let log: ViewLog = Arc::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .map(vec![1_u32, 2], |_child, item, _idx| async move { Ok(item) })
            .item_namer(|_, i| {
                if i == 0 {
                    String::new()
                } else {
                    "named".into()
                }
            })
            .max_concurrency(1)
            .completion(logging_predicate(&log))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names = BatchNames::of(&client, &batch, &log);
        assert_eq!(names.starts, some(&["map-item-0", "named"]));
        assert_eq!(names.results, owned(&["map-item-0", "named"]));
        assert_eq!(names.predicate, some(&["", "named"]));
    }

    /// An empty branch name records `parallel-branch-{index}`, and the
    /// predicate sees `Some("")`.
    #[tokio::test]
    async fn empty_branch_name_records_default_name() {
        use crate::future::Branch;
        let log: ViewLog = Arc::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .parallel([
                Branch::new("", |_c| async move { Ok(1_u32) }),
                Branch::new("x", |_c| async move { Ok(2_u32) }),
            ])
            .max_concurrency(1)
            .completion(logging_predicate(&log))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names = BatchNames::of(&client, &batch, &log);
        assert_eq!(names.starts, some(&["parallel-branch-0", "x"]));
        assert_eq!(names.results, owned(&["parallel-branch-0", "x"]));
        assert_eq!(names.predicate, some(&["", "x"]));
    }

    /// A `Branch::unnamed` branch records `parallel-branch-{index}`, and the
    /// predicate sees `None`.
    #[tokio::test]
    async fn unnamed_branch_records_default_name() {
        use crate::future::Branch;
        let log: ViewLog = Arc::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = ctx
            .parallel([
                Branch::unnamed(|_c| async move { Ok(1_u32) }),
                Branch::new("x", |_c| async move { Ok(2_u32) }),
            ])
            .max_concurrency(1)
            .completion(logging_predicate(&log))
            .await_batch()
            .await
            .expect("await_batch returns the batch");
        let names = BatchNames::of(&client, &batch, &log);
        assert_eq!(names.starts, some(&["parallel-branch-0", "x"]));
        assert_eq!(names.results, owned(&["parallel-branch-0", "x"]));
        assert_eq!(names.predicate, [None, Some("x".to_owned())]);
    }

    /// The namer runs once for every input item when the map starts,
    /// including the two items that never start because the batch completes
    /// after the first success.
    #[tokio::test]
    async fn namer_runs_once_per_item() {
        let calls = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&calls);
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.map(
            vec![1_u32, 2, 3],
            |_child, item, _idx| async move { Ok(item) },
        )
        .item_namer(move |_, _| {
            counter.fetch_add(1, Ordering::SeqCst);
            String::new()
        })
        .max_concurrency(1)
        .completion(Config::with_min_successful(1))
        .await_batch()
        .await
        .expect("await_batch returns the batch");
        assert_eq!(child_start_names(&client), some(&["map-item-0"]));
        assert_eq!(calls.load(Ordering::SeqCst), 3);
    }

    /// On the sequential path, a resumed batch replays its recorded-terminal
    /// item without a dispatch gate: the replay pass is not a live dispatch.
    /// So the predicate is first asked after item 0's recorded settle, and
    /// the live items still get the IDs the first run would give them.
    #[tokio::test]
    async fn sequential_replay_asks_no_gate_for_a_recorded_item() {
        let log = CheckpointLog::from_records(vec![succeeded_record("1-1", "1")]);
        let (ctx, client) = test_ctx_with_client(log);
        let views: ViewLog = Arc::default();
        let writer = Arc::clone(&views);
        let ran = Arc::new(AtomicUsize::new(0));
        let body_ran = Arc::clone(&ran);
        let batch = ctx
            .map(vec![0_u32, 1, 2], move |_child, item, _idx| {
                body_ran.fetch_add(1, Ordering::SeqCst);
                async move { Ok(item + 10) }
            })
            .max_concurrency(1)
            .completion(Config::with_completion_predicate(move |s| {
                writer.lock().expect("no poisoned lock").push(view_of(s));
                CompletionDecision::Continue
            }))
            .await_batch()
            .await
            .expect("await_batch returns the batch");

        let ok = Some(BatchItemStatus::Succeeded);
        let after_0 = vec![(None, ok), (None, None), (None, None)];
        let after_1 = vec![(None, ok), (None, ok), (None, None)];
        let after_2 = vec![(None, ok), (None, ok), (None, ok)];
        assert_eq!(
            *views.lock().expect("no poisoned lock"),
            vec![after_0.clone(), after_0, after_1.clone(), after_1, after_2],
            "settle of item 0, gate and settle of item 1, gate and settle of item 2"
        );
        assert_eq!(batch.results().collect::<Vec<_>>(), [&1, &11, &12]);
        assert_eq!(ran.load(Ordering::SeqCst), 2, "only the live items ran");

        let started: Vec<String> = client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Start) && u.parent_id().is_some())
            .map(|u| u.id().to_owned())
            .collect();
        assert_eq!(
            started,
            [
                crate::engine::compute_wire_id_public("1-2"),
                crate::engine::compute_wire_id_public("1-3")
            ],
            "the live items keep the IDs the first run gives them"
        );
    }

    /// A custom completion predicate ends a live map batch early, dispatch
    /// stops, and the recorded batch payload carries the
    /// `CUSTOM_COMPLETION_SUCCEEDED` reason.
    #[tokio::test]
    async fn completion_predicate_ends_map_batch_early() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .map(
                vec![10_u32, 20, 30, 40, 50],
                |_child, item, _idx| async move { Ok(item) },
            )
            .name("predicated")
            .max_concurrency(1)
            .completion(
                crate::builders::map_parallel::CompletionConfig::builder()
                    .completion_predicate(|stats| succeed_when(stats.settled() >= 2))
                    .build()
                    .expect("valid completion config"),
            )
            .await_batch()
            .await
            .expect("a predicate-completed batch must not become an operation error");

        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
        assert_eq!(
            batch.items.len(),
            2,
            "the predicate fires after the second settle; later items never start"
        );
        assert_eq!(batch.success_count(), 2);

        // The batch parent SUCCEED payload records the reason string, which
        // is what replay reads back through `CompletionReason::from_wire`.
        let parent_success_payload = client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Succeed) && u.parent_id().is_none())
            .filter_map(|u| u.payload().map(str::to_owned))
            .next_back()
            .expect("the batch parent must record a SUCCEED payload");
        assert!(
            parent_success_payload.contains("CUSTOM_COMPLETION_SUCCEEDED"),
            "recorded payload must carry the predicate reason, got: {parent_success_payload}"
        );
    }

    /// The predicate receives every item's status, so it can key off WHICH
    /// item settled and how, not just the counts.
    #[tokio::test]
    async fn completion_predicate_observes_settled_outcomes() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        // Stop as soon as item index 1 is observed to have failed.
        let batch = ctx
            .map(vec![0_u32, 1, 2, 3], |_child, item, _idx| async move {
                if item == 1 {
                    Err("item 1 fails".into())
                } else {
                    Ok(item)
                }
            })
            .max_concurrency(1)
            .completion(
                crate::builders::map_parallel::CompletionConfig::builder()
                    .completion_predicate(|stats| {
                        succeed_when(item_is(stats, 1, BatchItemStatus::Failed))
                    })
                    .build()
                    .expect("valid completion config"),
            )
            .await_batch()
            .await
            .expect("a predicate-completed batch must not become an operation error");

        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
        assert_eq!(
            batch.items.len(),
            2,
            "items 2 and 3 must never start once the predicate fires"
        );
        assert_eq!(batch.failure_count(), 1);
    }

    /// A zero-item batch asks the predicate once, on an empty view, as JS
    /// does: a `Complete(Succeeded)` decision records
    /// `CUSTOM_COMPLETION_SUCCEEDED`.
    #[tokio::test]
    async fn empty_batch_predicate_succeeded_records_custom_succeeded() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .map(
                Vec::<u32>::new(),
                |_child, item, _idx| async move { Ok(item) },
            )
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_completion_predicate(|_| {
                    CompletionDecision::complete(CompletionOutcome::Succeeded)
                }),
            )
            .await_batch()
            .await
            .expect("an empty batch completes immediately");

        assert_eq!(batch.reason, CompletionReason::CustomCompletionSucceeded);
        assert!(batch.items.is_empty());
    }

    /// Both custom reasons survive the checkpoint round-trip, through the
    /// tolerant and the strict parser.
    #[test]
    fn custom_reasons_round_trip_wire() {
        for reason in [
            CompletionReason::CustomCompletionSucceeded,
            CompletionReason::CustomCompletionFailed,
        ] {
            assert_eq!(CompletionReason::from_wire(reason.as_str()), reason);
            assert_eq!(
                CompletionReason::try_from_wire(reason.as_str()),
                Some(reason)
            );
        }
    }

    /// An unknown completion reason is not parsed.
    #[test]
    fn unknown_completion_reason_is_not_parsed() {
        assert_eq!(CompletionReason::try_from_wire("NOT_A_REASON"), None);
    }

    /// `status()` follows a custom outcome whatever the items did.
    #[test]
    fn status_follows_custom_outcome() {
        let failed_item = || {
            vec![BatchItem::<u32>::new(
                0,
                String::new(),
                BatchItemStatus::Failed,
                None,
                None,
                None,
            )]
        };
        let ok_item = || {
            vec![BatchItem::<u32>::new(
                0,
                String::new(),
                BatchItemStatus::Succeeded,
                Some(1),
                None,
                None,
            )]
        };
        assert_eq!(
            BatchResult::new(failed_item(), CompletionReason::CustomCompletionSucceeded).status(),
            BatchStatus::Succeeded
        );
        assert_eq!(
            BatchResult::new(ok_item(), CompletionReason::CustomCompletionFailed).status(),
            BatchStatus::Failed
        );
        assert_eq!(
            BatchResult::new(ok_item(), CompletionReason::MinSuccessfulReached).status(),
            BatchStatus::Succeeded
        );
        assert_eq!(
            BatchResult::new(failed_item(), CompletionReason::AllCompleted).status(),
            BatchStatus::Failed
        );
    }

    // Gap 1: BatchResult/BatchItem public API tests

    #[test]
    fn batch_item_new_constructs_correctly() {
        let item: BatchItem<String> = BatchItem::new(
            3,
            "my-item".to_owned(),
            BatchItemStatus::Succeeded,
            Some("hello".to_owned()),
            None,
            None,
        );
        assert_eq!(item.index, 3);
        assert_eq!(item.name, "my-item");
        assert_eq!(item.status, BatchItemStatus::Succeeded);
        assert_eq!(item.result.as_deref(), Some("hello"));
        assert!(item.error_message.is_none());
        assert!(item.error_type.is_none());
    }

    #[test]
    fn batch_result_accessors_match_go_sdk() {
        let result: BatchResult<i32> = BatchResult::new(
            vec![
                BatchItem::new(
                    0,
                    String::new(),
                    BatchItemStatus::Succeeded,
                    Some(10),
                    None,
                    None,
                ),
                BatchItem::new(
                    1,
                    String::new(),
                    BatchItemStatus::Failed,
                    None,
                    Some("err".into()),
                    Some("Error".into()),
                ),
                BatchItem::new(
                    2,
                    String::new(),
                    BatchItemStatus::Succeeded,
                    Some(30),
                    None,
                    None,
                ),
            ],
            CompletionReason::FailureToleranceExceeded,
        );
        assert_eq!(result.success_count(), 2);
        assert_eq!(result.failure_count(), 1);
        assert_eq!(result.total_count(), 3);
        assert!(result.has_failure());
        assert_eq!(result.status(), BatchStatus::Failed);
        let errors = result.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].index, 1);
        assert_eq!(errors[0].name, "");
        assert_eq!(errors[0].message, "err");
        assert_eq!(errors[0].error_type, Some("Error"));
        assert_eq!(result.results().collect::<Vec<_>>(), vec![&10, &30]);
        assert_eq!(result.reason, CompletionReason::FailureToleranceExceeded);
    }

    #[test]
    fn batch_result_all_succeeded() {
        let result: BatchResult<&str> = BatchResult::new(
            vec![
                BatchItem::new(
                    0,
                    String::new(),
                    BatchItemStatus::Succeeded,
                    Some("a"),
                    None,
                    None,
                ),
                BatchItem::new(
                    1,
                    String::new(),
                    BatchItemStatus::Succeeded,
                    Some("b"),
                    None,
                    None,
                ),
            ],
            CompletionReason::AllCompleted,
        );
        assert!(!result.has_failure());
        assert_eq!(result.status(), BatchStatus::Succeeded);
        assert_eq!(result.success_count(), 2);
        assert_eq!(result.failure_count(), 0);
        assert_eq!(result.errors().next(), None);
    }

    /// `BatchStatus` must render exactly the strings the old string-typed
    /// `status()` accessor returned.
    #[test]
    fn batch_status_display_preserves_wire_strings() {
        assert_eq!(BatchStatus::Succeeded.as_str(), "SUCCEEDED");
        assert_eq!(BatchStatus::Failed.as_str(), "FAILED");
        assert_eq!(BatchStatus::Succeeded.to_string(), "SUCCEEDED");
        assert_eq!(BatchStatus::Failed.to_string(), "FAILED");
    }

    /// Every completion reason `execute_batch` can produce must round-trip
    /// through its wire representation.
    #[test]
    fn completion_reason_round_trips_through_wire() {
        for reason in [
            CompletionReason::AllCompleted,
            CompletionReason::MinSuccessfulReached,
            CompletionReason::FailureToleranceExceeded,
            CompletionReason::CustomCompletionSucceeded,
            CompletionReason::CustomCompletionFailed,
        ] {
            assert_eq!(CompletionReason::from_wire(reason.as_str()), reason);
        }
        // Unknown strings from a newer SDK degrade to AllCompleted.
        assert_eq!(
            CompletionReason::from_wire("SOME_FUTURE_REASON"),
            CompletionReason::AllCompleted
        );
    }

    /// `errors()` must associate each error with the item that produced it:
    /// the item's index, its display name, the error type, and the message.
    #[test]
    fn errors_carry_item_index_name_and_message() {
        let result: BatchResult<i32> = BatchResult::new(
            vec![
                BatchItem::new(
                    0,
                    "a".to_owned(),
                    BatchItemStatus::Succeeded,
                    Some(1),
                    None,
                    None,
                ),
                BatchItem::new(
                    1,
                    "b".to_owned(),
                    BatchItemStatus::Failed,
                    None,
                    Some("first failure".into()),
                    Some("Error".into()),
                ),
                BatchItem::new(
                    2,
                    "c".to_owned(),
                    BatchItemStatus::Succeeded,
                    Some(3),
                    None,
                    None,
                ),
                BatchItem::new(
                    4,
                    "e".to_owned(),
                    BatchItemStatus::Failed,
                    None,
                    Some("second failure".into()),
                    Some("TimeoutError".into()),
                ),
            ],
            CompletionReason::AllCompleted,
        );

        let errors = result.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 2);
        assert_eq!(errors[0].index, 1);
        assert_eq!(errors[0].name, "b");
        assert_eq!(errors[0].message, "first failure");
        assert_eq!(errors[0].error_type, Some("Error"));
        assert_eq!(errors[1].index, 4);
        assert_eq!(errors[1].name, "e");
        assert_eq!(errors[1].message, "second failure");
        assert_eq!(errors[1].error_type, Some("TimeoutError"));
    }

    /// A failed item with no recorded message or error type yields an empty
    /// message and a `None` type rather than being dropped from `errors()`.
    #[test]
    fn errors_include_failed_items_without_messages() {
        let result: BatchResult<i32> = BatchResult::new(
            vec![BatchItem::new(
                0,
                "x".to_owned(),
                BatchItemStatus::Failed,
                None,
                None,
                None,
            )],
            CompletionReason::AllCompleted,
        );
        let errors = result.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].index, 0);
        assert_eq!(errors[0].name, "x");
        assert_eq!(errors[0].message, "");
        assert_eq!(errors[0].error_type, None);
    }

    /// A failed item's COMPLETE wire failure record — type, message,
    /// `error_data`, and `stack_trace` — must survive the checkpoint
    /// payload round-trip (`from_batch_result` → `to_batch_result`), so
    /// error identity is preserved across suspension and replay rather
    /// than being discarded on the way back in.
    #[tokio::test]
    async fn batch_checkpoint_round_trips_error_type_and_message() {
        let mut failed_item = BatchItem::new(
            1,
            "boom".to_owned(),
            BatchItemStatus::Failed,
            None,
            Some("it broke".to_owned()),
            Some("CustomFailure".to_owned()),
        );
        failed_item.error_data = Some(r#"{"attempt":3}"#.to_owned());
        failed_item.stack_trace = vec!["frame-a".to_owned(), "frame-b".to_owned()];
        let original: BatchResult<i32> = BatchResult::new(
            vec![
                BatchItem::new(
                    0,
                    "ok".to_owned(),
                    BatchItemStatus::Succeeded,
                    Some(7),
                    None,
                    None,
                ),
                failed_item,
            ],
            CompletionReason::FailureToleranceExceeded,
        );

        let json = Arc::new(crate::serdes::JsonSerdes);
        let payload = from_batch_result(
            &original,
            &[Some("7".to_owned()), None],
            &ItemEncoding::AllJson,
        );
        let replayed: BatchResult<i32> = to_batch_result(
            &test_ctx(CheckpointLog::empty()),
            &payload,
            &json,
            ItemEncoding::AllJson,
            2,
            "arn:test",
            &ItemIds::new(&OperationId::new("1".to_owned()), 2),
        )
        .await
        .expect("deserializing the payload must succeed");

        assert_eq!(replayed.reason, CompletionReason::FailureToleranceExceeded);
        assert_eq!(replayed.items.len(), 2);
        let failed = &replayed.items[1];
        assert_eq!(failed.index, 1);
        assert_eq!(failed.name, "boom");
        assert_eq!(failed.status, BatchItemStatus::Failed);
        assert_eq!(failed.error_message.as_deref(), Some("it broke"));
        assert_eq!(failed.error_type.as_deref(), Some("CustomFailure"));
        assert_eq!(failed.error_data.as_deref(), Some(r#"{"attempt":3}"#));
        assert_eq!(
            failed.stack_trace,
            ["frame-a".to_owned(), "frame-b".to_owned()]
        );
        let errors = replayed.errors().collect::<Vec<_>>();
        assert_eq!(errors[0].error_type, Some("CustomFailure"));
        assert_eq!(errors[0].message, "it broke");
        let ok = &replayed.items[0];
        assert_eq!(ok.result, Some(7));
        assert!(ok.error_type.is_none());
        assert!(ok.error_data.is_none());
        assert_eq!(ok.stack_trace, Vec::<String>::new());
    }

    /// A failed item that recorded no error type writes the default
    /// `"Error"` as its `Cause.ErrorType`, and an item that recorded no
    /// message writes an empty `ErrorMessage`.
    #[test]
    fn from_batch_result_defaults_missing_error_type() {
        let original: BatchResult<i32> = BatchResult::new(
            vec![BatchItem::new(
                0,
                String::new(),
                BatchItemStatus::Failed,
                None,
                Some("boom".to_owned()),
                None,
            )],
            CompletionReason::AllCompleted,
        );
        let payload = record_json(&from_batch_result(
            &original,
            &[None],
            &ItemEncoding::AllJson,
        ));
        assert_eq!(
            payload.pointer("/all/0/error/Cause/ErrorType"),
            Some(&serde_json::json!("Error"))
        );
        assert_eq!(
            payload.pointer("/all/0/error/ErrorMessage"),
            Some(&serde_json::json!("boom"))
        );
        let untyped: BatchResult<i32> = BatchResult::new(
            vec![BatchItem::new(
                0,
                String::new(),
                BatchItemStatus::Failed,
                None,
                None,
                None,
            )],
            CompletionReason::AllCompleted,
        );
        let payload = record_json(&from_batch_result(
            &untyped,
            &[None],
            &ItemEncoding::AllJson,
        ));
        assert_eq!(
            payload.pointer("/all/0/error/Cause/ErrorMessage"),
            Some(&serde_json::json!(""))
        );
    }

    /// A checkpoint payload whose failed item carries no `ErrorType`
    /// replays with `error_type: None` rather than a fabricated type.
    #[tokio::test]
    async fn to_batch_result_missing_err_type_is_none() {
        let payload = r#"{"all":[{"index":0,"name":"map-item-0","status":"FAILED","error":{"ErrorMessage":"boom"}}],"completionReason":"ALL_COMPLETED"}"#;
        let json = Arc::new(crate::serdes::JsonSerdes);
        let replayed: BatchResult<i32> = to_batch_result(
            &test_ctx(CheckpointLog::empty()),
            payload,
            &json,
            ItemEncoding::AllJson,
            2,
            "arn:test",
            &ItemIds::new(&OperationId::new("1".to_owned()), 2),
        )
        .await
        .expect("deserializing the payload must succeed");
        let item = replayed.items.first().expect("one item");
        assert_eq!(item.error_message.as_deref(), Some("boom"));
        assert_eq!(item.error_type, None);
        // A failure without `ErrorData` and `StackTrace` replays with an
        // empty failure payload rather than a fabricated one.
        assert_eq!(item.error_data, None);
        assert_eq!(item.stack_trace, Vec::<String>::new());
        assert_eq!(replayed.errors().next().map(|e| e.error_type), Some(None));
    }

    /// Replaying a frozen terminal batch whose payload carries a per-item
    /// error type exposes that type through `errors()` without re-executing
    /// any item body.
    #[tokio::test]
    async fn replay_frozen_batch_preserves_error_type() {
        let payload = serde_json::json!({
            "all": [
                {"index": 0, "name": "map-item-0", "status": "SUCCEEDED", "result": "hello"},
                {
                    "index": 1,
                    "name": "map-item-1",
                    "status": "FAILED",
                    "error": {
                        "ErrorType": "ChildContextError",
                        "Cause": {"ErrorType": "ChildFnError", "ErrorMessage": "boom"}
                    }
                }
            ],
            "completionReason": "ALL_COMPLETED"
        });
        let log = CheckpointLog::from_records(vec![{
            let wire_id = crate::engine::compute_wire_id_public("1");
            (
                wire_id.clone(),
                CheckpointRecord {
                    id: wire_id,
                    status: CheckpointStatus::Succeeded,
                    result: Some(payload.to_string()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            )
        }]);
        let ctx = test_ctx(log);

        let batch = ctx
            .map(
                vec!["a".to_owned(), "b".to_owned()],
                |_child, _item: String, _idx| async move {
                    Err::<String, _>("should not execute during replay".into())
                },
            )
            .await_batch()
            .await
            .expect("frozen batch must replay from the payload");

        assert_eq!(batch.success_count(), 1);
        assert_eq!(batch.failure_count(), 1);
        let errors = batch.errors().collect::<Vec<_>>();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].index, 1);
        assert_eq!(errors[0].message, "boom");
        assert_eq!(errors[0].error_type, Some("ChildFnError"));
    }

    // Gap 3: NestingMode tests

    #[test]
    fn nesting_mode_default_is_normal() {
        assert_eq!(NestingMode::default(), NestingMode::Normal);
    }

    #[test]
    fn nesting_mode_equality() {
        assert_ne!(NestingMode::Flat, NestingMode::Normal);
    }

    // Gap 5: Completion reason wire strings

    #[test]
    fn completion_reason_as_str_values() {
        assert_eq!(CompletionReason::AllCompleted.as_str(), "ALL_COMPLETED");
        assert_eq!(
            CompletionReason::MinSuccessfulReached.as_str(),
            "MIN_SUCCESSFUL_REACHED"
        );
        assert_eq!(
            CompletionReason::FailureToleranceExceeded.as_str(),
            "FAILURE_TOLERANCE_EXCEEDED"
        );
        assert_eq!(
            CompletionReason::CustomCompletionSucceeded.as_str(),
            "CUSTOM_COMPLETION_SUCCEEDED"
        );
        assert_eq!(
            CompletionReason::CustomCompletionFailed.as_str(),
            "CUSTOM_COMPLETION_FAILED"
        );
    }

    // Bug 1: Early-stopping race: stopped re-check after acquire

    #[tokio::test]
    async fn early_stop_recheck_after_semaphore_acquire() {
        // Simulates the fix: with concurrency=1, once `stopped` is set, the
        // next iteration must NOT slip through after acquiring the permit.
        let sem = Arc::new(Semaphore::new(1));
        let stopped = Arc::new(AtomicBool::new(false));
        let launched = Arc::new(AtomicUsize::new(0));

        let mut handles = Vec::new();
        for i in 0..3 {
            let sem = Arc::clone(&sem);
            let stopped = Arc::clone(&stopped);
            let launched = Arc::clone(&launched);
            handles.push(tokio::spawn(async move {
                // Acquire
                let permit = sem.acquire_owned().await.unwrap();
                // Re-check stopped AFTER acquire (the fix).
                if stopped.load(Ordering::SeqCst) {
                    drop(permit);
                    return;
                }
                launched.fetch_add(1, Ordering::SeqCst);
                // Simulate work, then stop after item 0.
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
                if i == 0 {
                    stopped.store(true, Ordering::SeqCst);
                }
                drop(permit);
            }));
        }
        for h in handles {
            h.await.unwrap();
        }
        // With the fix, only item 0 should launch (item 1 sees stopped=true
        // after acquiring, item 2 likewise). Without the fix, item 1 would
        // slip through.
        assert_eq!(
            launched.load(Ordering::SeqCst),
            1,
            "only one item should launch before stopped is honoured"
        );
    }

    // Bug 3: FLAT nesting ParentId points to batch parent

    #[test]
    fn flat_child_context_reports_batch_parent_wire_id() {
        let ctx = test_ctx(CheckpointLog::empty());
        // Mint an ID for the batch parent.
        let batch_op = ctx.mint_id();
        let batch_wire = batch_op.wire().to_owned();
        // Mint an ID for the virtual child.
        let child_op = ctx.mint_id();
        let child_positional = child_op.positional().to_owned();
        // Create a flat child context with the batch parent's wire ID.
        let flat_child = ctx.new_flat_child(&child_positional, &batch_wire, None);
        // Operations inside the flat child should report the batch parent
        // as their parent wire ID.
        assert_eq!(
            flat_child.parent_wire_id(),
            Some(batch_wire.as_str()),
            "flat child must report the batch parent's wire ID"
        );
    }

    // BatchResult views and into_result, over hand-built results.

    fn item(index: usize, status: BatchItemStatus, result: Option<i32>) -> BatchItem<i32> {
        BatchItem::new(index, format!("item-{index}"), status, result, None, None)
    }

    fn failed_item(index: usize, message: &str, error_type: Option<&str>) -> BatchItem<i32> {
        BatchItem::new(
            index,
            format!("item-{index}"),
            BatchItemStatus::Failed,
            None,
            Some(message.to_owned()),
            error_type.map(str::to_owned),
        )
    }

    fn indexes<'a>(items: impl Iterator<Item = &'a BatchItem<i32>>) -> Vec<usize> {
        items.map(|item| item.index).collect()
    }

    /// A `parallel_mixed` item serdes with one branch, on a fresh context.
    fn one_branch_mixed_serdes() -> (MixedItemSerdes, crate::BranchHandle<u32>) {
        let mut set = crate::BranchSet::new();
        let handle = set.add("only", |_ctx| async { Ok(1_u32) });
        let (_bodies, decoders, _json) = set.into_parts();
        let batch = OperationId::new("1".to_owned());
        let item_ids = ItemIds::new(&batch, decoders.len());
        (MixedItemSerdes::new(&item_ids, decoders), handle)
    }

    #[tokio::test]
    async fn mixed_item_serdes_rejects_unknown_operation_id() {
        let (serdes, _handle) = one_branch_mixed_serdes();
        let err = serdes
            .deserialize("1".to_owned(), SerdesContext::new("other", "arn:test"))
            .await
            .expect_err("an unknown operation ID is an error");
        assert_eq!(
            err.to_string(),
            r#"parallel_mixed: no branch has operation ID "other""#
        );
    }

    /// `BatchResult::value` reads each succeeded branch with its own key,
    /// whether a branch body or a decoder produced the value, and nothing
    /// for a failed, started or never-started branch, for a key of another
    /// set, or for an item that holds another branch's value.
    #[tokio::test]
    async fn batch_value_reads_each_success_by_its_key() {
        use std::cell::Cell;

        fn assert_send_debug<T: Send + std::fmt::Debug>() {}
        assert_send_debug::<BatchResult<crate::BranchValue>>();

        let mut set = crate::BranchSet::new();
        let label = set.add("label", |_ctx| async { Ok("ready-value".to_owned()) });
        let count = set.add("count", |_ctx| async { Ok(Cell::new(4242_u32)) });
        let failed = set.add("failed", |_ctx| async { Ok(0_u32) });
        let started = set.add("started", |_ctx| async { Ok(0_u32) });
        let never = set.add("never", |_ctx| async { Ok(0_u32) });
        let mut other = crate::BranchSet::new();
        let other_label = other.add("label", |_ctx| async { Ok("other".to_owned()) });

        let (bodies, decoders, _json) = set.into_parts();
        let decode = |index: usize, wire: &str| {
            let decoder = Arc::clone(decoders.get(index).expect("the set has the branch"));
            let wire = wire.to_owned();
            async move {
                decoder
                    .decode(wire, SerdesContext::new("item", "arn:test"))
                    .await
                    .expect("the wire is valid JSON of the branch's type")
            }
        };
        let label_value = decode(0, r#""ready-value""#).await;
        let (_, count_body) = bodies.into_iter().nth(1).expect("the set has branch 1");
        let count_value = count_body
            .start(test_ctx(CheckpointLog::empty()))
            .await
            .expect("the body succeeds");
        let succeeded = |index: usize, name: &str, value| {
            BatchItem::new(
                index,
                name.to_owned(),
                BatchItemStatus::Succeeded,
                Some(value),
                None,
                None,
            )
        };
        let batch = BatchResult::new(
            vec![
                succeeded(0, "label", label_value),
                succeeded(1, "count", count_value),
                BatchItem::new(
                    2,
                    "failed".to_owned(),
                    BatchItemStatus::Failed,
                    None,
                    Some("boom".to_owned()),
                    Some("Error".to_owned()),
                ),
                BatchItem::new(
                    3,
                    "started".to_owned(),
                    BatchItemStatus::Started,
                    None,
                    None,
                    None,
                ),
            ],
            CompletionReason::AllCompleted,
        );

        assert_eq!(
            batch.value(&label.key()).map(String::as_str),
            Some("ready-value")
        );
        assert_eq!(batch.value(&count.key()).map(Cell::get), Some(4242));
        assert_eq!(batch.value(&failed.key()), None);
        assert_eq!(batch.value(&started.key()), None);
        assert_eq!(batch.value(&never.key()), None);
        assert_eq!(batch.value(&other_label.key()), None);

        let first = batch.items.first().expect("the batch has item 0");
        let first = format!("{first:?}");
        assert!(
            first.contains("result: Some(BranchValue { .. })"),
            "{first}"
        );
        assert!(!first.contains("ready-value"), "{first}");
        assert_eq!(
            format!("{:?}", batch.results().collect::<Vec<_>>()),
            "[BranchValue { .. }, BranchValue { .. }]"
        );
        let text = format!("{batch:?}");
        assert!(text.contains("BranchValue { .. }"), "{text}");
        assert!(!text.contains("ready-value"), "{text}");
        assert!(!text.contains("4242"), "{text}");

        // An item whose index names one branch but whose value belongs to
        // another branch reads as nothing for the first branch's key.
        let misplaced = BatchResult::new(
            vec![succeeded(0, "label", decode(1, "4242").await)],
            CompletionReason::AllCompleted,
        );
        assert_eq!(misplaced.value(&label.key()), None);
    }

    #[tokio::test]
    async fn mixed_item_serdes_uses_item_id_table() {
        let mut set = crate::BranchSet::new();
        let _first = set.add("first", |_ctx| async { Ok(1_u32) });
        let second = set.add("second", |_ctx| async { Ok(2_u32) });
        let (_bodies, decoders, _json) = set.into_parts();
        let batch = OperationId::new("1".to_owned());
        let item_ids = ItemIds::new(&batch, decoders.len());
        let serdes = MixedItemSerdes::new(&item_ids, decoders);
        // With no registration, the wire ID of `1-2` names branch 1: the
        // serdes reads it from the table, and publishing the decoded value
        // fills branch 1's handle.
        let child = SerdesContext::new(crate::engine::compute_wire_id_public("1-2"), "arn:test");
        let value = serdes
            .deserialize("7".to_owned(), child)
            .await
            .expect("the ID 1-2 names branch 1");
        value.publish();
        assert_eq!(second.into_result().expect("branch 1 holds a value"), 7);
    }

    #[test]
    fn publish_outcome_publishes_nothing_for_an_error_or_a_valueless_item() {
        let mut set = crate::BranchSet::new();
        let handle = set.add("only", |_ctx| async { Ok(1_u32) });
        let (_bodies, decoders, _json) = set.into_parts();
        let err = publish_outcome(Err(batch_error("checkpoint failed")), &decoders)
            .expect_err("the batch error is returned");
        assert_eq!(
            format!("{err:#}"),
            format!("{:#}", batch_error("checkpoint failed"))
        );
        // A succeeded item without a value publishes nothing either.
        let item = BatchItem::<crate::future::BranchValue>::new(
            0,
            "only".to_owned(),
            BatchItemStatus::Succeeded,
            None,
            None,
            None,
        );
        let reason = publish_outcome(
            Ok(BatchResult::new(vec![item], CompletionReason::AllCompleted)),
            &decoders,
        )
        .expect("an all-completed batch succeeds");
        assert_eq!(reason, CompletionReason::AllCompleted);
        let err = handle.into_result().expect_err("the handle has no result");
        assert!(matches!(
            err.kind(),
            OperationErrorKind::ChildContext(child)
                if matches!(child.kind(), ChildContextErrorKind::NotCompleted)
        ));
    }

    #[test]
    fn parallel_mixed_builder_debug_shows_the_name() {
        let ctx = test_ctx(CheckpointLog::empty());
        let builder = ctx.parallel_mixed(crate::BranchSet::new()).name("pm");
        assert_eq!(
            format!("{builder:?}"),
            r#"ParallelMixedBuilder { name: Some("pm"), .. }"#
        );
    }

    #[test]
    fn publish_outcome_skips_item_without_branch() {
        let mut set = crate::BranchSet::new();
        let handle = set.add("only", |_ctx| async { Ok(1_u32) });
        let (_bodies, decoders, _json) = set.into_parts();
        let failed = |index: usize| {
            BatchItem::<crate::future::BranchValue>::new(
                index,
                format!("item-{index}"),
                BatchItemStatus::Failed,
                None,
                Some(format!("boom-{index}")),
                Some(format!("Type{index}")),
            )
        };
        let batch = BatchResult::new(
            vec![failed(0), failed(1)],
            CompletionReason::FailureToleranceExceeded,
        );
        let err = publish_outcome(Ok(batch), &decoders)
            .expect_err("a batch over its failure tolerance fails");
        let wire = err.wire().expect("the error carries item 0's record");
        assert_eq!(wire.error_type(), Some("Type0"));
        assert_eq!(wire.error_message(), Some("boom-0"));
        let held = handle
            .into_result()
            .expect_err("handle 0 holds item 0's error");
        let held = held.wire().expect("the handle's error carries a record");
        assert_eq!(held.error_type(), Some("Type0"));
        assert_eq!(held.error_message(), Some("boom-0"));
    }

    /// A batch whose reason is `FailureToleranceExceeded` but that holds no
    /// failed item, as only a corrupt record can, fails with the internal
    /// error `failure tolerance exceeded`. `parallel(...).await` and
    /// `parallel_mixed(...).await` return that same error.
    #[test]
    fn tolerance_exceeded_without_failed_item_is_an_internal_error() {
        let batch = || {
            BatchResult::new(
                vec![item(0, BatchItemStatus::Succeeded, Some(1))],
                CompletionReason::FailureToleranceExceeded,
            )
        };
        let is_tolerance_error = |err: &OperationError| {
            matches!(
                err.kind(),
                OperationErrorKind::ChildContext(child)
                    if matches!(child.kind(), ChildContextErrorKind::Internal)
            ) && crate::error::chain_string(err).contains("failure tolerance exceeded")
        };
        let err = await_error(&batch()).expect("the reason is a failing reason");
        assert!(is_tolerance_error(&err), "{err:?}");
        let err = collect_successful(batch()).expect_err("parallel fails the batch");
        assert!(is_tolerance_error(&err), "{err:?}");
        let mixed = BatchResult::<crate::future::BranchValue>::new(
            Vec::new(),
            CompletionReason::FailureToleranceExceeded,
        );
        let err = publish_outcome(Ok(mixed), &[]).expect_err("parallel_mixed fails the batch");
        assert!(is_tolerance_error(&err), "{err:?}");
    }

    #[test]
    fn batch_result_views_split_by_status() {
        let batch = BatchResult::new(
            vec![
                item(0, BatchItemStatus::Succeeded, Some(1)),
                failed_item(1, "boom", None),
                item(2, BatchItemStatus::Started, None),
                item(3, BatchItemStatus::Succeeded, Some(4)),
            ],
            CompletionReason::MinSuccessfulReached,
        );
        assert_eq!(indexes(batch.succeeded()), [0, 3]);
        assert_eq!(indexes(batch.failed()), [1]);
        assert_eq!(indexes(batch.started()), [2]);
        assert_eq!(batch.started_count(), 1);
    }

    #[test]
    fn into_result_returns_first_failure() {
        let batch = BatchResult::new(
            vec![
                item(0, BatchItemStatus::Succeeded, Some(1)),
                failed_item(1, "a", Some("AError")),
                failed_item(2, "b", None),
            ],
            CompletionReason::AllCompleted,
        );
        let err = batch.into_result().expect_err("an item failed");
        let OperationErrorKind::ChildContext(child_err) = err.kind() else {
            unreachable!("expected a child-context error, got {:?}", err.kind());
        };
        assert!(matches!(
            child_err.kind(),
            ChildContextErrorKind::ChildFailed
        ));
        let wire = err.wire().expect("the item's wire record is attached");
        assert_eq!(wire.error_type(), Some("AError"));
        assert_eq!(wire.error_message(), Some("a"));
    }

    #[test]
    fn into_result_returns_completion_error_without_failed_item() {
        let batch = BatchResult::new(
            vec![item(0, BatchItemStatus::Succeeded, Some(1))],
            CompletionReason::CustomCompletionFailed,
        );
        let err = batch.into_result().expect_err("the batch status is Failed");
        let OperationErrorKind::ChildContext(child_err) = err.kind() else {
            unreachable!("expected a child-context error, got {:?}", err.kind());
        };
        assert!(matches!(
            child_err.kind(),
            ChildContextErrorKind::BatchCompletionFailed
        ));
        let wire = err.wire().expect("the completion wire record is attached");
        assert_eq!(wire.error_type(), Some("BatchCompletionError"));
    }

    #[test]
    fn into_result_keeps_a_successful_batch() {
        let batch = BatchResult::new(
            vec![
                item(0, BatchItemStatus::Succeeded, Some(1)),
                item(1, BatchItemStatus::Started, None),
            ],
            CompletionReason::MinSuccessfulReached,
        );
        let batch = batch.into_result().expect("no item failed");
        let items: Vec<_> = batch
            .items
            .iter()
            .map(|item| (item.index, item.status, item.result))
            .collect();
        assert_eq!(
            items,
            [
                (0, BatchItemStatus::Succeeded, Some(1)),
                (1, BatchItemStatus::Started, None),
            ]
        );
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
    }

    // Checkpoint serialization tests

    /// A token-validating execution client that rejects checkpoint calls
    /// with stale tokens: simulating the service's actual behavior.
    /// Used to verify that concurrent callers are properly serialized.
    #[derive(Debug)]
    struct TokenValidatingClient {
        /// The current expected token; only calls with this token succeed.
        current_token: std::sync::Mutex<String>,
        /// Counter for generating unique next tokens.
        counter: std::sync::Mutex<u32>,
        /// Count of successful checkpoint calls.
        success_count: std::sync::Mutex<u32>,
        /// Count of calls that arrived with a stale (wrong) token.
        stale_token_count: std::sync::Mutex<u32>,
    }

    impl TokenValidatingClient {
        fn new(initial_token: &str) -> Self {
            Self {
                current_token: std::sync::Mutex::new(initial_token.to_owned()),
                counter: std::sync::Mutex::new(0),
                success_count: std::sync::Mutex::new(0),
                stale_token_count: std::sync::Mutex::new(0),
            }
        }

        fn success_count(&self) -> u32 {
            *self
                .success_count
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
        }

        fn stale_token_count(&self) -> u32 {
            *self
                .stale_token_count
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
        }
    }

    impl crate::client::ExecutionClient for TokenValidatingClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            checkpoint_token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::CheckpointOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            let submitted_token = checkpoint_token.to_owned();
            Box::pin(async move {
                // Simulate a brief network delay to increase race window.
                tokio::task::yield_now().await;

                let mut current = self
                    .current_token
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);

                if *current != submitted_token {
                    // Stale token: the real service would return an error.
                    let mut stale = self
                        .stale_token_count
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    *stale += 1;
                    return Err(crate::client::ExecutionClientError::non_retryable(format!(
                        "stale checkpoint token: expected {}, got {}",
                        *current, submitted_token
                    )));
                }

                // Rotate the token.
                let mut counter = self
                    .counter
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                *counter += 1;
                let new_token = format!("token-{counter}");
                *current = new_token.clone();

                let mut success = self
                    .success_count
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                *success += 1;

                Ok(crate::client::CheckpointOutput {
                    checkpoint_token: Some(new_token),
                    updated_operations: Vec::new(),
                    next_marker: None,
                })
            })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _marker: Option<&str>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::GetStateOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async { Ok(crate::client::GetStateOutput::new(Vec::new(), None)) })
        }
    }

    #[tokio::test]
    async fn concurrent_checkpoint_serialization_no_token_conflict() {
        // Spawn N tasks that all call checkpoint_updates concurrently.
        // With the tokio::sync::Mutex serialization, NO stale token errors
        // should occur. Without it, the token-validating client would
        // reject concurrent calls.
        let client = Arc::new(TokenValidatingClient::new("initial-token"));
        let log = Arc::new(CheckpointLog::empty());
        let ctx = DurableContext::new_root_with_client(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::clone(&log),
            client.clone() as Arc<dyn crate::client::ExecutionClient>,
            "initial-token".to_owned(),
        );

        let num_concurrent = 10;
        let mut handles = Vec::new();

        for i in 0..num_concurrent {
            let ctx = ctx.clone();
            handles.push(tokio::spawn(async move {
                let update = OperationUpdate::builder()
                    .id(format!("op-{i}"))
                    .r#type(OperationType::Context)
                    .sub_type("Test")
                    .action(OperationAction::Succeed)
                    .build()
                    .expect("valid update");
                ctx.checkpoint_updates(vec![update]).await
            }));
        }

        let mut success_count = 0_u32;
        for handle in handles {
            let result = handle.await.expect("task should not panic");
            assert!(
                result.is_ok(),
                "checkpoint should succeed due to serialization: {:?}",
                result.unwrap_err()
            );
            success_count += 1;
        }

        assert_eq!(success_count, num_concurrent);
        assert_eq!(client.success_count(), num_concurrent);
        assert_eq!(
            client.stale_token_count(),
            0,
            "no stale token conflicts should occur with serialization"
        );
    }

    #[tokio::test]
    async fn fail_fast_then_parent_terminal_checkpoint_emitted() {
        // Simulates a parallel batch where one branch fails (triggering
        // fail-fast via tolerated_failure_count=0). The parent SUCCEED
        // checkpoint must still be emitted after the failed branch's
        // best-effort FAIL checkpoint.
        //
        // With serialization, the parent's succeed checkpoint waits for
        // any in-flight child checkpoints to complete, then uses the
        // latest token: ensuring it succeeds.
        let client = Arc::new(TokenValidatingClient::new("initial-token"));
        let log = Arc::new(CheckpointLog::empty());
        let ctx = DurableContext::new_root_with_client(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::clone(&log),
            client.clone() as Arc<dyn crate::client::ExecutionClient>,
            "initial-token".to_owned(),
        );

        // Run a parallel batch: 3 branches, first fails, tolerated=0.
        // This triggers fail-fast after the first failure.
        // The public API converts FailureToleranceExceeded to an error,
        // but the internal batch engine still emits the parent terminal
        // checkpoint (ContextSucceeded) before returning.
        let result: Result<Vec<i32>, _> = ctx
            .parallel(vec![
                crate::future::Branch::new("fail", |_ctx| {
                    Box::pin(async { Err("intentional".into()) })
                }),
                crate::future::Branch::new("ok-1", |_ctx| Box::pin(async { Ok(1) })),
                crate::future::Branch::new("ok-2", |_ctx| Box::pin(async { Ok(2) })),
            ])
            .completion(
                crate::builders::map_parallel::CompletionConfig::builder()
                    .tolerated_failure_count(0)
                    .build()
                    .expect("valid completion config"),
            )
            .await;

        // The public API propagates failures as errors: that's correct
        // behavior. The key assertion is that no stale-token conflicts
        // occurred during the batch execution.
        assert!(
            result.is_err(),
            "parallel with fail-fast should surface the first failure"
        );

        // Critically: no stale token conflicts occurred, meaning the
        // parent succeed checkpoint was properly serialized after the
        // child fail checkpoint.
        assert_eq!(
            client.stale_token_count(),
            0,
            "all checkpoints must serialize without token conflicts"
        );

        // At minimum: parent START + child START + child FAIL + parent SUCCEED = 4.
        // (Other children may or may not start depending on scheduling.)
        assert!(
            client.success_count() >= 4,
            "expected at least 4 checkpoint calls (parent start + child start + child fail + parent succeed), got {}",
            client.success_count()
        );
    }

    /// Drives `run` through the invocation driver over a fresh recording
    /// context, asserts that the driver returned a panic, and returns its
    /// `&'static str` payload and whether any recorded update has action `FAIL`.
    async fn panic_of<F, Fut>(run: F) -> (Option<&'static str>, bool)
    where
        F: FnOnce(DurableContext) -> Fut,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let handler = run(ctx);
        let outcome = crate::driver::drive_outcome(
            async move {
                handler.await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        let Err(payload) = outcome else {
            unreachable!("the item panic must reach the invocation driver, got {outcome:?}");
        };
        let wrote_fail = client
            .recorded_updates()
            .iter()
            .any(|u| matches!(u.action(), OperationAction::Fail));
        (
            crate::task::test_support::str_payload(payload.as_ref()),
            wrote_fail,
        )
    }

    /// A panic in a map item fails the invocation with its original
    /// payload, and the batch records no failure for it.
    #[tokio::test]
    async fn map_item_panic_propagates_payload() {
        let (message, wrote_fail) = panic_of(|ctx| async move {
            let _ = ctx
                .map(vec![0_i32, 1], |_child, _item: i32, idx| async move {
                    assert!(idx != 1, "boom in map branch");
                    Ok(idx)
                })
                .await;
        })
        .await;
        assert_eq!(message, Some("boom in map branch"));
        assert!(!wrote_fail, "a panic records no FAIL");
    }

    /// A panic in a parallel branch fails the invocation with its original
    /// payload, and the batch records no failure for it.
    #[tokio::test]
    #[expect(clippy::panic)] // reason: the branch panic under test is the behavior being asserted
    async fn parallel_branch_panic_propagates_payload() {
        use crate::future::Branch;

        let (message, wrote_fail) = panic_of(|ctx| async move {
            let _ = ctx
                .parallel(vec![
                    Branch::new("steady", |_ctx| async move { Ok(1_i32) }),
                    Branch::new(
                        "boom",
                        |_ctx| async move { panic!("boom in parallel branch") },
                    ),
                ])
                .await;
        })
        .await;
        assert_eq!(message, Some("boom in parallel branch"));
        assert!(!wrote_fail, "a panic records no FAIL");
    }

    /// Polls `run` once on a thread with no Tokio runtime and asserts that
    /// the batch resolved to the no-runtime error, instead of panicking.
    fn assert_batch_no_runtime_error<F, Fut>(log: CheckpointLog, run: F)
    where
        F: FnOnce(DurableContext) -> Fut + Send + 'static,
        Fut: Future<Output = Result<Vec<i32>, OperationError>>,
    {
        // The context is built on the polling thread, so that thread owns it.
        let polled = crate::task::test_support::poll_once_without_runtime(move || {
            run(test_ctx_with_client(log).0)
        });
        let std::task::Poll::Ready(Err(err)) = polled else {
            unreachable!("expected an immediate error, got {polled:?}");
        };
        assert!(
            format!("{err:#}").contains(crate::task::NO_RUNTIME_MESSAGE),
            "unexpected error: {err:#}"
        );
    }

    #[test]
    fn map_without_runtime_returns_error() {
        assert_batch_no_runtime_error(CheckpointLog::empty(), |ctx| {
            ctx.map(
                vec![0_i32],
                |_child, item: i32, _idx| async move { Ok(item) },
            )
            .into_future()
        });
    }

    #[test]
    fn parallel_without_runtime_returns_error() {
        use crate::future::Branch;

        assert_batch_no_runtime_error(CheckpointLog::empty(), |ctx| {
            ctx.parallel(vec![Branch::new("one", |_ctx| async move { Ok(1_i32) })])
                .into_future()
        });
    }

    /// The reconstruction of a `ReplayChildren` item needs a task too.
    #[test]
    fn map_reconstruction_without_runtime_returns_error() {
        let log = CheckpointLog::from_records(vec![replay_children_success_record("2")]);
        assert_batch_no_runtime_error(log, |ctx| {
            ctx.map(
                vec![1_i32],
                |_child, item: i32, _idx| async move { Ok(item) },
            )
            .into_future()
        });
    }

    #[tokio::test]
    #[expect(clippy::panic)] // reason: the reconstruction panic under test is the behavior being asserted
    async fn map_replay_children_reconstruction_panic_unwinds_without_fail_checkpoint() {
        // A child recorded as terminal SUCCESS with `replay_children = true`
        // is re-executed on replay to reconstruct its oversized result. If
        // that reconstruction panics, the panic must unwind the coordinator
        // with the original payload, preserving the recorded success
        // history for the next attempt, NOT be graded as a branch failure
        // with a child FAIL checkpoint, which would overwrite durable
        // success and permanently fail the batch over a transient crash.
        let log = CheckpointLog::from_records(vec![replay_children_success_record("2")]);
        let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let task_client = Arc::clone(&client);

        // The context is created INSIDE the spawned task so the task owns
        // it: the unwind of that task is the observable coordinator unwind.
        let handle = tokio::spawn(async move {
            let ctx = DurableContext::new_root_with_client(
                "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
                lambda_runtime::Context::default(),
                Arc::new(log),
                task_client as Arc<dyn crate::client::ExecutionClient>,
                "token0".to_owned(),
            );
            let result: Result<Vec<i32>, OperationError> = ctx
                .map(vec![1_i32], |_child, _item: i32, _idx| async move {
                    panic!("boom in map reconstruction")
                })
                .await;
            result
        });

        let join_err = handle
            .await
            .expect_err("a reconstruction panic must unwind the coordinator, not settle");
        assert!(
            join_err.is_panic(),
            "the coordinator must rethrow the original panic payload"
        );
        let payload = join_err.into_panic();
        let message = payload
            .downcast_ref::<&str>()
            .map(|s| (*s).to_owned())
            .or_else(|| payload.downcast_ref::<String>().cloned());
        assert_eq!(
            message.as_deref(),
            Some("boom in map reconstruction"),
            "the rethrown payload must be the reconstruction panic's own"
        );

        // The recorded terminal success stays authoritative: nothing may be
        // checkpointed as FAILED on this path.
        assert!(
            client
                .recorded_updates()
                .iter()
                .all(|u| !matches!(u.action(), OperationAction::Fail)),
            "a reconstruction panic must not checkpoint any failure"
        );
    }

    #[tokio::test]
    #[expect(clippy::panic)] // reason: the reconstruction panic under test is the behavior being asserted
    async fn parallel_replay_children_reconstruction_panic_unwinds_without_fail_checkpoint() {
        use crate::future::Branch;

        // Same guarantee for parallel, through the concurrent replay pass:
        // branch 0 replays from a normal recorded success; branch 1 is
        // recorded ReplayChildren and its reconstruction panics. The panic
        // must unwind the coordinator without checkpointing failure.
        let log = CheckpointLog::from_records(vec![
            succeeded_record("2", "7"),
            replay_children_success_record("3"),
        ]);
        let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
        let task_client = Arc::clone(&client);

        // The context is created INSIDE the spawned task so the task owns
        // it: the unwind of that task is the observable coordinator unwind.
        let handle = tokio::spawn(async move {
            let ctx = DurableContext::new_root_with_client(
                "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
                lambda_runtime::Context::default(),
                Arc::new(log),
                task_client as Arc<dyn crate::client::ExecutionClient>,
                "token0".to_owned(),
            );
            let result: Result<Vec<i32>, OperationError> = ctx
                .parallel(vec![
                    // Replayed from the record; never re-executed.
                    Branch::new("steady", |_ctx| async move { Ok(999_i32) }),
                    Branch::new("boom", |_ctx| async move {
                        panic!("boom in parallel reconstruction")
                    }),
                ])
                .await;
            result
        });

        let join_err = handle
            .await
            .expect_err("a reconstruction panic must unwind the coordinator, not settle");
        assert!(
            join_err.is_panic(),
            "the coordinator must rethrow the original panic payload"
        );
        let payload = join_err.into_panic();
        let message = payload
            .downcast_ref::<&str>()
            .map(|s| (*s).to_owned())
            .or_else(|| payload.downcast_ref::<String>().cloned());
        assert_eq!(
            message.as_deref(),
            Some("boom in parallel reconstruction"),
            "the rethrown payload must be the reconstruction panic's own"
        );

        assert!(
            client
                .recorded_updates()
                .iter()
                .all(|u| !matches!(u.action(), OperationAction::Fail)),
            "a reconstruction panic must not checkpoint any failure"
        );
    }

    // Serialization-model equivalence tests
    //
    // These prove the point of the normalization: ONE `Serdes`
    // implementation, one that implements only the JSON-string transform
    // methods, behaves identically as a map item serdes, a parallel item
    // serdes, and a step serdes. Before the normalization, map/parallel item
    // results went through a separate mandatory byte API plus a runtime
    // downcast, so a serdes like this one could not even be written.

    /// A payload whose stored wire form plain `serde_json` cannot parse, and
    /// whose JSON needs real escaping (quotes, backslash, newline, non-ASCII).
    #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    struct Doc {
        label: String,
        nested: Vec<Vec<i64>>,
    }

    fn probe_doc() -> Doc {
        Doc {
            label: "quote:\" backslash:\\ newline:\n tab:\t ünïcodé ☃".to_owned(),
            nested: vec![vec![1, -2, i64::MIN], Vec::new()],
        }
    }

    /// Payloads recorded on SUCCEED updates that carry a `ParentId` (i.e. the
    /// map children / parallel branches, not the batch parent).
    fn child_success_payloads(client: &crate::client::InMemoryExecutionClient) -> Vec<String> {
        client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Succeed) && u.parent_id().is_some())
            .filter_map(|u| u.payload().map(str::to_owned))
            .collect()
    }

    /// The wire form a step, a map item and a parallel branch produce for the
    /// same value through the same custom serdes must be byte-identical, and
    /// each must round-trip back to the original value.
    #[tokio::test]
    async fn custom_serdes_is_equivalent_on_step_map_and_parallel_paths() {
        use crate::future::Branch;
        use crate::serdes::test_support::{HexEnvelopeSerdes, hex_envelope};

        let doc = probe_doc();
        let expected_wire = hex_envelope(&serde_json::to_string(&doc).expect("doc is JSON-able"));

        // Control: the wire form is NOT valid JSON, so any path that skipped
        // the serdes transform would fail rather than silently pass.
        assert!(
            serde_json::from_str::<Doc>(&expected_wire).is_err(),
            "the probe wire form must be unparseable by plain serde_json"
        );

        // step
        let (step_ctx, step_client) = test_ctx_with_client(CheckpointLog::empty());
        let step_doc = doc.clone();
        let step_out: Doc = step_ctx
            .step(move |_| {
                let d = step_doc.clone();
                async move { Ok(d) }
            })
            .serdes(HexEnvelopeSerdes)
            .await
            .expect("step with a string-transform serdes must succeed");
        assert_eq!(step_out, doc, "step must round-trip the value");
        let step_wire: Vec<String> = step_client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Succeed))
            .filter_map(|u| u.payload().map(str::to_owned))
            .collect();
        assert_eq!(step_wire, vec![expected_wire.clone()]);

        // map items
        let (map_ctx, map_client) = test_ctx_with_client(CheckpointLog::empty());
        let map_doc = doc.clone();
        let map_out: Vec<Doc> = map_ctx
            .map(vec![0_usize], move |_child, _item, _idx| {
                let d = map_doc.clone();
                async move { Ok(d) }
            })
            .serdes(HexEnvelopeSerdes)
            .await
            .expect("map with a string-transform item serdes must succeed");
        assert_eq!(map_out, vec![doc.clone()], "map must round-trip the value");
        assert_eq!(
            child_success_payloads(&map_client),
            vec![expected_wire.clone()],
            "a map item must produce the same wire form as a step"
        );

        // parallel branches
        let (par_ctx, par_client) = test_ctx_with_client(CheckpointLog::empty());
        let par_doc = doc.clone();
        let par_out: Vec<Doc> = par_ctx
            .parallel(vec![Branch::new("only", move |_c| {
                let d = par_doc.clone();
                async move { Ok(d) }
            })])
            .serdes(HexEnvelopeSerdes)
            .await
            .expect("parallel with a string-transform item serdes must succeed");
        assert_eq!(par_out, vec![doc], "parallel must round-trip the value");
        assert_eq!(
            child_success_payloads(&par_client),
            vec![expected_wire],
            "a parallel branch must produce the same wire form as a step"
        );
    }

    /// Every path hands a custom serdes its own typed value.
    ///
    /// The step, invoke, callback and map/parallel item serdes are handed
    /// the identical typed value. A quoting divergence between items (`X`)
    /// and everything else (`"X"`) once survived all the way to
    /// conformance case 9-14, so this test asserts every path. The batch
    /// result serdes is a `Serdes<String>`: it is handed a `String` that
    /// holds the batch record text.
    ///
    /// The probe payload is a bare `String`, the one case where the old split
    /// was visible, and the fixture's wire form is deliberately NOT JSON, so
    /// a path that bypassed the serdes would fail rather than quietly pass.
    #[tokio::test]
    #[expect(clippy::too_many_lines)] // reason: one test per path is the point; splitting it would let the paths drift apart again
    async fn custom_serdes_receives_its_typed_value_on_every_path() {
        use crate::future::Branch;
        use crate::serdes::test_support::{RecordingSerdes, hex_envelope_of};

        let value = "X".to_owned();
        // The one shape every path must provide.
        let expected = serde_json::json!("X");
        // What a *string*-boundary serdes would have received instead.
        let json_encoding = serde_json::to_string(&value).expect("a string is JSON-able");
        assert_eq!(json_encoding, "\"X\"");

        let wire = hex_envelope_of(&expected);
        assert!(
            serde_json::from_str::<String>(&wire).is_err(),
            "the probe wire form must be unparseable by plain serde_json, so a \
             path that skipped the transform cannot pass by accident"
        );

        // step
        let step_rec = RecordingSerdes::new();
        let (step_ctx, step_client) = test_ctx_with_client(CheckpointLog::empty());
        let step_value = value.clone();
        let step_out: String = step_ctx
            .step(move |_| {
                let v = step_value.clone();
                async move { Ok(v) }
            })
            .serdes(step_rec.clone())
            .await
            .expect("step with a recording serdes must succeed");
        assert_eq!(step_out, value, "step must round-trip the value");
        assert_eq!(
            step_rec.serialize_inputs(),
            vec![expected.clone()],
            "a step serdes must be handed the value, not its JSON encoding"
        );
        let step_wire: Vec<String> = step_client
            .recorded_updates()
            .iter()
            .filter(|u| matches!(u.action(), OperationAction::Succeed))
            .filter_map(|u| u.payload().map(str::to_owned))
            .collect();
        assert_eq!(step_wire, vec![wire.clone()]);

        // invoke payload
        let invoke_rec = RecordingSerdes::new();
        let (invoke_ctx, _invoke_client) = test_ctx_with_client(CheckpointLog::empty());
        let signal = Arc::clone(invoke_ctx.coordinator());
        let invoke_fut = invoke_ctx
            .invoke::<String>("target-fn", value.clone())
            .payload_serdes(invoke_rec.clone());
        let outcome = crate::driver::test_support::outcome_of(
            invoke_ctx.clone(),
            Arc::clone(invoke_ctx.task_ownership()),
            signal,
            invoke_fut,
        )
        .await;
        assert_eq!(outcome, crate::driver::InvocationOutcome::Pending);
        assert_eq!(
            invoke_rec.serialize_inputs(),
            vec![expected.clone()],
            "an invoke payload serdes must be handed the same value shape as a step"
        );

        // callback (deserialize-only path)
        //
        // Callbacks have no serialize side (an external caller writes the
        // payload), and `deserialize_callback_result` IS the whole boundary:
        // it is the only place the callback replay path consults a serdes. It
        // is fed the EXACT wire form the step path wrote above, so this asserts
        // the two paths agree on the reconstructed shape.
        let callback_rec = RecordingSerdes::new();
        let callback_ctx = SerdesContext::new("cb-1", "arn:test");
        let callback_out: String = crate::callback::deserialize_callback_result(
            &step_ctx,
            None,
            &callback_rec.clone(),
            wire.clone(),
            callback_ctx,
        )
        .await
        .expect("the callback path must decode the wire form the step path wrote");
        assert_eq!(callback_out, value, "callback must round-trip the value");
        assert_eq!(
            callback_rec.deserialize_outputs(),
            vec![expected.clone()],
            "the callback path must reconstruct the same value shape the step \
             path handed the serdes"
        );

        // map items
        //
        // The item serdes is consulted once per item, for the child's own
        // checkpoint. The batch summary takes the item value from the
        // child's wire string, so it calls no serdes.
        let map_rec = RecordingSerdes::new();
        let (map_ctx, _map_client) = test_ctx_with_client(CheckpointLog::empty());
        let map_value = value.clone();
        let map_out: Vec<String> = map_ctx
            .map(vec![0_usize], move |_child, _item, _idx| {
                let v = map_value.clone();
                async move { Ok(v) }
            })
            .serdes(map_rec.clone())
            .await
            .expect("map with a recording item serdes must succeed");
        assert_eq!(map_out, vec![value.clone()]);
        let map_inputs = map_rec.serialize_inputs();
        assert_eq!(
            map_inputs.len(),
            1,
            "the item serdes serializes the item once, for the child \
             checkpoint, got {map_inputs:?}"
        );
        assert_eq!(
            map_rec.distinct_serialize_inputs(),
            vec![expected.clone()],
            "every map item serdes call must be handed the identical value \
             shape, got {map_inputs:?}"
        );

        // parallel branches
        let par_rec = RecordingSerdes::new();
        let (par_ctx, _par_client) = test_ctx_with_client(CheckpointLog::empty());
        let par_value = value.clone();
        let par_out: Vec<String> = par_ctx
            .parallel(vec![Branch::new("only", move |_c| {
                let v = par_value.clone();
                async move { Ok(v) }
            })])
            .serdes(par_rec.clone())
            .await
            .expect("parallel with a recording item serdes must succeed");
        assert_eq!(par_out, vec![value.clone()]);
        assert_eq!(
            par_rec.distinct_serialize_inputs(),
            vec![expected.clone()],
            "a parallel branch serdes must be handed the same value shape"
        );

        // whole batch result
        //
        // The batch result serdes is a `Serdes<String>`. It is handed one
        // `String`: the batch record text. With the default item serdes,
        // the item's JSON text is embedded unchanged, as JS embeds the
        // value.
        let batch_rec = RecordingSerdes::new();
        let (batch_ctx, _batch_client) = test_ctx_with_client(CheckpointLog::empty());
        let batch_value = value.clone();
        let batch_out: Vec<String> = batch_ctx
            .map(vec![0_usize], move |_child, _item, _idx| {
                let v = batch_value.clone();
                async move { Ok(v) }
            })
            .result_serdes(batch_rec.clone())
            .await
            .expect("map with a recording result serdes must succeed");
        assert_eq!(batch_out, vec![value]);
        let batch_inputs = batch_rec.serialize_inputs();
        assert_eq!(
            batch_inputs,
            vec![serde_json::Value::String(format!(
                r#"{{"all":[{{"index":0,"status":"SUCCEEDED","name":"map-item-0","result":{json_encoding}}}],"completionReason":"ALL_COMPLETED"}}"#
            ))],
            "the batch result serdes must be handed the record text once"
        );
    }

    /// Replay must reverse the same transform: a terminal map child whose
    /// stored payload is the custom (non-JSON) wire form is decoded back to
    /// the typed value, with no downcast involved.
    #[tokio::test]
    async fn custom_serdes_item_replay_reverses_the_transform() {
        use crate::serdes::test_support::{HexEnvelopeSerdes, hex_envelope};

        let doc = probe_doc();
        let wire = hex_envelope(&serde_json::to_string(&doc).expect("doc is JSON-able"));

        // Batch parent "1" started; its single child "1-1" already succeeded
        // with the custom wire form in the log.
        let parent_wire_id = crate::engine::compute_wire_id_public("1");
        let child_wire_id = crate::engine::compute_wire_id_public("1-1");
        let log = CheckpointLog::from_records(vec![
            (
                parent_wire_id.clone(),
                CheckpointRecord {
                    id: parent_wire_id,
                    status: CheckpointStatus::Started,
                    result: None,
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
            (
                child_wire_id.clone(),
                CheckpointRecord {
                    id: child_wire_id,
                    status: CheckpointStatus::Succeeded,
                    result: Some(wire),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
        ]);
        let (ctx, _client) = test_ctx_with_client(log);

        let out: Vec<Doc> = ctx
            .map(vec![0_usize], |_child, _item, _idx| async move {
                unreachable!("a terminal child must be replayed, not re-executed")
            })
            .serdes(HexEnvelopeSerdes)
            .await
            .expect("replay of a custom-serdes item must succeed");
        assert_eq!(out, vec![probe_doc()]);
    }

    /// `FileSystemSerdes` used as a map ITEM serdes. This is the exact case    /// that failed at runtime before the normalization: the byte methods it
    /// was forced to implement returned an error, so the item path errored
    /// even though the same serdes worked on steps and batch results.
    ///
    /// It also pins per-item context identity: each item must resolve to its
    /// own file, otherwise every item would read back the last one written.
    #[tokio::test]
    async fn filesystem_serdes_works_as_a_map_item_serdes() {
        let tmp = std::env::temp_dir().join("map_item_fs_serdes");
        let _ = std::fs::remove_dir_all(&tmp);

        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let out: Vec<String> = ctx
            .map(vec![1_i32, 2, 3], |_child, item, _idx| async move {
                Ok(format!("item-{item}"))
            })
            .serdes(crate::serdes::FileSystemSerdes::new(
                tmp.to_string_lossy().to_string(),
            ))
            .await
            .expect("FileSystemSerdes must work as a map item serdes");
        assert_eq!(out, vec!["item-1", "item-2", "item-3"]);

        // Every item envelope must be a DISTINCT file pointer.
        let payloads = child_success_payloads(&client);
        assert_eq!(payloads.len(), 3, "payloads: {payloads:?}");
        let mut files: Vec<String> = payloads
            .iter()
            .map(|p| {
                let v: serde_json::Value =
                    serde_json::from_str(p).expect("envelope must be valid JSON");
                v.get("file")
                    .and_then(serde_json::Value::as_str)
                    .expect("envelope must be a file pointer")
                    .to_owned()
            })
            .collect();
        files.sort();
        files.dedup();
        assert_eq!(files.len(), 3, "each item needs its own file: {files:?}");

        let _ = std::fs::remove_dir_all(&tmp);
    }

    // Issue #36: ordered lazy admission + batch decision record

    /// Splits the recorded updates into child starts seen BEFORE the first
    /// child terminal write and the total child start count. A child update
    /// is one carrying a `ParentId`.
    fn child_starts_before_first_terminal(
        client: &crate::client::InMemoryExecutionClient,
    ) -> (usize, usize) {
        let updates = client.recorded_updates();
        let mut starts_before_first_terminal = 0;
        let mut total_starts = 0;
        let mut saw_terminal = false;
        for u in &updates {
            if u.parent_id().is_none() {
                continue;
            }
            match u.action() {
                OperationAction::Start => {
                    total_starts += 1;
                    if !saw_terminal {
                        starts_before_first_terminal += 1;
                    }
                }
                _ => saw_terminal = true,
            }
        }
        (starts_before_first_terminal, total_starts)
    }

    /// Acceptance (issue #36): a batch larger than the concurrency limit
    /// issues no child `Start` checkpoint before its first item runs.
    /// Ordered lazy admission writes each `Start` at dispatch, so at most
    /// `concurrency` starts can exist before the first item outcome: never
    /// the whole batch.
    #[tokio::test]
    async fn batch_larger_than_concurrency_issues_no_start_before_first_item_runs() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let result = ctx
            .map(
                vec![1_i32, 2, 3, 4, 5, 6],
                |_child, item, _idx| async move { Ok(item * 10) },
            )
            .max_concurrency(2)
            .await
            .expect("map must succeed");
        assert_eq!(result, vec![10, 20, 30, 40, 50, 60]);

        let (starts_before, total_starts) = child_starts_before_first_terminal(&client);
        assert_eq!(
            total_starts, 6,
            "every admitted item gets exactly one Start"
        );
        assert!(
            starts_before <= 2,
            "at most `concurrency` child Starts may precede the first item \
             outcome (lazy admission), found {starts_before}"
        );
    }

    /// Finds the batch parent's SUCCEED update (the terminal update with no
    /// `ParentId` on a root-level batch).
    fn parent_succeed_update(client: &crate::client::InMemoryExecutionClient) -> OperationUpdate {
        client
            .recorded_updates()
            .into_iter()
            .find(|u| u.parent_id().is_none() && matches!(u.action(), OperationAction::Succeed))
            .expect("batch parent SUCCEED update must be recorded")
    }

    /// A batch whose serialized result exceeds the checkpoint size limit
    /// records the JS `MapResult` summary as the `replay_children` payload,
    /// instead of no payload at all.
    #[tokio::test]
    async fn large_batch_result_checkpoints_decision_record() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let big = "x".repeat(200 * 1024);
        let result = ctx
            .map(
                vec![big.clone(), big],
                |_child, item: String, _idx| async move { Ok(item) },
            )
            .await
            .expect("map must succeed");
        assert_eq!(result.len(), 2);

        let parent = parent_succeed_update(&client);
        assert_eq!(
            parent.context_options().and_then(|c| c.replay_children),
            Some(true),
            "oversized batch payload must set replay_children"
        );
        let summary: serde_json::Value = serde_json::from_str(
            parent
                .payload()
                .expect("large-result parent must carry the summary"),
        )
        .expect("payload must parse as a plain-JSON summary");
        assert_eq!(summary["totalCount"], 2);
        assert_eq!(summary["completionReason"], "ALL_COMPLETED");
        // Everything completed: every started item is terminal.
        assert_eq!(summary["itemStatuses"], "SS");
    }

    /// Acceptance (issue #36): `totalCount` is the number of items EVER
    /// STARTED, not the input length. A sequential batch of 6 that stops on
    /// `min_successful(1)` after its first item records `totalCount = 1`.
    #[tokio::test]
    async fn decision_record_total_count_is_ever_started_not_input_length() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let batch = ctx
            .map(
                vec![0_usize, 1, 2, 3, 4, 5],
                |_child, _item, idx| async move { Ok("y".repeat(300 * 1024) + &idx.to_string()) },
            )
            .max_concurrency(1)
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
            .await_batch()
            .await
            .expect("map must succeed");
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(batch.items.len(), 1);

        let parent = parent_succeed_update(&client);
        let summary: serde_json::Value = serde_json::from_str(
            parent
                .payload()
                .expect("large-result parent must carry the summary"),
        )
        .expect("payload must parse as a plain-JSON summary");
        assert_eq!(
            summary["totalCount"], 1,
            "totalCount counts items ever started, not the 6 input items"
        );
        assert_eq!(summary["completionReason"], "MIN_SUCCESSFUL_REACHED");
        assert_eq!(summary["itemStatuses"], "S");
    }

    /// The oversized summary must be PLAIN JSON even when a custom
    /// `result_serdes` transforms the batch record: it is the SDK's own
    /// bookkeeping and must stay readable when the configured serdes is the
    /// reason the payload outgrew the limit.
    #[tokio::test]
    async fn oversized_summary_bypasses_result_serdes() {
        use crate::serdes::test_support::HexEnvelopeSerdes;

        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let big = "z".repeat(200 * 1024);
        let result = ctx
            .map(
                vec![big.clone(), big],
                |_child, item: String, _idx| async move { Ok(item) },
            )
            .result_serdes(HexEnvelopeSerdes)
            .await
            .expect("map must succeed");
        assert_eq!(result.len(), 2);

        let parent = parent_succeed_update(&client);
        let record: BatchDecisionRecord = serde_json::from_str(
            parent
                .payload()
                .expect("large-result parent must carry the decision record"),
        )
        .expect("the decision record must parse as plain JSON, not the hex wire form");
        assert_eq!(record.total_count, 2);
    }

    /// Builds a terminal batch-parent record carrying a decision record as
    /// its `replay_children` payload.
    fn decision_record_parent(positional_id: &str, decision: &str) -> (String, CheckpointRecord) {
        let wire_id = crate::engine::compute_wire_id_public(positional_id);
        (
            wire_id.clone(),
            CheckpointRecord {
                id: wire_id,
                status: CheckpointStatus::Succeeded,
                result: Some(decision.to_owned()),
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: true,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )
    }

    /// Acceptance (issue #36): a batch that stopped on a completion
    /// threshold, replayed on the large-result path, reproduces the live
    /// item statuses and reason from the decision record without re-running
    /// unstarted items (or any item body at all: completed items decode
    /// from their child records).
    #[tokio::test]
    async fn replay_of_threshold_stopped_large_batch_obeys_decision_record() {
        // Live history: 6 input items, min_successful stopped the batch
        // after items 0 and 1 completed; items 2..5 never started. The
        // parent's payload was too large to store, so the decision record
        // was written in its place. Children have the IDs "1-1" and "1-2".
        let decision =
            r#"{"totalCount":2,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[]}"#;
        let log = CheckpointLog::from_records(vec![
            decision_record_parent("1", decision),
            succeeded_record("1-1", "\"hello\""),
            succeeded_record("1-2", "\"world\""),
        ]);
        let ctx = test_ctx(log);

        let batch: BatchResult<String> = ctx
            .map(
                vec![0_usize, 1, 2, 3, 4, 5],
                |_child, _item, _idx| async move {
                    unreachable!("replay must not re-run any item body")
                },
            )
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(2))
            .await_batch()
            .await
            .expect("replay must succeed");

        assert_eq!(
            batch.reason,
            CompletionReason::MinSuccessfulReached,
            "the recorded reason is taken verbatim"
        );
        assert_eq!(batch.items.len(), 2, "unstarted items stay omitted");
        assert_eq!(batch.items[0].index, 0);
        assert_eq!(batch.items[0].result.as_deref(), Some("hello"));
        assert_eq!(batch.items[1].index, 1);
        assert_eq!(batch.items[1].result.as_deref(), Some("world"));
    }

    /// Acceptance (issue #36): an index in the decision record's STARTED
    /// set is reported as [`BatchItemStatus::Started`] without consulting
    /// its child checkpoints: the child here holds only a non-terminal
    /// `Started` record, which would error if replay tried to decode it as
    /// terminal. Never-started indexes (at or beyond `totalCount`) stay
    /// omitted.
    #[tokio::test]
    async fn replay_reports_started_set_as_started_without_reading_child_checkpoints() {
        let started_record = |positional_id: &str| {
            let wire_id = crate::engine::compute_wire_id_public(positional_id);
            (
                wire_id.clone(),
                CheckpointRecord {
                    id: wire_id,
                    status: CheckpointStatus::Started,
                    result: None,
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            )
        };
        // Items 0 and 2 completed; item 1 started but was still running
        // when the min-successful trigger completed the batch.
        let decision =
            r#"{"totalCount":3,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[1]}"#;
        let log = CheckpointLog::from_records(vec![
            decision_record_parent("1", decision),
            succeeded_record("1-1", "\"a\""),
            started_record("1-2"),
            succeeded_record("1-3", "\"c\""),
        ]);
        let ctx = test_ctx(log);

        let batch: BatchResult<String> = ctx
            .map(vec![0_usize, 1, 2, 3], |_child, _item, _idx| async move {
                unreachable!("replay must not re-run any item body")
            })
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(2))
            .await_batch()
            .await
            .expect("replay must succeed");

        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        let statuses: Vec<(usize, BatchItemStatus)> =
            batch.items.iter().map(|i| (i.index, i.status)).collect();
        assert_eq!(
            statuses,
            vec![
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started),
                (2, BatchItemStatus::Succeeded),
            ],
            "started-set item is reported STARTED; the never-started item is omitted"
        );
        assert!(
            batch.items[1].result.is_none() && batch.items[1].error_message.is_none(),
            "a STARTED item carries no result and no error"
        );
        // The Vec<O> success view skips the STARTED item.
        assert_eq!(batch.results().collect::<Vec<_>>(), vec!["a", "c"]);
    }

    /// The plan-constrained FALLBACK (fast replay hit a completed child
    /// recorded `replay_children` and fell through to re-execution) must
    /// consult child checkpoints only for indexes the plan admits as
    /// COMPLETED. Started-set and never-started indexes here hold records
    /// with a hostile identity (`op_type: Step`) that would raise
    /// `NonDeterministicExecution` if the concurrent pre-claim loop read
    /// them: as it did before this fix.
    #[tokio::test]
    async fn plan_constrained_fallback_reads_only_admitted_child_checkpoints() {
        // A record whose stored identity can never match a batch child's
        // claim ("Context"): any validated read of it fails.
        let poisoned_record = |positional_id: &str| {
            let wire_id = crate::engine::compute_wire_id_public(positional_id);
            (
                wire_id.clone(),
                CheckpointRecord {
                    id: wire_id,
                    status: CheckpointStatus::Started,
                    result: None,
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: Some("Step".to_owned()),
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            )
        };
        // Live history: items 0 and 2 completed, item 1 started-not-
        // terminal, item 3 never started. Item 0's own result was too
        // large to store inline (`replay_children`), so fast replay falls
        // through and the plan constrains the re-execution.
        let decision =
            r#"{"totalCount":3,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[1]}"#;
        let log = CheckpointLog::from_records(vec![
            decision_record_parent("1", decision),
            replay_children_success_record("1-1"),
            poisoned_record("1-2"),
            succeeded_record("1-3", "\"c\""),
            poisoned_record("1-4"),
        ]);
        // The fallback re-executes item 0's body to reconstruct its
        // oversized result, so a live client is needed.
        let (ctx, _client) = test_ctx_with_client(log);

        let batch: BatchResult<String> = ctx
            .map(vec![0_usize, 1, 2, 3], |_child, _item, idx| async move {
                assert_eq!(idx, 0, "only the replay_children item re-executes");
                Ok("a".to_owned())
            })
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(2))
            .await_batch()
            .await
            .expect("plan-constrained fallback must not read non-admitted child checkpoints");

        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        let statuses: Vec<(usize, BatchItemStatus)> =
            batch.items.iter().map(|i| (i.index, i.status)).collect();
        assert_eq!(
            statuses,
            vec![
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started),
                (2, BatchItemStatus::Succeeded),
            ],
            "started-set item reported STARTED from the record; never-started omitted"
        );
        assert_eq!(batch.results().collect::<Vec<_>>(), vec!["a", "c"]);
    }

    /// A succeeded `replay_children` batch parent must carry its summary.
    /// An absent payload and a blank payload each fail replay with a
    /// malformed decision record error, and no item body runs.
    #[tokio::test]
    async fn empty_replay_children_payload_fails_replay() {
        for payload in [None, Some("  ")] {
            let (parent_wire, mut parent) = decision_record_parent("1", "");
            parent.result = payload.map(str::to_owned);
            let log = CheckpointLog::from_records(vec![
                (parent_wire, parent),
                succeeded_record("1-1", "\"hello\""),
                succeeded_record("1-2", "\"world\""),
            ]);
            let (ctx, _client) = test_ctx_with_client(log);
            let ran = Arc::new(AtomicBool::new(false));
            let ran_probe = Arc::clone(&ran);

            let err = ctx
                .map(
                    vec!["a".to_owned(), "b".to_owned()],
                    move |_child, item: String, _idx| {
                        let ran = Arc::clone(&ran_probe);
                        async move {
                            ran.store(true, Ordering::SeqCst);
                            Ok(item)
                        }
                    },
                )
                .await
                .expect_err("a batch parent without its summary fails replay");
            assert!(
                format!("{err:#}").contains("malformed batch decision record"),
                "{payload:?}: unexpected error: {err:#}"
            );
            assert!(
                !ran.load(Ordering::SeqCst),
                "{payload:?}: no item body may run"
            );
        }
    }

    /// Acceptance (issue #36): `NestingMode::Flat` reports its started set
    /// from the record. Flat items have no child checkpoints, so the
    /// decision record is the only source: replay re-runs exactly the
    /// completed set (reconstructing values), reports the started set as
    /// [`BatchItemStatus::Started`] without running those bodies, skips
    /// the never-started items, and takes the reason verbatim.
    #[tokio::test]
    async fn flat_batch_replay_reports_started_set_from_record() {
        // Items 0 and 2 completed; item 1 started but was still running
        // when the trigger completed the batch; items 3..5 never started.
        let decision =
            r#"{"totalCount":3,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[1]}"#;
        let log = CheckpointLog::from_records(vec![decision_record_parent("1", decision)]);
        let ctx = test_ctx(log);

        let invoked = Arc::new(std::sync::Mutex::new(Vec::<usize>::new()));
        let invoked_probe = Arc::clone(&invoked);

        let batch = ctx
            .map(vec![0_usize, 1, 2, 3, 4, 5], move |_child, _item, idx| {
                let invoked = Arc::clone(&invoked_probe);
                async move {
                    invoked
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(idx);
                    Ok(format!("flat-{idx}"))
                }
            })
            .nesting(NestingMode::Flat)
            .max_concurrency(2)
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(2))
            .await_batch()
            .await
            .expect("flat replay must succeed");

        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        let statuses: Vec<(usize, BatchItemStatus)> =
            batch.items.iter().map(|i| (i.index, i.status)).collect();
        assert_eq!(
            statuses,
            vec![
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started),
                (2, BatchItemStatus::Succeeded),
            ],
            "the started set is reported STARTED from the record; unstarted items are omitted"
        );
        let mut ran = invoked
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        ran.sort_unstable();
        assert_eq!(
            ran,
            vec![0, 2],
            "flat replay re-runs the completed set only — never started-set or unstarted items"
        );
    }

    /// Under a replay plan, a completion rule that fires again on the
    /// reconstructed outcomes abandons and aborts nothing. The record says
    /// items 0 and 1 both completed, and the current configuration needs
    /// only one success. Item 0 settles first and meets that rule while
    /// item 1 is still running. The batch still waits for item 1 and
    /// reports both recorded completions, because the record, not the
    /// re-derived trigger, decides the outcome.
    #[tokio::test]
    async fn replay_plan_trigger_keeps_recorded_completed_items() {
        let decision =
            r#"{"totalCount":2,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[]}"#;
        let log = CheckpointLog::from_records(vec![decision_record_parent("1", decision)]);
        let ctx = test_ctx(log);
        let finished = Arc::new(AtomicBool::new(false));
        let finished_probe = Arc::clone(&finished);

        let batch = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            ctx.map(vec![0_usize, 1], move |_child, _item, idx| {
                let finished = Arc::clone(&finished_probe);
                async move {
                    if idx == 1 {
                        // Item 0 settles while item 1 is still running.
                        for _ in 0..20 {
                            tokio::task::yield_now().await;
                        }
                        finished.store(true, Ordering::SeqCst);
                    }
                    Ok(format!("flat-{idx}"))
                }
            })
            .nesting(NestingMode::Flat)
            .max_concurrency(2)
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
            .await_batch(),
        )
        .await
        .expect("the replay resolves")
        .expect("the replay succeeds");

        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        let items: Vec<(usize, BatchItemStatus, Option<String>)> = batch
            .items
            .iter()
            .map(|i| (i.index, i.status, i.result.clone()))
            .collect();
        assert_eq!(
            items,
            vec![
                (0, BatchItemStatus::Succeeded, Some("flat-0".to_owned())),
                (1, BatchItemStatus::Succeeded, Some("flat-1".to_owned())),
            ],
            "both recorded completions are reconstructed"
        );
        assert!(
            finished.load(Ordering::SeqCst),
            "item 1 ran to its end and was not aborted"
        );
    }
    #[test]
    fn replay_plan_reconstructs_either_index_form() {
        // From the started form.
        let record = BatchDecisionRecord {
            total_count: 4,
            completion_reason: "ALL_COMPLETED".to_owned(),
            started_indexes: Some(vec![1, 3]),
            completed_indexes: None,
        };
        let plan = ReplayPlan::from_record(&record, 10).expect("well-formed record");
        assert_eq!(plan.total_count, 4);
        assert!(plan.admits(0) && plan.admits(2));
        assert!(!plan.admits(1) && !plan.admits(3));
        assert!(!plan.admits(4), "beyond totalCount is never admitted");

        // From the completed form.
        let record = BatchDecisionRecord {
            total_count: 3,
            completion_reason: "MIN_SUCCESSFUL_REACHED".to_owned(),
            started_indexes: None,
            completed_indexes: Some(vec![2]),
        };
        let plan = ReplayPlan::from_record(&record, 10).expect("well-formed record");
        assert!(!plan.admits(0) && !plan.admits(1) && plan.admits(2));
        assert_eq!(plan.reason, CompletionReason::MinSuccessfulReached);
    }

    /// A syntactically valid decision record that the SDK's writer could
    /// not have produced is rejected outright: silently repairing it
    /// (clamping `totalCount`, ignoring out-of-range indexes, defaulting a
    /// missing index form or an unknown reason) would convert recorded
    /// outcomes into different ones.
    #[test]
    fn replay_plan_rejects_semantically_invalid_records() {
        let base = || BatchDecisionRecord {
            total_count: 3,
            completion_reason: "ALL_COMPLETED".to_owned(),
            started_indexes: Some(vec![1]),
            completed_indexes: None,
        };

        // totalCount larger than the current input length.
        let record = base();
        let err = ReplayPlan::from_record(&record, 2).expect_err("totalCount > input");
        assert!(
            crate::error::chain_string(&err).contains("exceeds the input length"),
            "unexpected error: {err}"
        );

        // Both index forms present.
        let mut record = base();
        record.completed_indexes = Some(vec![0, 2]);
        let err = ReplayPlan::from_record(&record, 10).expect_err("both index forms");
        assert!(crate::error::chain_string(&err).contains("both startedIndexes"));

        // Neither index form present.
        let mut record = base();
        record.started_indexes = None;
        let err = ReplayPlan::from_record(&record, 10).expect_err("neither index form");
        assert!(crate::error::chain_string(&err).contains("neither startedIndexes"));

        // Index outside [0, totalCount): in either form.
        let mut record = base();
        record.started_indexes = Some(vec![3]);
        let err = ReplayPlan::from_record(&record, 10).expect_err("started index out of range");
        assert!(crate::error::chain_string(&err).contains("outside [0, 3)"));
        let mut record = base();
        record.started_indexes = None;
        record.completed_indexes = Some(vec![50]);
        let err = ReplayPlan::from_record(&record, 10).expect_err("completed index out of range");
        assert!(crate::error::chain_string(&err).contains("outside [0, 3)"));

        // Unknown completion-reason wire value.
        let mut record = base();
        record.completion_reason = "SOME_FUTURE_REASON".to_owned();
        let err = ReplayPlan::from_record(&record, 10).expect_err("unknown reason");
        assert!(crate::error::chain_string(&err).contains("unknown completionReason"));
    }

    #[test]
    fn parse_decision_record_rejects_what_is_not_a_record() {
        // A payload that is not a decision record is corrupt bookkeeping:
        // an error, never a silent fall-back.
        assert!(parse_decision_record("not json").is_err());
        assert!(parse_decision_record(r#"{"unrelated":true}"#).is_err());
        let record = parse_decision_record(
            r#"{"totalCount":2,"completionReason":"ALL_COMPLETED","startedIndexes":[]}"#,
        )
        .expect("well-formed record must parse");
        assert_eq!(record.total_count, 2);
    }

    /// A malformed (non-empty, unparseable) decision record fails the
    /// replay instead of falling back to unconstrained re-execution, which
    /// could resurrect items the recorded batch never started.
    #[tokio::test]
    async fn malformed_decision_record_fails_replay_instead_of_reexecuting() {
        let log = CheckpointLog::from_records(vec![decision_record_parent(
            "1",
            r#"{"totalCount":"#, // truncated JSON: corrupt
        )]);
        let ctx = test_ctx(log);

        let result: Result<Vec<String>, _> = ctx
            .map(vec![0_usize, 1, 2], |_child, _item, _idx| async move {
                unreachable!("a corrupt decision record must not re-execute any item")
            })
            .await;

        let Err(err) = result else {
            unreachable!("replay of a corrupt decision record must fail")
        };
        // A payload that is neither a summary nor a decision record is
        // read as the batch's own result, which must be a batch record.
        let display = crate::error::chain_string(&err);
        assert!(
            display.contains("batch record is not valid"),
            "expected the corrupt-record error, got: {display}"
        );
    }

    /// The oversized-record path refuses to checkpoint rather than writing
    /// a terminal batch without the decision record replay requires.
    #[tokio::test]
    async fn oversized_decision_record_refuses_checkpoint_instead_of_dropping_record() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());

        let oversized_payload = "p".repeat(CHECKPOINT_SIZE_LIMIT_BYTES + 1);
        let oversized_decision = "d".repeat(CHECKPOINT_SIZE_LIMIT_BYTES + 1);
        let parent_wire = crate::engine::compute_wire_id_public("1");

        let result = checkpoint_batch_success_serialized(
            &ctx,
            &parent_wire,
            None,
            MAP_SUB_TYPE,
            &oversized_payload,
            &oversized_decision,
            None,
        )
        .await;

        let Err(err) = result else {
            unreachable!("an oversized decision record must refuse the checkpoint")
        };
        let display = crate::error::chain_string(&err);
        assert!(
            display.contains("batch summary exceeds the checkpoint size limit"),
            "expected the oversized-record error, got: {display}"
        );
        assert!(
            client
                .recorded_updates()
                .iter()
                .all(|u| !matches!(u.action(), OperationAction::Succeed)),
            "no terminal SUCCEED may be written without its decision record"
        );
    }

    /// Non-determinism regression (fast replay path): a completed child's
    /// replay identity is validated before its terminal payload is read, so
    /// a changed child sub-type raises `NonDeterministicExecution` instead
    /// of replaying the stale record successfully.
    #[tokio::test]
    async fn fast_replay_validates_completed_child_identity() {
        // Child "1-1" (item 0) carries a recorded identity that does NOT
        // match a map iteration: same type but a different sub-type.
        let mismatched_child = {
            let wire_id = crate::engine::compute_wire_id_public("1-1");
            (
                wire_id.clone(),
                CheckpointRecord {
                    id: wire_id,
                    status: CheckpointStatus::Succeeded,
                    result: Some("\"a\"".to_owned()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: Some("Context".to_owned()),
                    sub_type: Some("ParallelBranch".to_owned()),
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            )
        };
        let decision = r#"{"totalCount":2,"completionReason":"ALL_COMPLETED","startedIndexes":[]}"#;
        let log = CheckpointLog::from_records(vec![
            decision_record_parent("1", decision),
            mismatched_child,
            succeeded_record("1-2", "\"b\""),
        ]);
        let ctx = test_ctx(log);

        let result: Result<BatchResult<String>, _> = ctx
            .map(vec![0_usize, 1], |_child, _item, _idx| async move {
                unreachable!("identity mismatch must fail before any re-execution")
            })
            .await_batch()
            .await;

        let Err(err) = result else {
            unreachable!("a mismatched child identity must fail the replay")
        };
        assert!(
            matches!(err.kind(), OperationErrorKind::NonDeterministicExecution(_)),
            "expected NonDeterministicExecution, got: {err:#}"
        );
    }

    // Early completion: running items are abandoned, not drained.

    /// The bound on every batch await in the early-completion tests.
    const EARLY_BOUND: std::time::Duration = std::time::Duration::from_secs(5);

    /// The wire IDs of the two items of a root map at position 1: the
    /// items are numbered inside the batch.
    fn item_wires() -> [String; 2] {
        [
            crate::engine::compute_wire_id_public("1-1"),
            crate::engine::compute_wire_id_public("1-2"),
        ]
    }

    /// The number of recorded updates with `action` for item `index`'s
    /// child context.
    fn item_action_count(
        client: &crate::client::InMemoryExecutionClient,
        index: usize,
        action: &OperationAction,
    ) -> usize {
        let wire = item_wires()[index].clone();
        client
            .recorded_updates()
            .iter()
            .filter(|u| u.id == wire && u.action() == action)
            .count()
    }

    /// The statuses of a batch's items, in input order.
    fn statuses<O>(batch: &BatchResult<O>) -> Vec<(usize, BatchItemStatus)> {
        batch.items.iter().map(|i| (i.index, i.status)).collect()
    }

    /// A boxed item body future.
    type ItemFut = Pin<Box<dyn Future<Output = Result<i32, BoxError>> + Send>>;

    /// The body of the early-completion maps over `[0, 1]`. Item 0 waits
    /// until item 1 runs, then runs a step that returns at once, or returns
    /// `Err("boom")` from its body when `fail` is set. Item 1 holds `guard`
    /// until its task is dropped, and runs a step whose body never returns.
    /// So item 1 is running when item 0 settles.
    fn early_body(
        fail: bool,
        guard: Arc<AtomicBool>,
    ) -> impl Fn(DurableContext, i32, usize) -> ItemFut + Send + Sync + 'static {
        let running = Arc::new(tokio::sync::Notify::new());
        move |child, item, _idx| {
            let guard = Arc::clone(&guard);
            let running = Arc::clone(&running);
            Box::pin(async move {
                if item == 0 {
                    running.notified().await;
                    if fail {
                        return Err("boom".into());
                    }
                    return Ok(child.step(|_| async { Ok(0_i32) }).name("fast").await?);
                }
                let _guard = SetOnDrop(guard);
                running.notify_one();
                Ok(child
                    .step(|_| std::future::pending::<Result<i32, BoxError>>())
                    .name("forever")
                    .await?)
            })
        }
    }

    /// Sets its flag when dropped.
    struct SetOnDrop(Arc<AtomicBool>);

    impl Drop for SetOnDrop {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    fn no_guard() -> Arc<AtomicBool> {
        Arc::new(AtomicBool::new(false))
    }

    #[tokio::test]
    async fn early_completion_does_not_wait_for_running_item() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(false, no_guard()))
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect("the batch succeeds");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(batch.total_count(), 2);
        assert_started_defaults(&batch.items[1], "map-item-1");
        assert_eq!(item_action_count(&client, 0, &OperationAction::Succeed), 1);
        assert_eq!(item_action_count(&client, 1, &OperationAction::Succeed), 0);
        // The whole batch scope is closed: the settled item and the running
        // item admit no later checkpoint.
        let [settled, running] = item_wires();
        assert!(!ctx.admission().admits(&[settled]), "item 0 is closed");
        assert!(!ctx.admission().admits(&[running]), "item 1 is closed");
    }

    /// A client that, at the batch parent's `SUCCEED`, yields until
    /// `guard` is set (at most 1,000 times) and records whether it was.
    #[derive(Debug)]
    struct GuardAtParentWrite {
        guard: Arc<AtomicBool>,
        seen: Arc<AtomicBool>,
    }

    impl crate::client::ExecutionClient for GuardAtParentWrite {
        fn checkpoint(
            &self,
            _arn: &str,
            _token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::CheckpointOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            let parent = crate::engine::compute_wire_id_public("1");
            let at_parent = updates
                .iter()
                .any(|u| u.id == parent && u.action() == &OperationAction::Succeed);
            Box::pin(async move {
                if at_parent {
                    for _ in 0..1_000 {
                        if self.guard.load(Ordering::SeqCst) {
                            break;
                        }
                        tokio::task::yield_now().await;
                    }
                    self.seen
                        .store(self.guard.load(Ordering::SeqCst), Ordering::SeqCst);
                }
                Ok(crate::client::CheckpointOutput {
                    checkpoint_token: Some("token".to_owned()),
                    updated_operations: Vec::new(),
                    next_marker: None,
                })
            })
        }

        fn get_state(
            &self,
            _arn: &str,
            _token: &str,
            _marker: Option<&str>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::GetStateOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            Box::pin(async {
                Ok(crate::client::GetStateOutput {
                    operations: Vec::new(),
                    next_marker: None,
                })
            })
        }
    }

    /// The batch aborts its running items at the trigger, before it writes
    /// its own `SUCCEED`. So item 1's task unwinds while that write is in
    /// flight. Without the abort, the task would be dropped only with the
    /// join set, after the write.
    #[tokio::test]
    async fn early_completion_aborts_running_item_before_parent_write() {
        let guard = no_guard();
        let seen = no_guard();
        let client = Arc::new(GuardAtParentWrite {
            guard: Arc::clone(&guard),
            seen: Arc::clone(&seen),
        });
        let ctx = DurableContext::new_root_with_client(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client as Arc<dyn crate::client::ExecutionClient>,
            "token0".to_owned(),
        );
        tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(false, Arc::clone(&guard)))
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect("the batch succeeds");
        assert!(
            seen.load(Ordering::SeqCst),
            "item 1's task unwound before the batch parent's SUCCEED was written"
        );
    }

    /// A `Started` item of a `parallel` carries its branch name.
    #[tokio::test]
    async fn started_branch_keeps_its_name() {
        use crate::future::Branch;

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.parallel(vec![
                Branch::new("fast", |_child| async { Ok(0_i32) }),
                Branch::new("slow", |_child| std::future::pending()),
            ])
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
            .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running branch")
        .expect("the batch succeeds");
        let started = batch
            .items
            .iter()
            .find(|item| item.status == BatchItemStatus::Started)
            .expect("the running branch is reported as Started");
        assert_started_defaults(started, "slow");
        assert_eq!(started.index, 1);
    }

    /// A live `Started` item carries `name`, no result, no error fields and
    /// an empty stack trace.
    fn assert_started_defaults<O: std::fmt::Debug>(item: &BatchItem<O>, name: &str) {
        assert_eq!(item.status, BatchItemStatus::Started);
        assert_eq!(item.name, name);
        assert!(item.result.is_none(), "no result: {item:?}");
        assert_eq!(item.error_message, None);
        assert_eq!(item.error_type, None);
        assert_eq!(item.error_data, None);
        assert!(item.stack_trace.is_empty(), "no stack trace: {item:?}");
    }

    /// Yields until `client` recorded the `START` of the operation named
    /// `name`, at most 1,000 times. Panics at the bound.
    async fn wait_for_start(client: &crate::client::InMemoryExecutionClient, name: &str) {
        for _ in 0..1_000 {
            if has_start(client, name) {
                return;
            }
            tokio::task::yield_now().await;
        }
        assert!(
            has_start(client, name),
            "the START of {name} was never recorded"
        );
    }

    /// Whether `client` recorded the `START` of the operation named `name`.
    fn has_start(client: &crate::client::InMemoryExecutionClient, name: &str) -> bool {
        client
            .recorded_updates()
            .iter()
            .any(|u| u.name() == Some(name) && u.action() == &OperationAction::Start)
    }

    #[tokio::test(start_paused = true)]
    async fn early_completion_abandons_running_item() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let observer = Arc::clone(&client);
        let start = tokio::time::Instant::now();
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(
                vec![0_i32, 1],
                move |child: DurableContext, item: i32, _idx| {
                    let observer = Arc::clone(&observer);
                    async move {
                        if item == 0 {
                            // Item 0 settles only once item 1 runs step `a`:
                            // its START is recorded.
                            wait_for_start(&observer, "a").await;
                            return Ok(child.step(|_| async { Ok(0_i32) }).name("fast").await?);
                        }
                        child
                            .step(|_| async {
                                tokio::time::sleep(std::time::Duration::from_millis(800)).await;
                                Ok(1_i32)
                            })
                            .name("a")
                            .await?;
                        Ok(child.step(|_| async { Ok(2_i32) }).name("b").await?)
                    }
                },
            )
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
            .await_batch(),
        )
        .await
        .expect("the batch returns")
        .expect("the batch succeeds");
        assert!(
            start.elapsed() < std::time::Duration::from_millis(800),
            "the batch returned after {:?}, so it waited for item 1",
            start.elapsed()
        );
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
        assert!(has_start(&client, "a"), "item 1 entered step a");
        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
        assert!(
            !client
                .recorded_updates()
                .iter()
                .any(|u| u.name() == Some("b")),
            "the abandoned item started no later operation"
        );
        assert_eq!(item_action_count(&client, 1, &OperationAction::Succeed), 0);
    }

    #[tokio::test]
    async fn fail_fast_does_not_wait_for_running_sibling() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(true, no_guard()))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect("await_batch reports item failures as items");
        assert_eq!(
            statuses(&batch),
            [(0, BatchItemStatus::Failed), (1, BatchItemStatus::Started)]
        );
        assert_eq!(batch.reason, CompletionReason::FailureToleranceExceeded);
        assert_eq!(item_action_count(&client, 0, &OperationAction::Fail), 1);
        assert_eq!(item_action_count(&client, 1, &OperationAction::Fail), 0);

        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let err = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(true, no_guard()))
                .into_future(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect_err("fail-fast ends the batch with an error");
        assert!(
            matches!(
                err.kind(),
                OperationErrorKind::ChildContext(e) if matches!(e.kind(), ChildContextErrorKind::ChildFailed)
            ),
            "unexpected error kind: {:?}",
            err.kind()
        );
        assert_eq!(item_action_count(&client, 0, &OperationAction::Fail), 1);
        assert_eq!(item_action_count(&client, 1, &OperationAction::Fail), 0);
    }

    #[tokio::test]
    async fn predicate_completion_does_not_wait_for_running_item() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(false, no_guard()))
                .completion(
                    crate::builders::map_parallel::CompletionConfig::with_completion_predicate(
                        |s| succeed_when(s.succeeded() >= 1),
                    ),
                )
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect("the batch succeeds");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
    }

    #[tokio::test]
    async fn abandoned_item_leaves_no_task_after_invocation() {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let guard = no_guard();
        let handler = {
            let ctx = ctx.clone();
            let guard = Arc::clone(&guard);
            async move {
                ctx.map(vec![0_i32, 1], early_body(false, guard))
                    .completion(
                        crate::builders::map_parallel::CompletionConfig::with_min_successful(1),
                    )
                    .await_batch()
                    .await
                    .expect("the batch succeeds");
                Ok::<_, crate::error::WireError>("done".to_owned())
            }
        };
        let outcome = tokio::time::timeout(
            EARLY_BOUND,
            crate::driver::drive_outcome(handler, ownership, signal, root, None),
        )
        .await
        .expect("the invocation does not wait for the abandoned item");
        assert!(
            matches!(outcome, Ok(crate::driver::InvocationOutcome::Complete(_))),
            "unexpected outcome: {outcome:?}"
        );
        assert!(
            guard.load(Ordering::SeqCst),
            "the abandoned item's task unwound before the invocation returned"
        );
        assert_eq!(ctx.coordinator().tasks().live(), 0);
    }

    /// Plain `.await` of an early-completing map or parallel returns only
    /// the succeeded values: the running item, reported `Started`, adds
    /// none.
    #[tokio::test]
    async fn early_completion_await_returns_only_succeeded_values() {
        use crate::future::Branch;

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let values = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], early_body(false, no_guard()))
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .into_future(),
        )
        .await
        .expect("the map does not wait for its running item")
        .expect("the map succeeds");
        assert_eq!(values, [0]);

        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let values = tokio::time::timeout(
            EARLY_BOUND,
            ctx.parallel(vec![
                Branch::new("fast", |_child| async { Ok(0_i32) }),
                Branch::new("slow", |_child| std::future::pending()),
            ])
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
            .into_future(),
        )
        .await
        .expect("the parallel does not wait for its running branch")
        .expect("the parallel succeeds");
        assert_eq!(values, [0]);
    }

    /// How the late item of `queued_outcome_batch` finishes.
    #[derive(Debug, Clone, Copy)]
    enum Late {
        Value,
        Error,
        Panic,
    }

    /// Runs a FLAT map over `[0, 1]` with `min_successful(1)`, so that
    /// both items have finished, item 0 first, before the coordinator joins
    /// either outcome. Item 1 finishes as `late` says. The coordinator then
    /// joins item 0, the trigger fires, and item 1's queued outcome is
    /// never joined.
    #[expect(clippy::panic)] // reason: the late item's panic is a case under test
    async fn queued_outcome_batch(late: Late) -> BatchResult<i32> {
        let (ctx, _client) = test_ctx_with_client(CheckpointLog::empty());
        let tasks = Arc::clone(ctx.coordinator().tasks());
        let entered = Arc::new(AtomicUsize::new(0));
        let ready = Arc::new([tokio::sync::Notify::new(), tokio::sync::Notify::new()]);
        let body = {
            let entered = Arc::clone(&entered);
            let ready = Arc::clone(&ready);
            move |_child: DurableContext, item: i32, idx: usize| {
                let entered = Arc::clone(&entered);
                let ready = Arc::clone(&ready);
                async move {
                    entered.fetch_add(1, Ordering::SeqCst);
                    ready[idx].notified().await;
                    if item == 0 {
                        return Ok(0_i32);
                    }
                    match late {
                        Late::Value => Ok(1_i32),
                        Late::Error => Err("late failure".into()),
                        Late::Panic => panic!("late panic"),
                    }
                }
            }
        };
        let mut batch = std::pin::pin!(
            ctx.map(vec![0_i32, 1], body)
                .nesting(NestingMode::Flat)
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .await_batch()
        );

        // 1. Drive the batch until both items wait.
        let early = std::future::poll_fn(|cx| {
            if entered.load(Ordering::SeqCst) == 2 {
                return std::task::Poll::Ready(None);
            }
            if let std::task::Poll::Ready(done) = batch.as_mut().poll(cx) {
                return std::task::Poll::Ready(Some(done));
            }
            cx.waker().wake_by_ref();
            std::task::Poll::Pending
        });
        let early = tokio::time::timeout(EARLY_BOUND, early)
            .await
            .expect("both items start");
        assert!(early.is_none(), "the batch completed before its items ran");

        // 2. Without polling the batch, let item 0 finish, then item 1.
        //    Each finished task releases its count once its outcome is
        //    queued.
        let wait_live = |n: usize| {
            let tasks = Arc::clone(&tasks);
            async move {
                for _ in 0..10_000 {
                    if tasks.live() == n {
                        return;
                    }
                    tokio::task::yield_now().await;
                }
                assert_eq!(tasks.live(), n, "the live task count never reached {n}");
            }
        };
        ready[0].notify_one();
        wait_live(1).await;
        ready[1].notify_one();
        wait_live(0).await;

        // 3. The coordinator joins item 0 first, and the trigger fires.
        tokio::time::timeout(EARLY_BOUND, batch)
            .await
            .expect("the batch completes")
            .expect("the late outcome is not observed")
    }

    /// An item that finished but whose outcome the coordinator had not
    /// joined when the trigger fired is reported `Started`: its value, its
    /// error and its panic are never observed.
    #[tokio::test]
    async fn finished_unjoined_item_is_started() {
        for late in [Late::Value, Late::Error, Late::Panic] {
            let batch = queued_outcome_batch(late).await;
            assert_eq!(
                statuses(&batch),
                [
                    (0, BatchItemStatus::Succeeded),
                    (1, BatchItemStatus::Started)
                ],
                "late {late:?}"
            );
            assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
            assert_started_defaults(&batch.items[1], "map-item-1");
        }
    }

    /// The payload of a terminal map or parallel parent with two
    /// succeeded items.
    fn terminal_batch_payload() -> String {
        serde_json::json!({
            "all": [
                {"index": 0, "name": "a", "status": "SUCCEEDED", "result": "hello"},
                {"index": 1, "name": "b", "status": "SUCCEEDED", "result": "world"}
            ],
            "completionReason": "ALL_COMPLETED"
        })
        .to_string()
    }

    /// An abandoned owner does not replay a recorded map or parallel from
    /// `await_batch`. The terminal parent replays without a write, so only
    /// the admission check at the terminal can hold it back.
    #[tokio::test]
    async fn abandoned_owner_replays_no_batch() {
        use crate::future::Branch;

        let bound = std::time::Duration::from_secs(1);
        for parallel in [false, true] {
            let log = CheckpointLog::from_records(vec![succeeded_record(
                "1-1",
                &terminal_batch_payload(),
            )]);
            let (root, client) = test_ctx_with_client(log);
            let replay = |ctx: DurableContext| async move {
                if parallel {
                    ctx.parallel(vec![
                        Branch::new("a", |_c| async { Ok(String::new()) }),
                        Branch::new("b", |_c| async { Ok(String::new()) }),
                    ])
                    .await_batch()
                    .await
                } else {
                    ctx.map(vec![0_i32, 1], |_c, _item, _idx| async {
                        Ok(String::new())
                    })
                    .await_batch()
                    .await
                }
            };
            // The control: an owner that is not abandoned replays the batch.
            let control = root.new_child("1", None);
            let replayed = tokio::time::timeout(bound, replay(control))
                .await
                .expect("the recorded batch replays")
                .expect("the replay succeeds");
            assert_eq!(
                replayed.results().collect::<Vec<_>>(),
                [&"hello".to_owned(), &"world".to_owned()]
            );

            let item = root.new_child("1", None);
            root.admission()
                .abandon(item.owners().iter().map(String::as_str));
            let replayed = tokio::time::timeout(bound, replay(item)).await;
            assert!(
                replayed.is_err(),
                "parallel {parallel}: the recorded batch is not replayed for an abandoned owner"
            );
            assert!(client.recorded_updates().is_empty(), "nothing is sent");
        }
    }

    /// An item that is abandoned while its body runs on another worker
    /// thread does not write its terminal update afterwards. Item 1 blocks
    /// its worker thread inside its body, so the abort cannot land, until
    /// the batch has completed. Then item 1 returns, and its `SUCCEED` is
    /// rejected because the item is abandoned.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn abandoned_item_terminal_write_is_rejected() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let tasks = Arc::clone(ctx.coordinator().tasks());
        let entered = Arc::new(tokio::sync::Notify::new());
        let (release, released) = std::sync::mpsc::channel::<()>();
        let released = Arc::new(std::sync::Mutex::new(Some(released)));
        let body = {
            let entered = Arc::clone(&entered);
            move |_child: DurableContext, item: i32, _idx: usize| {
                let entered = Arc::clone(&entered);
                let released = Arc::clone(&released);
                async move {
                    if item == 0 {
                        entered.notified().await;
                        return Ok(0_i32);
                    }
                    let released = released.lock().unwrap().take().expect("item 1 runs once");
                    entered.notify_one();
                    // Blocks inside the poll, so the abort of this task
                    // cannot take effect. `block_in_place` hands this
                    // worker's queued tasks to another thread, so item 0
                    // still runs.
                    tokio::task::block_in_place(|| {
                        released.recv().expect("the test releases item 1");
                    });
                    Ok(1_i32)
                }
            }
        };
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.map(vec![0_i32, 1], body)
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for its running item")
        .expect("the batch succeeds");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
        assert_eq!(item_action_count(&client, 0, &OperationAction::Succeed), 1);

        // Release item 1, and wait until its task and any write it started
        // have ended.
        release.send(()).expect("item 1 waits");
        let mut ended = false;
        for _ in 0..500 {
            if tasks.live() == 0 {
                ended = true;
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        assert!(ended, "item 1's task ended");
        assert_eq!(
            item_action_count(&client, 1, &OperationAction::Succeed),
            0,
            "the abandoned item wrote no terminal update"
        );
    }

    /// A waiting item is not terminal, so an early completion abandons it
    /// too. An operation it created but did not await then never starts.
    /// Item 1 creates a step future and waits. Only then does item 0
    /// succeed and fire the trigger: paused time advances item 0's timer
    /// only once every other task is idle.
    #[tokio::test(start_paused = true)]
    async fn early_completion_abandons_parked_item() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let slot: Arc<std::sync::Mutex<Option<crate::DurableFuture<i32>>>> =
            Arc::new(std::sync::Mutex::new(None));
        let ran = no_guard();
        let body = {
            let slot = Arc::clone(&slot);
            let ran = Arc::clone(&ran);
            move |child: DurableContext, item: i32, _idx: usize| {
                let slot = Arc::clone(&slot);
                let ran = Arc::clone(&ran);
                async move {
                    if item == 0 {
                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                        return Ok(0_i32);
                    }
                    let escaped = child
                        .step(move |_| async move {
                            ran.store(true, Ordering::SeqCst);
                            Ok(5_i32)
                        })
                        .name("escaped")
                        .future();
                    *slot.lock().unwrap() = Some(escaped);
                    child
                        .wait(std::time::Duration::from_secs(5))
                        .name("park")
                        .await?;
                    Ok(1_i32)
                }
            }
        };
        // The test awaits the batch on its own root future, which the SDK
        // does not poll through a permit-aware task. The held activity
        // stands in for the handler task's permit.
        let batch = tokio::time::timeout(
            EARLY_BOUND,
            ctx.hold_activity(
                ctx.map(vec![0_i32, 1], body)
                    .completion(
                        crate::builders::map_parallel::CompletionConfig::with_min_successful(1),
                    )
                    .await_batch(),
            ),
        )
        .await
        .expect("the batch completes")
        .expect("the batch succeeds");
        assert_eq!(
            statuses(&batch),
            [
                (0, BatchItemStatus::Succeeded),
                (1, BatchItemStatus::Started)
            ]
        );
        assert!(has_start(&client, "park"), "item 1 parked on its wait");
        let [_, parked] = item_wires();
        assert!(
            !ctx.admission().admits(&[parked]),
            "the parked item is abandoned"
        );

        let escaped = slot
            .lock()
            .unwrap()
            .take()
            .expect("item 1 stored its step future");
        let awaited = tokio::time::timeout(std::time::Duration::from_secs(1), escaped).await;
        assert!(awaited.is_err(), "the escaped step never resolves");
        assert!(!ran.load(Ordering::SeqCst), "the escaped step never ran");
        assert!(
            !has_start(&client, "escaped"),
            "the escaped step wrote nothing"
        );
    }

    // The batch record in JS's shape (issue: write the batch record and the
    // oversized batch summary in JS's shape, and keep empty item payloads
    // across replay).

    /// A serdes that logs each call as `(method, operation id)` and encodes
    /// values as JSON.
    #[derive(Clone, Default)]
    struct CallLog(Arc<std::sync::Mutex<Vec<(&'static str, String)>>>);

    impl CallLog {
        fn calls(&self) -> Vec<(&'static str, String)> {
            let mut calls = self.0.lock().expect("lock").clone();
            calls.sort();
            calls
        }
    }

    impl<T> Serdes<T> for CallLog
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
    {
        fn serialize(
            &self,
            value: T,
            context: SerdesContext,
        ) -> impl Future<Output = Result<String, BoxError>> + Send {
            self.0
                .lock()
                .expect("lock")
                .push(("serialize", context.operation_id().to_owned()));
            std::future::ready(serde_json::to_string(&value).map_err(Into::into))
        }

        fn deserialize(
            &self,
            wire: String,
            context: SerdesContext,
        ) -> impl Future<Output = Result<T, BoxError>> + Send {
            self.0
                .lock()
                .expect("lock")
                .push(("deserialize", context.operation_id().to_owned()));
            std::future::ready(serde_json::from_str(&wire).map_err(Into::into))
        }
    }

    /// A struct a map item returns.
    #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
    struct Order {
        id: u32,
        sku: String,
    }

    /// A serdes for [`Order`] that writes its JSON prefixed with `order:`.
    struct OrderSerdes;

    impl Serdes<Order> for OrderSerdes {
        fn serialize(
            &self,
            value: Order,
            _context: SerdesContext,
        ) -> impl Future<Output = Result<String, BoxError>> + Send {
            std::future::ready(
                serde_json::to_string(&value)
                    .map(|json| format!("order:{json}"))
                    .map_err(Into::into),
            )
        }

        fn deserialize(
            &self,
            wire: String,
            _context: SerdesContext,
        ) -> impl Future<Output = Result<Order, BoxError>> + Send {
            std::future::ready(
                wire.strip_prefix("order:")
                    .ok_or_else(|| BoxError::from("missing order: prefix"))
                    .and_then(|json| serde_json::from_str(json).map_err(Into::into)),
            )
        }
    }

    fn order(id: u32) -> Order {
        Order {
            id,
            sku: format!("sku-{id}"),
        }
    }

    /// The wire ID of the child at positional ID `positional`.
    fn wire_of(positional: &str) -> String {
        crate::engine::compute_wire_id_public(positional)
    }

    /// The parent payload of a batch as JSON.
    fn parent_payload_json(client: &crate::client::InMemoryExecutionClient) -> serde_json::Value {
        serde_json::from_str(&parent_payload(client)).expect("the batch payload is JSON")
    }

    /// The JSON structure of the batch record that an explicit
    /// `.result_serdes(JsonSerdes)` stored: the payload is a quoted JSON
    /// string, and its content is the record text.
    fn json_serdes_record_json(
        client: &crate::client::InMemoryExecutionClient,
    ) -> serde_json::Value {
        let payload = parent_payload(client);
        let record_text: String =
            serde_json::from_str(&payload).expect("JsonSerdes stores a quoted JSON string");
        record_json(&record_text)
    }

    /// A checkpoint log holding one terminal batch parent at positional ID
    /// `1` whose payload is `payload`.
    fn terminal_batch_log(payload: &str) -> CheckpointLog {
        CheckpointLog::from_records(vec![succeeded_record("1", payload)])
    }

    /// The JS-form record a batch record text holds.
    fn js_record(record_text: &str) -> JsBatchRecord {
        parse_batch_record(record_text).expect("the record parses")
    }

    #[test]
    fn batch_checkpoint_item_round_trips_empty_result() {
        let result: BatchResult<()> = BatchResult::new(
            vec![BatchItem::new(
                0,
                "map-item-0".to_owned(),
                BatchItemStatus::Succeeded,
                Some(()),
                None,
                None,
            )],
            CompletionReason::AllCompleted,
        );
        let json = from_batch_result(&result, &[Some(String::new())], &ItemEncoding::AllSerdes);
        assert!(json.contains(r#""result":"""#), "json: {json}");
        let back = js_record(&json);
        assert_eq!(
            back.all[0].result.as_deref().map(RawValue::get),
            Some(r#""""#)
        );
    }

    /// A started item is written with neither `result` nor `error`.
    #[test]
    fn batch_checkpoint_started_item_has_no_result_or_error() {
        let started: BatchResult<u32> = BatchResult::new(
            vec![BatchItem::new(
                0,
                "map-item-0".to_owned(),
                BatchItemStatus::Started,
                None,
                None,
                None,
            )],
            CompletionReason::MinSuccessfulReached,
        );
        let json = record_json(&from_batch_result(
            &started,
            &[None],
            &ItemEncoding::AllJson,
        ));
        let item = json.pointer("/all/0").expect("one item");
        assert!(item.get("result").is_none(), "item: {item}");
        assert!(item.get("error").is_none(), "item: {item}");
        assert_eq!(
            json,
            serde_json::json!({
                "all": [{"index": 0, "status": "STARTED", "name": "map-item-0"}],
                "completionReason": "MIN_SUCCESSFUL_REACHED",
            })
        );
    }

    #[tokio::test]
    async fn map_struct_values_are_embedded_as_json() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let out = ctx
            .map(vec![1_u32, 2], |_child, item, _idx| async move {
                Ok(order(item))
            })
            .await
            .expect("map succeeds");
        assert_eq!(out, vec![order(1), order(2)]);
        let payload = parent_payload_json(&client);
        for (i, id) in [1_u32, 2].into_iter().enumerate() {
            assert_eq!(
                payload["all"][i]["result"],
                serde_json::to_value(order(id)).expect("JSON"),
                "payload: {payload}"
            );
        }
    }

    #[tokio::test]
    async fn map_custom_serdes_values_are_strings() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let out = ctx
            .map(vec![1_u32, 2], |_child, item, _idx| async move {
                Ok(order(item))
            })
            .serdes(OrderSerdes)
            .await
            .expect("map succeeds");
        assert_eq!(out, vec![order(1), order(2)]);
        let mut child_payloads = child_success_payloads(&client);
        child_payloads.sort();
        let payload = parent_payload_json(&client);
        let mut results: Vec<String> = payload["all"]
            .as_array()
            .expect("all is an array")
            .iter()
            .map(|item| item["result"].as_str().expect("a string result").to_owned())
            .collect();
        results.sort();
        assert_eq!(results, child_payloads);
        assert!(results.iter().all(|r| r.starts_with("order:")));
    }

    /// `.result_serdes(..)` after `.serdes(..)` keeps the custom item
    /// encoding.
    #[tokio::test]
    async fn result_serdes_keeps_the_custom_item_encoding() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.map(
            vec![1_u32],
            |_child, item, _idx| async move { Ok(order(item)) },
        )
        .serdes(OrderSerdes)
        .result_serdes(crate::serdes::JsonSerdes)
        .await
        .expect("map succeeds");
        assert_eq!(
            json_serdes_record_json(&client)["all"][0]["result"],
            serde_json::json!(r#"order:{"id":1,"sku":"sku-1"}"#)
        );

        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.parallel(vec![crate::future::Branch::new("a", |_c| async {
            Ok(order(1))
        })])
        .serdes(OrderSerdes)
        .result_serdes(crate::serdes::JsonSerdes)
        .await
        .expect("parallel succeeds");
        assert_eq!(
            json_serdes_record_json(&client)["all"][0]["result"],
            serde_json::json!(r#"order:{"id":1,"sku":"sku-1"}"#)
        );
    }

    /// The error a typed serdes fails with: the type `PaymentError`, the
    /// message `declined` and the data `d`.
    fn typed_declined() -> BoxError {
        Box::new(crate::TypedError::with_type("PaymentError", "declined").with_error_data("d"))
    }

    /// An item serdes whose `serialize` fails, unmarked, with
    /// [`typed_declined`].
    struct TypedItemSerializeFailure;

    impl Serdes<u32> for TypedItemSerializeFailure {
        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn serialize(
            &self,
            _value: u32,
            _context: SerdesContext,
        ) -> Result<String, BoxError> {
            Err(typed_declined())
        }

        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn deserialize(
            &self,
            wire: String,
            _context: SerdesContext,
        ) -> Result<u32, BoxError> {
            Ok(wire.parse()?)
        }
    }

    /// An item serdes that stores the value as its decimal text and whose
    /// `deserialize` fails, unmarked, with [`typed_declined`].
    struct TypedItemDeserializeFailure;

    impl Serdes<u32> for TypedItemDeserializeFailure {
        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn serialize(&self, value: u32, _context: SerdesContext) -> Result<String, BoxError> {
            Ok(value.to_string())
        }

        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn deserialize(
            &self,
            _wire: String,
            _context: SerdesContext,
        ) -> Result<u32, BoxError> {
            Err(typed_declined())
        }
    }

    /// A batch result serdes that stores the record text and whose
    /// `deserialize` fails, unmarked, with [`typed_declined`].
    struct TypedResultDeserializeFailure;

    impl Serdes<String> for TypedResultDeserializeFailure {
        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn serialize(
            &self,
            value: String,
            _context: SerdesContext,
        ) -> Result<String, BoxError> {
            Ok(value)
        }

        // reason: a test serdes that completes at once, in the async-fn form user code writes
        #[expect(clippy::unused_async_trait_impl)]
        async fn deserialize(
            &self,
            _wire: String,
            _context: SerdesContext,
        ) -> Result<String, BoxError> {
            Err(typed_declined())
        }
    }

    /// A typed permanent serialize failure of an item result fails the
    /// item with the serialization type and the wrapped message without
    /// the type name, with no data and no stack, live and on replay.
    #[tokio::test]
    async fn typed_item_serialize_failure_records_the_wrapped_message() {
        const MESSAGE: &str =
            "operation error: child_context: internal error: serialize result: declined";
        let assert_item = |batch: &BatchResult<u32>| {
            let item = &batch.items[0];
            assert_eq!(item.status, BatchItemStatus::Failed);
            assert_eq!(
                item.error_type.as_deref(),
                Some(crate::error::SERIALIZATION_FAILED_ERROR_TYPE)
            );
            assert_eq!(item.error_message.as_deref(), Some(MESSAGE));
            assert_eq!(item.error_data, None);
            assert!(item.stack_trace.is_empty(), "{item:?}");
        };
        let tolerate_one =
            || crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1);
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let live = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .serdes(TypedItemSerializeFailure)
            .completion(tolerate_one())
            .await_batch()
            .await
            .expect("a tolerated failure is a batch result");
        assert_item(&live);

        let payload = parent_payload(&client);
        let replayed = test_ctx(terminal_batch_log(&payload))
            .map(vec![1_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .serdes(TypedItemSerializeFailure)
            .completion(tolerate_one())
            .await_batch()
            .await
            .expect("replay succeeds");
        assert_item(&replayed);
    }

    /// A typed permanent deserialize failure of a recorded batch result
    /// gives an `Internal` error whose recorded message omits the type
    /// name, with the child type and no data or stack. The live run does
    /// not decode its own record, so only the replay reaches the decode.
    #[tokio::test]
    async fn typed_result_deserialize_failure_records_the_wrapped_message() {
        let expected = crate::error::WireError::new(
            Some("ChildContextError"),
            Some("operation error: child_context: internal error: deserialize result: declined"),
        );
        let assert_error = |err: &OperationError| {
            let OperationErrorKind::ChildContext(child) = err.kind() else {
                unreachable!("expected a child context error, got {:?}", err.kind());
            };
            assert!(
                matches!(child.kind(), ChildContextErrorKind::Internal),
                "{err:?}"
            );
            assert_eq!(
                std::error::Error::source(child)
                    .map(ToString::to_string)
                    .as_deref(),
                Some("deserialize result: declined")
            );
            assert_eq!(err.wire(), None);
            assert_eq!(crate::error::wire_error_for(err, "Error"), expected);
        };
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let live = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .result_serdes(TypedResultDeserializeFailure)
            .await
            .expect("the live run returns its items");
        assert_eq!(live, [1]);

        let payload = parent_payload(&client);
        let replayed: Result<Vec<u32>, OperationError> = test_ctx(terminal_batch_log(&payload))
            .map(vec![1_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .result_serdes(TypedResultDeserializeFailure)
            .await;
        let replayed = replayed.expect_err("the recorded batch cannot be decoded");
        assert_error(&replayed);
    }

    /// A typed permanent deserialize failure of an item result: the live
    /// round trip after the item's `SUCCEED` and the replay of the
    /// succeeded item record both decode through the item serdes, and both
    /// give the same error, whose recorded message omits the type name.
    #[tokio::test]
    async fn typed_item_deserialize_failure_records_the_wrapped_message() {
        let expected = crate::error::WireError::new(
            Some("ChildContextError"),
            Some("operation error: child_context: internal error: deserialize result: declined"),
        );
        let assert_error = |err: &OperationError| {
            let OperationErrorKind::ChildContext(child) = err.kind() else {
                unreachable!("expected a child context error, got {:?}", err.kind());
            };
            assert!(
                matches!(child.kind(), ChildContextErrorKind::Internal),
                "{err:?}"
            );
            assert_eq!(
                std::error::Error::source(child)
                    .map(ToString::to_string)
                    .as_deref(),
                Some("deserialize result: declined")
            );
            assert_eq!(err.wire(), None);
            assert_eq!(crate::error::wire_error_for(err, "Error"), expected);
        };
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let live: Result<Vec<u32>, OperationError> = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .serdes(TypedItemDeserializeFailure)
            .await;
        let live = live.expect_err("the item value cannot be decoded");
        assert_error(&live);
        assert_eq!(child_success_payloads(&client), ["1"]);

        // The record the live run's item `SUCCEED` wrote: the serialized
        // value `1` under the item's ID.
        let replayed: Result<Vec<u32>, OperationError> = test_ctx(CheckpointLog::from_records(
            vec![succeeded_record("1-1", "1")],
        ))
        .map(vec![1_u32], |_child, _item, _idx| async move {
            unreachable!("a recorded item replays")
        })
        .serdes(TypedItemDeserializeFailure)
        .await;
        let replayed = replayed.expect_err("the recorded item cannot be decoded");
        assert_error(&replayed);
    }

    #[tokio::test]
    async fn failed_item_error_has_js_shape() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let live = ctx
            .map(vec![1_u32], |_child, _item, _idx| async move {
                Err::<u32, BoxError>(Box::new(
                    crate::TypedError::with_type("PaymentError", "declined").with_error_data("d"),
                ))
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("a tolerated failure is a batch result");
        assert_eq!(live.items[0].error_message.as_deref(), Some("declined"));
        let payload = parent_payload(&client);
        let json: serde_json::Value = serde_json::from_str(&payload).expect("JSON");
        assert_eq!(
            json["all"][0]["error"],
            serde_json::json!({
                "ErrorType": "ChildContextError",
                "ErrorMessage": "declined",
                "ErrorData": "d",
                "Cause": {"ErrorType": "PaymentError", "ErrorMessage": "declined", "ErrorData": "d"},
            })
        );

        let replayed: BatchResult<u32> = test_ctx(terminal_batch_log(&payload))
            .map(vec![1_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("replay succeeds");
        assert_eq!(
            replayed.items[0].error_type.as_deref(),
            Some("PaymentError")
        );
        assert_eq!(replayed.items[0].error_data.as_deref(), Some("d"));
        assert_eq!(replayed.items[0].error_message.as_deref(), Some("declined"));
    }

    #[tokio::test]
    async fn failed_item_without_recorded_type_falls_back_to_error() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.map(vec![1_u32], |_child, _item, _idx| async move {
            Err::<u32, BoxError>("boom".into())
        })
        .completion(
            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
        )
        .await_batch()
        .await
        .expect("a tolerated failure is a batch result");
        let payload = parent_payload(&client);
        let json: serde_json::Value = serde_json::from_str(&payload).expect("JSON");
        assert_eq!(json["all"][0]["error"]["Cause"]["ErrorType"], "Error");

        let replayed: BatchResult<u32> = test_ctx(terminal_batch_log(&payload))
            .map(vec![1_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("replay succeeds");
        assert_eq!(replayed.items[0].error_type.as_deref(), Some("Error"));
    }

    /// A JS error object without `Cause` reads its fields from the top
    /// level.
    #[tokio::test]
    async fn js_error_without_cause_reads_top_level() {
        let payload = serde_json::json!({
            "all": [{
                "index": 0,
                "status": "FAILED",
                "name": "map-item-0",
                "error": {
                    "ErrorType": "TopError",
                    "ErrorMessage": "top",
                    "ErrorData": "top-data",
                    "StackTrace": ["top-frame"],
                },
                "result": 5,
            }],
            "completionReason": "ALL_COMPLETED",
        });
        let replayed: BatchResult<u32> = test_ctx(terminal_batch_log(&payload.to_string()))
            .map(vec![1_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
            )
            .await_batch()
            .await
            .expect("replay succeeds");
        let item = &replayed.items[0];
        assert_eq!(item.error_type.as_deref(), Some("TopError"));
        assert_eq!(item.error_message.as_deref(), Some("top"));
        assert_eq!(item.error_data.as_deref(), Some("top-data"));
        assert_eq!(item.stack_trace, ["top-frame".to_owned()]);
        // Only a succeeded item decodes a value.
        assert_eq!(item.result, None);
    }

    /// A terminal map parent whose payload is the `{results, reason}` form
    /// that no SDK writes fails replay: the record has neither `all` nor
    /// `completionReason`.
    #[tokio::test]
    async fn results_reason_record_fails_replay() {
        let payload = r#"{"results":[{"index":0,"name":"a","status":"SUCCEEDED","result":"\"hello\""}],"reason":"ALL_COMPLETED"}"#;
        let err = test_ctx(terminal_batch_log(payload))
            .map(vec![0_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .item_namer(|_, _| "a".to_owned())
            .await_batch()
            .await
            .map(|batch: BatchResult<String>| batch.items.len())
            .expect_err("the record fails replay");
        assert!(
            format!("{err:#}").contains("batch record has neither `all` nor `completionReason`"),
            "unexpected error: {err:#}"
        );
    }

    /// The batch record text of `wires`, one succeeded `map` item per wire.
    fn record_of_wires(wires: &[&str], encoding: &ItemEncoding) -> String {
        let items = (0..wires.len())
            .map(|index| {
                BatchItem::new(
                    index,
                    format!("map-item-{index}"),
                    BatchItemStatus::Succeeded,
                    Some(()),
                    None,
                    None,
                )
            })
            .collect();
        let result: BatchResult<()> = BatchResult::new(items, CompletionReason::AllCompleted);
        let wires: Vec<Option<String>> = wires.iter().map(|w| Some((*w).to_owned())).collect();
        from_batch_result(&result, &wires, encoding)
    }

    /// The exact `result` texts of a JS-form record text.
    fn result_texts(record_text: &str) -> Vec<Option<String>> {
        js_record(record_text)
            .all
            .iter()
            .map(|item| item.result.as_deref().map(|raw| raw.get().to_owned()))
            .collect()
    }

    /// A `Serdes<String>` item serdes that returns each wire unchanged and
    /// logs the serdes context it was handed.
    #[derive(Clone, Default)]
    struct WireLog(Arc<std::sync::Mutex<Vec<(String, String)>>>);

    impl WireLog {
        fn calls(&self) -> Vec<(String, String)> {
            self.0.lock().expect("lock").clone()
        }
    }

    impl Serdes<String> for WireLog {
        fn serialize(
            &self,
            value: String,
            _context: SerdesContext,
        ) -> impl Future<Output = Result<String, BoxError>> + Send {
            std::future::ready(Ok(value))
        }

        fn deserialize(
            &self,
            wire: String,
            context: SerdesContext,
        ) -> impl Future<Output = Result<String, BoxError>> + Send {
            self.0
                .lock()
                .expect("lock")
                .push((context.operation_id().to_owned(), wire.clone()));
            std::future::ready(Ok(wire))
        }
    }

    /// A JSON item value keeps its exact text through the record and back:
    /// the record embeds the wire string unchanged, and replay hands the
    /// item serdes that same text.
    #[tokio::test]
    async fn record_round_trip_keeps_exact_json_item_text() {
        let wires = [
            "null",
            r#""a string""#,
            "[1,2,3]",
            r#"{"n":340282366920938463463374607431768211455,"m":{"k":-170141183460469231731687303715884105728}}"#,
            "1e2",
            "1.0",
            "-0",
        ];
        let text = record_of_wires(&wires, &ItemEncoding::AllJson);
        for wire in wires {
            assert!(
                text.contains(&format!(r#""result":{wire}}}"#)),
                "the record embeds {wire} unchanged: {text}"
            );
        }
        assert_eq!(
            result_texts(&text),
            wires
                .iter()
                .map(|w| Some((*w).to_owned()))
                .collect::<Vec<_>>()
        );

        let log = WireLog::default();
        let ctx = test_ctx(CheckpointLog::empty());
        let replayed: BatchResult<String> = to_batch_result(
            &ctx,
            &text,
            &Arc::new(log.clone()),
            ItemEncoding::AllJson,
            wires.len(),
            "arn:test",
            &ItemIds::new(&OperationId::new("1".to_owned()), wires.len()),
        )
        .await
        .expect("the record replays");
        let values: Vec<String> = replayed
            .items
            .into_iter()
            .map(|item| item.result.expect("a value"))
            .collect();
        assert_eq!(values, wires);
        let handed: Vec<String> = log.calls().into_iter().map(|(_, wire)| wire).collect();
        assert_eq!(handed, wires);
    }

    /// A custom-serdes item records its wire string as a JSON string, also
    /// when the wire is empty or looks like JSON, and replay hands the item
    /// serdes the original wire.
    #[tokio::test]
    async fn custom_serdes_item_records_a_json_string() {
        let wires = [
            "",
            r#"{"a":1}"#,
            "340282366920938463463374607431768211455",
            "plain",
        ];
        let text = record_of_wires(&wires, &ItemEncoding::AllSerdes);
        assert_eq!(
            result_texts(&text),
            vec![
                Some(r#""""#.to_owned()),
                Some(r#""{\"a\":1}""#.to_owned()),
                Some(r#""340282366920938463463374607431768211455""#.to_owned()),
                Some(r#""plain""#.to_owned()),
            ]
        );
        let replayed: BatchResult<String> = to_batch_result(
            &test_ctx(CheckpointLog::empty()),
            &text,
            &Arc::new(WireLog::default()),
            ItemEncoding::AllSerdes,
            wires.len(),
            "arn:test",
            &ItemIds::new(&OperationId::new("1".to_owned()), wires.len()),
        )
        .await
        .expect("the record replays");
        let values: Vec<String> = replayed
            .items
            .into_iter()
            .map(|item| item.result.expect("a value"))
            .collect();
        assert_eq!(values, wires);
    }

    /// The error `parse_batch_record` returns for `text`.
    fn record_error(text: &str) -> String {
        parse_batch_record(text).expect_err("the record must be rejected")
    }

    #[test]
    fn record_parser_reads_the_js_form() {
        let js = r#"{"all":[{"index":0,"status":"SUCCEEDED","name":"a","result":7}],"completionReason":"ALL_COMPLETED"}"#;
        let record = parse_batch_record(js).expect("the JS form parses");
        assert_eq!(record.completion_reason, "ALL_COMPLETED");
        assert_eq!(
            record
                .all
                .first()
                .and_then(|i| i.result.as_deref())
                .map(RawValue::get),
            Some("7")
        );
    }

    #[test]
    fn record_parser_rejects_non_records() {
        assert!(record_error(r#"{"all":"#).contains("batch record is not valid"));
        let trailing = record_error(r#"{"all":[],"completionReason":"ALL_COMPLETED"} {}"#);
        assert!(trailing.contains("trailing characters"), "{trailing}");
        for text in [
            "[]",
            r#"[{"all":[],"completionReason":"ALL_COMPLETED"}]"#,
            "5",
            r#""s""#,
            "null",
            "true",
        ] {
            let err = record_error(text);
            assert!(
                err.contains("expected a batch record object"),
                "{text}: {err}"
            );
        }
    }

    #[test]
    fn record_parser_requires_both_fields() {
        let neither = "batch record has neither `all` nor `completionReason`";
        let cases = [
            ("{}", neither),
            (r#"{"results":[],"reason":"ALL_COMPLETED"}"#, neither),
            (
                r#"{"all":[]}"#,
                "batch record has `all` without `completionReason`",
            ),
            (
                r#"{"completionReason":"ALL_COMPLETED"}"#,
                "batch record has `completionReason` without `all`",
            ),
        ];
        for (text, expected) in cases {
            assert_eq!(record_error(text), expected, "{text}");
        }
    }

    /// A recognized field whose value is `null` counts as absent.
    #[test]
    fn record_parser_reads_null_fields_as_absent() {
        let cases = [
            (
                r#"{"all":null,"completionReason":"ALL_COMPLETED"}"#,
                "batch record has `completionReason` without `all`",
            ),
            (
                r#"{"all":[],"completionReason":null}"#,
                "batch record has `all` without `completionReason`",
            ),
        ];
        for (text, expected) in cases {
            assert_eq!(record_error(text), expected, "{text}");
        }
    }

    #[test]
    fn record_parser_rejects_wrong_field_types() {
        for (text, field_type) in [
            (
                r#"{"all":5,"completionReason":"ALL_COMPLETED"}"#,
                "invalid type: integer `5`, expected a sequence",
            ),
            (
                r#"{"all":[],"completionReason":5}"#,
                "invalid type: integer `5`, expected a string",
            ),
        ] {
            let err = record_error(text);
            assert!(err.contains(field_type), "{text}: {err}");
        }
    }

    #[test]
    fn record_parser_rejects_duplicate_fields() {
        for (text, field) in [
            (
                r#"{"all":[],"all":[],"completionReason":"ALL_COMPLETED"}"#,
                "all",
            ),
            (
                r#"{"all":null,"all":[],"completionReason":"ALL_COMPLETED"}"#,
                "all",
            ),
            (
                r#"{"all":[],"completionReason":"ALL_COMPLETED","completionReason":"ALL_COMPLETED"}"#,
                "completionReason",
            ),
            (
                r#"{"all":[],"completionReason":null,"completionReason":"ALL_COMPLETED"}"#,
                "completionReason",
            ),
        ] {
            let err = record_error(text);
            assert!(
                err.contains(&format!("duplicate field `{field}`")),
                "{text}: {err}"
            );
        }
    }

    #[test]
    fn record_parser_ignores_unknown_fields() {
        for text in [
            r#"{"extra":{"nested":[1,{"a":null}]},"all":[],"completionReason":"ALL_COMPLETED","type":"MapResult"}"#,
            r#"{"all":[],"completionReason":"ALL_COMPLETED","results":"x","reason":5}"#,
        ] {
            assert!(parse_batch_record(text).is_ok(), "{text}");
        }
    }

    /// Replays a JS-form batch record `payload` through a map over one
    /// `u32` item, with a custom item serdes when `custom` is set, and
    /// returns the error text.
    async fn js_replay_error(payload: &serde_json::Value, custom: bool) -> String {
        async fn never_runs(
            _child: DurableContext,
            _item: u32,
            _idx: usize,
        ) -> Result<u32, BoxError> {
            unreachable!("a terminal batch replays")
        }
        let ctx = test_ctx(terminal_batch_log(&payload.to_string()));
        let map = ctx.map(vec![1_u32], never_runs);
        let err = if custom {
            map.serdes(CallLog::default()).await_batch().await
        } else {
            map.await_batch().await
        }
        .expect_err("the record fails replay");
        crate::error::chain_string(&err)
    }

    /// A stored record without both `all` and `completionReason` fails
    /// replay with the parser's error.
    #[tokio::test]
    async fn malformed_stored_record_fails_replay() {
        let payload = serde_json::json!({"completionReason": "ALL_COMPLETED"});
        let err = js_replay_error(&payload, false).await;
        assert!(
            err.contains("batch record has `completionReason` without `all`"),
            "{err}"
        );
    }

    #[tokio::test]
    async fn serdes_item_with_non_string_result_fails_replay() {
        let payload = serde_json::json!({
            "all": [{"index": 0, "status": "SUCCEEDED", "name": "map-item-0", "result": 1}],
            "completionReason": "ALL_COMPLETED",
        });
        let err = js_replay_error(&payload, true).await;
        assert!(
            err.contains("batch record item 0: expected a string result"),
            "{err}"
        );
    }

    #[tokio::test]
    async fn js_item_without_name_fails_replay() {
        let payload = serde_json::json!({
            "all": [{"index": 0, "status": "SUCCEEDED", "result": 1}],
            "completionReason": "ALL_COMPLETED",
        });
        let err = js_replay_error(&payload, false).await;
        assert!(err.contains("batch record item 0: missing name"), "{err}");
    }

    #[tokio::test]
    async fn js_item_with_unknown_status_fails_replay() {
        let payload = serde_json::json!({
            "all": [{"index": 0, "status": "WEIRD", "name": "map-item-0"}],
            "completionReason": "ALL_COMPLETED",
        });
        let err = js_replay_error(&payload, false).await;
        assert!(err.contains("unknown item status: WEIRD"), "{err}");
    }

    #[tokio::test]
    async fn oversized_map_writes_js_summary() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let big = "x".repeat(101 * 1024);
        ctx.map(vec![0_u32, 1, 2], move |_child, _item, _idx| {
            let big = big.clone();
            async move { Ok(big) }
        })
        .await
        .expect("map succeeds");
        let parent = parent_succeed_update(&client);
        assert_eq!(
            parent.context_options().and_then(|c| c.replay_children),
            Some(true)
        );
        assert_eq!(
            parent_payload_json(&client),
            serde_json::json!({
                "type": "MapResult",
                "totalCount": 3,
                "successCount": 3,
                "failureCount": 0,
                "completionReason": "ALL_COMPLETED",
                "status": "SUCCEEDED",
                "itemStatuses": "SSS",
            })
        );
    }

    /// The oversized summary text has JS's key order, whether or not the
    /// build enables `serde_json`'s `preserve_order`.
    #[test]
    fn oversized_summary_text_has_js_key_order() {
        let result = BatchResult::new(
            vec![BatchItem::<u32>::new(
                0,
                "a".to_owned(),
                BatchItemStatus::Succeeded,
                Some(1),
                None,
                None,
            )],
            CompletionReason::AllCompleted,
        );
        assert_eq!(
            oversized_batch_summary(&result, MAP_SUB_TYPE, None),
            r#"{"type":"MapResult","totalCount":1,"successCount":1,"failureCount":0,"completionReason":"ALL_COMPLETED","status":"SUCCEEDED","itemStatuses":"S"}"#
        );
        assert_eq!(
            oversized_batch_summary(&result, PARALLEL_SUB_TYPE, None),
            r#"{"type":"ParallelResult","totalCount":1,"successCount":1,"failureCount":0,"startedCount":0,"completionReason":"ALL_COMPLETED","status":"SUCCEEDED","itemStatuses":"S"}"#
        );
        assert_eq!(
            oversized_batch_summary(&result, MAP_SUB_TYPE, Some("ok")),
            r#"{"type":"MapResult","totalCount":1,"successCount":1,"failureCount":0,"completionReason":"ALL_COMPLETED","status":"SUCCEEDED","itemStatuses":"S","summary":"ok"}"#
        );
    }

    /// The caller's summary is the last key of the summary text, as a JSON
    /// string, and the other keys keep their values.
    #[test]
    fn caller_summary_is_last_key() {
        let result = BatchResult::new(
            vec![BatchItem::<u32>::new(
                0,
                "a".to_owned(),
                BatchItemStatus::Succeeded,
                Some(1),
                None,
                None,
            )],
            CompletionReason::AllCompleted,
        );
        let plain = oversized_batch_summary(&result, MAP_SUB_TYPE, None);
        let text = oversized_batch_summary(&result, MAP_SUB_TYPE, Some("ok \"1\""));
        assert!(text.ends_with(r#","summary":"ok \"1\""}"#), "{text}");
        let mut value: serde_json::Value = serde_json::from_str(&text).expect("JSON");
        assert_eq!(value["summary"], "ok \"1\"");
        value.as_object_mut().expect("an object").remove("summary");
        assert_eq!(
            value,
            serde_json::from_str::<serde_json::Value>(&plain).expect("JSON")
        );
    }

    /// An oversized batch with a failed item records `F` and the status
    /// `FAILED`.
    #[tokio::test]
    async fn oversized_map_with_failure_writes_failed_status() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let big = "x".repeat(300 * 1024);
        ctx.map(vec![0_u32, 1], move |_child, item, _idx| {
            let big = big.clone();
            async move {
                if item == 0 {
                    Ok(big)
                } else {
                    Err("boom".into())
                }
            }
        })
        .completion(
            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1),
        )
        .await_batch()
        .await
        .expect("a tolerated failure is a batch result");
        let summary = parent_payload_json(&client);
        assert_eq!(summary["status"], "FAILED", "summary: {summary}");
        assert_eq!(summary["itemStatuses"], "SF");
        assert_eq!(summary["failureCount"], 1);
    }

    #[tokio::test]
    async fn oversized_parallel_writes_started_count() {
        use crate::future::Branch;
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let big = "x".repeat(300 * 1024);
        let branches = vec![
            Branch::new("big", move |_c| async move { Ok(big) }),
            Branch::new("slow", |c| async move {
                Ok(
                    c.step(|_| std::future::pending::<Result<String, BoxError>>())
                        .name("forever")
                        .await?,
                )
            }),
        ];
        let batch = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            ctx.parallel(branches)
                .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(1))
                .await_batch(),
        )
        .await
        .expect("the batch does not wait for the running branch")
        .expect("the batch succeeds");
        assert_eq!(batch.items[1].status, BatchItemStatus::Started);
        assert_eq!(
            parent_payload_json(&client),
            serde_json::json!({
                "type": "ParallelResult",
                "totalCount": 2,
                "successCount": 1,
                "failureCount": 0,
                "startedCount": 1,
                "completionReason": "MIN_SUCCESSFUL_REACHED",
                "status": "SUCCEEDED",
                "itemStatuses": "S-",
            })
        );
    }

    /// The oversized summary's `status` comes from `BatchResult::status()`:
    /// a predicate that completed the batch as succeeded writes
    /// `SUCCEEDED` although an item failed, and one that completed it as
    /// failed writes `FAILED` although no item failed.
    #[test]
    fn oversized_summary_status_follows_custom_completion() {
        let failed_item = || {
            BatchItem::<u32>::new(
                0,
                "a".to_owned(),
                BatchItemStatus::Failed,
                None,
                Some("boom".to_owned()),
                None,
            )
        };
        let succeeded_item = || {
            BatchItem::<u32>::new(
                0,
                "a".to_owned(),
                BatchItemStatus::Succeeded,
                Some(1),
                None,
                None,
            )
        };
        let summary = |items, reason| -> serde_json::Value {
            let result = BatchResult::new(items, reason);
            serde_json::from_str(&oversized_batch_summary(&result, MAP_SUB_TYPE, None))
                .expect("the summary is JSON")
        };
        let custom_ok = summary(
            vec![failed_item()],
            CompletionReason::CustomCompletionSucceeded,
        );
        assert_eq!(custom_ok["status"], "SUCCEEDED", "summary: {custom_ok}");
        assert_eq!(custom_ok["itemStatuses"], "F");
        assert_eq!(custom_ok["completionReason"], "CUSTOM_COMPLETION_SUCCEEDED");
        let custom_failed = summary(
            vec![succeeded_item()],
            CompletionReason::CustomCompletionFailed,
        );
        assert_eq!(
            custom_failed["status"], "FAILED",
            "summary: {custom_failed}"
        );
        assert_eq!(custom_failed["itemStatuses"], "S");
        assert_eq!(
            custom_failed["completionReason"],
            "CUSTOM_COMPLETION_FAILED"
        );
    }

    /// A failed item writes its non-empty frames and its data at both
    /// error levels, under `ChildContextError` with one cause.
    #[test]
    fn failed_item_writes_stack_trace_at_both_levels() {
        let mut item = BatchItem::<u32>::new(
            0,
            "a".to_owned(),
            BatchItemStatus::Failed,
            None,
            Some("it broke".to_owned()),
            Some("CustomFailure".to_owned()),
        );
        item.error_data = Some("data".to_owned());
        item.stack_trace = vec!["frame-a".to_owned(), "frame-b".to_owned()];
        let result = BatchResult::new(vec![item], CompletionReason::AllCompleted);
        let payload = record_json(&from_batch_result(&result, &[None], &ItemEncoding::AllJson));
        assert_eq!(
            payload.pointer("/all/0/error"),
            Some(&serde_json::json!({
                "ErrorType": "ChildContextError",
                "ErrorMessage": "it broke",
                "ErrorData": "data",
                "StackTrace": ["frame-a", "frame-b"],
                "Cause": {
                    "ErrorType": "CustomFailure",
                    "ErrorMessage": "it broke",
                    "ErrorData": "data",
                    "StackTrace": ["frame-a", "frame-b"],
                },
            }))
        );
    }

    /// A failed item reads type, message and data from `Cause` when
    /// `Cause` has them, and from the top level when `Cause` lacks them.
    /// Its frames come from `Cause` whenever `Cause` is present.
    #[tokio::test]
    async fn js_error_prefers_cause_and_falls_back_per_field() {
        let payload = serde_json::json!({
            "all": [
                {
                    "index": 0,
                    "status": "FAILED",
                    "name": "map-item-0",
                    "error": {
                        "ErrorType": "TopError",
                        "ErrorMessage": "top",
                        "ErrorData": "top-data",
                        "StackTrace": ["top-frame"],
                        "Cause": {
                            "ErrorType": "CauseError",
                            "ErrorMessage": "cause",
                            "ErrorData": "cause-data",
                            "StackTrace": ["cause-frame"],
                        },
                    },
                },
                {
                    "index": 1,
                    "status": "FAILED",
                    "name": "map-item-1",
                    "error": {
                        "ErrorType": "TopError",
                        "ErrorMessage": "top",
                        "ErrorData": "top-data",
                        "StackTrace": ["top-frame"],
                        "Cause": {},
                    },
                },
            ],
            "completionReason": "ALL_COMPLETED",
        });
        let replayed: BatchResult<u32> = test_ctx(terminal_batch_log(&payload.to_string()))
            .map(vec![1_u32, 2], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .completion(
                crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(2),
            )
            .await_batch()
            .await
            .expect("replay succeeds");
        let fields = |item: &BatchItem<u32>| {
            (
                item.error_type.clone(),
                item.error_message.clone(),
                item.error_data.clone(),
                item.stack_trace.clone(),
            )
        };
        assert_eq!(
            fields(&replayed.items[0]),
            (
                Some("CauseError".to_owned()),
                Some("cause".to_owned()),
                Some("cause-data".to_owned()),
                vec!["cause-frame".to_owned()],
            )
        );
        assert_eq!(
            fields(&replayed.items[1]),
            (
                Some("TopError".to_owned()),
                Some("top".to_owned()),
                Some("top-data".to_owned()),
                Vec::new(),
            )
        );
    }

    /// Replays a JS-form batch record `payload` through a map over
    /// `inputs` `u32` items with a recording item serdes. Returns the
    /// error text and the serdes calls.
    async fn js_replay_error_over(
        payload: &serde_json::Value,
        inputs: u32,
    ) -> (String, Vec<(&'static str, String)>) {
        async fn never_runs(
            _child: DurableContext,
            _item: u32,
            _idx: usize,
        ) -> Result<u32, BoxError> {
            unreachable!("a terminal batch replays")
        }
        let calls = CallLog::default();
        let err = test_ctx(terminal_batch_log(&payload.to_string()))
            .map((0..inputs).collect::<Vec<_>>(), never_runs)
            .serdes(calls.clone())
            .await_batch()
            .await
            .expect_err("the record fails replay");
        (crate::error::chain_string(&err), calls.calls())
    }

    /// A JS-form record with one succeeded item per index in `indexes`, in
    /// that order.
    fn js_record_with_indexes(indexes: &[usize]) -> serde_json::Value {
        let all: Vec<_> = indexes
            .iter()
            .map(|index| {
                serde_json::json!({
                    "index": index,
                    "status": "SUCCEEDED",
                    "name": format!("map-item-{index}"),
                    "result": "1",
                })
            })
            .collect();
        serde_json::json!({"all": all, "completionReason": "ALL_COMPLETED"})
    }

    /// A record whose `all` is not the started prefix in index order fails
    /// the replay before any item value is decoded.
    #[tokio::test]
    async fn js_record_with_malformed_indexes_fails_replay() {
        let cases: [(&[usize], &str); 4] = [
            (&[0, 2], "batch record item at position 1 has index 2"),
            (&[0, 0], "batch record item at position 1 has index 0"),
            (&[1, 0], "batch record item at position 0 has index 1"),
            (
                &[usize::MAX],
                "batch record item at position 0 has index 18446744073709551615",
            ),
        ];
        for (indexes, expected) in cases {
            let (err, calls) = js_replay_error_over(&js_record_with_indexes(indexes), 3).await;
            assert!(err.contains(expected), "indexes {indexes:?}: {err}");
            assert_eq!(calls, vec![], "indexes {indexes:?}");
        }
    }

    /// A record with more items than the current input fails the replay
    /// before any item value is decoded. A record as long as the input
    /// replays.
    #[tokio::test]
    async fn js_record_longer_than_the_input_fails_replay() {
        let (err, calls) = js_replay_error_over(&js_record_with_indexes(&[0, 1, 2, 3]), 3).await;
        assert!(
            err.contains("batch record has 4 items but the input has 3"),
            "{err}"
        );
        assert_eq!(calls, vec![]);

        let replayed: BatchResult<u32> = test_ctx(terminal_batch_log(
            &js_record_with_indexes(&[0, 1, 2]).to_string(),
        ))
        .map(vec![0_u32, 1, 2], |_child, _item, _idx| async move {
            unreachable!("a terminal batch replays")
        })
        .serdes(CallLog::default())
        .await_batch()
        .await
        .expect("a record as long as the input replays");
        assert_eq!(replayed.items.len(), 3);
    }

    /// The records of a batch whose items 0 and 2 completed while item 1
    /// ran, with `payload` as the oversized parent's payload.
    fn started_middle_log(payload: &str) -> CheckpointLog {
        CheckpointLog::from_records(vec![
            decision_record_parent("1", payload),
            succeeded_record("1-1", "\"a\""),
            succeeded_record("1-3", "\"c\""),
        ])
    }

    /// Replays a map of 4 items from `log`, without running a body.
    async fn replay_started_middle(log: CheckpointLog) -> BatchResult<String> {
        test_ctx(log)
            .map(vec![0_usize, 1, 2, 3], |_child, _item, _idx| async move {
                unreachable!("replay must not re-run any item body")
            })
            .completion(crate::builders::map_parallel::CompletionConfig::with_min_successful(2))
            .await_batch()
            .await
            .expect("replay succeeds")
    }

    fn started_middle_rows(
        batch: &BatchResult<String>,
    ) -> Vec<(usize, BatchItemStatus, Option<String>)> {
        batch
            .items
            .iter()
            .map(|i| (i.index, i.status, i.result.clone()))
            .collect()
    }

    const STARTED_MIDDLE: [(usize, BatchItemStatus, Option<&str>); 3] = [
        (0, BatchItemStatus::Succeeded, Some("a")),
        (1, BatchItemStatus::Started, None),
        (2, BatchItemStatus::Succeeded, Some("c")),
    ];

    fn started_middle_expected() -> Vec<(usize, BatchItemStatus, Option<String>)> {
        STARTED_MIDDLE
            .iter()
            .map(|(i, s, r)| (*i, *s, r.map(str::to_owned)))
            .collect()
    }

    #[tokio::test]
    async fn python_decision_record_replays() {
        let batch = replay_started_middle(started_middle_log(
            r#"{"totalCount":3,"completionReason":"MIN_SUCCESSFUL_REACHED","startedIndexes":[1]}"#,
        ))
        .await;
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(started_middle_rows(&batch), started_middle_expected());
    }

    /// `ContextOptions.replay_children` of `update`.
    fn depth_flag(update: &OperationUpdate) -> Option<bool> {
        update
            .context_options()
            .and_then(aws_sdk_lambda::types::ContextOptions::replay_children)
    }

    /// The update of the operation named `name` with `action`.
    fn depth_update(
        client: &crate::client::InMemoryExecutionClient,
        name: &str,
        action: &OperationAction,
    ) -> OperationUpdate {
        client
            .recorded_updates()
            .into_iter()
            .find(|u| u.name() == Some(name) && u.action() == action)
            .unwrap_or_else(|| unreachable!("no {action:?} update for {name}"))
    }

    /// Runs a map named `m` over `[1, 2]` whose items return ten times
    /// their input, on a root with the plugin child operations depth
    /// `depth`.
    async fn depth_map(depth: u32) -> Arc<crate::client::InMemoryExecutionClient> {
        let (ctx, client) = DurableContext::test_context_with_depth(depth);
        let out: Vec<u32> = ctx
            .map(
                vec![1_u32, 2],
                |_child, item, _idx| async move { Ok(item * 10) },
            )
            .name("m")
            .await
            .expect("map succeeds");
        assert_eq!(out, vec![10, 20]);
        client
    }

    /// Depth 1 flags the container's SUCCEED and keeps the payload a run
    /// without the depth writes; the item records are not flagged.
    #[tokio::test]
    async fn preserved_container_records_result_payload() {
        let plain_client = depth_map(0).await;
        let plain = depth_update(&plain_client, "m", &OperationAction::Succeed);
        let client = depth_map(1).await;
        let container = depth_update(&client, "m", &OperationAction::Succeed);
        assert_eq!(depth_flag(&container), Some(true));
        assert_eq!(depth_flag(&plain), None);
        assert_eq!(container.payload(), plain.payload());
        for item in ["map-item-0", "map-item-1"] {
            let update = depth_update(&client, item, &OperationAction::Succeed);
            assert_eq!(depth_flag(&update), None, "{item}");
        }
    }

    /// Depth 2 also flags each item's SUCCEED, which keeps its payload.
    #[tokio::test]
    async fn depth_two_flags_items() {
        let client = depth_map(2).await;
        for (item, payload) in [("map-item-0", "10"), ("map-item-1", "20")] {
            let update = depth_update(&client, item, &OperationAction::Succeed);
            assert_eq!(depth_flag(&update), Some(true), "{item}");
            assert_eq!(update.payload(), Some(payload), "{item}");
        }
    }

    /// Within the depth, a failed item's FAIL carries the flag, and so does
    /// the FAIL of an item whose result fails to serialize.
    #[tokio::test]
    async fn preserved_item_failures_have_flag() {
        for (depth, flag) in [(2, Some(true)), (1, None)] {
            let (ctx, client) = DurableContext::test_context_with_depth(depth);
            let batch = ctx
                .map(vec![0_u32], |_child, _item, _idx| async move {
                    Err::<u32, BoxError>("boom".into())
                })
                .name("m")
                .completion(
                    crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(
                        1,
                    ),
                )
                .await_batch()
                .await
                .expect("the batch tolerates the failure");
            assert_eq!(batch.items[0].status, BatchItemStatus::Failed);
            let fail = depth_update(&client, "map-item-0", &OperationAction::Fail);
            assert_eq!(depth_flag(&fail), flag, "body failure at depth {depth}");

            let (ctx, client) = DurableContext::test_context_with_depth(depth);
            let batch = ctx
                .map(vec![0_u32], |_child, _item, _idx| async move {
                    Ok("x".to_owned())
                })
                .name("m")
                .serdes(FailingResultSerdes)
                .completion(
                    crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(
                        1,
                    ),
                )
                .await_batch()
                .await
                .expect("the batch tolerates the failure");
            assert_eq!(batch.items[0].status, BatchItemStatus::Failed);
            let fail = depth_update(&client, "map-item-0", &OperationAction::Fail);
            assert_eq!(
                depth_flag(&fail),
                flag,
                "serialization failure at depth {depth}"
            );
        }
    }

    /// A client that permanently rejects the first update `rejects`
    /// matches, and records every other update in the in-memory client.
    #[derive(Debug)]
    struct RejectsFirstMatch {
        inner: Arc<crate::client::InMemoryExecutionClient>,
        rejects: fn(&OperationUpdate) -> bool,
        done: AtomicBool,
    }

    impl crate::client::ExecutionClient for RejectsFirstMatch {
        fn checkpoint(
            &self,
            arn: &str,
            token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::CheckpointOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            if updates.iter().any(|u| (self.rejects)(u)) && !self.done.swap(true, Ordering::SeqCst)
            {
                return Box::pin(async {
                    Err(crate::client::ExecutionClientError::new_non_retryable(
                        "rejected",
                    ))
                });
            }
            self.inner.checkpoint(arn, token, updates)
        }

        fn get_state(
            &self,
            arn: &str,
            token: &str,
            marker: Option<&str>,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            crate::client::GetStateOutput,
                            crate::client::ExecutionClientError,
                        >,
                    > + Send
                    + '_,
            >,
        > {
            self.inner.get_state(arn, token, marker)
        }
    }

    /// When an item's outcome write is rejected, within the depth or not,
    /// no terminal FAIL replaces it, so the item's record stays at its
    /// accepted START: after a rejected SUCCEED, a rejected FAIL, and a
    /// rejected FAIL of a result that fails to serialize.
    #[tokio::test]
    async fn preserved_item_rejected_outcome_sends_no_replacement_fail() {
        fn item_outcome(u: &OperationUpdate) -> bool {
            u.name() == Some("map-item-0")
                && matches!(u.action(), OperationAction::Succeed | OperationAction::Fail)
        }
        for case in ["succeed", "fail", "serialize"] {
            for depth in [2, 1] {
                let inner = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
                let client = Arc::new(RejectsFirstMatch {
                    inner: Arc::clone(&inner),
                    rejects: item_outcome,
                    done: AtomicBool::new(false),
                });
                let ctx = DurableContext::test_context_with_depth_and_client(depth, client);
                let outcome = tokio::time::timeout(
                    std::time::Duration::from_secs(5),
                    crate::driver::test_support::drive_handler(ctx, None, move |ctx| async move {
                        let builder = ctx.map(vec![0_u32], move |_child, _item, _idx| async move {
                            if case == "fail" {
                                Err::<String, BoxError>("boom".into())
                            } else {
                                Ok("x".to_owned())
                            }
                        });
                        let result = if case == "serialize" {
                            builder.name("m").serdes(FailingResultSerdes).await
                        } else {
                            builder.name("m").await
                        };
                        result.map_err(crate::driver::test_support::wire_err)?;
                        Ok("done".to_owned())
                    }),
                )
                .await
                .expect("the invocation ends within 5 s")
                .expect("no panic");
                assert!(
                    matches!(outcome, crate::driver::InvocationOutcome::Failed { .. }),
                    "{case}: {outcome:?}"
                );
                let accepted: Vec<OperationAction> = inner
                    .recorded_updates()
                    .into_iter()
                    .filter(|u| u.name() == Some("map-item-0"))
                    .map(|u| u.action().clone())
                    .collect();
                assert_eq!(
                    accepted,
                    [OperationAction::Start],
                    "{case} at depth {depth}: no replacement FAIL"
                );
            }
        }
    }

    /// A preserved batch's own result replays as the decision record does:
    /// its started item stays `Started`, and no item body runs.
    #[tokio::test]
    async fn preserved_full_result_replays_like_the_decision_record() {
        let batch = replay_started_middle(started_middle_log(
            r#"{"all":[{"index":0,"status":"SUCCEEDED","name":"map-item-0","result":"a"},{"index":1,"status":"STARTED","name":"map-item-1"},{"index":2,"status":"SUCCEEDED","name":"map-item-2","result":"c"}],"completionReason":"MIN_SUCCESSFUL_REACHED"}"#,
        ))
        .await;
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(started_middle_rows(&batch), started_middle_expected());
    }

    /// A preserved batch result with an unknown item status fails the
    /// replay, and no item body runs.
    #[tokio::test]
    async fn preserved_full_result_rejects_unknown_item_status() {
        let log = started_middle_log(
            r#"{"all":[{"index":0,"status":"DONE","name":"map-item-0"}],"completionReason":"ALL_COMPLETED"}"#,
        );
        let result: Result<Vec<String>, _> = test_ctx(log)
            .map(vec![0_usize, 1, 2, 3], |_child, _item, _idx| async move {
                unreachable!("a corrupt record must not re-run any item")
            })
            .await;
        let err = result.expect_err("an unknown status is corrupt");
        assert!(
            crate::error::chain_string(&err).contains("DONE"),
            "{}",
            crate::error::chain_string(&err)
        );
    }

    /// A preserved batch result whose items are not the started prefix in
    /// index order fails the replay, as an ordinary batch record does, and
    /// no item body runs.
    #[tokio::test]
    async fn preserved_full_result_rejects_misplaced_indexes() {
        for all in [
            // A duplicate index.
            r#"[{"index":0,"status":"SUCCEEDED","name":"map-item-0","result":"a"},{"index":0,"status":"STARTED","name":"map-item-0"}]"#,
            // Reordered indexes.
            r#"[{"index":1,"status":"STARTED","name":"map-item-1"},{"index":0,"status":"SUCCEEDED","name":"map-item-0","result":"a"}]"#,
        ] {
            let log = started_middle_log(&format!(
                r#"{{"all":{all},"completionReason":"MIN_SUCCESSFUL_REACHED"}}"#
            ));
            let result: Result<Vec<String>, _> = test_ctx(log)
                .map(vec![0_usize, 1, 2, 3], |_child, _item, _idx| async move {
                    unreachable!("a corrupt record must not re-run any item")
                })
                .await;
            let err = result.expect_err("a misplaced index is corrupt");
            assert!(
                crate::error::chain_string(&err).contains("at position"),
                "{all}: {}",
                crate::error::chain_string(&err)
            );
        }
    }

    /// A preserved batch result that the result serdes cannot decode fails
    /// the replay with the serdes error.
    #[tokio::test]
    async fn preserved_full_result_decode_failure_fails_replay() {
        let log = started_middle_log(r#"{"all":[],"completionReason":"ALL_COMPLETED"}"#);
        let result: Result<Vec<String>, _> = test_ctx(log)
            .map(vec![0_usize, 1, 2, 3], |_child, _item, _idx| async move {
                unreachable!("a payload that fails to decode must not re-run any item")
            })
            .result_serdes(FailingResultSerdes)
            .await;
        let err = result.expect_err("the decode fails");
        assert!(
            crate::error::chain_string(&err).contains("cannot decode"),
            "{}",
            crate::error::chain_string(&err)
        );
    }

    /// The JS summary replays to the same result as the Python decision
    /// record.
    #[tokio::test]
    async fn js_summary_replays_like_the_decision_record() {
        let batch = replay_started_middle(started_middle_log(
            r#"{"type":"MapResult","totalCount":3,"successCount":2,"failureCount":0,"completionReason":"MIN_SUCCESSFUL_REACHED","status":"SUCCEEDED","itemStatuses":"S-S"}"#,
        ))
        .await;
        assert_eq!(batch.reason, CompletionReason::MinSuccessfulReached);
        assert_eq!(started_middle_rows(&batch), started_middle_expected());
    }

    /// The order of rule 10: JS summary, Python decision record, corrupt.
    #[test]
    fn replay_children_payload_is_read_in_order() {
        let record = parse_replay_children_payload(Some(
            r#"{"itemStatuses":"S-F","completionReason":"ALL_COMPLETED","totalCount":99}"#,
        ))
        .expect("a JS summary parses")
        .expect("a JS summary is a decision");
        assert_eq!(record.total_count, 3, "the length of itemStatuses wins");
        assert_eq!(record.completed_indexes, Some(vec![0, 2]));
        assert_eq!(record.started_indexes, None);
        assert_eq!(record.completion_reason, "ALL_COMPLETED");

        for statuses in [r#""""#, r#""SX""#, "1", "null"] {
            let payload =
                format!(r#"{{"itemStatuses":{statuses},"completionReason":"ALL_COMPLETED"}}"#);
            let err = parse_replay_children_payload(Some(&payload))
                .expect_err("an invalid itemStatuses is corrupt");
            assert!(
                crate::error::chain_string(&err).contains("itemStatuses must be a non-empty"),
                "{statuses}"
            );
        }

        // Without a completion reason, the plan rejects the record.
        let record = parse_replay_children_payload(Some(r#"{"itemStatuses":"S"}"#))
            .expect("parses")
            .expect("a JS summary is a decision");
        let err = ReplayPlan::from_record(&record, 1).expect_err("no reason");
        assert!(crate::error::chain_string(&err).contains("unknown completionReason"));

        let record = parse_replay_children_payload(Some(
            r#"{"totalCount":2,"completionReason":"ALL_COMPLETED","completedIndexes":[0]}"#,
        ))
        .expect("a decision record parses")
        .expect("a decision record is a decision");
        assert_eq!(record.completed_indexes, Some(vec![0]));
        let record = parse_replay_children_payload(Some(
            r#"{"totalCount":2,"completionReason":"ALL_COMPLETED","startedIndexes":[1]}"#,
        ))
        .expect("a decision record parses")
        .expect("a decision record is a decision");
        assert_eq!(record.started_indexes, Some(vec![1]));

        // An absent or empty payload is corrupt.
        for corrupt in [None, Some(""), Some("  ")] {
            let err = parse_replay_children_payload(corrupt)
                .expect_err("an absent or empty payload is corrupt");
            assert!(
                crate::error::chain_string(&err).contains("malformed batch decision record"),
                "{corrupt:?}"
            );
        }

        // Every other non-empty payload is the batch's own result, whose
        // items re-run.
        for result in [
            "not json",
            r#"{"unrelated":true}"#,
            r#"{"totalCount":2,"completionReason":"ALL_COMPLETED"}"#,
            r#"{"startedIndexes":[]}"#,
            "[1]",
            r#"{"all":[],"completionReason":"ALL_COMPLETED"}"#,
        ] {
            let parsed = parse_replay_children_payload(Some(result)).expect("not corrupt");
            assert!(parsed.is_none(), "{result}");
        }
    }

    #[tokio::test]
    async fn item_serdes_called_once_per_item() {
        let calls = CallLog::default();
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let out: Vec<u32> = ctx
            .map(
                vec![10_u32, 20],
                |_child, item, _idx| async move { Ok(item) },
            )
            .serdes(calls.clone())
            .await
            .expect("map succeeds");
        assert_eq!(out, vec![10, 20]);
        let (c0, c1) = (wire_of("1-1"), wire_of("1-2"));
        let mut live = vec![
            ("deserialize", c0.clone()),
            ("deserialize", c1.clone()),
            ("serialize", c0.clone()),
            ("serialize", c1.clone()),
        ];
        live.sort();
        assert_eq!(calls.calls(), live);

        let replay_calls = CallLog::default();
        let replayed: Vec<u32> = test_ctx(terminal_batch_log(&parent_payload(&client)))
            .map(vec![10_u32, 20], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .serdes(replay_calls.clone())
            .await
            .expect("replay succeeds");
        assert_eq!(replayed, vec![10, 20]);
        let mut replay = vec![("deserialize", c0), ("deserialize", c1)];
        replay.sort();
        assert_eq!(replay_calls.calls(), replay);
        assert!(
            calls
                .calls()
                .iter()
                .chain(replay_calls.calls().iter())
                .all(|(_, id)| !id.contains("/item-"))
        );
    }

    #[tokio::test]
    async fn batch_item_name_survives_summary_replay() {
        use crate::future::Branch;
        let branches = || {
            vec![
                Branch::new("a", |_c| async { Err::<u32, BoxError>("a failed".into()) }),
                Branch::unnamed(|_c| async { Err::<u32, BoxError>("b failed".into()) }),
            ]
        };
        let tolerate = || {
            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_percentage(
                100.0,
            )
            .expect("a valid percentage")
        };
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        ctx.parallel(branches())
            .completion(tolerate())
            .await_batch()
            .await
            .expect("tolerated failures are a batch result");

        let replayed = test_ctx(terminal_batch_log(&parent_payload(&client)))
            .parallel(vec![
                Branch::<u32>::new("a", |_c| async { unreachable!("a terminal batch replays") }),
                Branch::<u32>::unnamed(|_c| async { unreachable!("a terminal batch replays") }),
            ])
            .completion(tolerate())
            .await_batch()
            .await
            .expect("replay succeeds");
        let names: Vec<&str> = replayed.items.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(names, ["a", "parallel-branch-1"]);
        let error_names: Vec<&str> = replayed.errors().map(|e| e.name).collect();
        assert_eq!(error_names, names);
    }

    /// A Flat map writes each item value into the record, and replays it.
    #[tokio::test]
    async fn flat_map_values_replay_from_the_record() {
        let (ctx, client) = test_ctx_with_client(CheckpointLog::empty());
        let live: Vec<u32> = ctx
            .map(
                vec![1_u32, 2],
                |_child, item, _idx| async move { Ok(item * 10) },
            )
            .nesting(NestingMode::Flat)
            .await
            .expect("map succeeds");
        assert_eq!(live, vec![10, 20]);
        let payload = parent_payload(&client);
        let replayed: Vec<u32> = test_ctx(terminal_batch_log(&payload))
            .map(vec![1_u32, 2], |_child, _item, _idx| async move {
                unreachable!("a terminal batch replays")
            })
            .nesting(NestingMode::Flat)
            .await
            .expect("replay succeeds");
        assert_eq!(replayed, live);
    }

    /// An item replayed from its terminal child record writes the record's
    /// wire string into the batch record.
    #[tokio::test]
    async fn resumed_terminal_item_writes_its_recorded_value() {
        let log = CheckpointLog::from_records(vec![
            (
                wire_of("1"),
                CheckpointRecord {
                    status: CheckpointStatus::Started,
                    result: None,
                    ..succeeded_record("1", "").1
                },
            ),
            succeeded_record("1-1", "\"hello\""),
        ]);
        let (ctx, client) = test_ctx_with_client(log);
        let out: Vec<String> = ctx
            .map(vec![0_u32], |_child, _item, _idx| async move {
                unreachable!("a terminal child replays")
            })
            .await
            .expect("map succeeds");
        assert_eq!(out, vec!["hello"]);
        assert_eq!(parent_payload_json(&client)["all"][0]["result"], "hello");
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: an item panics on purpose, and test assertions
mod coordinator_tests {
    use crate::DurableContext;
    use crate::builders::map_parallel::CompletionConfig;
    use crate::driver::InvocationOutcome;
    use crate::driver::test_support::{
        ScriptedClient, drive_handler, named, operation_like, scripted_ctx, wire_err,
    };
    use aws_sdk_lambda::types::{OperationAction, OperationStatus};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    /// Counts the items whose body is running and keeps the peak.
    #[derive(Default)]
    struct InFlight {
        now: AtomicUsize,
        peak: AtomicUsize,
        events: Mutex<Vec<String>>,
    }

    impl InFlight {
        fn enter(&self, idx: usize) {
            let now = self.now.fetch_add(1, Ordering::SeqCst) + 1;
            self.peak.fetch_max(now, Ordering::SeqCst);
            self.events
                .lock()
                .expect("lock")
                .push(format!("start{idx}"));
        }

        fn leave(&self, idx: usize) {
            self.events.lock().expect("lock").push(format!("end{idx}"));
            self.now.fetch_sub(1, Ordering::SeqCst);
        }

        fn position(&self, event: &str) -> usize {
            self.events
                .lock()
                .expect("lock")
                .iter()
                .position(|e| e == event)
                .unwrap_or_else(|| panic!("no event {event}"))
        }
    }

    #[tokio::test(start_paused = true)]
    async fn waiting_item_keeps_slot_and_continues() {
        let client = Arc::new(ScriptedClient::new(|updates, history| {
            if named(updates, "s1", &OperationAction::Succeed).is_none() {
                return Vec::new();
            }
            named(history, "w0", &OperationAction::Start)
                .map(|start| {
                    operation_like(start, OperationStatus::Succeeded)
                        .build()
                        .expect("all required fields set")
                })
                .into_iter()
                .collect()
        }));
        let ctx = scripted_ctx(&client);
        let flight = Arc::new(InFlight::default());
        let body_flight = Arc::clone(&flight);
        let body_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let batch = ctx
                .map(
                    vec![0_u32, 1, 2],
                    move |child: DurableContext, _item, idx| {
                        let flight = Arc::clone(&body_flight);
                        let client = Arc::clone(&body_client);
                        async move {
                            flight.enter(idx);
                            match idx {
                                0 => {
                                    child.wait(Duration::from_secs(1)).name("w0").await?;
                                    child.step(|_| async { Ok(0_u32) }).name("after0").await?;
                                }
                                1 => {
                                    child
                                        .step(move |_| async move {
                                            // The response that completes w0
                                            // comes after w0 registered.
                                            for _ in 0..1000 {
                                                if client.received("w0", &OperationAction::Start) {
                                                    return Ok(1_u32);
                                                }
                                                tokio::time::sleep(Duration::from_millis(1)).await;
                                            }
                                            Err("w0 never started".into())
                                        })
                                        .name("s1")
                                        .await?;
                                }
                                _ => {
                                    child.step(|_| async { Ok(2_u32) }).name("s2").await?;
                                }
                            }
                            flight.leave(idx);
                            Ok(idx)
                        }
                    },
                )
                .max_concurrency(2)
                .await_batch()
                .await
                .map_err(wire_err)?;
            let statuses: Vec<String> = batch
                .items
                .iter()
                .map(|item| format!("{:?}", item.status))
                .collect();
            Ok(statuses.join(","))
        })
        .await
        .expect("no panic");
        assert_eq!(
            outcome,
            InvocationOutcome::Complete("Succeeded,Succeeded,Succeeded".to_owned()),
            "the batch completes in one invocation"
        );
        assert_eq!(flight.peak.load(Ordering::SeqCst), 2);
        assert!(
            flight.position("end1") < flight.position("start2"),
            "item 2 starts after item 1 finished"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn item_panic_while_others_wait_propagates() {
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let _ = ctx
                .map(
                    vec![0_u32, 1, 2],
                    |child: DurableContext, _item, idx| async move {
                        if idx == 0 {
                            child
                                .step(|_| async {
                                    tokio::time::sleep(Duration::from_millis(10)).await;
                                    Ok(0_u32)
                                })
                                .await?;
                            panic!("boom while others wait");
                        }
                        child.wait(Duration::from_secs(3600)).await?;
                        Ok(idx)
                    },
                )
                .max_concurrency(3)
                .await;
            Ok("done".to_owned())
        })
        .await;
        let Err(payload) = outcome else {
            panic!("expected the item panic, got {outcome:?}");
        };
        assert_eq!(
            payload.downcast_ref::<&str>(),
            Some(&"boom while others wait")
        );
    }

    #[tokio::test(start_paused = true)]
    async fn early_completion_cancels_running_item_while_others_wait() {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let batch = ctx
                .map(
                    vec![0_u32, 1, 2, 3],
                    |child: DurableContext, _item, idx| async move {
                        match idx {
                            0 => {}
                            1 | 2 => child.wait(Duration::from_secs(3600)).await?,
                            _ => {
                                child
                                    .step(|_| async {
                                        tokio::time::sleep(Duration::from_millis(800)).await;
                                        Ok(())
                                    })
                                    .name("a")
                                    .await?;
                                child.step(|_| async { Ok(()) }).name("late").await?;
                            }
                        }
                        Ok(idx)
                    },
                )
                .max_concurrency(4)
                .completion(CompletionConfig::with_min_successful(1))
                .await_batch()
                .await
                .map_err(wire_err)?;
            ctx.hold_activity(ctx.coordinator().tasks().wait_idle())
                .await;
            let waits = ctx.coordinator().live_waits();
            let statuses: Vec<String> = batch
                .items
                .iter()
                .map(|item| format!("{:?}", item.status))
                .collect();
            Ok(format!("{}:{waits}", statuses.join(",")))
        })
        .await
        .expect("no panic");
        assert_eq!(
            outcome,
            InvocationOutcome::Complete("Succeeded,Started,Started,Started:0".to_owned())
        );
        assert!(
            client.updates().iter().all(|u| u.name() != Some("late")),
            "the cancelled item wrote no later update"
        );
        assert_eq!(coordinator.tasks().live(), 0);
    }
}

/// The batch terminals (`.await`, `await_batch()` and `spawn_batch()`)
/// driven through `LocalRunner`.
#[cfg(all(test, feature = "test-util"))]
mod batch_terminal_tests {
    use std::future::Future;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    use super::{BatchItemStatus, BatchResult, CompletionReason, MAX_CONCURRENCY_ZERO_MESSAGE};
    use crate::builders::map_parallel::CompletionConfig;
    use crate::test_util::{ExecutionStatus, LocalRunner};
    use crate::{BoxError, Branch, DurableContext};

    /// `(index, name, status, result)` of each item, and the reason.
    type Record = (
        Vec<(usize, String, BatchItemStatus, Option<i32>)>,
        CompletionReason,
    );

    fn record_of(batch: &BatchResult<i32>) -> Record {
        let items = batch
            .items
            .iter()
            .map(|item| (item.index, item.name.clone(), item.status, item.result))
            .collect();
        (items, batch.reason)
    }

    fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
        mutex
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    type ItemFuture = std::pin::Pin<Box<dyn Future<Output = Result<i32, BoxError>> + Send>>;

    /// `map(vec![1, 2])` named `m`, where each item's step appends the
    /// current invocation number to `log` and returns `i * 10`.
    fn logged_map(
        ctx: &DurableContext,
        invocation: usize,
        log: &Arc<Mutex<Vec<usize>>>,
    ) -> crate::builders::MapBuilder<
        i32,
        i32,
        impl Fn(DurableContext, i32, usize) -> ItemFuture + Send + Sync + 'static,
        ItemFuture,
    > {
        let log = Arc::clone(log);
        ctx.map(vec![1, 2], move |child, i: i32, _idx| -> ItemFuture {
            let log = Arc::clone(&log);
            Box::pin(async move {
                child
                    .step(move |_| async move {
                        lock(&log).push(invocation);
                        Ok(i * 10)
                    })
                    .name("scale")
                    .await
                    .map_err(Into::into)
            })
        })
        .name("m")
    }

    #[tokio::test]
    async fn spawn_batch_runs_while_the_handler_waits() {
        let invocations = Arc::new(AtomicUsize::new(0));
        let log = Arc::new(Mutex::new(Vec::new()));
        let (inv, step_log) = (Arc::clone(&invocations), Arc::clone(&log));
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let invocation = inv.fetch_add(1, Ordering::SeqCst) + 1;
                    let log = Arc::clone(&step_log);
                    async move {
                        let batch = logged_map(&ctx, invocation, &log).spawn_batch();
                        ctx.wait(Duration::from_secs(1)).await?;
                        let batch = batch.await?;
                        Ok::<_, BoxError>(batch.results().copied().collect::<Vec<_>>())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Succeeded);
        assert_eq!(result.output(), Some(&vec![10, 20]));
        assert_eq!(result.invocation_count(), 2);
        assert_eq!(*lock(&log), [1, 1]);
    }

    #[tokio::test]
    async fn spawn_batch_equals_await_batch() {
        let spawned: Arc<Mutex<Vec<Record>>> = Arc::default();
        let awaited: Arc<Mutex<Vec<Record>>> = Arc::default();

        let records = Arc::clone(&spawned);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let records = Arc::clone(&records);
                    async move {
                        let log = Arc::default();
                        let batch = logged_map(&ctx, 0, &log).spawn_batch();
                        ctx.wait(Duration::from_secs(1)).await?;
                        let batch = batch.await?;
                        lock(&records).push(record_of(&batch));
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Succeeded);

        let records = Arc::clone(&awaited);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let records = Arc::clone(&records);
                    async move {
                        let log = Arc::default();
                        let batch = logged_map(&ctx, 0, &log).await_batch().await?;
                        lock(&records).push(record_of(&batch));
                        ctx.wait(Duration::from_secs(1)).await?;
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Succeeded);

        let spawned = lock(&spawned).clone();
        let awaited = lock(&awaited).clone();
        let [spawned] = spawned.as_slice() else {
            unreachable!("A awaits the batch once, after the wait: {spawned:?}");
        };
        assert_eq!(awaited.len(), 2, "B awaits the batch in both invocations");
        for record in &awaited {
            assert_eq!(record, spawned);
        }
    }

    #[tokio::test]
    async fn parallel_tolerated_failure_percentage_fails_the_batch() {
        let seen: Arc<Mutex<Option<Record>>> = Arc::default();
        let slot = Arc::clone(&seen);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let slot = Arc::clone(&slot);
                    async move {
                        let branches = vec![
                            Branch::new("ok", |_| async { Ok(1) }),
                            Branch::new("bad-1", |_| async { Err::<i32, BoxError>("boom".into()) }),
                            Branch::new("bad-2", |_| async { Err::<i32, BoxError>("boom".into()) }),
                        ];
                        let batch = ctx
                            .parallel(branches)
                            .max_concurrency(1)
                            .completion(
                                CompletionConfig::with_tolerated_failure_percentage(50.0)
                                    .expect("a valid percentage"),
                            )
                            .await_batch()
                            .await?;
                        *lock(&slot) = Some(record_of(&batch));
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Succeeded);
        let (items, reason) = lock(&seen).clone().expect("the handler recorded the batch");
        let statuses: Vec<_> = items
            .iter()
            .map(|(index, _, status, value)| (*index, *status, *value))
            .collect();
        assert_eq!(
            statuses,
            [
                (0, BatchItemStatus::Succeeded, Some(1)),
                (1, BatchItemStatus::Failed, None),
                (2, BatchItemStatus::Failed, None),
            ]
        );
        assert_eq!(reason, CompletionReason::FailureToleranceExceeded);
    }

    /// Records a step at the first position in invocation 1, then runs a
    /// map named `m` there on replay, through `await_batch()` or `.await`.
    async fn replay_identity_case(
        use_await_batch: bool,
    ) -> (Option<String>, Option<String>, usize) {
        let invocations = Arc::new(AtomicUsize::new(0));
        let bodies = Arc::new(AtomicUsize::new(0));
        let ran = Arc::clone(&bodies);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let first = invocations.fetch_add(1, Ordering::SeqCst) == 0;
                    let ran = Arc::clone(&ran);
                    async move {
                        if first {
                            ctx.step(|_| async { Ok(1_i32) }).name("s").await?;
                            ctx.wait(Duration::from_secs(1)).await?;
                            return Ok::<_, BoxError>(());
                        }
                        let map = ctx
                            .map(vec![1], move |_child, i: i32, _idx| {
                                let ran = Arc::clone(&ran);
                                async move {
                                    ran.fetch_add(1, Ordering::SeqCst);
                                    Ok(i)
                                }
                            })
                            .name("m");
                        if use_await_batch {
                            map.await_batch().await?;
                        } else {
                            map.await?;
                        }
                        Ok(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Failed);
        (
            result.error_type().map(str::to_owned),
            result.error_message().map(str::to_owned),
            bodies.load(Ordering::SeqCst),
        )
    }

    #[tokio::test]
    async fn await_batch_checks_replay_identity_like_await() {
        let batch = replay_identity_case(true).await;
        let plain = replay_identity_case(false).await;
        assert_eq!(batch.0.as_deref(), Some("NonDeterministicExecutionError"));
        assert_eq!(plain.0.as_deref(), Some("NonDeterministicExecutionError"));
        assert!(batch.1.is_some());
        assert_eq!(batch.1, plain.1);
        assert_eq!((batch.2, plain.2), (0, 0), "no item body ran");
    }

    #[tokio::test]
    async fn parallel_spawn_batch_returns_branch_statuses() {
        let seen: Arc<Mutex<Option<Record>>> = Arc::default();
        let slot = Arc::clone(&seen);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let slot = Arc::clone(&slot);
                    async move {
                        let branches = vec![
                            Branch::new("ok", |_| async { Ok(1) }),
                            Branch::new("bad", |_| async { Err::<i32, BoxError>("boom".into()) }),
                        ];
                        let batch = ctx
                            .parallel(branches)
                            .completion(CompletionConfig::with_tolerated_failure_count(1))
                            .spawn_batch();
                        ctx.wait(Duration::from_secs(1)).await?;
                        let batch = batch.await?;
                        *lock(&slot) = Some(record_of(&batch));
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Succeeded);
        let (items, reason) = lock(&seen).clone().expect("the handler recorded the batch");
        let statuses: Vec<_> = items
            .iter()
            .map(|(index, _, status, value)| (*index, *status, *value))
            .collect();
        assert_eq!(
            statuses,
            [
                (0, BatchItemStatus::Succeeded, Some(1)),
                (1, BatchItemStatus::Failed, None),
            ]
        );
        assert_eq!(reason, CompletionReason::AllCompleted);
    }

    #[derive(Clone, Copy)]
    enum Terminal {
        Await,
        AwaitBatch,
        SpawnBatch,
    }

    async fn max_concurrency_zero_case(terminal: Terminal) {
        let after = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&after);
        let result = LocalRunner::new()
            .run(
                move |(): (), ctx: DurableContext| {
                    let counter = Arc::clone(&counter);
                    async move {
                        let map = ctx
                            .map(vec![1, 2], |_child, i: i32, _idx| async move { Ok(i) })
                            .name("m")
                            .max_concurrency(0);
                        match terminal {
                            Terminal::Await => drop(map.await),
                            Terminal::AwaitBatch => drop(map.await_batch().await),
                            Terminal::SpawnBatch => drop(map.spawn_batch().await),
                        }
                        counter.fetch_add(1, Ordering::SeqCst);
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Failed);
        assert_eq!(result.error_type(), Some("Error"));
        assert_eq!(result.error_message(), Some(MAX_CONCURRENCY_ZERO_MESSAGE));
        assert_eq!(
            MAX_CONCURRENCY_ZERO_MESSAGE,
            "Invalid max_concurrency: 0. Must be a positive number or unset for unlimited \
             concurrency."
        );
        assert!(
            result.operation("m").is_none(),
            "no batch record is written"
        );
        assert_eq!(after.load(Ordering::SeqCst), 0, "the await never resolves");
    }

    #[tokio::test]
    async fn max_concurrency_zero_fails_the_execution() {
        max_concurrency_zero_case(Terminal::Await).await;
        max_concurrency_zero_case(Terminal::AwaitBatch).await;
        max_concurrency_zero_case(Terminal::SpawnBatch).await;
    }

    /// The same check on `parallel`, which has its own builder.
    #[tokio::test]
    async fn parallel_max_concurrency_zero_fails_the_execution() {
        let result = LocalRunner::new()
            .run(
                |(): (), ctx: DurableContext| async move {
                    let branches = vec![Branch::new("ok", |_| async { Ok(1) })];
                    drop(ctx.parallel(branches).name("p").max_concurrency(0).await);
                    Ok::<_, BoxError>(())
                },
                (),
            )
            .await
            .expect("the run finishes");
        assert_eq!(result.status(), ExecutionStatus::Failed);
        assert_eq!(result.error_message(), Some(MAX_CONCURRENCY_ZERO_MESSAGE));
        assert!(result.operation("p").is_none());
    }
}