aws-durable-execution-sdk 1.0.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
//! The batch operations: [`MapBuilder`] and [`ParallelBuilder`], returned
//! by [`DurableContext::map`](crate::DurableContext::map) and
//! [`DurableContext::parallel`](crate::DurableContext::parallel), plus
//! their shared completion configuration ([`CompletionConfig`]) and the
//! batch result types.
//!
//! The [map operation guide](https://docs.aws.amazon.com/durable-execution/sdk-reference/operations/map/) and the
//! [parallel operation guide](https://docs.aws.amazon.com/durable-execution/sdk-reference/operations/parallel/)
//! describe these operations independently of any language SDK.

use std::future::{Future, IntoFuture};
use std::marker::PhantomData;
use std::sync::Arc;

use crate::BoxError;
use crate::Serdes;
use crate::context::DurableContext;
use crate::engine::OperationId;
use crate::error::OperationError;
use crate::future::DurableFuture;
use crate::map_parallel::ItemEncoding;
use crate::serdes::{JsonSerdes, PassthroughSerdes};

pub use crate::map_parallel::{
    BatchError, BatchItem, BatchItemStatus, BatchResult, BatchStats, BatchStatus,
    CompletionDecision, CompletionItem, CompletionOutcome, CompletionReason, NestingMode,
};

/// Builder for a durable map operation.
///
/// Created by [`DurableContext::map`]. Applies a function to each item
/// with configurable concurrency and completion behavior.
///
/// The builder is generic over the item closure `F` and its future `Fut`;
/// both parameters are inferred at the call site and never written by
/// users.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct Item { id: u64 }
///
/// #[derive(Serialize, Deserialize)]
/// struct Output { processed: bool }
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let items = vec![Item { id: 1 }, Item { id: 2 }];
///     let _results: Vec<Output> = ctx.map(items, |child, item, _idx| async move {
///         Ok(Output { processed: true })
///     }).name("process-all")
///       .max_concurrency(4)
///       .await?;
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct MapBuilder<I, O, F, Fut, IS = JsonSerdes, RS = PassthroughSerdes> {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    max_concurrency: Option<usize>,
    completion: Option<CompletionConfig>,
    serdes: IS,
    encoding: ItemEncoding,
    result_serdes: RS,
    nesting: NestingMode,
    item_namer: Option<crate::map_parallel::ItemNamer<I>>,
    summary: Option<crate::map_parallel::BatchSummary<O>>,
    items: Vec<I>,
    closure: F,
    _marker: PhantomData<fn() -> (O, Fut)>,
}

impl<I, O, F, Fut, IS, RS> std::fmt::Debug for MapBuilder<I, O, F, Fut, IS, RS> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MapBuilder")
            .field("name", &self.name)
            .field("max_concurrency", &self.max_concurrency)
            .finish_non_exhaustive()
    }
}

impl<I, O, F, Fut> MapBuilder<I, O, F, Fut>
where
    I: Send + 'static,
    O: Send + 'static,
    F: Fn(DurableContext, I, usize) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
{
    /// Creates a new builder (internal). Taking the items and closure here
    /// keeps the closure field non-optional: a builder without a body is
    /// unrepresentable.
    pub(crate) fn new_internal(
        ctx: DurableContext,
        op_id: OperationId,
        items: Vec<I>,
        closure: F,
    ) -> Self {
        Self {
            ctx,
            op_id,
            name: None,
            max_concurrency: None,
            completion: None,
            serdes: JsonSerdes,
            encoding: ItemEncoding::AllJson,
            result_serdes: PassthroughSerdes,
            nesting: NestingMode::Normal,
            item_namer: None,
            summary: None,
            items,
            closure,
            _marker: PhantomData,
        }
    }
}

impl<I, O, F, Fut, IS, RS> MapBuilder<I, O, F, Fut, 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,
{
    /// Sets a human-readable name for this map operation.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the maximum number of concurrent items to process.
    ///
    /// `0` fails the execution with the error `Invalid max_concurrency: 0.
    /// Must be a positive number or unset for unlimited concurrency.`; it
    /// cannot be caught, and the map records nothing. Unset means
    /// unlimited.
    pub fn max_concurrency(mut self, max: usize) -> Self {
        self.max_concurrency = Some(max);
        self
    }

    /// Sets the completion configuration.
    ///
    /// **Default: fail fast.** Without this call, or with an empty
    /// [`CompletionConfig`] (no threshold, no predicate), the first item
    /// failure fails the batch, matching the Python and JS SDKs.
    /// Configuring any criterion replaces that implicit fail-fast with the
    /// configured criteria:
    ///
    /// - explicit fail-fast:
    ///   [`CompletionConfig::with_tolerated_failure_count(0)`](CompletionConfig::with_tolerated_failure_count)
    /// - tolerate all failures:
    ///   [`CompletionConfig::with_tolerated_failure_percentage(100.0)?`](CompletionConfig::with_tolerated_failure_percentage),
    ///   which returns a `Result` because it checks the percentage
    pub fn completion(mut self, config: CompletionConfig) -> Self {
        self.completion = Some(config);
        self
    }

    /// Sets a custom serializer/deserializer for item results.
    ///
    /// The serdes must implement [`Serdes<O>`](crate::Serdes) for this
    /// map's item output type: attaching a serdes for a different type
    /// fails at compile time. It goes through the same transform boundary
    /// as every other operation, so a [`Serdes`] attached here behaves
    /// exactly as it does on a step, invoke or callback. It is a different
    /// serdes from `result_serdes`, which transforms the whole batch record.
    ///
    /// `serdes` corresponds to JS `itemSerdes` and Python `item_serdes`.
    pub fn serdes<IS2>(self, serdes: IS2) -> MapBuilder<I, O, F, Fut, IS2, RS>
    where
        IS2: Serdes<O>,
    {
        MapBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes,
            encoding: ItemEncoding::AllSerdes,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            item_namer: self.item_namer,
            summary: self.summary,
            items: self.items,
            closure: self.closure,
            _marker: PhantomData,
        }
    }

    /// Sets a custom serializer/deserializer for the whole batch record.
    ///
    /// The serdes is a [`Serdes<String>`](crate::Serdes). Its serializer
    /// receives the batch record as JSON text, in the shape of the JS SDK's
    /// batch result (`{"all": [...], "completionReason": "..."}`), and
    /// returns the payload to store. Its deserializer receives that stored
    /// payload on replay, and must reconstruct the exact input record text:
    /// `deserialize(serialize(record_text))` must return `record_text`
    /// unchanged. The stored payload may use any format, for example a
    /// compressed or binary encoding of the text. The SDK does not read the
    /// record back on the live path, so a serdes that changes the record
    /// text is not supported.
    ///
    /// The default, [`PassthroughSerdes`], stores
    /// the record text unchanged. [`JsonSerdes`] stores it as a quoted JSON
    /// string.
    ///
    /// `result_serdes` corresponds to JS and Python `serdes`. Those receive
    /// the batch result object.
    pub fn result_serdes<RS2>(self, serdes: RS2) -> MapBuilder<I, O, F, Fut, IS, RS2>
    where
        RS2: Serdes<String>,
    {
        MapBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: serdes,
            nesting: self.nesting,
            item_namer: self.item_namer,
            summary: self.summary,
            items: self.items,
            closure: self.closure,
            _marker: PhantomData,
        }
    }

    /// Sets the nesting mode for the map operation.
    ///
    /// [`NestingMode::Flat`] causes items to run in virtual contexts
    /// without per-item context events.
    pub fn nesting(mut self, mode: NestingMode) -> Self {
        self.nesting = mode;
        self
    }

    /// Sets a custom item namer for per-iteration display names.
    ///
    /// The namer receives a reference to the item and its zero-based index,
    /// and returns the name history records for that item's child context.
    /// It runs once per input item when the map starts, before any item
    /// runs, including items that never start. It also runs on every
    /// replay, so it must be deterministic: a name that changes between
    /// invocations fails replay with a non-determinism error.
    ///
    /// A missing namer, or a namer that returns an empty string, records
    /// `map-item-{index}`. A completion predicate sees the namer's result,
    /// including `Some("")`, or `None` when no namer is set.
    pub fn item_namer(
        mut self,
        namer: impl Fn(&I, usize) -> String + Send + Sync + 'static,
    ) -> Self {
        self.item_namer = Some(Box::new(namer));
        self
    }

    /// Sets a summary stored with the batch record when the batch result is
    /// too large to checkpoint.
    ///
    /// Called only when the serialized result is over 256 KiB, once per
    /// write of that record. The batch then records a summary of its
    /// outcome instead of the item results. With [`NestingMode::Normal`] a
    /// replay reads each item from its own record; an item with
    /// [`NestingMode::Flat`] has no record of its own, so a replay runs the
    /// items again to rebuild the result. The summary receives the
    /// [`BatchResult`], and its output is stored under the key `summary`,
    /// the last key of the `MapResult` record. A batch record that fits is
    /// written as usual, and the summary is not called.
    ///
    /// The output is observability only: replay never reads it. A replay
    /// that rebuilds a completed batch does not call the summary; a batch
    /// that is still running when an invocation resumes it calls the
    /// summary when it completes with an oversized result. Keep it under
    /// 256 KiB, because the service rejects a larger payload. A second call
    /// replaces the first.
    pub fn summary(
        mut self,
        summary: impl Fn(&BatchResult<O>) -> String + Send + Sync + 'static,
    ) -> Self {
        self.summary = Some(Arc::new(summary));
        self
    }

    /// Executes the map and returns the full [`BatchResult`] including
    /// completion metadata (reason, success/failure counts, per-item status).
    ///
    /// Use this when you need to inspect batch completion details (e.g., when
    /// using a completion config that tolerates failures). The standard
    /// `.await` returns `Vec<O>` with only the successful items and cannot
    /// report which items failed. It returns an error when the batch ends
    /// because the configured failure tolerance was exceeded, or because
    /// the completion predicate completed it as failed
    /// ([`CompletionReason::CustomCompletionFailed`]). This method returns
    /// the `BatchResult` in both cases.
    ///
    /// Always returns the full `BatchResult<O>` including per-item outcomes.
    /// [`BatchResult::status`] reports the overall outcome as a
    /// [`BatchStatus`], and [`BatchResult::errors`] associates each failure
    /// with the index and name of the item that produced it. When the
    /// completion rule ends the batch early, an item that is still running
    /// or parked is cancelled at its next `.await` and appears live as
    /// [`BatchItemStatus::Started`].
    ///
    /// The batch starts when the returned future is first polled. To start
    /// it at once and run it in the background, use
    /// [`spawn_batch`](Self::spawn_batch).
    ///
    /// # Errors
    ///
    /// Returns an error if the batch execution encounters an infrastructure
    /// failure (a task-ownership violation). `max_concurrency(0)` returns no error: it fails the
    /// execution, and the handler cannot catch it. A failed checkpoint
    /// write returns no error either: it ends the invocation, and the batch
    /// does not resolve. Item-level failures are
    /// NOT errors: they appear as
    /// `BatchItemStatus::Failed` entries in the result, and the batch's
    /// [`CompletionReason`] records why the batch ended.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     event: Vec<String>,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<(), durable::BoxError> {
    ///     let batch = ctx
    ///         .map(event, |child, item, _idx| async move {
    ///             let len = child
    ///                 .step(move |_| async move { Ok(item.len()) })
    ///                 .name("measure")
    ///                 .await?;
    ///             Ok(len)
    ///         })
    ///         .name("measure-all")
    ///         .completion(durable::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(2))
    ///         .await_batch()
    ///         .await?;
    ///
    ///     if batch.status() == durable::builders::map_parallel::BatchStatus::Failed {
    ///         for error in batch.errors() {
    ///             println!(
    ///                 "item {} failed with {}: {}",
    ///                 error.index,
    ///                 error.error_type.unwrap_or("unknown error type"),
    ///                 error.message,
    ///             );
    ///         }
    ///     }
    ///     println!("batch ended because {:?}", batch.reason);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// [`BatchResult`]: BatchResult
    /// [`BatchResult::status`]: BatchResult::status
    /// [`BatchResult::errors`]: BatchResult::errors
    /// [`BatchStatus`]: BatchStatus
    /// [`CompletionReason`]: CompletionReason
    pub async fn await_batch(self) -> Result<BatchResult<O>, OperationError>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future().await
    }

    /// Starts the operation on its own task and returns its full
    /// [`BatchResult`].
    ///
    /// This is [`await_batch`](Self::await_batch) started at once, as
    /// [`spawn`](Self::spawn) is for the `Vec<O>` form. A handler can run
    /// other operations before it awaits the returned future.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// `.spawn_batch()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn_batch()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn_batch()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn_batch()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::time::Duration;
    ///
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<Vec<u32>, durable::BoxError> {
    ///     let batch = ctx
    ///         .map(vec![1_u32, 2], |child, i, _idx| async move {
    ///             Ok(child.step(move |_| async move { Ok(i * 10) }).name("scale").await?)
    ///         })
    ///         .name("scale-all")
    ///         .spawn_batch();
    ///     ctx.wait(Duration::from_secs(1)).name("meanwhile").await?;
    ///     let batch = batch.await?.into_result()?;
    ///     Ok(batch.results().copied().collect())
    /// }
    /// ```
    pub fn spawn_batch(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        spawn_terminal!(self, started_batch)
    }

    /// The lazy terminal of the full [`BatchResult`]: the body of
    /// `into_future`, with the full `BatchResult` in place of its `Vec<O>` view.
    /// So `.await`, `await_batch()` and `spawn_batch()` run the same
    /// replay identity check and the same admission check.
    fn batch_future(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future_with(false)
    }

    /// [`Self::batch_future`] with the start step run now, on the caller's
    /// task (see [`crate::start`]). `spawn_batch()` and `.spawn()` use it.
    fn started_batch_future(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future_with(true)
    }

    /// The body of [`Self::batch_future`] and [`Self::started_batch_future`].
    fn batch_future_with(self, started: bool) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        use crate::map_parallel::MapExecution;

        preflight_identity!(self, "Context", crate::map_parallel::MAP_SUB_TYPE);

        let execution = MapExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            item_namer: self.item_namer,
            summary: self.summary,
            items: self.items,
            closure: Arc::new(self.closure),
            _marker: PhantomData,
        };

        if started {
            DurableFuture::for_started_operation(
                &execution.ctx.clone(),
                execution.execute_batch_result_started(),
            )
        } else {
            DurableFuture::for_start_step(&execution.ctx.clone(), move || {
                execution.execute_batch_result_started()
            })
        }
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// A combinator begins its `.future()` inputs' start phases, in input
    /// order, before its own start step. So this operation's `START` is
    /// queued before the combinator's, and a start hook it fires when it
    /// queues `START` runs before the combinator's; a start hook that waits
    /// for the `START` response keeps that timing. A replay of the
    /// combinator's final record starts no `.future()` input.
    ///
    /// A handle that [`.spawn()`](Self::spawn) returned already runs on its
    /// own task. A combinator that receives it never starts it again, and
    /// it keeps running independently: when the combinator resolves first,
    /// it does not cancel the handle, and the handle's result is dropped.
    pub fn future(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.into_future()
    }

    /// Eagerly spawns the map operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// `.spawn()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        spawn_terminal!(self, started)
    }

    /// The `Vec<O>` future of `.spawn()`: the full batch, started now on
    /// the caller's task, projected as `.await` projects it.
    fn started_future(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        // `map_output` keeps the batch's task context, so a combinator that
        // receives the handle runs it in the frames of its creation.
        self.started_batch_future()
            .map_output(|outcome| crate::map_parallel::collect_successful(outcome?))
    }
}

impl<I, O, F, Fut, IS, RS> IntoFuture for MapBuilder<I, O, F, Fut, 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>,
{
    type Output = Result<Vec<O>, OperationError>;
    type IntoFuture = DurableFuture<Vec<O>>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::map_parallel::MapExecution;

        preflight_identity!(self, "Context", crate::map_parallel::MAP_SUB_TYPE);

        let execution = MapExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            item_namer: self.item_namer,
            summary: self.summary,
            items: self.items,
            closure: Arc::new(self.closure),
            _marker: PhantomData,
        };

        DurableFuture::for_start_step(&execution.ctx.clone(), move || {
            let batch = execution.execute_batch_result_started();
            async move { crate::map_parallel::collect_successful(batch.await?) }
        })
    }
}

/// Builder for a parallel operation with named branches.
///
/// Created by [`DurableContext::parallel`]. Each branch gets its own child
/// context.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let branches = vec![
///         durable::Branch::new("a", |_| async { Ok(1) }),
///         durable::Branch::new("b", |_| async { Ok(2) }),
///     ];
///     let _results: Vec<i32> = ctx.parallel(branches)
///         .name("fan-out")
///         .max_concurrency(2)
///         .await?;
///     Ok(())
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct ParallelBuilder<O, IS = JsonSerdes, RS = PassthroughSerdes> {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    max_concurrency: Option<usize>,
    completion: Option<CompletionConfig>,
    serdes: IS,
    encoding: ItemEncoding,
    result_serdes: RS,
    nesting: NestingMode,
    branches: Vec<(Option<String>, crate::future::BranchBody<O>)>,
    summary: Option<crate::map_parallel::BatchSummary<O>>,
    _marker: PhantomData<O>,
}

impl<O, IS, RS> std::fmt::Debug for ParallelBuilder<O, IS, RS> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParallelBuilder")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl<O: Send + 'static> ParallelBuilder<O> {
    /// Creates a new builder (internal). Taking the branches here keeps the
    /// builder complete from construction: `context.parallel()` always has
    /// them in hand.
    pub(crate) fn new_internal(
        ctx: DurableContext,
        op_id: OperationId,
        branches: Vec<(Option<String>, crate::future::BranchBody<O>)>,
    ) -> Self {
        Self {
            ctx,
            op_id,
            name: None,
            max_concurrency: None,
            completion: None,
            serdes: JsonSerdes,
            encoding: ItemEncoding::AllJson,
            result_serdes: PassthroughSerdes,
            nesting: NestingMode::Normal,
            branches,
            summary: None,
            _marker: PhantomData,
        }
    }
}

impl<O: Send + 'static, IS, RS> ParallelBuilder<O, IS, RS> {
    /// Sets a human-readable name for this parallel operation.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the maximum number of concurrent branches.
    ///
    /// `0` fails the execution with the error `Invalid max_concurrency: 0.
    /// Must be a positive number or unset for unlimited concurrency.`; it
    /// cannot be caught, and the parallel records nothing. Unset means
    /// unlimited.
    pub fn max_concurrency(mut self, max: usize) -> Self {
        self.max_concurrency = Some(max);
        self
    }

    /// Sets the completion configuration.
    ///
    /// **Default: fail fast.** Without this call, or with an empty
    /// [`CompletionConfig`] (no threshold, no predicate), the first branch
    /// failure fails the batch, matching the Python and JS SDKs.
    /// Configuring any criterion replaces that implicit fail-fast with the
    /// configured criteria:
    ///
    /// - explicit fail-fast:
    ///   [`CompletionConfig::with_tolerated_failure_count(0)`](CompletionConfig::with_tolerated_failure_count)
    /// - tolerate all failures:
    ///   [`CompletionConfig::with_tolerated_failure_percentage(100.0)?`](CompletionConfig::with_tolerated_failure_percentage),
    ///   which returns a `Result` because it checks the percentage
    ///
    /// A failure percentage applies to `parallel` as it does to `map`, as
    /// in JS and Python `ParallelConfig`.
    pub fn completion(mut self, config: CompletionConfig) -> Self {
        self.completion = Some(config);
        self
    }

    /// Sets a custom serializer/deserializer for branch results.
    ///
    /// The serdes must implement [`Serdes<O>`](crate::Serdes) for this
    /// operation's branch output type: attaching a serdes for a different
    /// type fails at compile time. It goes through the same transform
    /// boundary as every other operation, so a [`Serdes`] attached here
    /// behaves exactly as it does on a step, invoke or callback. It is a
    /// different serdes from `result_serdes`, which transforms the whole
    /// batch record.
    ///
    /// `serdes` corresponds to JS `itemSerdes` and Python `item_serdes`.
    pub fn serdes<IS2>(self, serdes: IS2) -> ParallelBuilder<O, IS2, RS>
    where
        IS2: Serdes<O>,
    {
        ParallelBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes,
            encoding: ItemEncoding::AllSerdes,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            branches: self.branches,
            summary: self.summary,
            _marker: PhantomData,
        }
    }

    /// Sets a custom serializer/deserializer for the whole batch record.
    ///
    /// The serdes is a [`Serdes<String>`](crate::Serdes). Its serializer
    /// receives the batch record as JSON text, in the shape of the JS SDK's
    /// batch result (`{"all": [...], "completionReason": "..."}`), and
    /// returns the payload to store. Its deserializer receives that stored
    /// payload on replay, and must reconstruct the exact input record text:
    /// `deserialize(serialize(record_text))` must return `record_text`
    /// unchanged. The stored payload may use any format, for example a
    /// compressed or binary encoding of the text. The SDK does not read the
    /// record back on the live path, so a serdes that changes the record
    /// text is not supported.
    ///
    /// The default, [`PassthroughSerdes`], stores
    /// the record text unchanged. [`JsonSerdes`] stores it as a quoted JSON
    /// string.
    ///
    /// `result_serdes` corresponds to JS and Python `serdes`. Those receive
    /// the batch result object.
    pub fn result_serdes<RS2>(self, serdes: RS2) -> ParallelBuilder<O, IS, RS2>
    where
        RS2: Serdes<String>,
    {
        ParallelBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: serdes,
            nesting: self.nesting,
            branches: self.branches,
            summary: self.summary,
            _marker: PhantomData,
        }
    }

    /// Sets the nesting mode for the parallel operation.
    ///
    /// [`NestingMode::Flat`] causes branches to run in virtual contexts
    /// without per-branch context events.
    pub fn nesting(mut self, mode: NestingMode) -> Self {
        self.nesting = mode;
        self
    }

    /// Sets a summary stored with the batch record when the batch result is
    /// too large to checkpoint.
    ///
    /// Called only when the serialized result is over 256 KiB, once per
    /// write of that record. The batch then records a summary of its
    /// outcome instead of the branch results. With [`NestingMode::Normal`] a
    /// replay reads each branch from its own record; a branch with
    /// [`NestingMode::Flat`] has no record of its own, so a replay runs the
    /// branches again to rebuild the result. The summary receives the
    /// [`BatchResult`], and its output is stored under the key `summary`,
    /// the last key of the `ParallelResult` record. A batch record that fits is
    /// written as usual, and the summary is not called.
    ///
    /// The output is observability only: replay never reads it. A replay
    /// that rebuilds a completed batch does not call the summary; a batch
    /// that is still running when an invocation resumes it calls the
    /// summary when it completes with an oversized result. Keep it under
    /// 256 KiB, because the service rejects a larger payload. A second call
    /// replaces the first.
    pub fn summary(
        mut self,
        summary: impl Fn(&BatchResult<O>) -> String + Send + Sync + 'static,
    ) -> Self {
        self.summary = Some(Arc::new(summary));
        self
    }

    /// Executes the parallel operation and returns the full [`BatchResult`]
    /// including completion metadata (reason, success/failure counts,
    /// per-branch status).
    ///
    /// Use this when you need to inspect batch completion details (e.g., when
    /// using a completion config that tolerates failures). The standard
    /// `.await` returns `Vec<O>` with only the successful branches and
    /// cannot report which branches failed. It returns an error when the
    /// batch ends because the configured failure tolerance was exceeded, or
    /// because the completion predicate completed it as failed
    /// ([`CompletionReason::CustomCompletionFailed`]). This method returns
    /// the `BatchResult` in both cases.
    ///
    /// Always returns the full `BatchResult<O>` including per-branch
    /// outcomes. [`BatchResult::status`] reports the overall outcome as a
    /// [`BatchStatus`], and [`BatchResult::errors`] associates each failure
    /// with the index and name of the branch that produced it. When the
    /// completion rule ends the batch early, a branch that is still running
    /// or parked is cancelled at its next `.await` and appears live as
    /// [`BatchItemStatus::Started`].
    ///
    /// The batch starts when the returned future is first polled. To start
    /// it at once and run it in the background, use
    /// [`spawn_batch`](Self::spawn_batch).
    ///
    /// # Errors
    ///
    /// Returns an error if the batch execution encounters an infrastructure
    /// failure (a task-ownership violation). `max_concurrency(0)` returns no error: it fails the
    /// execution, and the handler cannot catch it. A failed checkpoint
    /// write returns no error either: it ends the invocation, and the batch
    /// does not resolve. Branch-level failures are
    /// NOT errors: they appear as
    /// `BatchItemStatus::Failed` entries in the result, and the batch's
    /// [`CompletionReason`] records why the batch ended.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<(), durable::BoxError> {
    ///     let branches = vec![
    ///         durable::Branch::new("a", |_| async { Ok(1) }),
    ///         durable::Branch::new("b", |_| async { Ok(2) }),
    ///     ];
    ///     let batch = ctx
    ///         .parallel(branches)
    ///         .name("fan-out")
    ///         .completion(durable::builders::map_parallel::CompletionConfig::with_tolerated_failure_count(1))
    ///         .await_batch()
    ///         .await?;
    ///     if batch.status() == durable::builders::map_parallel::BatchStatus::Failed {
    ///         for error in batch.errors() {
    ///             println!(
    ///                 "branch {} failed with {}: {}",
    ///                 error.name,
    ///                 error.error_type.unwrap_or("unknown error type"),
    ///                 error.message,
    ///             );
    ///         }
    ///     }
    ///     println!("batch ended because {:?}", batch.reason);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// [`BatchResult`]: BatchResult
    /// [`BatchResult::status`]: BatchResult::status
    /// [`BatchResult::errors`]: BatchResult::errors
    /// [`BatchStatus`]: BatchStatus
    /// [`CompletionReason`]: CompletionReason
    pub async fn await_batch(self) -> Result<BatchResult<O>, OperationError>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future().await
    }

    /// Starts the operation on its own task and returns its full
    /// [`BatchResult`].
    ///
    /// This is [`await_batch`](Self::await_batch) started at once, as
    /// [`spawn`](Self::spawn) is for the `Vec<O>` form. A handler can run
    /// other operations before it awaits the returned future.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// `.spawn_batch()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn_batch()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn_batch()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn_batch()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::time::Duration;
    ///
    /// use aws_durable_execution_sdk as durable;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<usize, durable::BoxError> {
    ///     let branches = vec![
    ///         durable::Branch::new("a", |_| async { Ok(1) }),
    ///         durable::Branch::new("b", |_| async { Ok(2) }),
    ///     ];
    ///     let batch = ctx.parallel(branches).name("fan-out").spawn_batch();
    ///     ctx.wait(Duration::from_secs(1)).name("meanwhile").await?;
    ///     let batch = batch.await?;
    ///     Ok(batch.succeeded().count())
    /// }
    /// ```
    pub fn spawn_batch(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        spawn_terminal!(self, started_batch)
    }

    /// The lazy terminal of the full [`BatchResult`]: the body of
    /// `into_future`, with the full `BatchResult` in place of its `Vec<O>` view.
    /// So `.await`, `await_batch()` and `spawn_batch()` run the same
    /// replay identity check and the same admission check.
    fn batch_future(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future_with(false)
    }

    /// [`Self::batch_future`] with the start step run now, on the caller's
    /// task (see [`crate::start`]). `spawn_batch()` and `.spawn()` use it.
    fn started_batch_future(self) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.batch_future_with(true)
    }

    /// The body of [`Self::batch_future`] and [`Self::started_batch_future`].
    fn batch_future_with(self, started: bool) -> DurableFuture<BatchResult<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        use crate::map_parallel::{ItemIds, ParallelExecution};

        preflight_identity!(self, "Context", crate::map_parallel::PARALLEL_SUB_TYPE);

        let item_ids = ItemIds::new(&self.op_id, self.branches.len());
        let execution = ParallelExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            branches: self.branches,
            summary: self.summary,
            item_ids,
        };

        if started {
            DurableFuture::for_started_operation(
                &execution.ctx.clone(),
                execution.execute_batch_result_started(),
            )
        } else {
            DurableFuture::for_start_step(&execution.ctx.clone(), move || {
                execution.execute_batch_result_started()
            })
        }
    }

    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// A combinator begins its `.future()` inputs' start phases, in input
    /// order, before its own start step. So this operation's `START` is
    /// queued before the combinator's, and a start hook it fires when it
    /// queues `START` runs before the combinator's; a start hook that waits
    /// for the `START` response keeps that timing. A replay of the
    /// combinator's final record starts no `.future()` input.
    ///
    /// A handle that [`.spawn()`](Self::spawn) returned already runs on its
    /// own task. A combinator that receives it never starts it again, and
    /// it keeps running independently: when the combinator resolves first,
    /// it does not cancel the handle, and the handle's result is dropped.
    pub fn future(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        self.into_future()
    }

    /// Eagerly spawns the parallel operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// `.spawn()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        spawn_terminal!(self, started)
    }

    /// The `Vec<O>` future of `.spawn()`: the full batch, started now on
    /// the caller's task, projected as `.await` projects it.
    fn started_future(self) -> DurableFuture<Vec<O>>
    where
        IS: Serdes<O>,
        RS: Serdes<String>,
    {
        // `map_output` keeps the batch's task context, so a combinator that
        // receives the handle runs it in the frames of its creation.
        self.started_batch_future()
            .map_output(|outcome| crate::map_parallel::collect_successful(outcome?))
    }
}

impl<O, IS, RS> IntoFuture for ParallelBuilder<O, IS, RS>
where
    O: Send + 'static,
    IS: Serdes<O>,
    RS: Serdes<String>,
{
    type Output = Result<Vec<O>, OperationError>;
    type IntoFuture = DurableFuture<Vec<O>>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::map_parallel::{ItemIds, ParallelExecution};

        preflight_identity!(self, "Context", crate::map_parallel::PARALLEL_SUB_TYPE);

        let item_ids = ItemIds::new(&self.op_id, self.branches.len());
        let execution = ParallelExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes: self.serdes,
            encoding: self.encoding,
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            branches: self.branches,
            summary: self.summary,
            item_ids,
        };

        DurableFuture::for_start_step(&execution.ctx.clone(), move || {
            let batch = execution.execute_batch_result_started();
            async move { crate::map_parallel::collect_successful(batch.await?) }
        })
    }
}

/// Builder for a parallel operation over branches whose results have
/// different types.
///
/// Created by [`DurableContext::parallel_mixed`]. Each branch's result is
/// read through the [`BranchHandle`](crate::BranchHandle) that
/// [`BranchSet`](crate::BranchSet) returned when the branch was added, so
/// the builder has no item serdes and no `await_batch`. `.await` returns
/// the batch's [`CompletionReason`].
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
///     let mut branches = durable::BranchSet::new();
///     let count = branches.add("count", |_| async { Ok(7_u32) });
///     let label = branches.add("label", |_| async { Ok("ready".to_owned()) });
///     ctx.parallel_mixed(branches)
///         .name("fan-out")
///         .max_concurrency(2)
///         .await?;
///     Ok(format!("{}: {}", count.into_result()?, label.into_result()?))
/// }
/// ```
#[must_use = "builders do nothing unless awaited or spawned"]
#[non_exhaustive]
pub struct ParallelMixedBuilder<RS = PassthroughSerdes> {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    max_concurrency: Option<usize>,
    completion: Option<CompletionConfig>,
    result_serdes: RS,
    nesting: NestingMode,
    branches: Vec<(
        Option<String>,
        crate::future::BranchBody<crate::future::BranchValue>,
    )>,
    decoders: Arc<Vec<Arc<dyn crate::future::BranchDecoder>>>,
    json: Arc<[bool]>,
    summary: Option<crate::map_parallel::BatchSummary<crate::future::BranchValue>>,
}

impl<RS> std::fmt::Debug for ParallelMixedBuilder<RS> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParallelMixedBuilder")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl ParallelMixedBuilder {
    /// Creates a new builder (internal).
    pub(crate) fn new_internal(
        ctx: DurableContext,
        op_id: OperationId,
        branches: crate::future::BranchSet,
    ) -> Self {
        let (branches, decoders, json) = branches.into_parts();
        Self {
            ctx,
            op_id,
            name: None,
            max_concurrency: None,
            completion: None,
            result_serdes: PassthroughSerdes,
            nesting: NestingMode::Normal,
            branches,
            decoders,
            json,
            summary: None,
        }
    }
}

impl<RS> ParallelMixedBuilder<RS> {
    /// Sets a human-readable name for this parallel operation.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the maximum number of concurrent branches.
    ///
    /// `0` fails the execution with the error `Invalid max_concurrency: 0.
    /// Must be a positive number or unset for unlimited concurrency.`; it
    /// cannot be caught, and the parallel records nothing. Unset means
    /// unlimited.
    pub fn max_concurrency(mut self, max: usize) -> Self {
        self.max_concurrency = Some(max);
        self
    }

    /// Sets the completion configuration.
    ///
    /// **Default: fail fast.** Without this call, or with an empty
    /// [`CompletionConfig`] (no threshold, no predicate), the first branch
    /// failure fails the batch, matching the Python and JS SDKs.
    /// Configuring any criterion replaces that implicit fail-fast with the
    /// configured criteria:
    ///
    /// - explicit fail-fast:
    ///   [`CompletionConfig::with_tolerated_failure_count(0)`](CompletionConfig::with_tolerated_failure_count)
    /// - tolerate all failures:
    ///   [`CompletionConfig::with_tolerated_failure_percentage(100.0)?`](CompletionConfig::with_tolerated_failure_percentage),
    ///   which returns a `Result` because it checks the percentage
    ///
    /// A failure percentage applies to `parallel_mixed` as it does to
    /// `map`, as in JS and Python `ParallelConfig`.
    ///
    /// A [`BranchHandle`](crate::BranchHandle) has a result exactly when its
    /// branch settled, whatever the parallel's own outcome. A succeeded
    /// branch's handle returns its value, and a failed branch's handle
    /// returns its error. A branch that was waiting or running when the
    /// batch ended, or that never started, returns
    /// [`ChildContextErrorKind::NotCompleted`](crate::ChildContextErrorKind::NotCompleted).
    /// This holds when the completion rule fails the batch too: after a
    /// predicate completes the batch as failed with no failed branch,
    /// `.await` returns
    /// [`ChildContextErrorKind::BatchCompletionFailed`](crate::ChildContextErrorKind::BatchCompletionFailed),
    /// and every branch that succeeded still returns its value.
    pub fn completion(mut self, config: CompletionConfig) -> Self {
        self.completion = Some(config);
        self
    }

    /// Sets a custom serializer/deserializer for the whole batch record.
    ///
    /// The serdes is a [`Serdes<String>`](crate::Serdes). Its serializer
    /// receives the batch record as JSON text, in the shape of the JS SDK's
    /// batch result (`{"all": [...], "completionReason": "..."}`), and
    /// returns the payload to store. Its deserializer receives that stored
    /// payload on replay, and must reconstruct the exact input record text:
    /// `deserialize(serialize(record_text))` must return `record_text`
    /// unchanged. The stored payload may use any format, for example a
    /// compressed or binary encoding of the text. The SDK does not read the
    /// record back on the live path, so a serdes that changes the record
    /// text is not supported.
    ///
    /// The default, [`PassthroughSerdes`], stores
    /// the record text unchanged. [`JsonSerdes`] stores it as a quoted JSON
    /// string.
    ///
    /// `result_serdes` corresponds to JS and Python `serdes`. Those receive
    /// the batch result object.
    pub fn result_serdes<RS2>(self, serdes: RS2) -> ParallelMixedBuilder<RS2>
    where
        RS2: Serdes<String>,
    {
        ParallelMixedBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            result_serdes: serdes,
            nesting: self.nesting,
            branches: self.branches,
            decoders: self.decoders,
            json: self.json,
            summary: self.summary,
        }
    }

    /// Sets the nesting mode for the parallel operation.
    ///
    /// [`NestingMode::Flat`] causes branches to run in virtual contexts
    /// without per-branch context events.
    pub fn nesting(mut self, mode: NestingMode) -> Self {
        self.nesting = mode;
        self
    }

    /// Sets a summary stored with the batch record when the batch result is
    /// too large to checkpoint.
    ///
    /// Called only when the serialized result, as
    /// [`result_serdes`](Self::result_serdes) returns it, is over 256 KiB,
    /// once per write of that record, before the write is awaited. The batch
    /// then records a summary of its outcome instead of the branch results,
    /// and the summary's output is stored under the key `summary`, the last
    /// key of the `ParallelResult` record. A batch record that fits is
    /// written as usual, and the summary is not called.
    ///
    /// The summary receives the [`BatchResult`], with each started branch's
    /// index, name, status and error and the completion reason, as
    /// [`ParallelBuilder::summary`] does. Each item holds a
    /// [`BranchValue`](crate::BranchValue), which exposes nothing of its
    /// value: the summary reads each value with its branch's key, from
    /// [`BranchHandle::key`](crate::BranchHandle::key), and
    /// [`BatchResult::value`]. The handles receive their results only after
    /// the batch completes, so they are empty while the summary runs.
    ///
    /// The output is observability only: replay never reads it. A replay
    /// that rebuilds a completed batch does not call the summary; a batch
    /// that is still running when an invocation resumes it calls the
    /// summary when it completes with an oversized result. Keep it under
    /// 256 KiB, because the service rejects a larger payload. A second call
    /// replaces the first.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    /// use durable::BranchSet;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<String, durable::BoxError> {
    ///     let mut branches = BranchSet::new();
    ///     let report = branches.add("report", |_ctx| async { Ok("x".repeat(300_000)) });
    ///     let rows = branches.add("rows", |_ctx| async { Ok(vec![1_u64; 40_000]) });
    ///     let (report_key, rows_key) = (report.key(), rows.key());
    ///     ctx.parallel_mixed(branches)
    ///         .name("build-report")
    ///         .summary(move |batch| {
    ///             let report_len = batch.value(&report_key).map_or(0, String::len);
    ///             let row_count = batch.value(&rows_key).map_or(0, Vec::len);
    ///             format!("report: {report_len} bytes, rows: {row_count}")
    ///         })
    ///         .await?;
    ///     let report = report.into_result()?;
    ///     let rows = rows.into_result()?;
    ///     Ok(format!("{} bytes, {} rows", report.len(), rows.len()))
    /// }
    /// ```
    pub fn summary(
        mut self,
        summary: impl Fn(&BatchResult<crate::future::BranchValue>) -> String + Send + Sync + 'static,
    ) -> Self {
        self.summary = Some(Arc::new(summary));
        self
    }

    /// Eagerly spawns the parallel operation on a tokio task.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations. The handles receive their results when the returned
    /// future is awaited, not when the spawned task finishes.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// `.spawn()` runs the operation's start step on the caller's task
    /// before it returns, as JS starts the operation inside the call. When
    /// the operation's current state requires a `START` (it has no record,
    /// or its record begins a new attempt), that `START` is admitted to the
    /// write order before `.spawn()` returns, so it reaches the service
    /// before every update the caller sends afterwards, on any runtime
    /// flavor. The task-ownership check runs on the caller too: a
    /// `.spawn()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body. A start hook that JS fires when it queues the `START`, and the
    /// replay start hook of a record that resumes work, fire before
    /// `.spawn()` returns. The rest of the operation, including
    /// `on_attempt_start` and the body, runs on the spawned task. The
    /// exceptions are `invoke`, `wait_for_condition` and the combinators,
    /// whose `.spawn()` starts the whole operation on the spawned task.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<CompletionReason>
    where
        RS: Serdes<String>,
    {
        use crate::map_parallel::publish_outcome;

        let decoders = Arc::clone(&self.decoders);
        let spawned = spawn_terminal!(self, started_batch);
        // `map_output` keeps the handle's task context, so a combinator that
        // takes it runs it inside the creator's frames.
        spawned.map_output(move |outcome| publish_outcome(outcome, &decoders))
    }

    /// The lazy terminal of the full [`BatchResult`], shared by `.await`
    /// and `.spawn()`. So both run the same replay identity check and the
    /// same admission check.
    fn batch_future(self) -> DurableFuture<BatchResult<crate::future::BranchValue>>
    where
        RS: Serdes<String>,
    {
        self.batch_future_with(false)
    }

    /// [`Self::batch_future`] with the start step run now, on the caller's
    /// task (see [`crate::start`]). `spawn_batch()` and `.spawn()` use it.
    fn started_batch_future(self) -> DurableFuture<BatchResult<crate::future::BranchValue>>
    where
        RS: Serdes<String>,
    {
        self.batch_future_with(true)
    }

    /// The body of [`Self::batch_future`] and [`Self::started_batch_future`].
    fn batch_future_with(
        self,
        started: bool,
    ) -> DurableFuture<BatchResult<crate::future::BranchValue>>
    where
        RS: Serdes<String>,
    {
        use crate::map_parallel::{ItemIds, MixedItemSerdes, PARALLEL_SUB_TYPE, ParallelExecution};

        preflight_identity!(self, "Context", PARALLEL_SUB_TYPE);

        // One table of branch IDs, read by the batch engine and by the item
        // serdes, which finds each branch's serdes from it.
        let item_ids = ItemIds::new(&self.op_id, self.branches.len());
        let serdes = MixedItemSerdes::new(&item_ids, self.decoders);
        let execution = ParallelExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            max_concurrency: self.max_concurrency,
            completion: self.completion,
            serdes,
            encoding: ItemEncoding::PerItem(self.json),
            result_serdes: self.result_serdes,
            nesting: self.nesting,
            branches: self.branches,
            summary: self.summary,
            item_ids,
        };

        if started {
            DurableFuture::for_started_operation(
                &execution.ctx.clone(),
                execution.execute_batch_result_started(),
            )
        } else {
            DurableFuture::for_start_step(&execution.ctx.clone(), move || {
                execution.execute_batch_result_started()
            })
        }
    }
}

impl<RS> IntoFuture for ParallelMixedBuilder<RS>
where
    RS: Serdes<String>,
{
    type Output = Result<CompletionReason, OperationError>;
    type IntoFuture = DurableFuture<CompletionReason>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::map_parallel::publish_outcome;

        let decoders = Arc::clone(&self.decoders);
        let batch = self.batch_future();
        // `map_output` keeps the batch's task context, so a
        // combinator that starts it runs the branches inside the frames of
        // the batch's creation.
        batch.map_output(move |outcome| publish_outcome(outcome, &decoders))
    }
}

/// A shared completion predicate consulted by map/parallel batch execution.
///
/// Receives a [`BatchStats`] snapshot before each item starts and after
/// each item settles, and returns a [`CompletionDecision`].
///
/// Crate-internal: the `Arc` wrapping is an implementation detail (it is what
/// keeps [`CompletionConfig`] cheaply cloneable with a closure inside, the
/// same way per-operation serdes are stored). Public setters
/// ([`CompletionConfig::with_completion_predicate`],
/// [`CompletionConfigBuilder::completion_predicate`]) take a generic closure
/// and wrap it here.
pub(crate) type CompletionPredicate =
    Arc<dyn Fn(&BatchStats<'_>) -> CompletionDecision + Send + Sync>;

/// Configuration for completion behavior in map and parallel operations.
///
/// Controls early-completion thresholds: how many items must succeed and
/// how many failures are tolerated before stopping. Thresholds can be
/// combined, and the first to fire wins. A concurrent batch that resumes
/// with recorded item outcomes applies all of them, then checks the
/// thresholds once, in the order failure tolerance, every item finished,
/// `min_successful`. A [completion predicate](Self::with_completion_predicate)
/// cannot be combined with a threshold: [`CompletionConfigBuilder::build`]
/// rejects the mix.
///
/// # Default: fail fast
///
/// An **empty** config: [`CompletionConfig::default()`], with no threshold
/// and no predicate: fails the batch on the **first item failure**, exactly
/// as running with no config at all does. This matches the Python and JS
/// SDKs. Configuring any criterion opts out of that implicit fail-fast and
/// hands the decision to the configured criteria:
///
/// - explicit fail-fast: [`with_tolerated_failure_count(0)`](Self::with_tolerated_failure_count)
/// - tolerate all failures: [`with_tolerated_failure_percentage(100.0)?`](Self::with_tolerated_failure_percentage),
///   which returns a `Result` because it checks the percentage
///
/// Construct with [`CompletionConfig::builder`] (which combines thresholds
/// and validates them at [`build`](CompletionConfigBuilder::build) time) or
/// with one of the single-threshold constructors. Both
/// [`build`](CompletionConfigBuilder::build) and
/// [`with_tolerated_failure_percentage`](Self::with_tolerated_failure_percentage)
/// return [`CompletionConfigValidationError`] for an invalid percentage, so
/// an invalid config never reaches a batch; the other constructors cannot
/// fail. Read values back through the accessors.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::{
///     CompletionConfig, CompletionDecision, CompletionOutcome,
/// };
///
/// // Fail-fast: stop on the first failure.
/// let fail_fast = CompletionConfig::with_tolerated_failure_count(0);
/// assert_eq!(fail_fast.tolerated_failure_count(), Some(0));
///
/// // Early completion: stop after 2 successes.
/// let min_success = CompletionConfig::with_min_successful(2);
/// assert_eq!(min_success.min_successful(), Some(2));
///
/// // Custom predicate: complete as a success once two items have settled.
/// let custom = CompletionConfig::with_completion_predicate(|stats| {
///     if stats.settled() >= 2 {
///         CompletionDecision::complete(CompletionOutcome::Succeeded)
///     } else {
///         CompletionDecision::Continue
///     }
/// });
/// assert!(custom.has_completion_predicate());
///
/// // Combined thresholds: first to fire wins.
/// let combined = CompletionConfig::builder()
///     .min_successful(2)
///     .tolerated_failure_count(1)
///     .build()?;
/// assert_eq!(combined.min_successful(), Some(2));
/// assert_eq!(combined.tolerated_failure_count(), Some(1));
/// # Ok::<(), aws_durable_execution_sdk::builders::map_parallel::CompletionConfigValidationError>(())
/// ```
#[derive(Clone, Default)]
#[non_exhaustive]
// Fields are private so the struct can grow without breaking callers;
// see the Rust API Guidelines on structs with private fields:
// https://rust-lang.github.io/api-guidelines/future-proofing.html#c-struct-private
pub struct CompletionConfig {
    /// Completes the batch early once this many items succeed.
    /// `None` means no minimum-success threshold.
    min_successful: Option<usize>,

    /// Fails the batch once more than this many items fail.
    /// `Some(0)` means fail-fast (stop on first failure).
    /// `None` means no count-based failure tolerance.
    tolerated_failure_count: Option<usize>,

    /// Fails the batch once the failure percentage strictly exceeds this
    /// threshold (0.0 to 100.0, fractions allowed). Uses
    /// cross-multiplication rather than a division.
    /// `Some(0.0)` means fail-fast (stop on first failure).
    /// `None` means no percentage-based failure tolerance.
    tolerated_failure_percentage: Option<f64>,

    /// User-supplied completion predicate over the batch view. It cannot be
    /// combined with a threshold. A `Complete` decision records
    /// [`CompletionReason::CustomCompletionSucceeded`] or
    /// [`CompletionReason::CustomCompletionFailed`].
    /// `None` means no custom predicate.
    completion_predicate: Option<CompletionPredicate>,
}

impl std::fmt::Debug for CompletionConfig {
    // Hand-written because the stored predicate closure has no `Debug`;
    // its presence is reported instead (same approach the builders take
    // for their stored closures).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompletionConfig")
            .field("min_successful", &self.min_successful)
            .field("tolerated_failure_count", &self.tolerated_failure_count)
            .field(
                "tolerated_failure_percentage",
                &self.tolerated_failure_percentage,
            )
            .field(
                "completion_predicate",
                &self.completion_predicate.as_ref().map(|_| "<closure>"),
            )
            .finish()
    }
}

impl CompletionConfig {
    /// Creates a new [`CompletionConfigBuilder`].
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::builders::map_parallel::CompletionConfig;
    ///
    /// let config = CompletionConfig::builder().min_successful(3).build()?;
    /// assert_eq!(config.min_successful(), Some(3));
    /// # Ok::<(), aws_durable_execution_sdk::builders::map_parallel::CompletionConfigValidationError>(())
    /// ```
    pub fn builder() -> CompletionConfigBuilder {
        CompletionConfigBuilder::default()
    }

    /// Creates a config with just a `min_successful` threshold.
    ///
    /// **Default when unset:** the batch runs until every item settles.
    /// Note that a config carrying only this threshold has no failure
    /// tolerance configured, so item failures are tolerated while the
    /// batch waits to reach `min` successes: the implicit fail-fast of an
    /// empty config no longer applies once any criterion is set.
    ///
    /// `with_min_successful(0)` completes a non-empty batch at its first
    /// settle, as in JS. A batch of one item then records
    /// [`CompletionReason::AllCompleted`], because the batch checks "every
    /// item finished" before the minimum.
    #[must_use]
    pub fn with_min_successful(min: usize) -> Self {
        Self {
            min_successful: Some(min),
            ..Self::default()
        }
    }

    /// Creates a config with just a `tolerated_failure_count` threshold.
    ///
    /// Use `0` for explicit fail-fast behavior (stop on first failure).
    ///
    /// **Default when unset:** an empty config fails fast on the first
    /// failure; a config with some other criterion set applies only that
    /// criterion.
    #[must_use]
    pub fn with_tolerated_failure_count(count: usize) -> Self {
        Self {
            tolerated_failure_count: Some(count),
            ..Self::default()
        }
    }

    /// Creates a config with just a `tolerated_failure_percentage` threshold.
    ///
    /// The batch stops once the true failure rate **strictly exceeds** the
    /// given percentage. It accepts a fraction such as `12.5`; the batch
    /// fails when the failure rate strictly exceeds it. Internally this uses
    /// cross-multiplication (`failure_count * 100.0 > pct * total_items`)
    /// rather than a division, so 7 failures of 50 do not exceed `14.0`.
    /// The check is exact for integer percentages and totals below 2^53.
    ///
    /// Use `0.0` for explicit fail-fast behavior (stop on first failure).
    /// Use `100.0` to tolerate all failures (the failure rate can never
    /// strictly exceed 100%).
    ///
    /// The percentage applies to `parallel` as it does to `map`, as in JS
    /// and Python `ParallelConfig`.
    ///
    /// **Default when unset:** an empty config fails fast on the first
    /// failure; a config with some other criterion set applies only that
    /// criterion.
    ///
    /// # Errors
    ///
    /// Returns [`CompletionConfigValidationError`] when `pct` is not finite
    /// or lies outside `0.0..=100.0`, with the message `invalid
    /// CompletionConfig: tolerated_failure_percentage must be 0-100, got
    /// {pct}`. [`CompletionConfigBuilder::build`] applies the same check.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::builders::map_parallel::CompletionConfig;
    ///
    /// let config = CompletionConfig::with_tolerated_failure_percentage(12.5)?;
    /// assert_eq!(config.tolerated_failure_percentage(), Some(12.5));
    ///
    /// assert!(CompletionConfig::with_tolerated_failure_percentage(150.0).is_err());
    /// # Ok::<(), aws_durable_execution_sdk::builders::map_parallel::CompletionConfigValidationError>(())
    /// ```
    pub fn with_tolerated_failure_percentage(
        pct: f64,
    ) -> Result<Self, CompletionConfigValidationError> {
        check_percentage(Some(pct))?;
        Ok(Self {
            tolerated_failure_percentage: Some(pct),
            ..Self::default()
        })
    }

    /// Creates a config with just a custom completion predicate.
    ///
    /// The predicate receives a [`BatchStats`] snapshot and returns a
    /// [`CompletionDecision`]:
    ///
    /// - [`CompletionDecision::Continue`] keeps starting and awaiting items.
    ///   A batch whose predicate never completes it records
    ///   [`CompletionReason::AllCompleted`].
    /// - `CompletionDecision::complete(CompletionOutcome::Succeeded)` ends
    ///   the batch now and records [`CompletionReason::CustomCompletionSucceeded`]. Item
    ///   failures inside it are tolerated rather than propagated as errors.
    /// - `CompletionDecision::complete(CompletionOutcome::Failed)` ends the
    ///   batch now and records [`CompletionReason::CustomCompletionFailed`]. Awaiting the batch
    ///   returns the first failed item's error, or a
    ///   [`BatchCompletionFailed`](crate::ChildContextErrorKind::BatchCompletionFailed)
    ///   error when no item failed.
    ///
    /// A predicate counts as a completion criterion, so the implicit
    /// fail-fast of an empty config does not apply. A predicate cannot be
    /// combined with a threshold. A zero-item batch asks the predicate once,
    /// on an empty view.
    ///
    /// # When the predicate runs
    ///
    /// The SDK asks the predicate before each item starts and after each
    /// item settles. The counts follow the settle order, and
    /// [`BatchStats::items`] holds every input item by index. The SDK stops
    /// asking once the first trigger fires, so within one run a predicate is
    /// never asked to reverse a decision.
    ///
    /// # Determinism: read this before using
    ///
    /// The live settle order is not recorded. On resume, the recorded items
    /// settle first, in index order. So the predicate MUST be a pure function
    /// of the [`BatchStats`] it receives, and it MUST be monotonic. A
    /// predicate is monotonic when, after it returns
    /// `CompletionDecision::complete(outcome)` for a snapshot, it returns
    /// `CompletionDecision::complete(outcome)` with the same outcome for
    /// every later snapshot of the same batch. A later snapshot is one where
    /// each item's status is the same or further along, in the order `None`,
    /// `Started`, then `Succeeded` or `Failed`. Under that rule the recorded
    /// reason and outcome do not depend on the settle order, so two runs
    /// agree. See [`CompletionConfigBuilder::completion_predicate`] for a
    /// counterexample.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::builders::map_parallel::{
    ///     CompletionConfig, CompletionDecision, CompletionOutcome,
    /// };
    ///
    /// // Complete as a success once half the items have settled.
    /// let config = CompletionConfig::with_completion_predicate(|stats| {
    ///     if stats.settled() * 2 >= stats.total_items() {
    ///         CompletionDecision::complete(CompletionOutcome::Succeeded)
    ///     } else {
    ///         CompletionDecision::Continue
    ///     }
    /// });
    /// assert!(config.has_completion_predicate());
    /// ```
    #[must_use]
    pub fn with_completion_predicate<F>(predicate: F) -> Self
    where
        F: Fn(&BatchStats<'_>) -> CompletionDecision + Send + Sync + 'static,
    {
        Self {
            completion_predicate: Some(Arc::new(predicate)),
            ..Self::default()
        }
    }

    /// Returns the minimum-success threshold, if set.
    pub fn min_successful(&self) -> Option<usize> {
        self.min_successful
    }

    /// Returns the count-based failure tolerance, if set.
    pub fn tolerated_failure_count(&self) -> Option<usize> {
        self.tolerated_failure_count
    }

    /// Returns the percentage-based failure tolerance, if set.
    pub fn tolerated_failure_percentage(&self) -> Option<f64> {
        self.tolerated_failure_percentage
    }

    /// Reports whether a custom completion predicate is set.
    ///
    /// The predicate itself is not exposed: its boxing is an implementation
    /// detail, matching how the crate stores other user closures (for
    /// example retry strategies).
    pub fn has_completion_predicate(&self) -> bool {
        self.completion_predicate.is_some()
    }

    /// Reports whether ANY completion criterion is configured: a threshold
    /// or a custom predicate (crate-internal).
    ///
    /// An empty config (nothing set) fails the batch on the first item
    /// failure, exactly as running with no config does; configuring any
    /// criterion opts out of that implicit fail-fast (issue #52, matching
    /// the Python and JS SDKs).
    pub(crate) fn has_criteria(&self) -> bool {
        self.min_successful.is_some()
            || self.tolerated_failure_count.is_some()
            || self.tolerated_failure_percentage.is_some()
            || self.completion_predicate.is_some()
    }

    /// Calls the predicate. Returns `CompletionDecision::Continue` when none is set.
    pub(crate) fn predicate_decision(&self, stats: &BatchStats<'_>) -> CompletionDecision {
        self.completion_predicate
            .as_ref()
            .map_or(CompletionDecision::Continue, |predicate| predicate(stats))
    }
}

/// Checks the failure percentage: it must be finite and lie in
/// `0.0..=100.0`. Both [`CompletionConfig::with_tolerated_failure_percentage`]
/// and [`CompletionConfigBuilder::build`] call it, so they report the same
/// error.
fn check_percentage(pct: Option<f64>) -> Result<(), CompletionConfigValidationError> {
    match pct {
        Some(pct) if !(pct.is_finite() && (0.0..=100.0).contains(&pct)) => {
            Err(CompletionConfigValidationError {
                message: format!("tolerated_failure_percentage must be 0-100, got {pct}"),
            })
        }
        _ => Ok(()),
    }
}

/// Error returned while constructing a [`CompletionConfig`]: by
/// [`CompletionConfig::with_tolerated_failure_percentage`] and by
/// [`CompletionConfigBuilder::build`].
///
/// Mirrors [`OptionsValidationError`](crate::OptionsValidationError): misconfiguration fails at
/// construction time rather than mid-execution. No map, parallel or
/// `parallel_mixed` operation returns it, because an invalid config never
/// reaches one.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::CompletionConfig;
///
/// let err = CompletionConfig::builder()
///     .tolerated_failure_percentage(101.0)
///     .build()
///     .unwrap_err();
/// assert!(err.to_string().contains("tolerated_failure_percentage"));
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CompletionConfigValidationError {
    message: String,
}

impl std::fmt::Display for CompletionConfigValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid CompletionConfig: {}", self.message)
    }
}

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

/// Builder for [`CompletionConfig`].
///
/// Follows the Rust API Guidelines C-BUILDER pattern. All methods consume
/// and return `self` for chaining, so multiple thresholds combine in one
/// expression instead of requiring post-construction mutation.
/// [`build`](Self::build) validates the combination and rejects a
/// misconfiguration at construction time.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::map_parallel::CompletionConfig;
///
/// let config = CompletionConfig::builder()
///     .min_successful(2)
///     .tolerated_failure_percentage(25.0)
///     .build()?;
/// assert_eq!(config.tolerated_failure_percentage(), Some(25.0));
/// # Ok::<(), aws_durable_execution_sdk::builders::map_parallel::CompletionConfigValidationError>(())
/// ```
#[derive(Clone, Default)]
#[must_use = "builders do nothing unless .build() is called"]
#[non_exhaustive]
pub struct CompletionConfigBuilder {
    min_successful: Option<usize>,
    tolerated_failure_count: Option<usize>,
    tolerated_failure_percentage: Option<f64>,
    completion_predicate: Option<CompletionPredicate>,
}

impl std::fmt::Debug for CompletionConfigBuilder {
    // Hand-written because the stored predicate closure has no `Debug`;
    // its presence is reported instead.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CompletionConfigBuilder")
            .field("min_successful", &self.min_successful)
            .field("tolerated_failure_count", &self.tolerated_failure_count)
            .field(
                "tolerated_failure_percentage",
                &self.tolerated_failure_percentage,
            )
            .field(
                "completion_predicate",
                &self.completion_predicate.as_ref().map(|_| "<closure>"),
            )
            .finish()
    }
}

impl CompletionConfigBuilder {
    /// Completes the batch early once this many items succeed.
    ///
    /// **Default when unset:** the batch runs until every item settles.
    /// Setting this (or any other criterion) replaces the implicit
    /// fail-fast of an empty config; a config carrying only this threshold
    /// tolerates item failures while waiting to reach `min` successes.
    ///
    /// `min_successful(0)` completes a non-empty batch at its first settle,
    /// as in JS. A batch of one item then records
    /// [`CompletionReason::AllCompleted`].
    pub fn min_successful(mut self, min: usize) -> Self {
        self.min_successful = Some(min);
        self
    }

    /// Fails the batch once more than this many items fail.
    ///
    /// Use `0` for explicit fail-fast behavior (stop on first failure).
    ///
    /// **Default when unset:** an empty config fails fast on the first
    /// failure; a config with some other criterion set applies only that
    /// criterion.
    pub fn tolerated_failure_count(mut self, count: usize) -> Self {
        self.tolerated_failure_count = Some(count);
        self
    }

    /// Fails the batch once the failure percentage strictly exceeds this
    /// threshold (0.0 to 100.0).
    ///
    /// It accepts a fraction such as `12.5`; the batch fails when the
    /// failure rate strictly exceeds it. Use `0.0` for explicit fail-fast
    /// behavior (stop on first failure). Use `100.0` to tolerate all
    /// failures (the failure rate can never strictly exceed 100%).
    ///
    /// **Default when unset:** an empty config fails fast on the first
    /// failure; a config with some other criterion set applies only that
    /// criterion.
    ///
    /// A value that is not finite or lies outside `0.0..=100.0` is rejected
    /// by [`build`](Self::build).
    ///
    /// The percentage applies to `parallel` as it does to `map`, as in JS
    /// and Python `ParallelConfig`.
    pub fn tolerated_failure_percentage(mut self, pct: f64) -> Self {
        self.tolerated_failure_percentage = Some(pct);
        self
    }

    /// Sets a custom completion predicate over the batch view.
    ///
    /// The predicate receives a [`BatchStats`] snapshot and returns a
    /// [`CompletionDecision`]. `Continue` keeps the batch running, and a
    /// batch whose predicate never completes it records
    /// [`CompletionReason::AllCompleted`].
    /// `CompletionDecision::complete(CompletionOutcome::Succeeded)` ends the
    /// batch and records [`CompletionReason::CustomCompletionSucceeded`].
    /// `CompletionDecision::complete(CompletionOutcome::Failed)` ends the
    /// batch and records
    /// [`CompletionReason::CustomCompletionFailed`]; awaiting the batch then
    /// returns an error. A predicate counts as a completion criterion, so
    /// the implicit fail-fast of an empty config does not apply. A
    /// zero-item batch asks the predicate once, on an empty view.
    ///
    /// A predicate cannot be combined with `min_successful`,
    /// `tolerated_failure_count` or `tolerated_failure_percentage`:
    /// [`build`](Self::build) rejects the mix, as JS does.
    ///
    /// # When the predicate runs
    ///
    /// The SDK asks the predicate before each item starts and after each
    /// item settles. The counts follow the settle order, and
    /// [`BatchStats::items`] holds every input item by index, with its name
    /// and status. The SDK calls the predicate only until the first trigger
    /// fires, so a predicate is never asked to reverse a decision within one
    /// run.
    ///
    /// # Determinism: read this before using
    ///
    /// The live settle order is not recorded. On resume, the recorded items
    /// settle first, in index order. So the sequence of snapshots can differ
    /// between the original run and a resume.
    ///
    /// So the predicate MUST be a pure function of the [`BatchStats`] it
    /// receives, and it MUST be monotonic. A predicate is monotonic when,
    /// after it returns `CompletionDecision::complete(outcome)` for a
    /// snapshot, it returns `CompletionDecision::complete(outcome)` with the
    /// same outcome for every later snapshot of the same batch. A later
    /// snapshot is one where each item's status is the same or further
    /// along, in the order `None`, `Started`, then `Succeeded` or `Failed`.
    /// Under that rule the recorded reason and outcome do not depend on the
    /// settle order. Monotonicity is what keeps
    /// two runs in agreement.
    ///
    /// A counterexample, as JS gives one: `succeeded() == 1 && failed() == 0`
    /// is not monotonic. One run can see one success first and complete. A
    /// resume can see the failure first, then `(1, 1)`, and never complete.
    /// See JS's own advice in
    /// [batch.ts](https://github.com/aws/aws-durable-execution-sdk-js/blob/67549feacd5568ea305b7c2d533d3549974f8c9c/packages/aws-durable-execution-sdk-js/src/types/batch.ts#L276-L282).
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::builders::map_parallel::{
    ///     BatchItemStatus, CompletionConfig, CompletionDecision, CompletionOutcome,
    /// };
    ///
    /// // Complete when item 0 succeeds, or when items 1 and 2 both succeed.
    /// // The rule stays met once it is met, so it is monotonic.
    /// let config = CompletionConfig::builder()
    ///     .completion_predicate(|stats| {
    ///         let ok = |i: usize| {
    ///             stats
    ///                 .items()
    ///                 .get(i)
    ///                 .is_some_and(|item| item.status == Some(BatchItemStatus::Succeeded))
    ///         };
    ///         if ok(0) || (ok(1) && ok(2)) {
    ///             CompletionDecision::complete(CompletionOutcome::Succeeded)
    ///         } else {
    ///             CompletionDecision::Continue
    ///         }
    ///     })
    ///     .build()?;
    /// assert!(config.has_completion_predicate());
    /// # Ok::<(), aws_durable_execution_sdk::builders::map_parallel::CompletionConfigValidationError>(())
    /// ```
    pub fn completion_predicate<F>(mut self, predicate: F) -> Self
    where
        F: Fn(&BatchStats<'_>) -> CompletionDecision + Send + Sync + 'static,
    {
        self.completion_predicate = Some(Arc::new(predicate));
        self
    }

    /// Builds the [`CompletionConfig`] from the configured thresholds,
    /// validating them at construction time.
    ///
    /// # Errors
    ///
    /// Returns [`CompletionConfigValidationError`] in two cases, checked in
    /// this order:
    ///
    /// 1. `tolerated_failure_percentage` is not finite or lies outside
    ///    `0.0..=100.0`.
    /// 2. A completion predicate is set together with `min_successful`,
    ///    `tolerated_failure_count` or `tolerated_failure_percentage`. The
    ///    message is `completion_predicate is mutually exclusive with
    ///    min_successful, tolerated_failure_count and
    ///    tolerated_failure_percentage`.
    ///
    /// A batch does not check its config again: an error here is the only
    /// place an invalid config is reported.
    pub fn build(self) -> Result<CompletionConfig, CompletionConfigValidationError> {
        check_percentage(self.tolerated_failure_percentage)?;
        if self.completion_predicate.is_some()
            && (self.min_successful.is_some()
                || self.tolerated_failure_count.is_some()
                || self.tolerated_failure_percentage.is_some())
        {
            return Err(CompletionConfigValidationError {
                message: "completion_predicate is mutually exclusive with min_successful, \
                          tolerated_failure_count and tolerated_failure_percentage"
                    .to_owned(),
            });
        }
        Ok(CompletionConfig {
            min_successful: self.min_successful,
            tolerated_failure_count: self.tolerated_failure_count,
            tolerated_failure_percentage: self.tolerated_failure_percentage,
            completion_predicate: self.completion_predicate,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The `CompletionConfig` builder combines thresholds in one expression,
    /// no `Default`-then-mutate, and the built config drives the same
    /// completion decisions the single-threshold constructors do.
    #[test]
    fn completion_config_builder_combines_thresholds() {
        let combined = CompletionConfig::builder()
            .min_successful(2)
            .tolerated_failure_count(1)
            .tolerated_failure_percentage(25.0)
            .build()
            .expect("valid config");

        assert_eq!(combined.min_successful(), Some(2));
        assert_eq!(combined.tolerated_failure_count(), Some(1));
        assert_eq!(combined.tolerated_failure_percentage(), Some(25.0));

        // An unset threshold stays `None`.
        let only_min = CompletionConfig::builder()
            .min_successful(3)
            .build()
            .expect("valid config");
        assert_eq!(only_min.min_successful(), Some(3));
        assert_eq!(only_min.tolerated_failure_count(), None);
        assert_eq!(only_min.tolerated_failure_percentage(), None);
        assert!(!only_min.has_completion_predicate());

        // Builder output matches the equivalent single-threshold constructor.
        assert_eq!(
            CompletionConfig::builder()
                .tolerated_failure_count(0)
                .build()
                .expect("valid config")
                .tolerated_failure_count(),
            CompletionConfig::with_tolerated_failure_count(0).tolerated_failure_count(),
        );

        // Default is still "no thresholds".
        let default = CompletionConfig::default();
        assert_eq!(default.min_successful(), None);
        assert_eq!(default.tolerated_failure_count(), None);
        assert_eq!(default.tolerated_failure_percentage(), None);
        assert!(!default.has_completion_predicate());
    }

    /// The direct constructor and the builder reject the same invalid
    /// percentages with the same complete error, and accept every value in
    /// `0.0..=100.0` unchanged.
    #[test]
    fn percentage_is_checked_when_built() {
        for pct in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0, 150.0] {
            let expected = format!(
                "invalid CompletionConfig: \
                 tolerated_failure_percentage must be 0-100, got {pct}"
            );
            let direct = CompletionConfig::with_tolerated_failure_percentage(pct)
                .expect_err("the constructor rejects an invalid percentage");
            assert_eq!(direct.to_string(), expected);
            let built = CompletionConfig::builder()
                .tolerated_failure_percentage(pct)
                .build()
                .expect_err("the builder rejects an invalid percentage");
            assert_eq!(built.to_string(), expected);
        }
        for pct in [0.0, 12.5, 100.0] {
            let direct = CompletionConfig::with_tolerated_failure_percentage(pct)
                .expect("the constructor accepts a valid percentage");
            assert_eq!(direct.tolerated_failure_percentage(), Some(pct));
            let built = CompletionConfig::builder()
                .tolerated_failure_percentage(pct)
                .build()
                .expect("the builder accepts a valid percentage");
            assert_eq!(built.tolerated_failure_percentage(), Some(pct));
        }
    }

    /// A stored completion predicate keeps `CompletionConfig`'s `Clone` and
    /// `Debug` story intact: the clone shares the predicate (`Arc`), and
    /// `Debug` reports the predicate's presence instead of requiring the
    /// closure to implement `Debug`.
    #[test]
    fn completion_config_predicate_clone_and_debug() {
        let config = CompletionConfig::builder()
            .completion_predicate(|stats| {
                if stats.settled() >= 3 {
                    CompletionDecision::complete(CompletionOutcome::Succeeded)
                } else {
                    CompletionDecision::Continue
                }
            })
            .build()
            .expect("valid config");
        assert!(config.has_completion_predicate());

        let cloned = config.clone();
        assert!(cloned.has_completion_predicate());
        assert_eq!(cloned.min_successful(), None);

        let debugged = format!("{config:?}");
        assert!(
            debugged.contains("completion_predicate") && debugged.contains("<closure>"),
            "Debug should report predicate presence, got: {debugged}"
        );

        // Constructor parity: `with_completion_predicate` sets only the
        // predicate.
        let only_predicate = CompletionConfig::with_completion_predicate(|stats| {
            if stats.failed() > stats.succeeded() {
                CompletionDecision::complete(CompletionOutcome::Succeeded)
            } else {
                CompletionDecision::Continue
            }
        });
        assert!(only_predicate.has_completion_predicate());
        assert_eq!(only_predicate.min_successful(), None);

        // The predicate is evaluated against the stats it receives.
        let more_failed = [
            CompletionItem::new(0, None, Some(BatchItemStatus::Failed)),
            CompletionItem::new(1, None, Some(BatchItemStatus::Failed)),
            CompletionItem::new(2, None, Some(BatchItemStatus::Succeeded)),
        ];
        let stats = BatchStats::new(&more_failed);
        assert_eq!(
            only_predicate.predicate_decision(&stats),
            CompletionDecision::complete(CompletionOutcome::Succeeded)
        );
        let even = [
            CompletionItem::new(0, None, Some(BatchItemStatus::Failed)),
            CompletionItem::new(1, None, Some(BatchItemStatus::Succeeded)),
        ];
        assert_eq!(
            only_predicate.predicate_decision(&BatchStats::new(&even)),
            CompletionDecision::Continue
        );
        // No predicate configured: the decision is `Continue`.
        assert_eq!(
            CompletionConfig::default().predicate_decision(&stats),
            CompletionDecision::Continue
        );
    }

    fn complete_on_first_settle(stats: &BatchStats<'_>) -> CompletionDecision {
        if stats.settled() >= 1 {
            CompletionDecision::complete(CompletionOutcome::Succeeded)
        } else {
            CompletionDecision::Continue
        }
    }

    /// `build()` rejects a predicate together with `min_successful`, as JS
    /// rejects `shouldComplete` with a threshold.
    #[test]
    fn build_rejects_predicate_with_min_successful() {
        let err = CompletionConfig::builder()
            .min_successful(1)
            .completion_predicate(complete_on_first_settle)
            .build()
            .expect_err("a predicate with min_successful must be rejected");
        assert!(
            err.to_string().contains("mutually exclusive"),
            "unexpected message: {err}"
        );
        assert_eq!(
            err.to_string(),
            "invalid CompletionConfig: completion_predicate is mutually exclusive with \
             min_successful, tolerated_failure_count and tolerated_failure_percentage"
        );
    }

    /// `build()` rejects a predicate together with `tolerated_failure_count`.
    #[test]
    fn build_rejects_predicate_with_failure_count() {
        let result = CompletionConfig::builder()
            .tolerated_failure_count(0)
            .completion_predicate(complete_on_first_settle)
            .build();
        assert!(result.is_err());
    }

    /// `build()` rejects a predicate together with
    /// `tolerated_failure_percentage`.
    #[test]
    fn build_rejects_predicate_with_failure_percentage() {
        let result = CompletionConfig::builder()
            .tolerated_failure_percentage(10.0)
            .completion_predicate(complete_on_first_settle)
            .build();
        assert!(result.is_err());
    }

    /// A predicate alone is a valid config.
    #[test]
    fn build_accepts_predicate_alone() {
        let config = CompletionConfig::builder()
            .completion_predicate(complete_on_first_settle)
            .build()
            .expect("a predicate alone is valid");
        assert!(config.has_completion_predicate());
    }

    /// `build()` checks the percentage before the predicate exclusion, so a
    /// config that breaks both rules reports the percentage.
    #[test]
    fn build_checks_percentage_before_predicate_exclusion() {
        let err = CompletionConfig::builder()
            .tolerated_failure_percentage(150.0)
            .completion_predicate(complete_on_first_settle)
            .build()
            .expect_err("both rules are broken");
        assert_eq!(
            err.to_string(),
            "invalid CompletionConfig: tolerated_failure_percentage must be 0-100, got 150"
        );
    }

    /// A context whose log holds a succeeded STEP record at position 1,
    /// where the batch under test claims a `Context` operation.
    fn ctx_with_step_record_at_1() -> DurableContext {
        use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};

        let wire = crate::engine::compute_wire_id_public("1");
        let record = CheckpointRecord {
            id: wire.clone(),
            status: CheckpointStatus::Succeeded,
            result: Some("0".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("Step".to_owned()),
            sub_type: Some("Step".to_owned()),
            due_at: None,
            op_name: None,
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        };
        DurableContext::new_root(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::from_records(vec![(wire, record)])),
        )
    }

    /// `batch_future` checks the replay identity when it is called, before
    /// the returned future is polled, as `into_future` does. The log holds a
    /// STEP where the map claims a `Context`. So the fatal mismatch is
    /// recorded at once. Without the preflight, the mismatch is recorded only
    /// when the batch first runs.
    #[tokio::test]
    async fn map_batch_future_checks_replay_identity_before_first_poll() {
        let ctx = ctx_with_step_record_at_1();
        let future = ctx
            .map(
                vec![1_i32],
                |_child, item: i32, _idx| async move { Ok(item) },
            )
            .batch_future();
        let fatal = ctx
            .coordinator()
            .fatal_error()
            .expect("the mismatch is recorded before the first poll");
        assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
        drop(future);
    }

    /// The parallel counterpart of
    /// `map_batch_future_checks_replay_identity_before_first_poll`.
    #[tokio::test]
    async fn parallel_batch_future_checks_replay_identity_before_first_poll() {
        let ctx = ctx_with_step_record_at_1();
        let branches = vec![crate::future::Branch::new("b", |_child| async {
            Ok(1_i32)
        })];
        let future = ctx.parallel(branches).batch_future();
        let fatal = ctx
            .coordinator()
            .fatal_error()
            .expect("the mismatch is recorded before the first poll");
        assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
        drop(future);
    }

    /// A `BranchSet` with one `i32` branch, for the `parallel_mixed` tests.
    fn one_branch_set() -> crate::BranchSet {
        let mut set = crate::BranchSet::new();
        let _handle = set.add("b", |_child| async { Ok(1_i32) });
        set
    }

    /// `parallel_mixed`'s `into_future` checks the replay identity when it is
    /// called, before the returned future is polled. The log holds a STEP
    /// where the parallel claims a `Context`. So the fatal mismatch is
    /// recorded at once. If `into_future` called `batch_future` inside the
    /// returned async block, the mismatch would be recorded only at the first
    /// poll, and this test would fail.
    #[tokio::test]
    async fn parallel_mixed_into_future_checks_replay_identity_before_first_poll() {
        let ctx = ctx_with_step_record_at_1();
        let future = ctx.parallel_mixed(one_branch_set()).into_future();
        let fatal = ctx
            .coordinator()
            .fatal_error()
            .expect("the mismatch is recorded before the first poll");
        assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
        drop(future);
    }

    /// The `.spawn()` counterpart of
    /// `parallel_mixed_into_future_checks_replay_identity_before_first_poll`.
    #[tokio::test]
    async fn parallel_mixed_spawn_checks_replay_identity_before_first_poll() {
        let ctx = ctx_with_step_record_at_1();
        let future = ctx.parallel_mixed(one_branch_set()).spawn();
        let fatal = ctx
            .coordinator()
            .fatal_error()
            .expect("the mismatch is recorded before the first poll");
        assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
        drop(future);
    }

    /// The summary of a map and of a parallel: a second call replaces the
    /// first, and `serdes` and `result_serdes` keep it.
    #[test]
    fn batch_summary_setter_replaces_and_survives_serdes() {
        let result = BatchResult::<u32>::new(Vec::new(), CompletionReason::AllCompleted);
        let ctx = DurableContext::test_context();
        let map = ctx
            .map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
            .summary(|r| format!("first {}", r.total_count()))
            .summary(|r| format!("second {}", r.total_count()))
            .serdes(Arc::new(JsonSerdes))
            .result_serdes(JsonSerdes);
        let summary = map.summary.as_ref().expect("the map keeps the summary");
        assert_eq!(summary(&result), "second 0");

        let parallel = ctx
            .parallel(vec![crate::Branch::new("a", |_child| async { Ok(1_u32) })])
            .summary(|r| format!("first {}", r.total_count()))
            .summary(|r| format!("second {}", r.total_count()))
            .serdes(Arc::new(JsonSerdes))
            .result_serdes(JsonSerdes);
        let summary = parallel
            .summary
            .as_ref()
            .expect("the parallel keeps the summary");
        assert_eq!(summary(&result), "second 0");

        let mixed_result =
            BatchResult::<crate::BranchValue>::new(Vec::new(), CompletionReason::AllCompleted);
        let mut branches = crate::BranchSet::new();
        let _a = branches.add("a", |_child| async { Ok(1_u32) });
        let parallel_mixed = ctx
            .parallel_mixed(branches)
            .summary(|r| format!("first {}", r.total_count()))
            .summary(|r| format!("second {}", r.total_count()))
            .result_serdes(JsonSerdes);
        let summary = parallel_mixed
            .summary
            .as_ref()
            .expect("the parallel_mixed keeps the summary");
        assert_eq!(summary(&mixed_result), "second 0");
    }
}