asupersync 0.5.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
//! Bounded execution and outcome-fold helpers for map-reduce.
//!
//! [`execute_map_reduce`] and [`Scope::map_reduce`] lazily spawn real scoped
//! maps under independent concurrency and retained-work limits. Values enter a
//! fixed input-order left fold, so reducers need neither associativity nor
//! commutativity. Completed values waiting for an earlier input retain credit.
//! A failing execution stops admission, cancels and joins its owned children,
//! including asynchronous cleanup, before returning the severity join
//! `Ok < Err < Cancelled < Panicked`. Dropping the execution requests abort;
//! the region remains responsible for children that have not yet terminated.
//!
//! The unchanged [`MapReduce`] marker and helpers such as
//! [`map_reduce_outcomes`] and [`make_map_reduce_result`] operate on outcomes
//! already supplied by the caller. Those helpers retain partial successes;
//! they do not spawn tasks or provide the executing engine's work bounds.

use core::fmt;
use std::collections::VecDeque;
use std::future::Future;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::task::Poll;

use crate::cx::{CancelWakerToken, Cx, Scope};
use crate::runtime::{JoinError, SpawnError, TaskHandle};
use crate::types::Outcome;
use crate::types::Policy;
use crate::types::cancel::CancelReason;
use crate::types::outcome::PanicPayload;
use crate::types::policy::AggregateDecision;

/// A compatibility marker for map-reduce computation.
///
/// This marker does not execute work. Use [`execute_map_reduce`] or
/// [`Scope::map_reduce`] for bounded task execution, or the outcome-fold
/// helpers below to aggregate outcomes already obtained by the caller.
///
/// # Type Parameters
/// * `T` - The output type from the map phase (also the reduce input/output)
///
/// # Executing work
/// ```no_run
/// # async fn example(cx: &asupersync::Cx) {
/// use asupersync::{Outcome, combinator::MapReduceLimits};
/// use std::num::NonZeroUsize;
/// let limits = MapReduceLimits::new(
///     NonZeroUsize::new(2).unwrap(), NonZeroUsize::new(4).unwrap(),
/// );
/// let report = cx.scope().map_reduce(
///     cx, limits, [1, 2, 3, 4, 5],
///     |_child, n| async move { Outcome::<_, ()>::Ok(n * 2) },
///     |acc, val| acc + val,
/// ).await;
/// assert!(matches!(report.outcome, Outcome::Ok(Some(30))));
/// # }
/// ```
#[derive(Debug)]
pub struct MapReduce<T> {
    _t: PhantomData<T>,
}

impl<T> MapReduce<T> {
    /// Creates a new map-reduce combinator (internal use).
    #[must_use]
    pub const fn new() -> Self {
        Self { _t: PhantomData }
    }
}

impl<T> Default for MapReduce<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Clone for MapReduce<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for MapReduce<T> {}

/// Result from a map-reduce operation.
///
/// Contains the aggregate decision, the reduced value (if all succeeded or
/// partial reduction is possible), and metadata about the operation.
pub struct MapReduceResult<T, E> {
    /// The aggregate decision following the severity lattice.
    pub decision: AggregateDecision<E>,
    /// The reduced value from successful tasks, if any succeeded.
    /// `None` if no tasks succeeded or reduction requires all to succeed.
    pub reduced: Option<T>,
    /// Successful values with their original indices (before reduction).
    /// Useful for debugging or partial result recovery.
    pub successes: Vec<(usize, T)>,
    /// The total number of tasks that were spawned.
    pub total_count: usize,
}

impl<T, E> MapReduceResult<T, E> {
    /// Creates a new map-reduce result.
    #[must_use]
    pub fn new(
        decision: AggregateDecision<E>,
        reduced: Option<T>,
        successes: Vec<(usize, T)>,
        total_count: usize,
    ) -> Self {
        Self {
            decision,
            reduced,
            successes,
            total_count,
        }
    }

    /// Returns true if all tasks succeeded and at least one task was present.
    ///
    /// Returns `false` for empty input (zero tasks) even though the
    /// aggregate decision is `AllOk` (vacuously true), because callers
    /// typically expect `reduced` to be `Some` when this returns `true`.
    #[must_use]
    pub fn all_succeeded(&self) -> bool {
        self.total_count > 0
            && matches!(self.decision, AggregateDecision::AllOk)
            && self.successes.len() == self.total_count
    }

    /// Returns the number of successful tasks.
    #[must_use]
    pub fn success_count(&self) -> usize {
        self.successes.len()
    }

    /// Returns the number of failed tasks.
    #[must_use]
    pub fn failure_count(&self) -> usize {
        // Saturating: `total_count` is `>= successes.len()` by construction, but
        // this is a public accessor and a caller-supplied result built through a
        // public constructor could violate that — never panic/underflow here.
        self.total_count.saturating_sub(self.successes.len())
    }

    /// Returns true if there's a reduced value available.
    #[must_use]
    pub fn has_reduced(&self) -> bool {
        self.reduced.is_some()
    }
}

impl<T: fmt::Debug, E: fmt::Debug> fmt::Debug for MapReduceResult<T, E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MapReduceResult")
            .field("decision", &self.decision)
            .field("reduced", &self.reduced)
            .field("successes", &self.successes)
            .field("total_count", &self.total_count)
            .finish()
    }
}

/// Error type for map-reduce operations.
///
/// When a map-reduce fails (not all tasks succeeded), this type
/// indicates the nature of the failure.
#[derive(Debug, Clone)]
pub enum MapReduceError<E> {
    /// At least one task encountered an error.
    Error {
        /// The error from the first failing task.
        error: E,
        /// Index of the task that produced this error.
        index: usize,
        /// Total number of tasks that failed.
        total_failures: usize,
        /// Number of tasks that succeeded.
        success_count: usize,
    },
    /// At least one task was cancelled.
    Cancelled(CancelReason),
    /// At least one task panicked.
    Panicked {
        /// The panic payload.
        payload: PanicPayload,
        /// Index of the first task that panicked.
        index: usize,
    },
    /// No tasks were provided (empty input).
    Empty,
}

impl<E> MapReduceError<E> {
    /// Returns the error index if this was an application error.
    #[must_use]
    pub const fn error_index(&self) -> Option<usize> {
        match self {
            Self::Error { index, .. } => Some(*index),
            _ => None,
        }
    }

    /// Returns the panic index if this was a panic.
    #[must_use]
    pub const fn panic_index(&self) -> Option<usize> {
        match self {
            Self::Panicked { index, .. } => Some(*index),
            _ => None,
        }
    }

    /// Returns true if this was an application error.
    #[must_use]
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Error { .. })
    }

    /// Returns true if a task was cancelled.
    #[must_use]
    pub const fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled(_))
    }

    /// Returns true if a task panicked.
    #[must_use]
    pub const fn is_panicked(&self) -> bool {
        matches!(self, Self::Panicked { .. })
    }

    /// Returns true if the input was empty.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        matches!(self, Self::Empty)
    }
}

impl<E: fmt::Display> fmt::Display for MapReduceError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Error {
                error,
                index,
                total_failures,
                success_count,
            } => write!(
                f,
                "map-reduce task {index} failed: {error} ({total_failures} failures, {success_count} successes)"
            ),
            Self::Cancelled(r) => write!(f, "map-reduce cancelled: {r}"),
            Self::Panicked { payload, index } => {
                write!(f, "map-reduce task {index} panicked: {payload}")
            }
            Self::Empty => write!(f, "map-reduce requires at least one input"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for MapReduceError<E> {}

/// Aggregates N outcomes and reduces successful values in input order.
///
/// This is the semantic core of `map_reduce`:
/// 1. Aggregate outcomes under the severity lattice
/// 2. Collect successful values with their indices
/// 3. Apply the reduce function to successful values (in input order)
///
/// # Arguments
/// * `outcomes` - The outcomes from all tasks, in their original order
/// * `reduce` - Function to combine two values into one
///
/// # Returns
/// A tuple of (aggregate decision, optional reduced value, successful values with indices).
///
/// # Reduction Order
/// Values are reduced in input order using a left fold:
/// `reduce(reduce(reduce(v[0], v[1]), v[2]), v[3])`
///
/// This is deterministic and predictable, but requires the reduce function
/// to be associative for equivalent parallel execution.
pub fn map_reduce_outcomes<T, E, F>(
    outcomes: Vec<Outcome<T, E>>,
    reduce: F,
) -> (AggregateDecision<E>, Option<T>, Vec<(usize, T)>)
where
    F: Fn(T, T) -> T,
    T: Clone,
{
    let total = outcomes.len();
    let mut successes: Vec<(usize, T)> = Vec::with_capacity(total);
    let mut first_error: Option<E> = None;
    let mut strongest_cancel: Option<CancelReason> = None;

    let mut panic_payload: Option<PanicPayload> = None;
    let mut panic_index: Option<usize> = None;

    // Collect outcomes
    for (i, outcome) in outcomes.into_iter().enumerate() {
        match outcome {
            Outcome::Panicked(p) => {
                // Panic is the strongest - record it but keep collecting successes
                if panic_payload.is_none() {
                    panic_payload = Some(p);
                    panic_index = Some(i);
                }
            }
            Outcome::Cancelled(r) => match &mut strongest_cancel {
                None => strongest_cancel = Some(r),
                Some(existing) => {
                    existing.strengthen(&r);
                }
            },
            Outcome::Err(e) => {
                if first_error.is_none() {
                    first_error = Some(e);
                }
            }
            Outcome::Ok(v) => {
                successes.push((i, v));
            }
        }
    }

    // Determine aggregate decision (panic takes precedence)
    let decision = panic_payload.map_or_else(
        || {
            strongest_cancel.map_or_else(
                || first_error.map_or(AggregateDecision::AllOk, AggregateDecision::FirstError),
                AggregateDecision::Cancelled,
            )
        },
        |p| AggregateDecision::Panicked {
            payload: p,
            first_panic_index: panic_index.expect("panic index missing"),
        },
    );

    // Note: successes are already in input order since we iterate outcomes
    // sequentially with enumerate(). No sort needed.

    // Reduce successful values (left fold in input order)
    let reduced = if successes.is_empty() {
        None
    } else {
        let mut iter = successes.iter();
        let (_, first) = iter.next().expect("already checked non-empty");
        let result = iter.fold(first.clone(), |acc, (_, v)| reduce(acc, v.clone()));
        Some(result)
    };

    (decision, reduced, successes)
}

/// Constructs a [`MapReduceResult`] from a vector of outcomes.
///
/// This is the primary entry point for map-reduce result construction.
/// All tasks must have completed (no task is abandoned).
///
/// # Arguments
/// * `outcomes` - The outcomes from all tasks, in their original order
/// * `reduce` - Function to combine two values into one
///
/// # Returns
/// A [`MapReduceResult`] containing the aggregate decision, reduced value, and metadata.
///
/// # Example
/// ```
/// use asupersync::combinator::map_reduce::make_map_reduce_result;
/// use asupersync::types::Outcome;
///
/// let outcomes: Vec<Outcome<i32, &str>> = vec![
///     Outcome::Ok(1),
///     Outcome::Ok(2),
///     Outcome::Ok(3),
/// ];
/// let result = make_map_reduce_result(outcomes, |a, b| a + b);
/// assert!(result.all_succeeded());
/// assert_eq!(result.reduced, Some(6)); // 1 + 2 + 3
/// ```
#[must_use]
pub fn make_map_reduce_result<T, E, F>(
    outcomes: Vec<Outcome<T, E>>,
    reduce: F,
) -> MapReduceResult<T, E>
where
    F: Fn(T, T) -> T,
    T: Clone,
{
    let total_count = outcomes.len();
    let (decision, reduced, successes) = map_reduce_outcomes(outcomes, reduce);
    MapReduceResult::new(decision, reduced, successes, total_count)
}

/// Converts a [`MapReduceResult`] to a Result for fail-fast handling.
///
/// If all tasks succeeded, returns `Ok` with the reduced value.
/// If any task failed (error, cancelled, or panicked), returns `Err`.
///
/// # Special Cases
/// - Empty input returns `Err(MapReduceError::Empty)`
///
/// # Example
/// ```
/// use asupersync::combinator::map_reduce::{make_map_reduce_result, map_reduce_to_result};
/// use asupersync::types::Outcome;
///
/// let outcomes: Vec<Outcome<i32, &str>> = vec![
///     Outcome::Ok(1),
///     Outcome::Ok(2),
///     Outcome::Ok(3),
/// ];
/// let result = make_map_reduce_result(outcomes, |a, b| a + b);
/// let reduced = map_reduce_to_result(result);
/// assert_eq!(reduced.unwrap(), 6);
/// ```
pub fn map_reduce_to_result<T, E>(result: MapReduceResult<T, E>) -> Result<T, MapReduceError<E>> {
    // Handle empty input
    if result.total_count == 0 {
        return Err(MapReduceError::Empty);
    }

    match result.decision {
        AggregateDecision::AllOk => {
            // All succeeded - return reduced value
            // Safety: if AllOk and total_count > 0, reduced must be Some
            result.reduced.ok_or_else(|| MapReduceError::Empty)
        }
        AggregateDecision::FirstError(e) => {
            // Find the first error index (any index not in successes)
            let success_indices: std::collections::HashSet<usize> =
                result.successes.iter().map(|(i, _)| *i).collect();
            let first_error_index = (0..result.total_count)
                .find(|i| !success_indices.contains(i))
                .unwrap_or(0);
            let total_failures = result.total_count.saturating_sub(result.successes.len());
            Err(MapReduceError::Error {
                error: e,
                index: first_error_index,
                total_failures,
                success_count: result.successes.len(),
            })
        }
        AggregateDecision::Cancelled(r) => Err(MapReduceError::Cancelled(r)),
        AggregateDecision::Panicked {
            payload,
            first_panic_index,
        } => Err(MapReduceError::Panicked {
            payload,
            index: first_panic_index,
        }),
    }
}

/// Reduces successful values from a map-reduce result without requiring all to succeed.
///
/// This is a lenient version that returns the reduced value from whatever
/// tasks succeeded, or `None` if no tasks succeeded.
///
/// # Use Cases
/// - Partial aggregation where some failures are acceptable
/// - Best-effort reduction with degraded results
///
/// # Example
/// ```
/// use asupersync::combinator::map_reduce::{make_map_reduce_result, reduce_successes};
/// use asupersync::types::Outcome;
///
/// let outcomes: Vec<Outcome<i32, &str>> = vec![
///     Outcome::Ok(1),
///     Outcome::Err("failed"),
///     Outcome::Ok(3),
/// ];
/// let result = make_map_reduce_result(outcomes, |a, b| a + b);
/// let partial = reduce_successes(&result);
/// assert_eq!(partial, Some(4)); // 1 + 3 (skipping the failure)
/// ```
#[must_use]
pub fn reduce_successes<T: Clone, E>(result: &MapReduceResult<T, E>) -> Option<T> {
    result.reduced.clone()
}

/// Independent bounds for executing map-reduce work.
///
/// The retained bound counts every admitted input until its result is folded:
/// pending admission, running tasks, and completed results waiting for an
/// earlier input. It bounds work items, not their payload sizes or the reducer's
/// accumulator. Both limits are enforced, including when concurrency is larger.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MapReduceLimits {
    concurrency: NonZeroUsize,
    retained_work: NonZeroUsize,
}

impl MapReduceLimits {
    /// Constructs bounds that cannot admit a zero-capacity execution.
    #[must_use]
    pub const fn new(concurrency: NonZeroUsize, retained_work: NonZeroUsize) -> Self {
        Self {
            concurrency,
            retained_work,
        }
    }

    /// Maximum admitted children whose terminal results have not been collected.
    #[must_use]
    pub const fn concurrency(self) -> usize {
        self.concurrency.get()
    }

    /// Maximum admitted inputs not yet reduced in input order.
    #[must_use]
    pub const fn retained_work(self) -> usize {
        self.retained_work.get()
    }
}

/// Application or synchronous admission failure in executing map-reduce.
#[derive(Debug)]
#[non_exhaustive]
pub enum MapReduceExecutionError<E> {
    /// A map returned an application error.
    Map(E),
    /// The runtime refused synchronous child admission.
    Spawn(SpawnError),
    /// The input index cannot be represented by this platform.
    InputIndexExhausted,
}

impl<E: fmt::Display> fmt::Display for MapReduceExecutionError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Map(error) => write!(f, "map failed: {error}"),
            Self::Spawn(error) => write!(f, "map admission failed: {error}"),
            Self::InputIndexExhausted => f.write_str("map input index exhausted"),
        }
    }
}

impl<E: fmt::Debug + fmt::Display> std::error::Error for MapReduceExecutionError<E> {}

/// The first observed reason that stopped further input admission.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MapReduceStopCause {
    /// The input iterator panicked.
    InputPanicked,
    /// A map or admission returned an error.
    Error,
    /// A child was cancelled, or the caller requested cancellation.
    Cancelled,
    /// A map factory, future, or discarded result panicked.
    MapPanicked,
    /// The input-order reducer panicked.
    ReducerPanicked,
}

/// Terminal report for one executing map-reduce operation.
///
/// Every admitted child has been joined when this report is returned. Empty
/// input produces `Ok(None)`. Equal-severity failures select the lowest input
/// index. Cancellation requested while draining also participates in the
/// `Err < Cancelled < Panicked` join; `stopped_by` and `errors` retain the cause
/// when a later, more severe cleanup outcome wins. A selected error is owned by
/// `outcome`; the other indexed errors remain in `errors` (at most one stopped
/// admission window). Successful values are consumed by the reducer, never
/// cloned into an additional results collection.
#[derive(Debug)]
#[non_exhaustive]
pub struct MapReduceExecution<T, E> {
    /// Final severity-joined outcome, with an input-order fold on success.
    pub outcome: Outcome<Option<T>, MapReduceExecutionError<E>>,
    /// Input index of the selected non-success outcome, if any.
    pub failure_index: Option<usize>,
    /// First observed admission stop, before draining may strengthen severity.
    pub stopped_by: Option<(usize, MapReduceStopCause)>,
    /// Non-selected application/admission errors, sorted by input index.
    pub errors: Vec<(usize, MapReduceExecutionError<E>)>,
    /// Number of child handles accepted by the spawn gateway, including queued
    /// runtime admission. A later runtime refusal still terminates that handle.
    pub admitted: usize,
    /// Number of admitted child terminal results actually joined.
    pub completed: usize,
    /// Number of successful input values consumed by the ordered fold.
    pub reduced: usize,
    /// Observed maximum admitted children not yet joined.
    pub max_in_flight: usize,
    /// Observed maximum admitted inputs not yet reduced.
    pub max_retained: usize,
}

struct ExecutingMapSlot<T, E> {
    index: usize,
    handle: Option<TaskHandle<()>>,
    returned: Arc<parking_lot::Mutex<Option<Outcome<T, E>>>>,
    value: Option<T>,
}

struct ExecutingMapOwner<T, E> {
    cx: Cx,
    cancel_waker: Option<CancelWakerToken>,
    slots: VecDeque<ExecutingMapSlot<T, E>>,
    accumulator: Option<T>,
    next_scan: usize,
    scan_end: usize,
}

impl<T, E> ExecutingMapOwner<T, E> {
    fn abort(&self, reason: &CancelReason) {
        for slot in &self.slots {
            if let Some(handle) = &slot.handle
                && !handle.is_finished()
            {
                handle.abort_with_reason(reason.clone());
            }
        }
    }

    fn discard_completed_values(
        &mut self,
        failures: &mut ExecutingMapFailures<E>,
        reduced: usize,
    ) -> bool {
        let mut retired = 0;
        if let Some(value) = self.accumulator.take() {
            if let Some(payload) = executing_map_discard(value) {
                failures.panic(
                    reduced.saturating_sub(1),
                    MapReduceStopCause::MapPanicked,
                    payload,
                );
            }
            retired += 1;
        }
        for slot in &mut self.slots {
            if retired == 64 {
                break;
            }
            if let Some(value) = slot.value.take() {
                if let Some(payload) = executing_map_discard(value) {
                    failures.panic(slot.index, MapReduceStopCause::MapPanicked, payload);
                }
                retired += 1;
            }
        }
        self.slots.iter().any(|slot| slot.value.is_some())
    }
}

impl<T, E> Drop for ExecutingMapOwner<T, E> {
    fn drop(&mut self) {
        // Drop requests cancellation; it cannot claim to have awaited cleanup.
        // The existing region owns any child that still needs cooperative polls.
        for slot in &self.slots {
            if let Some(handle) = &slot.handle
                && !handle.is_finished()
                && let Err(payload) = catch_unwind(AssertUnwindSafe(|| handle.abort()))
            {
                // Do not let a secondary arbitrary panic payload destructor
                // prevent cancellation requests to the remaining children.
                std::mem::forget(payload);
            }
        }
        if let Some(token) = self.cancel_waker.take()
            && let Err(payload) =
                catch_unwind(AssertUnwindSafe(|| self.cx.clear_cancel_waker(token)))
        {
            std::mem::forget(payload);
        }
        // Values and result cells can own arbitrary user destructors. Retire
        // them one at a time after every cancellation request was issued.
        while let Some(slot) = self.slots.pop_front() {
            let ExecutingMapSlot {
                handle,
                returned,
                value,
                ..
            } = slot;
            executing_map_drop_during_teardown(handle);
            executing_map_drop_during_teardown(value);
            let logical = returned.lock().take();
            executing_map_drop_during_teardown(logical);
            // The child may have published after take(), making this Arc the
            // last owner of a newly filled cell. Catch that retirement too.
            executing_map_drop_during_teardown(returned);
        }
        executing_map_drop_during_teardown(self.accumulator.take());
    }
}

struct ExecutingMapFailures<E> {
    stopped_by: Option<(usize, MapReduceStopCause)>,
    errors: Vec<(usize, MapReduceExecutionError<E>)>,
    cancelled: Option<(usize, CancelReason)>,
    panicked: Option<(usize, PanicPayload)>,
}

impl<E> ExecutingMapFailures<E> {
    fn stop(&mut self, index: usize, cause: MapReduceStopCause) {
        self.stopped_by.get_or_insert((index, cause));
    }

    fn error(&mut self, index: usize, error: MapReduceExecutionError<E>) {
        self.stop(index, MapReduceStopCause::Error);
        self.errors.push((index, error));
    }

    fn cancel(&mut self, index: usize, reason: CancelReason) {
        self.stop(index, MapReduceStopCause::Cancelled);
        if self.cancelled.as_ref().is_none_or(|(old, _)| index < *old) {
            self.cancelled = Some((index, reason));
        } else if let Some((old, retained)) = &mut self.cancelled
            && *old == index
        {
            retained.strengthen(&reason);
        }
    }

    fn panic(&mut self, index: usize, cause: MapReduceStopCause, payload: PanicPayload) {
        self.stop(index, cause);
        if self.panicked.as_ref().is_none_or(|(old, _)| index < *old) {
            self.panicked = Some((index, payload));
        }
    }
}

impl<E> Drop for ExecutingMapFailures<E> {
    fn drop(&mut self) {
        for (_, error) in self.errors.drain(..) {
            executing_map_drop_during_teardown(error);
        }
    }
}

fn executing_map_drop_during_teardown<T>(value: T) {
    if let Err(payload) = catch_unwind(AssertUnwindSafe(|| drop(value))) {
        // No result can be published when the execution itself is being
        // dropped; preserve any primary unwind and finish the other cleanup.
        std::mem::forget(payload);
    }
}

fn executing_map_discard<T>(value: T) -> Option<PanicPayload> {
    catch_unwind(AssertUnwindSafe(|| drop(value)))
        .err()
        .map(executing_map_panic)
}

fn executing_map_panic(payload: Box<dyn std::any::Any + Send>) -> PanicPayload {
    let message = crate::cx::scope::payload_to_string(&payload);
    // Match the runtime's panic boundary: an arbitrary payload destructor must
    // not replace the original panic while owned children still need draining.
    std::mem::forget(payload);
    PanicPayload::new(message)
}

fn executing_map_caller_cancel<E>(
    cx: &Cx,
    observed: &mut Option<(usize, CancelReason)>,
    failures: &mut ExecutingMapFailures<E>,
    index: usize,
) -> bool {
    // A checkpoint publishes an acknowledgement consumed by the scheduler.
    // Re-acknowledging on every Pending cleanup poll would continuously
    // reschedule the coordinator even when only an external child wake can
    // make progress. Keep the owned cancellation registration, but acknowledge
    // once per reason. A stronger explicit request still needs one new
    // acknowledgement to reconcile the authoritative task state/budget.
    if let Some((first_index, acknowledged)) = observed {
        let changed = cx.cancel_reason().is_some_and(|current| {
            let mut merged = acknowledged.clone();
            merged.strengthen(&current)
        });
        if changed
            && cx.checkpoint().is_err()
            && let Some(current) = cx.cancel_reason()
        {
            acknowledged.strengthen(&current);
        }
        failures.cancel(*first_index, acknowledged.clone());
        true
    } else if cx.checkpoint().is_err() {
        let reason = cx
            .cancel_reason()
            .unwrap_or_else(|| CancelReason::user("map-reduce cancelled"));
        failures.cancel(index, reason.clone());
        *observed = Some((index, reason));
        true
    } else {
        false
    }
}

/// Lazily maps inputs as real scoped children and folds results in input order.
///
/// The mapper runs inside each cancellation-dominant child, including factory
/// construction. The reducer is a fixed left fold; it need not be associative
/// or commutative. Empty input returns `Ok(None)` and a singleton never calls
/// the reducer. No input or mapped value needs `Clone`.
///
/// Both limits apply before requesting the next input. A later completed map
/// continues to consume retained-work credit while an earlier map is pending.
/// Admission and ordered folding each yield after at most 64 inputs per poll,
/// independently of the configured limits, so a large window still permits
/// other tasks to run.
/// Input/reducer panics and all non-success child outcomes stop admission,
/// request cancellation of unfinished children and join every child, including
/// asynchronous cleanup, before reporting. A noncooperative child keeps this
/// future pending. Dropping the future requests cancellation; region ownership
/// remains the cleanup backstop, with no claim of synchronous drainage.
pub async fn execute_map_reduce<I, M, F, R, T, E, P>(
    cx: &Cx,
    scope: &Scope<'_, P>,
    limits: MapReduceLimits,
    inputs: I,
    map: M,
    mut reduce: R,
) -> MapReduceExecution<T, E>
where
    P: Policy,
    I: IntoIterator,
    I::Item: Send + 'static,
    M: Fn(Cx, I::Item) -> F + Send + Sync + 'static,
    F: Future<Output = Outcome<T, E>> + Send + 'static,
    R: FnMut(T, T) -> T,
    T: Send + 'static,
    E: Send + 'static,
{
    let mut owner = ExecutingMapOwner {
        cx: cx.clone(),
        cancel_waker: None,
        slots: VecDeque::new(),
        accumulator: None,
        next_scan: 0,
        scan_end: 0,
    };
    let mut failures = ExecutingMapFailures {
        stopped_by: None,
        errors: Vec::new(),
        cancelled: None,
        panicked: None,
    };
    let mut inputs = match catch_unwind(AssertUnwindSafe(|| inputs.into_iter())) {
        Ok(inputs) => Some(inputs),
        Err(payload) => {
            failures.panic(
                0,
                MapReduceStopCause::InputPanicked,
                executing_map_panic(payload),
            );
            None
        }
    };
    let map = Arc::new(map);
    let mut exhausted = false;
    let mut abort_requested = false;
    let mut caller_cancel_observed = None;
    let mut admitted = 0_usize;
    let mut completed = 0_usize;
    let mut reduced = 0_usize;
    let mut max_in_flight = 0_usize;
    let mut max_retained = 0_usize;
    // Child terminations, counted by the guard each child future carries;
    // ahead of `completed` whenever a join sweep has passed a finished child.
    let terminated = Arc::new(std::sync::atomic::AtomicUsize::new(0));

    std::future::poll_fn(|poll_cx| {
        owner.cancel_waker = Some(cx.refresh_cancel_waker(owner.cancel_waker, poll_cx.waker()));
        executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted);
        // Snapshot a finite input-index sweep. Absolute indices stay valid
        // when front folds remove slots; later admissions receive a subsequent
        // sweep. This bounds both terminal polling and canceled-value disposal.
        let first_index = owner.slots.front().map_or(admitted, |slot| slot.index);
        if owner.next_scan >= owner.scan_end {
            owner.next_scan = first_index;
            owner.scan_end = admitted;
        } else {
            owner.next_scan = owner.next_scan.max(first_index);
        }
        for _ in 0..64 {
            if owner.next_scan >= owner.scan_end {
                break;
            }
            let offset = owner.next_scan - first_index;
            owner.next_scan += 1;
            let slot = owner.slots.get_mut(offset).expect("retained input index");
            let Some(handle) = &mut slot.handle else {
                continue;
            };
            let Poll::Ready(joined) = handle.poll_join(poll_cx) else {
                continue;
            };
            slot.handle = None;
            completed += 1;
            // The logical four-way value becomes observable only AFTER actual
            // task termination. An encoded panic must still outrank runtime
            // cancellation, whose generic spawn policy sees only returned ().
            let returned = slot.returned.lock().take();
            match returned {
                Some(Outcome::Ok(value)) if joined.is_ok() => slot.value = Some(value),
                Some(Outcome::Ok(value)) => {
                    if let Some(payload) = executing_map_discard(value) {
                        failures.panic(slot.index, MapReduceStopCause::MapPanicked, payload);
                    }
                }
                Some(Outcome::Err(error)) => {
                    failures.error(slot.index, MapReduceExecutionError::Map(error))
                }
                Some(Outcome::Cancelled(reason)) => failures.cancel(slot.index, reason),
                Some(Outcome::Panicked(payload)) => {
                    failures.panic(slot.index, MapReduceStopCause::MapPanicked, payload)
                }
                None if joined.is_ok() => failures.panic(
                    slot.index,
                    MapReduceStopCause::MapPanicked,
                    PanicPayload::new("map child completed without its logical outcome"),
                ),
                None => {}
            }
            match joined {
                Ok(()) => {}
                Err(JoinError::Cancelled(reason)) => failures.cancel(slot.index, reason),
                Err(JoinError::Panicked(payload)) => {
                    failures.panic(slot.index, MapReduceStopCause::MapPanicked, payload)
                }
                Err(JoinError::PolledAfterCompletion) => failures.panic(
                    slot.index,
                    MapReduceStopCause::MapPanicked,
                    PanicPayload::new("map child join polled after completion"),
                ),
            }
        }
        let mut folded = 0;
        if failures.stopped_by.is_none() {
            while owner
                .slots
                .front()
                .is_some_and(|slot| slot.handle.is_none())
                && folded < 64
            {
                let mut slot = owner.slots.pop_front().expect("front was present");
                let value = slot
                    .value
                    .take()
                    .expect("successful completed map owns its value");
                if let Some(previous) = owner.accumulator.take() {
                    match catch_unwind(AssertUnwindSafe(|| reduce(previous, value))) {
                        Ok(value) => owner.accumulator = Some(value),
                        Err(payload) => {
                            failures.panic(
                                slot.index,
                                MapReduceStopCause::ReducerPanicked,
                                executing_map_panic(payload),
                            );
                            break;
                        }
                    }
                } else {
                    owner.accumulator = Some(value);
                }
                reduced += 1;
                folded += 1;
                // A reducer can publish cancellation even when no input is
                // left to admit. Observe it before any further fold or result.
                if executing_map_caller_cancel(
                    cx,
                    &mut caller_cancel_observed,
                    &mut failures,
                    slot.index,
                ) {
                    break;
                }
            }
        }
        let fold_pending = owner
            .slots
            .front()
            .is_some_and(|slot| slot.handle.is_none());
        let scan_pending = owner.next_scan < owner.scan_end || owner.scan_end < admitted;
        if failures.stopped_by.is_some() {
            if !abort_requested {
                let reason = cx.cancel_reason().unwrap_or_else(CancelReason::race_loser);
                owner.abort(&reason);
                abort_requested = true;
            }
            let values_pending = owner.discard_completed_values(&mut failures, reduced);
            // A termination the sweep already passed restarts the sweep.
            let unobserved_terminations =
                terminated.load(std::sync::atomic::Ordering::Acquire) > completed;
            if values_pending || scan_pending || unobserved_terminations {
                poll_cx.waker().wake_by_ref();
            }
            return if completed == admitted && !values_pending {
                Poll::Ready(())
            } else {
                Poll::Pending
            };
        }
        let mut in_flight = admitted - completed;
        let mut spawned = 0;
        while !exhausted
            && in_flight < limits.concurrency()
            && owner.slots.len() < limits.retained_work()
            && spawned < 64
        {
            // A synchronous reducer/input callback can itself publish caller
            // cancellation. Recheck immediately before every admission.
            if executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted)
            {
                break;
            }
            let item = match catch_unwind(AssertUnwindSafe(|| {
                inputs.as_mut().expect("iterator exists before stop").next()
            })) {
                Ok(Some(item)) => item,
                Ok(None) => {
                    exhausted = true;
                    break;
                }
                Err(payload) => {
                    failures.panic(
                        admitted,
                        MapReduceStopCause::InputPanicked,
                        executing_map_panic(payload),
                    );
                    break;
                }
            };
            let Some(next_admitted) = admitted.checked_add(1) else {
                failures.error(admitted, MapReduceExecutionError::InputIndexExhausted);
                break;
            };
            if executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted)
            {
                break;
            }
            let mapper = Arc::clone(&map);
            let returned = Arc::new(parking_lot::Mutex::new(None));
            let child_returned = Arc::clone(&returned);
            // Moved into the future at spawn so it fires on every terminal
            // path, including cancellation before the first poll.
            match super::TerminationTally::track_spawn(&terminated, |tally| {
                cx.spawn_in_cancellation_dominant(scope, move |child| async move {
                    let _tally = tally;
                    let outcome = mapper(child, item).await;
                    *child_returned.lock() = Some(outcome);
                })
            }) {
                Ok(handle) => {
                    owner.slots.push_back(ExecutingMapSlot {
                        index: admitted,
                        handle: Some(handle),
                        returned,
                        value: None,
                    });
                    admitted = next_admitted;
                    in_flight += 1;
                    max_in_flight = max_in_flight.max(in_flight);
                    max_retained = max_retained.max(owner.slots.len());
                    spawned += 1;
                }
                Err(error) => {
                    failures.error(admitted, MapReduceExecutionError::Spawn(error));
                    break;
                }
            }
        }
        // next() can request cancellation and return None. This checkpoint is
        // also the success-publication boundary when no admission was needed.
        executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted);
        if failures.stopped_by.is_some() {
            owner.abort(&cx.cancel_reason().unwrap_or_else(CancelReason::race_loser));
            abort_requested = true;
        }
        let values_pending =
            failures.stopped_by.is_some() && owner.discard_completed_values(&mut failures, reduced);
        if (failures.stopped_by.is_some() || (exhausted && owner.slots.is_empty()))
            && completed == admitted
            && !values_pending
        {
            Poll::Ready(())
        } else {
            // Newly admitted handles need a first poll_join registration even
            // when their completion races admission. Yield once per batch.
            if spawned != 0
                || fold_pending
                || values_pending
                || owner.next_scan < owner.scan_end
                || owner.scan_end < admitted
                || terminated.load(std::sync::atomic::Ordering::Acquire) > completed
            {
                poll_cx.waker().wake_by_ref();
            }
            Poll::Pending
        }
    })
    .await;

    // These captures may run arbitrary destructors, including a new caller
    // cancellation request. Retire them before choosing the report, even when
    // iterator construction failed. Admitted children have all joined, so the
    // mapper Arc is no longer shared with any child execution.
    for (cause, panic) in [
        (
            MapReduceStopCause::InputPanicked,
            executing_map_discard(inputs.take()),
        ),
        (MapReduceStopCause::MapPanicked, executing_map_discard(map)),
        (
            MapReduceStopCause::ReducerPanicked,
            executing_map_discard(reduce),
        ),
    ] {
        if let Some(payload) = panic {
            failures.panic(admitted, cause, payload);
        }
    }
    executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted);
    if failures.stopped_by.is_some() {
        // A late cleanup failure must retire the formerly successful fold;
        // an actual successful return keeps its accumulator alive for callers.
        while owner.discard_completed_values(&mut failures, reduced) {
            crate::runtime::yield_now().await;
        }
        executing_map_caller_cancel(cx, &mut caller_cancel_observed, &mut failures, admitted);
    }

    failures.errors.sort_by_key(|(index, _)| *index);
    let (failure_index, outcome) = if let Some((index, payload)) = failures.panicked.take() {
        (Some(index), Outcome::Panicked(payload))
    } else if let Some((index, reason)) = failures.cancelled.take() {
        (Some(index), Outcome::Cancelled(reason))
    } else if !failures.errors.is_empty() {
        let (index, error) = failures.errors.remove(0);
        (Some(index), Outcome::Err(error))
    } else {
        (None, Outcome::Ok(owner.accumulator.take()))
    };
    MapReduceExecution {
        outcome,
        failure_index,
        stopped_by: failures.stopped_by,
        errors: std::mem::take(&mut failures.errors),
        admitted,
        completed,
        reduced,
        max_in_flight,
        max_retained,
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use crate::lab::{LabConfig, LabRuntime};
    use crate::types::Budget;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn executing_limits(concurrency: usize, retained: usize) -> MapReduceLimits {
        MapReduceLimits::new(
            NonZeroUsize::new(concurrency).unwrap(),
            NonZeroUsize::new(retained).unwrap(),
        )
    }

    fn assert_executing_lab_clean(lab: &mut LabRuntime, region: crate::types::RegionId) {
        let report = lab.run_until_quiescent_with_report();
        assert!(report.lab_test_passed(), "{report:?}");
        assert_eq!(lab.state.live_task_count(), 0);
        assert_eq!(lab.state.pending_obligation_count(), 0);
        assert_eq!(lab.state.region(region).unwrap().pending_spawn_count(), 0);
        let effects =
            lab.state
                .cancel_request(region, &CancelReason::user("map test complete"), None);
        let (tasks, wakes) = effects.into_parts();
        assert!(tasks.is_empty());
        wakes.dispatch();
        lab.state.advance_region_state(region);
        assert!(lab.state.region(region).is_none());
        assert!(lab.run_until_quiescent_with_report().lab_test_passed());
    }

    fn run_executing_case<F, Fut, T>(factory: F) -> T
    where
        F: FnOnce(Cx) -> Fut + Send + 'static,
        Fut: Future<Output = T> + Send + 'static,
        T: Send + 'static,
    {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0100).max_steps(4096));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let returned = Arc::new(parking_lot::Mutex::new(None));
        let publication = Arc::clone(&returned);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().expect("actual map coordinator");
                let value = factory(cx.clone()).await;
                *publication.lock() = Some((value, cx.cancel_reason()));
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        let (result, cancelled) = returned
            .lock()
            .take()
            .expect("bounded map execution returned");
        // RuntimeState::create_task deliberately uses cancellation-dominant
        // delivery. Its terminal receipt is distinct from the engine report.
        match cancelled {
            Some(reason) => assert_eq!(join.try_join(), Err(JoinError::Cancelled(reason))),
            None => assert_eq!(join.try_join(), Ok(Some(()))),
        }
        assert_executing_lab_clean(&mut lab, root);
        result
    }

    #[test]
    fn executing_map_zero_one_many_move_only_values_and_independent_limits() {
        struct MoveOnly(String);
        assert!(NonZeroUsize::new(0).is_none());
        for count in [0, 1, 9] {
            for (concurrency, retained) in [(1, 1), (4, 2), (2, 5)] {
                let report = run_executing_case(move |cx| async move {
                    cx.scope()
                        .map_reduce(
                            &cx,
                            executing_limits(concurrency, retained),
                            0..count,
                            |_child, index| async move {
                                Outcome::<_, ()>::Ok(MoveOnly(index.to_string()))
                            },
                            |left, right| MoveOnly(format!("{}>{}", left.0, right.0)),
                        )
                        .await
                });
                assert_eq!(report.admitted, count);
                assert_eq!(report.completed, count);
                assert_eq!(report.reduced, count);
                assert!(report.max_in_flight <= concurrency);
                assert!(report.max_retained <= retained);
                assert!(report.stopped_by.is_none());
                let Outcome::Ok(value) = report.outcome else {
                    panic!("all maps succeed")
                };
                assert_eq!(
                    value.map(|value| value.0),
                    (count > 0).then(|| (0..count)
                        .map(|i| i.to_string())
                        .collect::<Vec<_>>()
                        .join(">"))
                );
            }
        }
    }

    #[test]
    fn executing_map_owned_capture_retirement_precedes_terminal_publication() {
        struct Capture {
            cx: Cx,
            drops: Arc<[AtomicUsize; 3]>,
            index: usize,
            cancel: bool,
            panic: bool,
        }

        impl Capture {
            fn observe(&self) {
                assert_eq!(self.drops[self.index].load(Ordering::SeqCst), 0);
            }
        }

        impl Drop for Capture {
            fn drop(&mut self) {
                assert_eq!(self.drops[self.index].fetch_add(1, Ordering::SeqCst), 0);
                if self.cancel {
                    self.cx.cancel_with(
                        crate::types::CancelKind::User,
                        Some("map owned-capture retirement"),
                    );
                }
                if self.panic {
                    panic!("map capture {} retirement panic", self.index);
                }
            }
        }

        struct Inputs {
            capture: Capture,
            fail_construction: bool,
        }

        struct Iter {
            capture: Capture,
            next: u32,
        }

        impl IntoIterator for Inputs {
            type Item = u32;
            type IntoIter = Iter;

            fn into_iter(self) -> Iter {
                assert!(!self.fail_construction, "map primary construction panic");
                Iter {
                    capture: self.capture,
                    next: 0,
                }
            }
        }

        impl Iterator for Iter {
            type Item = u32;

            fn next(&mut self) -> Option<u32> {
                self.capture.observe();
                let value = self.next;
                self.next += 1;
                (value < 3).then_some(value)
            }
        }

        #[derive(Debug)]
        struct Value {
            text: String,
            drops: Arc<AtomicUsize>,
        }

        impl Drop for Value {
            fn drop(&mut self) {
                self.drops.fetch_add(1, Ordering::SeqCst);
            }
        }

        for mode in 0..12 {
            let mut lab = LabRuntime::new(LabConfig::new(0x32_0900 + mode).max_steps(4096));
            let root = lab.state.create_root_region(Budget::INFINITE);
            let drops = Arc::new(std::array::from_fn::<_, 3, _>(|_| AtomicUsize::new(0)));
            let value_drops = Arc::new(AtomicUsize::new(0));
            let children = Arc::new(parking_lot::Mutex::new(Vec::new()));
            let publication = Arc::new(parking_lot::Mutex::new(None));
            let task_drops = Arc::clone(&drops);
            let task_values = Arc::clone(&value_drops);
            let task_children = Arc::clone(&children);
            let task_publication = Arc::clone(&publication);
            let future: Pin<Box<dyn Future<Output = ()> + Send>> = Box::pin(async move {
                let cx = Cx::current().expect("actual retirement coordinator");
                let capture = |index| Capture {
                    cx: cx.clone(),
                    drops: Arc::clone(&task_drops),
                    index,
                    cancel: mode == index as u64 + 1 || (mode >= 7 && index == 0),
                    panic: mode == index as u64 + 4
                        || ((7..=9).contains(&mode) && index != 0)
                        || (mode == 11 && index == 0),
                };
                let inputs = Inputs {
                    capture: capture(0),
                    fail_construction: mode == 7,
                };
                let mapper = capture(1);
                let reducer = capture(2);
                let report = cx
                    .scope()
                    .map_reduce(
                        &cx,
                        executing_limits(1, 1),
                        inputs,
                        move |child, value| {
                            mapper.observe();
                            task_children.lock().push(child.task_id());
                            let drops = Arc::clone(&task_values);
                            async move {
                                if mode == 8 {
                                    panic!("map primary mapper panic");
                                }
                                if mode == 10 {
                                    Outcome::Err("map primary error")
                                } else {
                                    Outcome::Ok(Value {
                                        text: value.to_string(),
                                        drops,
                                    })
                                }
                            }
                        },
                        move |mut left: Value, right: Value| {
                            reducer.observe();
                            if mode == 9 {
                                panic!("map primary reducer panic");
                            }
                            left.text = format!("({}|{})", left.text, right.text);
                            left
                        },
                    )
                    .await;
                *task_publication.lock() = Some((report, cx.cancel_reason()));
            });
            let (parent, mut join) = lab
                .state
                .create_task(root, Budget::INFINITE, future)
                .unwrap();
            lab.scheduler.lock().schedule(parent, 0);
            lab.run_until_idle();
            let (report, reason) = publication.lock().take().expect("actual terminal report");
            match &reason {
                Some(reason) => {
                    assert_eq!(reason.kind(), crate::types::CancelKind::User);
                    assert_eq!(
                        reason.message.as_deref(),
                        Some("map owned-capture retirement")
                    );
                    assert_eq!(join.try_join(), Err(JoinError::Cancelled(reason.clone())));
                }
                None => assert_eq!(join.try_join(), Ok(Some(()))),
            }
            assert!(drops.iter().all(|count| count.load(Ordering::SeqCst) == 1));
            let counts = match mode {
                7 => (0, 0, 0),
                8 | 10 => (1, 1, 0),
                9 => (2, 2, 1),
                _ => (3, 3, 3),
            };
            assert_eq!((report.admitted, report.completed, report.reduced), counts);
            let trace = lab.state.trace_handle().snapshot();
            let completion =
                |expected| {
                    let matches: Vec<_> = trace.iter().filter(|event| {
                    event.kind == crate::trace::TraceEventKind::Complete
                        && matches!(event.data, crate::trace::TraceData::Task { task, region }
                            if task == expected && region == root)
                }).collect();
                    assert_eq!(matches.len(), 1, "exact terminal for {expected:?}");
                    matches[0].seq
                };
            let parent_complete = completion(parent);
            let children = children.lock();
            assert_eq!(children.len(), report.admitted);
            for (index, child) in children.iter().enumerate() {
                assert!(!children[..index].contains(child));
                assert!(completion(*child) < parent_complete);
            }
            assert_executing_lab_clean(&mut lab, root);
            eprintln!(
                "map capture retirement mode={mode} parent={parent:?} children={children:?} report={report:?} reason={reason:?}"
            );
            if mode == 0 {
                assert_eq!(report.failure_index, None);
                assert_eq!(
                    value_drops.load(Ordering::SeqCst),
                    2,
                    "returned accumulator remains live"
                );
                let Outcome::Ok(Some(value)) = report.outcome else {
                    panic!("successful retirement preserves the returned value");
                };
                assert_eq!(value.text, "((0|1)|2)");
                drop(value);
                assert_eq!(value_drops.load(Ordering::SeqCst), 3);
            } else if matches!(mode, 1..=3 | 10) {
                assert!(
                    matches!(&report.outcome, Outcome::Cancelled(actual) if Some(actual) == reason.as_ref())
                );
                assert_eq!(report.failure_index, Some(if mode == 10 { 1 } else { 3 }));
                if mode == 10 {
                    assert_eq!(report.stopped_by, Some((0, MapReduceStopCause::Error)));
                    assert!(matches!(
                        report.errors.as_slice(),
                        [(0, MapReduceExecutionError::Map("map primary error"))]
                    ));
                }
                assert_eq!(
                    value_drops.load(Ordering::SeqCst),
                    if mode == 10 { 0 } else { 3 }
                );
            } else {
                let (index, message) = match mode {
                    4..=6 => (3, format!("map capture {} retirement panic", mode - 4)),
                    7 => (0, "map primary construction panic".to_owned()),
                    8 => (0, "map primary mapper panic".to_owned()),
                    9 => (1, "map primary reducer panic".to_owned()),
                    11 => (3, "map capture 0 retirement panic".to_owned()),
                    _ => unreachable!(),
                };
                assert_eq!(report.failure_index, Some(index));
                assert!(
                    matches!(&report.outcome, Outcome::Panicked(payload) if payload.message() == message)
                );
                assert_eq!(
                    value_drops.load(Ordering::SeqCst),
                    match mode {
                        7 | 8 => 0,
                        9 => 2,
                        _ => 3,
                    }
                );
            }
        }
    }

    #[test]
    fn executing_map_held_first_input_keeps_completed_results_in_retained_window() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0101).max_steps(4096));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let gate = Arc::new(crate::sync::Mutex::new(()));
        let held = gate.try_lock_owned().unwrap();
        let pulled = Arc::new(AtomicUsize::new(0));
        let finished = Arc::new(AtomicUsize::new(0));
        let input_pulled = Arc::clone(&pulled);
        let mapped_finished = Arc::clone(&finished);
        let child_gate = Arc::clone(&gate);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                cx.scope()
                    .map_reduce(
                        &cx,
                        executing_limits(2, 3),
                        (0..20).inspect(move |_| {
                            input_pulled.fetch_add(1, Ordering::SeqCst);
                        }),
                        move |child, index| {
                            let gate = Arc::clone(&child_gate);
                            let finished = Arc::clone(&mapped_finished);
                            async move {
                                if index == 0 {
                                    drop(
                                        crate::sync::OwnedMutexGuard::lock(gate, &child)
                                            .await
                                            .unwrap(),
                                    );
                                }
                                finished.fetch_add(1, Ordering::SeqCst);
                                Outcome::<_, ()>::Ok(index.to_string())
                            }
                        },
                        |left, right| format!("{left}>{right}"),
                    )
                    .await
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert!(join.try_join().unwrap().is_none());
        assert_eq!(gate.waiters(), 1);
        assert_eq!(
            pulled.load(Ordering::SeqCst),
            3,
            "later completions cannot release retained credit"
        );
        assert_eq!(
            finished.load(Ordering::SeqCst),
            2,
            "later maps really completed"
        );
        drop(held);
        lab.run_until_idle();
        let report = join.try_join().unwrap().unwrap();
        assert_eq!(report.admitted, 20);
        assert_eq!(report.completed, 20);
        assert_eq!(report.reduced, 20);
        assert_eq!(report.max_in_flight, 2);
        assert_eq!(report.max_retained, 3);
        assert_eq!(
            report.outcome.unwrap(),
            Some((0..20).map(|i| i.to_string()).collect::<Vec<_>>().join(">"))
        );
        assert_eq!(gate.waiters(), 0);
        assert_executing_lab_clean(&mut lab, root);
        eprintln!(
            "map retained case: pulled=20 completed=20 reduced=20 max_active=2 max_retained=3 first_blocked_later_completed=2"
        );
    }

    #[test]
    fn executing_map_large_window_yields_admission_to_an_actual_other_task() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0106).max_steps(16384));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let gate = Arc::new(crate::sync::Mutex::new(()));
        let held = gate.try_lock_owned().unwrap();
        let pulled = Arc::new(AtomicUsize::new(0));
        let input_pulled = Arc::clone(&pulled);
        let child_gate = Arc::clone(&gate);
        let returned = Arc::new(parking_lot::Mutex::new(None));
        let publication = Arc::clone(&returned);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                let report = cx
                    .scope()
                    .map_reduce(
                        &cx,
                        executing_limits(4096, 4096),
                        (0..4096).inspect(move |_| {
                            input_pulled.fetch_add(1, Ordering::SeqCst);
                        }),
                        move |child, index| {
                            let gate = Arc::clone(&child_gate);
                            async move {
                                if index == 0 {
                                    match crate::sync::OwnedMutexGuard::lock(gate, &child).await {
                                        Ok(guard) => drop(guard),
                                        Err(_) => {
                                            return Outcome::Cancelled(
                                                child.cancel_reason().unwrap(),
                                            );
                                        }
                                    }
                                }
                                Outcome::<_, ()>::Ok(index)
                            }
                        },
                        |left, right| left + right,
                    )
                    .await;
                *publication.lock() = Some(report);
            })
            .unwrap();
        let parent_cx = lab.state.task(parent).unwrap().cx.clone().unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.step_for_test();
        assert_eq!(
            pulled.load(Ordering::SeqCst),
            64,
            "one real coordinator poll has a fixed admission burst"
        );
        assert!(join.try_join().unwrap().is_none());
        let observer_pulled = Arc::clone(&pulled);
        let (observer, mut observation) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let seen = observer_pulled.load(Ordering::SeqCst);
                parent_cx.cancel_with(
                    crate::types::CancelKind::User,
                    Some("observer made progress"),
                );
                // cancel_with publishes the real Cx reason and wakes its
                // registered waiters. It does not call the region cancellation
                // path that emits a canonical TraceData::Cancel event.
                let reason = parent_cx
                    .cancel_reason()
                    .expect("observer published actual parent cancellation");
                (seen, reason)
            })
            .unwrap();
        lab.scheduler.lock().schedule(observer, 255);
        lab.run_until_idle();
        let (seen, published_reason) = observation.try_join().unwrap().unwrap();
        assert!(
            (64..4096).contains(&seen),
            "other task must execute before a large window is exhausted: {seen}"
        );
        assert_eq!(published_reason.kind(), crate::types::CancelKind::User);
        assert_eq!(published_reason.message(), Some("observer made progress"));
        assert_eq!(published_reason.origin_task, Some(parent));
        assert_eq!(published_reason.origin_region, root);
        assert_eq!(
            join.try_join(),
            Err(JoinError::Cancelled(published_reason.clone()))
        );
        let report = returned.lock().take().expect("actual map engine report");
        assert!(
            matches!(&report.outcome, Outcome::Cancelled(reason) if reason == &published_reason)
        );
        let trace = lab.state.trace_handle().snapshot();
        let completion = |expected| {
            let events: Vec<_> = trace
                .iter()
                .filter(|event| {
                    event.kind == crate::trace::TraceEventKind::Complete
                        && matches!(event.data, crate::trace::TraceData::Task { task, region }
                            if task == expected && region == root)
                })
                .collect();
            assert_eq!(events.len(), 1, "exact real terminal for {expected:?}");
            events[0].seq
        };
        let observer_complete = completion(observer);
        let parent_complete = completion(parent);
        assert!(
            observer_complete < parent_complete,
            "actual observer publication must precede the parent terminal"
        );
        assert_eq!(report.admitted, pulled.load(Ordering::SeqCst));
        assert_eq!(report.completed, report.admitted);
        assert_eq!(gate.waiters(), 0);
        drop(held);
        assert_executing_lab_clean(&mut lab, root);
        eprintln!(
            "map admission fairness: first_poll=64 observer_at={seen} admitted={} joined={} observer={observer:?} parent={parent:?} observer_complete={observer_complete} parent_complete={parent_complete} published_reason={published_reason:?}",
            report.admitted, report.completed
        );
    }

    #[test]
    fn executing_map_single_error_remains_an_error_without_cancelled_siblings() {
        let report = run_executing_case(|cx| async move {
            cx.scope()
                .map_reduce(
                    &cx,
                    executing_limits(1, 1),
                    [5],
                    |_child, _| async { Outcome::<usize, _>::Err("map refused") },
                    |left, right| left + right,
                )
                .await
        });
        assert!(matches!(
            report.outcome,
            Outcome::Err(MapReduceExecutionError::Map("map refused"))
        ));
        assert_eq!(report.failure_index, Some(0));
        assert_eq!(report.stopped_by, Some((0, MapReduceStopCause::Error)));
        assert!(report.errors.is_empty());
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (1, 1, 0)
        );
    }

    #[test]
    fn executing_map_missing_gateway_is_an_admission_error_without_running_mapper() {
        let cx = Cx::new(
            crate::types::RegionId::new_for_test(0, 1),
            crate::types::TaskId::new_for_test(0, 1),
            Budget::INFINITE,
        );
        let scope = cx.scope();
        let mapped = Arc::new(AtomicUsize::new(0));
        let child_mapped = Arc::clone(&mapped);
        let mut execution = Box::pin(scope.map_reduce(
            &cx,
            executing_limits(2, 3),
            [1, 2, 3],
            move |_child, value| {
                child_mapped.fetch_add(1, Ordering::SeqCst);
                async move { Outcome::<_, ()>::Ok(value) }
            },
            |left, right| left + right,
        ));
        let mut poll_cx = std::task::Context::from_waker(std::task::Waker::noop());
        let Poll::Ready(report) = execution.as_mut().poll(&mut poll_cx) else {
            panic!("synchronous admission refusal cannot leave a fictitious child pending")
        };
        assert!(matches!(
            report.outcome,
            Outcome::Err(MapReduceExecutionError::Spawn(
                SpawnError::RuntimeUnavailable
            ))
        ));
        assert_eq!(report.failure_index, Some(0));
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (0, 0, 0)
        );
        assert_eq!(mapped.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn executing_map_cancellation_before_or_during_input_does_not_spawn() {
        for cancel_before_input in [false, true] {
            let pulled = Arc::new(AtomicUsize::new(0));
            let mapped = Arc::new(AtomicUsize::new(0));
            let input_pulled = Arc::clone(&pulled);
            let child_mapped = Arc::clone(&mapped);
            let report = run_executing_case(move |cx| async move {
                if cancel_before_input {
                    cx.cancel_with(crate::types::CancelKind::User, Some("before first input"));
                }
                let input_cx = cx.clone();
                let inputs = [1, 2, 3].into_iter().inspect(move |_| {
                    input_pulled.fetch_add(1, Ordering::SeqCst);
                    input_cx.cancel_with(crate::types::CancelKind::User, Some("inside next input"));
                });
                cx.scope()
                    .map_reduce(
                        &cx,
                        executing_limits(2, 3),
                        inputs,
                        move |_child, value| {
                            child_mapped.fetch_add(1, Ordering::SeqCst);
                            async move { Outcome::<_, ()>::Ok(value) }
                        },
                        |left, right| left + right,
                    )
                    .await
            });
            assert!(report.outcome.is_cancelled());
            assert_eq!(report.failure_index, Some(0));
            assert_eq!(
                (report.admitted, report.completed, report.reduced),
                (0, 0, 0)
            );
            assert_eq!(
                pulled.load(Ordering::SeqCst),
                usize::from(!cancel_before_input)
            );
            assert_eq!(mapped.load(Ordering::SeqCst), 0);
        }
    }

    #[test]
    fn executing_map_terminal_reducer_and_none_input_cancellation_cannot_return_success() {
        let report = run_executing_case(|cx| async move {
            let reducer_cx = cx.clone();
            cx.scope()
                .map_reduce(
                    &cx,
                    executing_limits(4, 4),
                    [2, 3],
                    |_child, value| async move { Outcome::<_, ()>::Ok(value) },
                    move |left, right| {
                        reducer_cx
                            .cancel_with(crate::types::CancelKind::User, Some("final reducer"));
                        left + right
                    },
                )
                .await
        });
        assert!(report.outcome.is_cancelled());
        assert_eq!(report.failure_index, Some(1));
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (2, 2, 2)
        );

        let calls = Arc::new(AtomicUsize::new(0));
        let input_calls = Arc::clone(&calls);
        let report = run_executing_case(move |cx| async move {
            let input_cx = cx.clone();
            let input = std::iter::from_fn(move || {
                input_calls.fetch_add(1, Ordering::SeqCst);
                input_cx.cancel_with(crate::types::CancelKind::User, Some("terminal None"));
                None::<usize>
            });
            cx.scope()
                .map_reduce(
                    &cx,
                    executing_limits(4, 4),
                    input,
                    |_child, value| async move { Outcome::<_, ()>::Ok(value) },
                    |left, right| left + right,
                )
                .await
        });
        assert!(report.outcome.is_cancelled());
        assert_eq!(report.failure_index, Some(0));
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (0, 0, 0)
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn executing_map_stronger_caller_cancel_reconciles_once_at_original_reducer_index() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0110).max_steps(8192));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let (started, first_wait) = crate::channel::oneshot::channel::<()>();
        let started = Arc::new(parking_lot::Mutex::new(Some(started)));
        let first_wait = Arc::new(parking_lot::Mutex::new(Some(first_wait)));
        let (release, held) = crate::channel::oneshot::channel::<()>();
        let held = Arc::new(parking_lot::Mutex::new(Some(held)));
        let returned = Arc::new(parking_lot::Mutex::new(None));
        let publication = Arc::clone(&returned);
        let third_id = Arc::new(parking_lot::Mutex::new(None));
        let actual_third = Arc::clone(&third_id);
        let (parent, mut joined) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                let reducer_cx = cx.clone();
                let report = cx
                    .scope()
                    .map_reduce(
                        &cx,
                        executing_limits(3, 3),
                        [0, 1, 2],
                        move |child, index| {
                            let started = Arc::clone(&started);
                            let first_wait = Arc::clone(&first_wait);
                            let held = Arc::clone(&held);
                            let actual_third = Arc::clone(&actual_third);
                            async move {
                                if index == 0 {
                                    let mut receiver = first_wait.lock().take().unwrap();
                                    receiver.recv_uninterruptible().await.unwrap();
                                } else if index == 2 {
                                    *actual_third.lock() = Some(child.task_id());
                                    started.lock().take().unwrap().send_blocking(()).unwrap();
                                    let mut receiver = held.lock().take().unwrap();
                                    receiver.recv_uninterruptible().await.unwrap();
                                }
                                Outcome::<_, ()>::Ok(index)
                            }
                        },
                        move |left, right| {
                            reducer_cx.cancel_with(
                                crate::types::CancelKind::User,
                                Some("reducer owns first cancellation"),
                            );
                            left + right
                        },
                    )
                    .await;
                *publication.lock() = Some(report);
            })
            .unwrap();
        let parent_cx = lab.state.task(parent).unwrap().cx.clone().unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert!(lab.steps() < 8192);
        assert!(lab.scheduler.lock().is_empty());
        assert_eq!(lab.run_until_idle(), 0);
        assert_eq!(joined.try_join(), Ok(None));
        assert!(returned.lock().is_none());
        let third = third_id.lock().unwrap();
        assert!(
            lab.state.task(third).is_some(),
            "the higher input really remains owned"
        );
        assert_eq!(lab.state.live_task_count(), 2);
        assert_eq!(
            lab.state
                .task(parent)
                .unwrap()
                .cancel_reason()
                .unwrap()
                .kind,
            crate::types::CancelKind::User
        );

        parent_cx.cancel_with(
            crate::types::CancelKind::Timeout,
            Some("stronger request during held cleanup"),
        );
        let stronger = parent_cx.cancel_reason().unwrap();
        assert_eq!(stronger.kind, crate::types::CancelKind::Timeout);
        let progress = lab.run_until_idle();
        assert!(
            progress > 0,
            "the owned cancellation waker must publish real progress"
        );
        assert!(lab.steps() < 8192);
        assert!(
            lab.scheduler.lock().is_empty(),
            "unchanged strengthened cancellation must park again"
        );
        assert_eq!(lab.run_until_idle(), 0);
        let holder = lab.state.task(parent).unwrap();
        assert_eq!(holder.cancel_reason(), Some(&stronger));
        assert_eq!(holder.cleanup_budget(), Some(stronger.cleanup_budget()));
        assert_eq!(joined.try_join(), Ok(None));
        assert!(returned.lock().is_none());
        assert!(lab.state.task(third).is_some());

        release.send_blocking(()).unwrap();
        lab.run_until_idle();
        assert_eq!(
            joined.try_join(),
            Err(JoinError::Cancelled(stronger.clone()))
        );
        let report = returned
            .lock()
            .take()
            .expect("engine waits for the actual third terminal");
        assert_eq!(
            report.failure_index,
            Some(1),
            "caller attribution stays at the actual reducer"
        );
        assert_eq!(report.stopped_by, Some((1, MapReduceStopCause::Cancelled)));
        assert!(matches!(report.outcome, Outcome::Cancelled(reason) if reason == stronger));
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (3, 3, 2)
        );
        assert_executing_lab_clean(&mut lab, root);
    }

    #[test]
    fn executing_map_completed_prefix_folds_in_bounded_cooperative_bursts() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0107).max_steps(8192));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let gate = Arc::new(crate::sync::Mutex::new(()));
        let held = gate.try_lock_owned().unwrap();
        let finished = Arc::new(AtomicUsize::new(0));
        let reductions = Arc::new(AtomicUsize::new(0));
        let child_gate = Arc::clone(&gate);
        let child_finished = Arc::clone(&finished);
        let reducer_calls = Arc::clone(&reductions);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                cx.scope()
                    .map_reduce(
                        &cx,
                        executing_limits(192, 193),
                        0..192,
                        move |child, value| {
                            let gate = Arc::clone(&child_gate);
                            let finished = Arc::clone(&child_finished);
                            async move {
                                if value == 0 {
                                    drop(
                                        crate::sync::OwnedMutexGuard::lock(gate, &child)
                                            .await
                                            .unwrap(),
                                    );
                                }
                                finished.fetch_add(1, Ordering::SeqCst);
                                Outcome::<_, ()>::Ok(value)
                            }
                        },
                        move |left, right| {
                            reducer_calls.fetch_add(1, Ordering::SeqCst);
                            left - right
                        },
                    )
                    .await
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert_eq!(finished.load(Ordering::SeqCst), 191);
        assert_eq!(reductions.load(Ordering::SeqCst), 0);
        assert_eq!(gate.waiters(), 1);
        drop(held);
        for _ in 0..1024 {
            lab.step_for_test();
            if reductions.load(Ordering::SeqCst) != 0 {
                break;
            }
        }
        assert_eq!(
            reductions.load(Ordering::SeqCst),
            63,
            "first fold consumes 64 values and yields with 128 still retained"
        );
        assert!(
            join.try_join().unwrap().is_none(),
            "all children being complete cannot publish an unfinished fold"
        );
        let observer_reductions = Arc::clone(&reductions);
        let (observer, mut observed) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                observer_reductions.load(Ordering::SeqCst)
            })
            .unwrap();
        lab.scheduler.lock().schedule(observer, 255);
        lab.run_until_idle();
        let seen = observed.try_join().unwrap().unwrap();
        assert!(
            (63..191).contains(&seen),
            "another task progresses before the entire buffered fold: {seen}"
        );
        let report = join.try_join().unwrap().unwrap();
        assert_eq!(report.outcome.unwrap(), Some(-(1..192).sum::<i32>()));
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (192, 192, 192)
        );
        assert_eq!(report.max_retained, 192);
        assert_eq!(reductions.load(Ordering::SeqCst), 191);
        assert_executing_lab_clean(&mut lab, root);
    }

    #[test]
    fn executing_map_failure_waits_for_real_pending_cleanup_and_preserves_cause() {
        for mode in ["error", "cancel", "panic", "encoded_panic"] {
            let mut lab = LabRuntime::new(LabConfig::new(0x32_0102).max_steps(4096));
            let root = lab.state.create_root_region(Budget::INFINITE);
            let trigger = Arc::new(crate::sync::Mutex::new(()));
            let held_trigger = trigger.try_lock_owned().unwrap();
            let (keep_sender, receiver) = crate::channel::mpsc::channel::<()>(1);
            let receiver = Arc::new(parking_lot::Mutex::new(Some(receiver)));
            let (finish_cleanup, cleanup) = crate::channel::oneshot::channel::<()>();
            let cleanup = Arc::new(parking_lot::Mutex::new(Some(cleanup)));
            let cleanup_started = Arc::new(AtomicUsize::new(0));
            let cleanup_finished = Arc::new(AtomicUsize::new(0));
            let started = Arc::clone(&cleanup_started);
            let finished = Arc::clone(&cleanup_finished);
            let child_trigger = Arc::clone(&trigger);
            let (parent, mut join) = lab
                .state
                .create_task(root, Budget::INFINITE, async move {
                    let cx = Cx::current().unwrap();
                    cx.scope()
                        .map_reduce(
                            &cx,
                            executing_limits(2, 2),
                            0..100,
                            move |child, index| {
                                let trigger = Arc::clone(&child_trigger);
                                let receiver = Arc::clone(&receiver);
                                let cleanup = Arc::clone(&cleanup);
                                let started = Arc::clone(&started);
                                let finished = Arc::clone(&finished);
                                async move {
                                    if index == 0 {
                                        drop(
                                            crate::sync::OwnedMutexGuard::lock(trigger, &child)
                                                .await
                                                .unwrap(),
                                        );
                                        match mode {
                                            "error" => Outcome::Err("triggering map failure"),
                                            "cancel" => Outcome::Cancelled(CancelReason::timeout()),
                                            "panic" => panic!("actual mapper panic"),
                                            "encoded_panic" => Outcome::Panicked(
                                                PanicPayload::new("encoded mapper panic"),
                                            ),
                                            _ => unreachable!(),
                                        }
                                    } else {
                                        assert_eq!(
                                            index, 1,
                                            "admission stops at the bounded failure window"
                                        );
                                        let mut receiver = receiver.lock().take().unwrap();
                                        assert_eq!(
                                            receiver.recv(&child).await,
                                            Err(crate::channel::mpsc::RecvError::Cancelled)
                                        );
                                        started.fetch_add(1, Ordering::SeqCst);
                                        let mut cleanup = cleanup.lock().take().unwrap();
                                        cleanup.recv_uninterruptible().await.unwrap();
                                        finished.fetch_add(1, Ordering::SeqCst);
                                        Outcome::Ok(index)
                                    }
                                }
                            },
                            |left, right| left + right,
                        )
                        .await
                })
                .unwrap();
            lab.scheduler.lock().schedule(parent, 0);
            lab.run_until_idle();
            assert_eq!(trigger.waiters(), 1);
            assert_eq!(keep_sender.telemetry_snapshot(3202).recv_waiter_count, 1);
            drop(held_trigger);
            lab.run_until_idle();
            assert!(
                join.try_join().unwrap().is_none(),
                "cleanup Pending is not a terminal child"
            );
            assert_eq!(cleanup_started.load(Ordering::SeqCst), 1);
            assert_eq!(cleanup_finished.load(Ordering::SeqCst), 0);
            assert_eq!(keep_sender.telemetry_snapshot(3202).recv_waiter_count, 0);
            finish_cleanup.send_blocking(()).unwrap();
            lab.run_until_idle();
            let report = join.try_join().unwrap().unwrap();
            assert_eq!(report.admitted, 2);
            assert_eq!(report.completed, 2);
            assert_eq!(report.reduced, 0);
            assert_eq!(cleanup_finished.load(Ordering::SeqCst), 1);
            assert_eq!(report.stopped_by.as_ref().unwrap().0, 0);
            if mode == "error" {
                assert!(
                    report.outcome.is_cancelled(),
                    "induced drain cancellation joins severity"
                );
                assert!(matches!(
                    report.errors.as_slice(),
                    [(0, MapReduceExecutionError::Map("triggering map failure"))]
                ));
            } else if mode == "cancel" {
                assert!(report.outcome.is_cancelled());
                assert_eq!(report.failure_index, Some(0));
            } else {
                assert!(report.outcome.is_panicked());
                assert_eq!(report.failure_index, Some(0));
            }
            assert_executing_lab_clean(&mut lab, root);
            eprintln!(
                "map failure mode={mode} admitted=2 joined=2 cleanup_started=1 cleanup_finished=1"
            );
        }
    }

    #[test]
    fn executing_map_iteration_factory_and_reducer_panics_stop_admission() {
        for mode in ["iterator", "factory", "reducer"] {
            let report = run_executing_case(move |cx| async move {
                let mut next = 0;
                let input = std::iter::from_fn(move || {
                    if mode == "iterator" && next == 2 {
                        panic!("actual input iterator panic");
                    }
                    if next == 8 {
                        return None;
                    }
                    let index = next;
                    next += 1;
                    Some(index)
                });
                cx.scope()
                    .map_reduce(
                        &cx,
                        executing_limits(1, 1),
                        input,
                        move |_child, index| {
                            if mode == "factory" {
                                panic!("actual factory construction panic");
                            }
                            async move { Outcome::<_, ()>::Ok(index) }
                        },
                        move |left, right| {
                            if mode == "reducer" {
                                panic!("actual reducer panic");
                            }
                            left - right
                        },
                    )
                    .await
            });
            assert!(report.outcome.is_panicked());
            assert_eq!(report.completed, report.admitted);
            assert_eq!(report.admitted, if mode == "factory" { 1 } else { 2 });
            assert_eq!(
                report.stopped_by.unwrap().1,
                match mode {
                    "iterator" => MapReduceStopCause::InputPanicked,
                    "factory" => MapReduceStopCause::MapPanicked,
                    "reducer" => MapReduceStopCause::ReducerPanicked,
                    _ => unreachable!(),
                }
            );
        }
    }

    #[test]
    fn executing_map_caller_cancel_wakes_coordinator_and_keeps_noncooperative_child_owned() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0103).max_steps(4096));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let (release, gate) = crate::channel::oneshot::channel::<()>();
        let gate = Arc::new(parking_lot::Mutex::new(Some(gate)));
        let started = Arc::new(AtomicUsize::new(0));
        let child_started = Arc::clone(&started);
        let returned = Arc::new(parking_lot::Mutex::new(None));
        let publication = Arc::clone(&returned);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                let report = cx
                    .scope()
                    .map_reduce(
                        &cx,
                        executing_limits(1, 1),
                        0..10,
                        move |_child, index| {
                            let gate = Arc::clone(&gate);
                            let started = Arc::clone(&child_started);
                            async move {
                                started.fetch_add(1, Ordering::SeqCst);
                                let mut gate = gate.lock().take().unwrap();
                                gate.recv_uninterruptible().await.unwrap();
                                Outcome::<_, ()>::Ok(index)
                            }
                        },
                        |left, right| left + right,
                    )
                    .await;
                *publication.lock() = Some(report);
            })
            .unwrap();
        let parent_cx = lab.state.task(parent).unwrap().cx.clone().unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert_eq!(started.load(Ordering::SeqCst), 1);
        let child = lab
            .state
            .region(root)
            .unwrap()
            .task_ids()
            .into_iter()
            .find(|id| *id != parent)
            .unwrap();
        let child_cx = lab.state.task(child).unwrap().cx.clone().unwrap();
        parent_cx.cancel_with(
            crate::types::CancelKind::User,
            Some("cancel map coordinator"),
        );
        lab.run_until_idle();
        assert!(join.try_join().unwrap().is_none());
        assert!(
            child_cx.is_cancel_requested(),
            "owned cancellation waker repolls coordinator to abort its child"
        );
        assert!(lab.state.task(child).is_some());
        assert_eq!(lab.state.live_task_count(), 2);
        assert_eq!(started.load(Ordering::SeqCst), 1);
        assert!(
            lab.steps() < 4096,
            "parked cleanup must not exhaust the step bound"
        );
        assert!(
            lab.scheduler.lock().is_empty(),
            "cancellation is acknowledged once, then the coordinator parks"
        );
        assert_eq!(
            lab.run_until_idle(),
            0,
            "no input or child wake means no draining polls"
        );
        assert!(
            returned.lock().is_none(),
            "no report before the actual child terminal"
        );
        release.send_blocking(()).unwrap();
        lab.run_until_idle();
        assert_eq!(
            join.try_join(),
            Err(JoinError::Cancelled(parent_cx.cancel_reason().unwrap()))
        );
        let report = returned
            .lock()
            .take()
            .expect("actual map engine report after child join");
        assert!(report.outcome.is_cancelled());
        assert_eq!(report.admitted, 1);
        assert_eq!(report.completed, 1);
        assert_executing_lab_clean(&mut lab, root);
    }

    #[test]
    fn executing_map_drop_requests_abort_without_claiming_child_completion() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0104).max_steps(4096));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let (release, gate) = crate::channel::oneshot::channel::<()>();
        let gate = Arc::new(parking_lot::Mutex::new(Some(gate)));
        let started = Arc::new(AtomicUsize::new(0));
        let child_started = Arc::clone(&started);
        let (notify_started, mut receive_started) = crate::channel::oneshot::channel::<()>();
        let notify_started = Arc::new(parking_lot::Mutex::new(Some(notify_started)));
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                let scope = cx.scope();
                let mut execution = Box::pin(scope.map_reduce(
                    &cx,
                    executing_limits(1, 1),
                    [7],
                    move |_child, value| {
                        let gate = Arc::clone(&gate);
                        let started = Arc::clone(&child_started);
                        let notify_started = Arc::clone(&notify_started);
                        async move {
                            started.fetch_add(1, Ordering::SeqCst);
                            notify_started
                                .lock()
                                .take()
                                .unwrap()
                                .send_blocking(())
                                .unwrap();
                            let mut gate = gate.lock().take().unwrap();
                            gate.recv_uninterruptible().await.unwrap();
                            Outcome::<_, ()>::Ok(value)
                        }
                    },
                    |left, right| left + right,
                ));
                std::future::poll_fn(|poll_cx| {
                    assert!(execution.as_mut().poll(poll_cx).is_pending());
                    Poll::Ready(())
                })
                .await;
                receive_started.recv_uninterruptible().await.unwrap();
                drop(execution);
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert_eq!(join.try_join().unwrap(), Some(()));
        assert_eq!(started.load(Ordering::SeqCst), 1);
        assert_eq!(
            lab.state.live_task_count(),
            1,
            "dropped owner did not fabricate a drain"
        );
        let child = lab.state.region(root).unwrap().task_ids()[0];
        assert!(
            lab.state
                .task(child)
                .unwrap()
                .cx
                .as_ref()
                .unwrap()
                .is_cancel_requested()
        );
        release.send_blocking(()).unwrap();
        lab.run_until_idle();
        assert_executing_lab_clean(&mut lab, root);
    }

    #[test]
    fn executing_map_late_lower_index_encoded_panic_outranks_drain_cancellation() {
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0105).max_steps(4096));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let (release, gate) = crate::channel::oneshot::channel::<()>();
        let gate = Arc::new(parking_lot::Mutex::new(Some(gate)));
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                cx.scope()
                    .map_reduce(
                        &cx,
                        executing_limits(2, 2),
                        0..10,
                        move |_child, index| {
                            let gate = Arc::clone(&gate);
                            async move {
                                if index == 0 {
                                    let mut gate = gate.lock().take().unwrap();
                                    gate.recv_uninterruptible().await.unwrap();
                                }
                                Outcome::<usize, ()>::Panicked(PanicPayload::new(format!(
                                    "panic at {index}"
                                )))
                            }
                        },
                        |left, right| left + right,
                    )
                    .await
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert!(join.try_join().unwrap().is_none());
        release.send_blocking(()).unwrap();
        lab.run_until_idle();
        let report = join.try_join().unwrap().unwrap();
        assert_eq!(
            report.stopped_by,
            Some((1, MapReduceStopCause::MapPanicked))
        );
        assert_eq!(report.failure_index, Some(0));
        let Outcome::Panicked(payload) = report.outcome else {
            panic!("encoded panic must survive cancellation-dominant generic spawn")
        };
        assert_eq!(payload.message(), "panic at 0");
        assert_eq!(report.admitted, 2);
        assert_eq!(report.completed, 2);
        assert_executing_lab_clean(&mut lab, root);
    }

    #[test]
    fn executing_map_result_destructor_panics_preserve_pending_cleanup_and_drop_abort() {
        #[derive(Debug)]
        struct ResultDrop {
            panics: bool,
            dropped: Arc<AtomicUsize>,
        }

        impl Drop for ResultDrop {
            fn drop(&mut self) {
                self.dropped.fetch_add(1, Ordering::SeqCst);
                assert!(!self.panics, "actual discarded map result panic");
            }
        }

        for (buffered, drop_execution) in [(false, false), (true, false), (true, true)] {
            let mut lab = LabRuntime::new(LabConfig::new(0x32_0108).max_steps(8192));
            let root = lab.state.create_root_region(Budget::INFINITE);
            let count = if buffered { 3 } else { 2 };
            let mut senders = Vec::new();
            let mut receivers = Vec::new();
            for _ in 0..count {
                let (sender, receiver) = crate::channel::mpsc::channel::<()>(1);
                senders.push(sender);
                receivers.push(parking_lot::Mutex::new(Some(receiver)));
            }
            let receivers = Arc::new(receivers);
            let (finish_cleanup, cleanup) = crate::channel::oneshot::channel::<()>();
            let cleanup = Arc::new(parking_lot::Mutex::new(Some(cleanup)));
            let (request_drop, mut drop_requested) = crate::channel::oneshot::channel::<()>();
            let ready_values = Arc::new(AtomicUsize::new(0));
            let dropped = Arc::new(AtomicUsize::new(0));
            let cleanup_started = Arc::new(AtomicUsize::new(0));
            let cleanup_finished = Arc::new(AtomicUsize::new(0));
            let child_ready = Arc::clone(&ready_values);
            let child_dropped = Arc::clone(&dropped);
            let child_started = Arc::clone(&cleanup_started);
            let child_finished = Arc::clone(&cleanup_finished);
            let returned = Arc::new(parking_lot::Mutex::new(None));
            let publication = Arc::clone(&returned);
            let (parent, mut join) = lab
                .state
                .create_task(root, Budget::INFINITE, async move {
                    let cx = Cx::current().unwrap();
                    let scope = cx.scope();
                    let mut execution = Box::pin(scope.map_reduce(
                        &cx,
                        executing_limits(count, count),
                        0..count,
                        move |child, index| {
                            let receivers = Arc::clone(&receivers);
                            let cleanup = Arc::clone(&cleanup);
                            let ready = Arc::clone(&child_ready);
                            let dropped = Arc::clone(&child_dropped);
                            let started = Arc::clone(&child_started);
                            let finished = Arc::clone(&child_finished);
                            async move {
                                if buffered && index != 0 {
                                    ready.fetch_add(1, Ordering::SeqCst);
                                    return Outcome::<_, ()>::Ok(ResultDrop {
                                        panics: true,
                                        dropped,
                                    });
                                }
                                let mut receiver = receivers[index].lock().take().unwrap();
                                assert_eq!(
                                    receiver.recv(&child).await,
                                    Err(crate::channel::mpsc::RecvError::Cancelled)
                                );
                                if buffered || index == 1 {
                                    started.fetch_add(1, Ordering::SeqCst);
                                    let mut cleanup = cleanup.lock().take().unwrap();
                                    cleanup.recv_uninterruptible().await.unwrap();
                                    finished.fetch_add(1, Ordering::SeqCst);
                                }
                                Outcome::Ok(ResultDrop {
                                    panics: !buffered && index == 0,
                                    dropped,
                                })
                            }
                        },
                        |_left, _right| -> ResultDrop {
                            panic!("a held first input prevents any reduction")
                        },
                    ));
                    let report = if drop_execution {
                        let mut requested = std::pin::pin!(drop_requested.recv_uninterruptible());
                        std::future::poll_fn(|poll_cx| {
                            if let Poll::Ready(result) = requested.as_mut().poll(poll_cx) {
                                result.unwrap();
                                return Poll::Ready(());
                            }
                            assert!(execution.as_mut().poll(poll_cx).is_pending());
                            Poll::Pending
                        })
                        .await;
                        drop(execution);
                        None
                    } else {
                        Some(execution.await)
                    };
                    *publication.lock() = Some(report);
                })
                .unwrap();
            let parent_cx = lab.state.task(parent).unwrap().cx.clone().unwrap();
            lab.scheduler.lock().schedule(parent, 0);
            lab.run_until_idle();
            assert_eq!(
                ready_values.load(Ordering::SeqCst),
                if buffered { 2 } else { 0 }
            );
            assert_eq!(dropped.load(Ordering::SeqCst), 0);
            assert_eq!(senders[0].telemetry_snapshot(3208).recv_waiter_count, 1);
            if !buffered {
                assert_eq!(senders[1].telemetry_snapshot(3208).recv_waiter_count, 1);
            }
            if drop_execution {
                request_drop.send_blocking(()).unwrap();
            } else {
                parent_cx.cancel_with(crate::types::CancelKind::User, Some("retire map results"));
            }
            lab.run_until_idle();
            assert_eq!(dropped.load(Ordering::SeqCst), if buffered { 2 } else { 1 });
            assert_eq!(cleanup_started.load(Ordering::SeqCst), 1);
            assert_eq!(cleanup_finished.load(Ordering::SeqCst), 0);
            assert!(
                lab.steps() < 8192,
                "cleanup Pending must park before the step bound"
            );
            assert!(
                lab.scheduler.lock().is_empty(),
                "all held cleanup tasks really parked"
            );
            assert_eq!(lab.run_until_idle(), 0);
            if drop_execution {
                assert_eq!(join.try_join(), Ok(Some(())));
                assert!(matches!(returned.lock().take(), Some(None)));
                assert_eq!(
                    lab.state.live_task_count(),
                    1,
                    "result destructor panics cannot skip the remaining child's abort"
                );
            } else {
                assert!(
                    join.try_join().unwrap().is_none(),
                    "Panicked is not permission to abandon asynchronous cleanup"
                );
                assert!(returned.lock().is_none());
            }
            finish_cleanup.send_blocking(()).unwrap();
            lab.run_until_idle();
            assert_eq!(cleanup_finished.load(Ordering::SeqCst), 1);
            assert_eq!(dropped.load(Ordering::SeqCst), count);
            if !drop_execution {
                assert_eq!(
                    join.try_join(),
                    Err(JoinError::Cancelled(parent_cx.cancel_reason().unwrap()))
                );
                let report = returned
                    .lock()
                    .take()
                    .expect("actual engine return")
                    .unwrap();
                let Outcome::Panicked(payload) = report.outcome else {
                    panic!("actual result destructor panic must dominate cancellation")
                };
                assert_eq!(payload.message(), "actual discarded map result panic");
                assert_eq!(
                    (report.admitted, report.completed, report.reduced),
                    (count, count, 0)
                );
            }
            assert_executing_lab_clean(&mut lab, root);
            eprintln!(
                "map destructor buffered={buffered} drop_execution={drop_execution} values_dropped={count} cleanup_completed=1"
            );
        }
    }

    #[test]
    fn executing_map_simultaneous_cancelled_results_retire_in_bounded_join_sweeps() {
        struct CountDrop(Arc<AtomicUsize>);
        impl Drop for CountDrop {
            fn drop(&mut self) {
                self.0.fetch_add(1, Ordering::SeqCst);
            }
        }

        let count = 192;
        let mut lab = LabRuntime::new(LabConfig::new(0x32_0109).max_steps(16384));
        let root = lab.state.create_root_region(Budget::INFINITE);
        let mut senders = Vec::new();
        let mut receivers = Vec::new();
        for _ in 0..count {
            let (sender, receiver) = crate::channel::mpsc::channel::<()>(1);
            senders.push(sender);
            receivers.push(parking_lot::Mutex::new(Some(receiver)));
        }
        let receivers = Arc::new(receivers);
        let started = Arc::new(AtomicUsize::new(0));
        let dropped = Arc::new(AtomicUsize::new(0));
        let (all_started, mut receive_started) = crate::channel::oneshot::channel::<()>();
        let all_started = Arc::new(parking_lot::Mutex::new(Some(all_started)));
        let (resume, mut receive_resume) = crate::channel::oneshot::channel::<()>();
        let child_started = Arc::clone(&started);
        let child_dropped = Arc::clone(&dropped);
        let probe_dropped = Arc::clone(&dropped);
        let (parent, mut join) = lab
            .state
            .create_task(root, Budget::INFINITE, async move {
                let cx = Cx::current().unwrap();
                let scope = cx.scope();
                let mut execution = Box::pin(scope.map_reduce(
                    &cx,
                    executing_limits(count, count),
                    0..count,
                    move |child, index| {
                        let receivers = Arc::clone(&receivers);
                        let started = Arc::clone(&child_started);
                        let all_started = Arc::clone(&all_started);
                        let dropped = Arc::clone(&child_dropped);
                        async move {
                            if started.fetch_add(1, Ordering::SeqCst) + 1 == count {
                                all_started
                                    .lock()
                                    .take()
                                    .unwrap()
                                    .send_blocking(())
                                    .unwrap();
                            }
                            let mut receiver = receivers[index].lock().take().unwrap();
                            assert_eq!(
                                receiver.recv(&child).await,
                                Err(crate::channel::mpsc::RecvError::Cancelled)
                            );
                            Outcome::<_, ()>::Ok(CountDrop(dropped))
                        }
                    },
                    |_left, _right| -> CountDrop { panic!("cancelled values cannot be reduced") },
                ));
                let mut ready = std::pin::pin!(receive_started.recv_uninterruptible());
                std::future::poll_fn(|poll_cx| {
                    assert!(execution.as_mut().poll(poll_cx).is_pending());
                    ready.as_mut().poll(poll_cx)
                })
                .await
                .unwrap();
                // Keep every real result cell owned but stop polling the engine
                // until the host has observed all actual children terminate.
                receive_resume.recv_uninterruptible().await.unwrap();
                assert_eq!(probe_dropped.load(Ordering::SeqCst), 0);
                std::future::poll_fn(|poll_cx| {
                    assert!(execution.as_mut().poll(poll_cx).is_pending());
                    Poll::Ready(())
                })
                .await;
                assert_eq!(
                    probe_dropped.load(Ordering::SeqCst),
                    64,
                    "one engine poll retires only one bounded terminal sweep"
                );
                execution.await
            })
            .unwrap();
        lab.scheduler.lock().schedule(parent, 0);
        lab.run_until_idle();
        assert_eq!(started.load(Ordering::SeqCst), count);
        assert!(
            senders
                .iter()
                .all(|sender| sender.telemetry_snapshot(3209).recv_waiter_count == 1)
        );
        let children: Vec<_> = lab
            .state
            .region(root)
            .unwrap()
            .task_ids()
            .into_iter()
            .filter(|id| *id != parent)
            .map(|id| lab.state.task(id).unwrap().cx.clone().unwrap())
            .collect();
        assert_eq!(children.len(), count);
        for child in &children {
            child.cancel_with(
                crate::types::CancelKind::User,
                Some("simultaneous result retirement"),
            );
        }
        lab.run_until_idle();
        assert_eq!(
            lab.state.live_task_count(),
            1,
            "every actual child has terminated before the bounded poll"
        );
        assert_eq!(
            dropped.load(Ordering::SeqCst),
            0,
            "all terminal values are still owned by the parked engine"
        );
        assert!(join.try_join().unwrap().is_none());
        resume.send_blocking(()).unwrap();
        lab.run_until_idle();
        let report = join.try_join().unwrap().unwrap();
        assert!(report.outcome.is_cancelled());
        assert_eq!(
            (report.admitted, report.completed, report.reduced),
            (count, count, 0)
        );
        assert_eq!(dropped.load(Ordering::SeqCst), count);
        assert!(
            senders
                .iter()
                .all(|sender| sender.telemetry_snapshot(3209).recv_waiter_count == 0)
        );
        assert_executing_lab_clean(&mut lab, root);
    }

    // ========== MapReduce marker type tests ==========

    #[test]
    fn map_reduce_marker_type() {
        let _mr: MapReduce<i32> = MapReduce::new();
        let _mr_default: MapReduce<String> = MapReduce::default();

        // Test Clone and Copy
        let m1: MapReduce<i32> = MapReduce::new();
        let m2 = m1;
        let m3 = m1;
        assert!(std::mem::size_of_val(&m1) == std::mem::size_of_val(&m2));
        assert!(std::mem::size_of_val(&m1) == std::mem::size_of_val(&m3));
    }

    // ========== MapReduceResult tests ==========

    #[test]
    fn map_reduce_result_all_succeeded() {
        let result: MapReduceResult<i32, &str> = MapReduceResult::new(
            AggregateDecision::AllOk,
            Some(6),
            vec![(0, 1), (1, 2), (2, 3)],
            3,
        );
        assert!(result.all_succeeded());
        assert_eq!(result.success_count(), 3);
        assert_eq!(result.failure_count(), 0);
        assert!(result.has_reduced());
    }

    #[test]
    fn map_reduce_result_partial_failure() {
        let result: MapReduceResult<i32, &str> = MapReduceResult::new(
            AggregateDecision::FirstError("oops"),
            Some(4), // Partial reduction of successes
            vec![(0, 1), (2, 3)],
            3,
        );
        assert!(!result.all_succeeded());
        assert_eq!(result.success_count(), 2);
        assert_eq!(result.failure_count(), 1);
        assert!(result.has_reduced());
    }

    // ========== MapReduceError tests ==========

    #[test]
    fn map_reduce_error_predicates() {
        let err: MapReduceError<&str> = MapReduceError::Error {
            error: "test",
            index: 2,
            total_failures: 1,
            success_count: 2,
        };
        assert!(err.is_error());
        assert!(!err.is_cancelled());
        assert!(!err.is_panicked());
        assert!(!err.is_empty());
        assert_eq!(err.error_index(), Some(2));

        let err: MapReduceError<&str> = MapReduceError::Cancelled(CancelReason::timeout());
        assert!(!err.is_error());
        assert!(err.is_cancelled());
        assert_eq!(err.error_index(), None);

        let err: MapReduceError<&str> = MapReduceError::Panicked {
            payload: PanicPayload::new("boom"),
            index: 3,
        };
        assert!(!err.is_error());
        assert!(err.is_panicked());
        assert_eq!(err.panic_index(), Some(3));

        let err: MapReduceError<&str> = MapReduceError::Empty;
        assert!(err.is_empty());
    }

    #[test]
    fn map_reduce_error_display() {
        let err: MapReduceError<&str> = MapReduceError::Error {
            error: "test error",
            index: 3,
            total_failures: 2,
            success_count: 5,
        };
        let msg = err.to_string();
        assert!(msg.contains("task 3"));
        assert!(msg.contains("test error"));
        assert!(msg.contains("2 failures"));
        assert!(msg.contains("5 successes"));

        let err: MapReduceError<&str> = MapReduceError::Panicked {
            payload: PanicPayload::new("boom"),
            index: 1,
        };
        assert!(err.to_string().contains("task 1 panicked"));
        assert!(err.to_string().contains("boom"));

        let err: MapReduceError<&str> = MapReduceError::Empty;
        assert!(err.to_string().contains("at least one input"));
    }

    // ========== map_reduce_outcomes tests ==========

    #[test]
    fn map_reduce_outcomes_all_ok_sum() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(2), Outcome::Ok(3)];

        let (decision, reduced, successes) = map_reduce_outcomes(outcomes, |a, b| a + b);

        assert!(matches!(decision, AggregateDecision::AllOk));
        assert_eq!(reduced, Some(6)); // 1 + 2 + 3
        assert_eq!(successes.len(), 3);
    }

    #[test]
    fn map_reduce_outcomes_all_ok_product() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(2), Outcome::Ok(3), Outcome::Ok(4)];

        let (decision, reduced, _) = map_reduce_outcomes(outcomes, |a, b| a * b);

        assert!(matches!(decision, AggregateDecision::AllOk));
        assert_eq!(reduced, Some(24)); // 2 * 3 * 4
    }

    #[test]
    fn map_reduce_outcomes_partial_failure() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Err("failed"), Outcome::Ok(3)];

        let (decision, reduced, successes) = map_reduce_outcomes(outcomes, |a, b| a + b);

        assert!(matches!(decision, AggregateDecision::FirstError("failed")));
        assert_eq!(reduced, Some(4)); // 1 + 3 (partial reduction)
        assert_eq!(successes.len(), 2);
    }

    #[test]
    fn map_reduce_outcomes_cancelled() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![
            Outcome::Ok(1),
            Outcome::Cancelled(CancelReason::timeout()),
            Outcome::Ok(3),
        ];

        let (decision, reduced, _) = map_reduce_outcomes(outcomes, |a, b| a + b);

        assert!(matches!(decision, AggregateDecision::Cancelled(_)));
        assert_eq!(reduced, Some(4)); // Partial reduction still works
    }

    #[test]
    fn map_reduce_outcomes_panicked() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![
            Outcome::Ok(1),
            Outcome::Panicked(PanicPayload::new("boom")),
            Outcome::Ok(3),
        ];

        let (decision, reduced, successes) = map_reduce_outcomes(outcomes, |a, b| a + b);

        match decision {
            AggregateDecision::Panicked {
                payload: _,
                first_panic_index,
            } => assert_eq!(first_panic_index, 1),
            _ => panic!("Expected Panicked decision"),
        }
        // All successful values collected and reduced (join semantics: all branches complete)
        assert_eq!(successes.len(), 2);
        assert_eq!(reduced, Some(4)); // 1 + 3 = 4
    }

    #[test]
    fn map_reduce_outcomes_preserves_input_order() {
        // Values should be reduced in input order regardless of completion order
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(10), Outcome::Ok(100)];

        // Using subtraction to verify order matters
        let (_, reduced, _) = map_reduce_outcomes(outcomes, |a, b| a - b);

        // Left fold: ((1 - 10) - 100) = -109
        assert_eq!(reduced, Some(-109));
    }

    #[test]
    fn map_reduce_outcomes_single_value() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Ok(42)];

        let (decision, reduced, successes) = map_reduce_outcomes(outcomes, |a, b| a + b);

        assert!(matches!(decision, AggregateDecision::AllOk));
        assert_eq!(reduced, Some(42)); // Single value returned as-is
        assert_eq!(successes.len(), 1);
    }

    #[test]
    fn map_reduce_outcomes_empty() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![];

        let (decision, reduced, successes) = map_reduce_outcomes(outcomes, |a, b| a + b);

        assert!(matches!(decision, AggregateDecision::AllOk));
        assert_eq!(reduced, None); // No values to reduce
        assert!(successes.is_empty());
    }

    #[test]
    fn map_reduce_result_empty_not_all_succeeded() {
        // Empty input should NOT report all_succeeded() = true,
        // even though the decision is vacuously AllOk.
        // This prevents callers from doing result.reduced.unwrap() after
        // checking all_succeeded(), which would panic on empty input.
        let result: MapReduceResult<i32, &str> =
            MapReduceResult::new(AggregateDecision::AllOk, None, vec![], 0);
        assert!(!result.all_succeeded());
        assert!(!result.has_reduced());
    }

    // ========== make_map_reduce_result tests ==========

    #[test]
    fn make_map_reduce_result_success() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(2), Outcome::Ok(3)];

        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        assert!(result.all_succeeded());
        assert_eq!(result.reduced, Some(6));
        assert_eq!(result.total_count, 3);
    }

    // ========== map_reduce_to_result tests ==========

    #[test]
    fn map_reduce_to_result_all_ok() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(2), Outcome::Ok(3)];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let value = map_reduce_to_result(result);
        assert_eq!(value.unwrap(), 6);
    }

    #[test]
    fn map_reduce_to_result_error() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Err("failed"), Outcome::Ok(3)];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let value = map_reduce_to_result(result);
        match value {
            Err(MapReduceError::Error {
                error,
                index,
                total_failures,
                success_count,
            }) => {
                assert_eq!(error, "failed");
                assert_eq!(index, 1);
                assert_eq!(total_failures, 1);
                assert_eq!(success_count, 2);
            }
            _ => panic!("expected MapReduceError::Error"),
        }
    }

    #[test]
    fn map_reduce_to_result_cancelled() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Cancelled(CancelReason::timeout())];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let value = map_reduce_to_result(result);
        assert!(matches!(value, Err(MapReduceError::Cancelled(_))));
    }

    #[test]
    fn map_reduce_to_result_panicked() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![Outcome::Panicked(PanicPayload::new("crash"))];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let value = map_reduce_to_result(result);
        match value {
            Err(MapReduceError::Panicked { payload: _, index }) => assert_eq!(index, 0),
            _ => panic!("Expected Panicked error"),
        }
    }

    #[test]
    fn map_reduce_to_result_empty() {
        let outcomes: Vec<Outcome<i32, &str>> = vec![];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let value = map_reduce_to_result(result);
        assert!(matches!(value, Err(MapReduceError::Empty)));
    }

    // ========== reduce_successes tests ==========

    #[test]
    fn reduce_successes_partial() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Err("failed"), Outcome::Ok(3)];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let partial = reduce_successes(&result);
        assert_eq!(partial, Some(4)); // 1 + 3
    }

    #[test]
    fn reduce_successes_none_succeeded() {
        let outcomes: Vec<Outcome<i32, &str>> =
            vec![Outcome::Err("failed1"), Outcome::Err("failed2")];
        let result = make_map_reduce_result(outcomes, |a, b| a + b);

        let partial = reduce_successes(&result);
        assert_eq!(partial, None);
    }

    // ========== String concatenation tests (non-numeric) ==========

    #[test]
    fn map_reduce_string_concat() {
        let outcomes: Vec<Outcome<String, &str>> = vec![
            Outcome::Ok("Hello".to_string()),
            Outcome::Ok(" ".to_string()),
            Outcome::Ok("World".to_string()),
        ];

        let result = make_map_reduce_result(outcomes, |a, b| a + &b);
        assert_eq!(result.reduced, Some("Hello World".to_string()));
    }

    // ========== Associativity documentation test ==========

    #[test]
    fn map_reduce_associative_vs_non_associative() {
        // Demonstrate that associative operations give consistent results
        let outcomes_a: Vec<Outcome<i32, &str>> =
            vec![Outcome::Ok(1), Outcome::Ok(2), Outcome::Ok(3)];
        let outcomes_b = outcomes_a.clone();

        // Addition is associative
        let sum_result = make_map_reduce_result(outcomes_a, |a, b| a + b);
        assert_eq!(sum_result.reduced, Some(6)); // Always 6

        // Subtraction is NOT associative - order matters
        let difference_result = make_map_reduce_result(outcomes_b, |a, b| a - b);
        // Left fold: ((1 - 2) - 3) = -4
        assert_eq!(difference_result.reduced, Some(-4));
        // Note: If we did right fold it would be different: (1 - (2 - 3)) = 2
        // Our implementation always does left fold for determinism
    }

    #[test]
    fn metamorphic_commutative_reducer_is_permutation_invariant() {
        let outcomes_a: Vec<Outcome<i32, &str>> = vec![
            Outcome::Ok(3),
            Outcome::Ok(1),
            Outcome::Ok(4),
            Outcome::Ok(2),
        ];
        let outcomes_b: Vec<Outcome<i32, &str>> = vec![
            Outcome::Ok(2),
            Outcome::Ok(4),
            Outcome::Ok(1),
            Outcome::Ok(3),
        ];

        let (decision_a, reduced_a, successes_a) = map_reduce_outcomes(outcomes_a, |a, b| a + b);
        let (decision_b, reduced_b, successes_b) = map_reduce_outcomes(outcomes_b, |a, b| a + b);

        assert!(matches!(decision_a, AggregateDecision::AllOk));
        assert!(matches!(decision_b, AggregateDecision::AllOk));
        assert_eq!(
            reduced_a, reduced_b,
            "commutative reduction should be invariant under permutation of successful inputs"
        );
        assert_eq!(reduced_a, Some(10));
        assert_eq!(successes_a.len(), successes_b.len());
        assert_eq!(successes_a.len(), 4);
        assert_ne!(
            successes_a, successes_b,
            "permuted inputs should still preserve their own input-order success traces"
        );
    }

    // --- wave 79 trait coverage ---

    #[test]
    fn map_reduce_error_debug_clone() {
        let e: MapReduceError<&str> = MapReduceError::Error {
            error: "bad",
            index: 2,
            total_failures: 1,
            success_count: 3,
        };
        let e2 = e.clone();
        let dbg = format!("{e:?}");
        assert!(dbg.contains("Error"));
        let dbg2 = format!("{e2:?}");
        assert!(dbg2.contains("Error"));

        let empty: MapReduceError<&str> = MapReduceError::Empty;
        let empty2 = empty.clone();
        let dbg3 = format!("{empty:?}");
        assert!(dbg3.contains("Empty"));
        let dbg4 = format!("{empty2:?}");
        assert!(dbg4.contains("Empty"));
    }
}