aws-durable-execution-sdk 0.2.0

Rust SDK for AWS Lambda Durable Functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
//!
//! The driver polls the user's handler future and controls the execution
//! lifecycle of one invocation:
//!
//! - **Suspension**: the invocation coordinator
//!   ([`crate::coordinator`]) decides when the invocation suspends. Local
//!   work that can make progress holds a permit: a polled or woken task, a
//!   step body, a `wait_for_condition` check, a serdes call, blocking work,
//!   and an admitted checkpoint write until its response is merged. An
//!   operation that waits on the service holds a wait registration. When no
//!   permit is held and at least one registration is live, the phase
//!   becomes `Suspending` and the driver ends the invocation with
//!   `PENDING`. The handler future is dropped at its current await point,
//!   so a suspension never surfaces to user code.
//!
//! - **Continuation inside the invocation**: a merged checkpoint response
//!   wakes the registrations of the operations it carries. A wait whose
//!   record is complete continues in the same invocation, before the
//!   response's checkpoint permit is released.
//!
//! - **Resume**: on a later invocation with existing checkpoint state, the
//!   engine reconstructs replay mode via [`CheckpointLog`] and re-runs the
//!   handler. Replayed operations return frozen results from the log
//!   without re-execution.
//!
//! - **Task-ownership**: each context records the `tokio::task::Id` of the
//!   task that created it. Durable operations invoked from a DIFFERENT task
//!   fail fast with a clear error. The engine's own tasks (the handler,
//!   `.spawn()`, batch items and combinator inputs) are exempt.
//!
//! Zero permits and zero registrations do not suspend: the handler awaits
//! work the SDK does not track, and the invocation runs until that work
//! finishes or the Lambda deadline passes. The driver logs a warning when
//! the deadline is reached in that state.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;

use crate::coordinator::{InvocationCoordinator, Phase};

// Imports used by tests: suppress dead-code warnings for the engine types
// which are consumed by operation execution.
#[cfg(test)]
use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus, EngineState};

/// The warning logged when the Lambda deadline is reached while nothing the
/// SDK tracks runs and no operation waits.
pub(crate) const UNTRACKED_DEADLINE_WARNING: &str = "the invocation reached its deadline while \
     the handler awaited work the SDK does not track; run that work in a step";

/// The outcome of driving a single invocation of the user's handler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InvocationOutcome {
    /// The handler completed successfully with a serialized result.
    Complete(String),
    /// The handler suspended: an operation requires an external event
    /// before it can proceed. The engine drops the handler future and
    /// reports PENDING to the runtime.
    Pending,
    /// The handler returned an error with its wire failure record.
    Failed {
        /// The wire failure record (type, message, opaque data, stack
        /// trace) reported in the response envelope.
        error: crate::error::WireError,
    },
    /// The INVOCATION itself must fail, a Lambda runtime error rather
    /// than a `FAILED` envelope, so the durable service re-invokes, the
    /// same recovery as an interruption. Produced by a retryable
    /// checkpoint write failure that exhausted transport-level retries:
    /// the write channel is down, so nothing more is written and the
    /// execution stays alive for the retry.
    Fault {
        /// The type of the fault, which the invocation end hook receives.
        /// It does not reach Lambda.
        error_type: String,
        /// The message reported as the Lambda invocation error.
        message: String,
    },
}

/// An unrecoverable error recorded by an operation, together with the
/// scope that must die for the execution to converge.
///
/// Producers:
/// - non-determinism detection
///   ([`crate::context::DurableContext::validate_replay_identity`]): a
///   replay identity mismatch means no amount of re-invocation can make
///   progress: [`FatalSeverity::FailExecution`];
/// - checkpoint write failures, recorded where the write's response
///   arrives, under the checkpoint-token lock
///   (`crate::context::DurableContext::record_write_failure`): an
///   `Invocation`-scoped failure fails the invocation so the service
///   re-invokes ([`FatalSeverity::FailInvocation`]); an `Execution`-scoped
///   one fails the execution ([`FatalSeverity::FailExecution`]).
/// - serdes faults ([`crate::context::DurableContext::serdes_fault`]): a
///   serdes error marked with
///   [`RetryableSerdesError`](crate::serdes::RetryableSerdesError) fails the
///   invocation so the service re-invokes
///   ([`FatalSeverity::FailInvocation`]).
///
/// The invocation driver checks this slot with priority over both
/// completion and suspension.
#[derive(Debug, Clone)]
pub(crate) struct FatalError {
    /// The wire error type (e.g. `NonDeterministicExecutionError`).
    pub(crate) error_type: String,
    /// The full error message.
    pub(crate) error_message: String,
    /// Which scope dies: the execution (terminal `FAILED` envelope) or
    /// only this invocation (Lambda runtime error; the service
    /// re-invokes).
    pub(crate) severity: FatalSeverity,
}

/// The recovery scope of a [`FatalError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FatalSeverity {
    /// The execution is over: report a `FAILED` envelope carrying the
    /// error, which the service records as the execution result.
    FailExecution,
    /// Only this invocation dies: report a Lambda runtime error (no
    /// envelope), and the service re-invokes: the interruption recovery
    /// path.
    FailInvocation,
}

impl FatalError {
    /// Converts the recorded fatal into the invocation outcome its
    /// severity demands.
    pub(crate) fn into_outcome(self) -> InvocationOutcome {
        match self.severity {
            FatalSeverity::FailExecution => InvocationOutcome::Failed {
                error: crate::error::WireError::new(
                    Some(self.error_type),
                    Some(self.error_message),
                ),
            },
            FatalSeverity::FailInvocation => InvocationOutcome::Fault {
                error_type: self.error_type,
                message: self.error_message,
            },
        }
    }
}

/// Identifies the task or thread that owns a context, and tracks the
/// blessed (SDK-started) task IDs.
///
/// A context created on a Tokio task is owned by that task. A context
/// created outside any task, as `lambda_runtime` and `LocalRunner` create
/// it under `block_on`, is owned by the OS thread that created it. A caller
/// may perform durable operations on the context when it is the owner task,
/// a blessed task, or, with no task ID, the owner thread. Every other task or
/// thread is refused: a raw `tokio::spawn` task has an unblessed task ID, and
/// a `std::thread` is a different thread.
///
/// The task gateway (`crate::task`) blesses every operation task it starts:
/// the handler itself, each `.spawn()`, each map item and parallel branch,
/// and each combinator input.
#[derive(Debug)]
pub(crate) struct TaskOwnership {
    /// The owner: a task, or the creating thread when the context was
    /// created outside any task.
    owner: Owner,
    /// The IDs of the running SDK operation tasks: these are exempt from
    /// the check. The task gateway (`crate::task`) inserts a task's ID
    /// before the task's first poll and removes it before the task exits,
    /// so tokio can reuse an ID only for a task that is not in the set.
    blessed_tasks: std::sync::Mutex<std::collections::HashSet<tokio::task::Id>>,
}

/// The task or thread that owns a context.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Owner {
    /// Created on this Tokio task.
    Task(tokio::task::Id),
    /// Created outside any Tokio task, on this OS thread.
    Thread(std::thread::ThreadId),
}

impl TaskOwnership {
    /// Creates ownership tracking anchored to the calling task, or to the
    /// calling OS thread when the caller runs outside any Tokio task.
    pub(crate) fn new_current() -> Self {
        let owner = match tokio::task::try_id() {
            Some(id) => Owner::Task(id),
            None => Owner::Thread(std::thread::current().id()),
        };
        Self {
            owner,
            blessed_tasks: std::sync::Mutex::new(std::collections::HashSet::new()),
        }
    }

    /// Registers a task ID as blessed (engine-spawned).
    ///
    /// Blessed tasks pass the ownership check even though they are not the
    /// original owner.
    pub(crate) fn bless_task(&self, task_id: tokio::task::Id) {
        let mut blessed = self
            .blessed_tasks
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        blessed.insert(task_id);
    }

    /// Removes a task ID from the blessed set. The task gateway calls it
    /// before a blessed task exits.
    pub(crate) fn unbless_task(&self, task_id: tokio::task::Id) {
        self.blessed_tasks
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&task_id);
    }

    /// Returns the number of blessed task IDs.
    #[cfg(test)]
    pub(crate) fn blessed_count(&self) -> usize {
        self.blessed_tasks
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    /// Checks whether the caller owns this context.
    ///
    /// A caller with a task ID passes when it is the owner task or a
    /// blessed task. A caller without a task ID passes only on the owner
    /// thread. Every other caller gets `Err` with a descriptive message.
    pub(crate) fn check_current_task(&self) -> Result<(), String> {
        if let Some(current_id) = tokio::task::try_id() {
            if matches!(self.owner, Owner::Task(owner_id) if owner_id == current_id) {
                return Ok(());
            }
            let blessed = self
                .blessed_tasks
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if blessed.contains(&current_id) {
                return Ok(());
            }
            Err(format!(
                "durable operation invoked from task {current_id:?}, which does not own the \
                     context (owner: {:?}). Use .spawn() instead of tokio::spawn for durable \
                     fan-out",
                self.owner
            ))
        } else {
            let current = std::thread::current().id();
            if matches!(self.owner, Owner::Thread(owner) if owner == current) {
                return Ok(());
            }
            Err(format!(
                "durable operation invoked from thread {current:?}, which does not own the \
                     context (owner: {:?}). Use .spawn() instead of std::thread::spawn for durable \
                     fan-out",
                self.owner
            ))
        }
    }
}

/// How the drive of the root task ended. It carries no panic payload: the
/// coordinator owns every invocation-failing panic.
enum DriveEnd<T> {
    /// The root task returned the handler's result.
    Completed(T),
    /// A fatal error or a panic was recorded, or the phase became
    /// `Suspending`.
    Interrupted,
}

/// Closes panic ownership when the drive is dropped before it arbitrated.
///
/// A kept payload can hold a `DurableContext`, which keeps the coordinator
/// alive, so the coordinator's own drop cannot be relied on to drop it.
/// The guard takes the payload out under the coordinator lock, which also
/// closes ownership, and drops it through [`crate::task::discard_panic`].
/// A detached task that panics after that gets its payload back from
/// `record_panic` and disposes of it. After the arbitration, `take_panic`
/// returns nothing, so the guard's drop does nothing.
struct PanicOwnershipGuard(Arc<InvocationCoordinator>);

impl Drop for PanicOwnershipGuard {
    fn drop(&mut self) {
        if let Some(payload) = self.0.take_panic() {
            crate::task::discard_panic(payload);
        }
    }
}

/// Ends the invocation and stops its operation tasks when dropped.
///
/// The drive holds one. Its normal cleanup aborts and joins every task
/// itself. When the drive future is dropped before that, for example at a
/// platform timeout, this guard's drop is what stops the operation tasks
/// whose handles were dropped.
///
/// The root task can still be in a poll on another worker thread when the
/// drive is dropped, and that poll can start an operation task after the
/// drop. So the drop moves the phase to `Finished`, which refuses every
/// later spawn, and closes the tracker, which aborts a task whose spawn
/// took its permit before that.
struct TeardownGuard(Arc<InvocationCoordinator>);

impl Drop for TeardownGuard {
    fn drop(&mut self) {
        self.0.finish();
        self.0.tasks().close();
    }
}

/// Drives a single invocation of the user's handler future.
///
/// The handler runs as the invocation's root task, started through the
/// task gateway (`crate::task::spawn_root`), and polled by its
/// permit-aware wrapper. The drive ends in one of four ways:
///
/// 1. A fatal error is recorded.
/// 2. An invocation-failing panic is recorded on the coordinator: the
///    handler panicked, the refresh scheduler panicked, a detached task
///    (the batch flusher or a direct write, which run the checkpoint
///    client) panicked, or a task's outcome holding a panic lost its
///    reader.
/// 3. The phase becomes `Suspending`.
/// 4. The handler resolves. A wait whose handle the handler dropped does
///    not change that; its record can stay `STARTED`.
///
/// The outcome is decided once, after the cleanup below, from the fatal
/// error and the panic the coordinator keeps, read one after the other.
/// Only a fatal error present when `fatal_error()` is read wins; untracked
/// plugin hook work can record one after that read, and the outcome
/// ignores it:
///
/// 1. A fatal error was recorded: the fatal outcome. A kept panic is
///    dropped through [`crate::task::discard_panic`].
/// 2. Otherwise a panic is kept: `Err` with its original payload, which
///    the caller resumes. The coordinator keeps the first panic recorded;
///    every later one is dropped.
/// 3. Otherwise the handler's result: `Complete` or `Failed`, or `Pending`
///    when the drive ended by suspension.
///
/// When `remaining` is `Some(d)`, the driver also polls a sleep of `d`
/// directly, so a timer wake takes no permit. When it fires while the
/// phase is `Running`, no permit is held and no wait is live, it logs
/// [`UNTRACKED_DEADLINE_WARNING`] once. The coordinator also counts its
/// refresh deadline down from `d` in tokio time.
///
/// While the phase is `Running`, the driver polls the refresh scheduler
/// ([`refresh_scheduler`]) beside the handler, directly, so a timer wake
/// takes no permit. The scheduler sends its refreshes through `root`, a
/// clone of the root context. When the drive ends the scheduler is
/// dropped. A refresh it started runs on a detached task, so the cleanup
/// waits for its response to be merged.
///
/// Cleanup, after every ending: the scheduler is dropped, the phase
/// becomes `Finished`, the root task is aborted and awaited, every other
/// tracked task is aborted, and the driver waits until every tracked task
/// has unwound. Dropping the futures retires their wait registrations and
/// releases their permits. A panic during the cleanup is recorded, and the
/// cleanup continues to its end. Last, every panic still unread in a task
/// slot is recorded, including one whose handle outlives the handler. So
/// when this function returns, no SDK task, permit or wait registration of
/// this invocation remains.
///
/// When this future is dropped before it decides the outcome, a guard
/// closes panic ownership and drops a kept panic (see
/// [`PanicOwnershipGuard`]), and another ends the invocation and aborts
/// every tracked operation task, including one started after the drop (see
/// [`TeardownGuard`]).
///
/// Beside the outcome it returns whether a fatal error won this
/// arbitration (`true` only for the outcome of a recorded fatal error).
/// The caller uses that value, not the coordinator's fatal slot, which
/// code after the drive can still fill.
pub(crate) async fn drive_invocation<F>(
    handler_future: F,
    root_cx: crate::task::TaskContext,
    task_ownership: Arc<TaskOwnership>,
    coordinator: Arc<InvocationCoordinator>,
    root: crate::DurableContext,
    remaining: Option<Duration>,
) -> Result<(InvocationOutcome, bool), Box<dyn std::any::Any + Send + 'static>>
where
    F: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
{
    drive_with_scheduler(
        root_cx,
        handler_future,
        task_ownership,
        coordinator,
        refresh_scheduler(root),
        remaining,
    )
    .await
}

/// [`drive_invocation`] with `scheduler` polled in place of the refresh
/// scheduler. Tests pass a scheduler of their own.
async fn drive_with_scheduler<F, S>(
    root_cx: crate::task::TaskContext,
    handler_future: F,
    task_ownership: Arc<TaskOwnership>,
    coordinator: Arc<InvocationCoordinator>,
    scheduler: S,
    remaining: Option<Duration>,
) -> Result<(InvocationOutcome, bool), Box<dyn std::any::Any + Send + 'static>>
where
    F: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
    S: Future<Output = ()>,
{
    let ownership_guard = PanicOwnershipGuard(Arc::clone(&coordinator));
    // Dropping a `.spawn()` handle does not stop its task. So when this
    // future is dropped before the cleanup below, this guard ends the
    // invocation and stops every tracked operation task, including one the
    // root starts after the drop. After the cleanup no task is live, the
    // phase is already `Finished`, and its drop only closes the tracker.
    let _teardown = TeardownGuard(Arc::clone(&coordinator));
    coordinator.start_deadline(remaining);
    // Boxed, so the cleanup below can drop it before it waits for the tasks.
    let mut scheduler = Box::pin(scheduler);
    // A panic can be recorded before the drive starts, for example from the
    // destructor of a plugin factory's error. Keeping it ends the drive, so
    // the handler must never run. The check in the poll
    // below comes too late: on a multi-thread runtime another worker can
    // poll the root task before the driver polls at all. So the phase ends
    // here, before the root is spawned. The root then starts idle, it can
    // take no permit, and the gateway never polls the handler.
    if coordinator.has_panic() {
        coordinator.finish();
    }
    // The handler runs as an operation task, so every SDK poll of user code
    // runs on a Tokio worker with the gateway wrapper.
    #[expect(clippy::expect_used)]
    // reason: this function awaits Tokio timers and tasks itself, so it is
    // always polled inside a Tokio runtime.
    let (mut root, root_join) =
        crate::task::spawn_root(root_cx, &task_ownership, &coordinator, handler_future)
            .expect("the invocation driver runs inside a Tokio runtime");

    let mut deadline = remaining.map(|d| Box::pin(tokio::time::sleep(d)));
    let ended = std::future::poll_fn(|cx| {
        coordinator.register_driver_waker(cx.waker());
        if coordinator.fatal_error().is_some() || coordinator.has_panic() {
            return Poll::Ready(DriveEnd::Interrupted);
        }
        match Pin::new(&mut root).poll(cx) {
            Poll::Ready(crate::task::TaskOutcome::Value(result)) => {
                return Poll::Ready(DriveEnd::Completed(result));
            }
            Poll::Ready(crate::task::TaskOutcome::Panicked(payload)) => {
                crate::task::record_or_discard(&coordinator, payload);
                return Poll::Ready(DriveEnd::Interrupted);
            }
            Poll::Pending => {}
        }
        if coordinator.phase() == Phase::Suspending {
            return Poll::Ready(DriveEnd::Interrupted);
        }
        // A fatal error or `Suspending` ended the drive above. The phase can
        // still be `Finished` for one poll, between the root task's finish
        // and its outcome. The coordinator then refuses the scheduler's
        // permit, so the scheduler sends nothing. It loops until it is
        // dropped, so it never resolves.
        //
        // The scheduler is polled here, outside every task, so a panic in
        // it would unwind this function and skip the cleanup below. The
        // panic is caught and recorded, which ends the drive.
        if let Err(payload) =
            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| scheduler.as_mut().poll(cx)))
        {
            crate::task::record_or_discard(&coordinator, payload);
            return Poll::Ready(DriveEnd::Interrupted);
        }
        if let Some(sleep) = deadline.as_mut()
            && sleep.as_mut().poll(cx).is_ready()
        {
            deadline = None;
            if coordinator.running_and_idle() {
                tracing::warn!("{UNTRACKED_DEADLINE_WARNING}");
            }
        }
        Poll::Pending
    })
    .await;

    // Cleanup, whatever ended the drive. No task is polled from here on.
    // The scheduler stops; a refresh it started runs on a detached task,
    // which the cleanup waits for. Its drop runs inside a catch, so a panic
    // is recorded and the cleanup goes on. The root task is aborted and
    // awaited, so the handler has unwound and dropped every handle it held
    // before the other tasks are aborted. The task gateway records a panic
    // of any future it drops, and a dropped handle records a panic it did
    // not read. Then the driver waits until every tracked task has unwound,
    // so no SDK task outlives the invocation, and claims every panic still
    // unread in a slot.
    crate::task::drop_recorded(&coordinator, scheduler);
    coordinator.finish();
    root.abort();
    drop(root);
    drop(root_join.await);
    let tasks = Arc::clone(coordinator.tasks());
    tasks.abort_all();
    tasks.wait_idle().await;
    tasks.claim_unread_panics(&coordinator);

    // The arbitration. Every SDK task has stopped. Plugin hook work is
    // untracked, so it can record a fatal error concurrently with the
    // `fatal_error()` read below: a record that lands before that read is
    // used, and one that lands after it is not read. `take_panic` closes
    // panic ownership, so a later panic record is returned to its caller.
    let fatal = coordinator.fatal_error();
    let panic = coordinator.take_panic();
    drop(ownership_guard);
    #[cfg(test)]
    test_hooks::after_arbitration(&coordinator);
    if let Some(fatal) = fatal {
        if let Some(payload) = panic {
            crate::task::discard_panic(payload);
        }
        return Ok((fatal.into_outcome(), true));
    }
    if let Some(payload) = panic {
        return Err(payload);
    }
    let outcome = match ended {
        DriveEnd::Completed(Ok(result)) => InvocationOutcome::Complete(result),
        DriveEnd::Completed(Err(err)) => InvocationOutcome::Failed { error: err },
        DriveEnd::Interrupted => InvocationOutcome::Pending,
    };
    Ok((outcome, false))
}

/// The answer of an invocation whose checkpoint token was withdrawn.
///
/// The invocation wrapper calls it after the end-of-invocation flush, on
/// every exit that returns a response or a Lambda error: handler `Ok` or
/// `Err`, a transport error of either scope, a recorded fatal error and a
/// serdes fault. A panic is not such an exit, and propagates.
///
/// Without the latch it returns `response` and `end` unchanged. With it the
/// response is exactly `{"Status":"PENDING"}`, nothing is recorded as a
/// fault or an execution failure, and the end hook receives `Pending` with
/// the error `end` carried, or none.
pub(crate) fn withdrawal_answer(
    ctx: &crate::DurableContext,
    response: Result<crate::InvocationResponse, lambda_runtime::Error>,
    end: crate::InvocationEnd,
) -> (
    Result<crate::InvocationResponse, lambda_runtime::Error>,
    crate::InvocationEnd,
) {
    if !ctx.coordinator().withdrawn() {
        return (response, end);
    }
    // The end keeps the error the same path carries without withdrawal: a
    // fatal error the arbitration read, else the handler's error, else
    // none. A recorded checkpoint failure never meets a withdrawal,
    // because either latch stops the next request.
    // A suspension already answers `PENDING`, and emitted its event.
    if end.status == crate::InvocationStatus::Pending {
        return (response, end);
    }
    drop(response);
    let (pending, mut pending_end) = crate::outcome_envelope(InvocationOutcome::Pending, ctx);
    pending_end.error = end.error;
    (pending, pending_end)
}

/// [`drive_invocation`] without the fatal-arbitration flag, for callers
/// that need only the outcome.
#[cfg(test)]
pub(crate) async fn drive_outcome<F>(
    handler_future: F,
    task_ownership: Arc<TaskOwnership>,
    coordinator: Arc<InvocationCoordinator>,
    root: crate::DurableContext,
    remaining: Option<Duration>,
) -> Result<InvocationOutcome, Box<dyn std::any::Any + Send + 'static>>
where
    F: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
{
    drive_invocation(
        handler_future,
        crate::task::TaskContext::current(),
        task_ownership,
        coordinator,
        root,
        remaining,
    )
    .await
    .map(|(outcome, _)| outcome)
}

/// Test-only hooks of the driver.
#[cfg(test)]
pub(crate) mod test_hooks {
    tokio::task_local! {
        /// When set, `drive_invocation` calls it with the coordinator after
        /// its arbitration and before it returns, as hook work that records
        /// at that point would.
        pub(crate) static AFTER_ARBITRATION: std::sync::Arc<
            dyn Fn(&super::InvocationCoordinator) + Send + Sync,
        >;
    }

    pub(crate) fn after_arbitration(coordinator: &super::InvocationCoordinator) {
        if let Ok(hook) = AFTER_ARBITRATION.try_with(std::sync::Arc::clone) {
            hook(coordinator);
        }
    }
}

/// Refreshes waiting operations on the schedule of [`crate::coordinator`],
/// until it is dropped.
///
/// It sleeps until the earliest due refresh, and re-arms when a
/// registration is added, armed or retired. When refreshes are due it
/// takes a scheduler permit, which the coordinator grants only beside an
/// activity or checkpoint permit. It sends one checkpoint with no updates
/// through `root`, whose merge wakes every operation the response
/// readied, and then schedules each due registration's next refresh. Only
/// then does it release the permit. A refused permit stops the scheduler.
/// A failed refresh is recorded as a failed checkpoint write of the
/// first due operation, and never resolves, so the scheduler sends nothing
/// more. The failure is recorded where the response arrives, not here, so
/// a refresh that is in flight when the handler returns still decides the
/// outcome (see [`crate::DurableContext::checkpoint_refresh`]).
async fn refresh_scheduler(root: crate::DurableContext) {
    use crate::coordinator::{DueRefresh, PermitKind};

    let coordinator = Arc::clone(root.coordinator());
    loop {
        match coordinator.next_refresh_at() {
            None => {
                coordinator.rearmed().await;
                continue;
            }
            Some(at) => {
                tokio::select! {
                    biased;
                    () = coordinator.rearmed() => continue,
                    () = tokio::time::sleep_until(at) => {}
                }
            }
        }
        let (keys, first_wire_id) = match coordinator.take_due(tokio::time::Instant::now()) {
            DueRefresh::Nothing | DueRefresh::UnderFloor => continue,
            DueRefresh::Due {
                keys,
                first_wire_id,
            } => (keys, first_wire_id),
        };
        let Some(permit) = coordinator.acquire(PermitKind::Scheduler) else {
            return std::future::pending().await;
        };
        root.checkpoint_refresh(&first_wire_id).await;
        let records = keys
            .iter()
            .filter_map(|(wire_id, _)| {
                root.refresh_view(wire_id)
                    .map(|view| (wire_id.clone(), view))
            })
            .collect();
        coordinator.after_refresh(&keys, &records);
        drop(permit);
    }
}

#[cfg(test)]
pub(crate) mod test_support {
    use super::{InvocationOutcome, TaskOwnership, drive_outcome};
    use crate::client::{CheckpointOutput, ExecutionClient, ExecutionClientError, GetStateOutput};
    use crate::coordinator::InvocationCoordinator;
    use aws_sdk_lambda::types::{Operation, OperationStatus, OperationUpdate};
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    /// Drives `fut` through [`drive_invocation`] and resumes a handler
    /// panic, for tests that expect an outcome.
    pub(crate) async fn drive_ok<F>(
        root: crate::DurableContext,
        fut: F,
        ownership: Arc<TaskOwnership>,
        coordinator: Arc<InvocationCoordinator>,
    ) -> InvocationOutcome
    where
        F: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
    {
        match drive_outcome(fut, ownership, coordinator, root, None).await {
            Ok(outcome) => outcome,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    /// Drives an operation future through the real invocation driver and
    /// returns the invocation outcome. The operation's own result is
    /// discarded: a waiting operation yields
    /// [`InvocationOutcome::Pending`] exactly as in production, and a
    /// completing one yields `Complete`. Used by operation unit tests to
    /// drive a waiting future to an outcome instead of awaiting it directly
    /// (a direct await would wait forever).
    ///
    /// `ownership` is the task-ownership tracker of the context the
    /// operation runs on: the driver blesses its root task there.
    pub(crate) async fn outcome_of<F>(
        root: crate::DurableContext,
        ownership: Arc<TaskOwnership>,
        coordinator: Arc<InvocationCoordinator>,
        fut: F,
    ) -> InvocationOutcome
    where
        F: IntoFuture + Send + 'static,
        F::IntoFuture: Send + 'static,
    {
        // Box the operation future: `drive_invocation` stack-pins its
        // argument, so a large operation future would otherwise inflate
        // every test future that awaits this helper (clippy
        // `large_futures`). Test-only; production handler futures are
        // driven unboxed.
        let fut = Box::pin(async move {
            let _ = fut.await;
            Ok::<_, crate::error::WireError>("ok".to_owned())
        });
        match drive_outcome(fut, ownership, coordinator, root, None).await {
            Ok(outcome) => outcome,
            Err(payload) => std::panic::resume_unwind(payload),
        }
    }

    /// Drives `fut` to its invocation outcome and asserts that it ended the
    /// invocation with a fault whose message contains `needle`.
    #[expect(clippy::panic)] // reason: test assertion on an unexpected outcome
    pub(crate) async fn expect_serdes_fault<F>(
        root: crate::DurableContext,
        ownership: Arc<TaskOwnership>,
        coordinator: Arc<InvocationCoordinator>,
        fut: F,
        needle: &str,
    ) where
        F: IntoFuture + Send + 'static,
        F::IntoFuture: Send + 'static,
    {
        let outcome = tokio::time::timeout(
            Duration::from_secs(5),
            outcome_of(root, ownership, coordinator, fut),
        )
        .await
        .expect("the operation must reach an invocation outcome within 5 s");
        let InvocationOutcome::Fault { message, .. } = outcome else {
            panic!("expected an invocation fault, got {outcome:?}");
        };
        assert!(
            message.contains(needle),
            "fault message {message:?} must contain {needle:?}"
        );
    }

    /// Decides the operations one checkpoint response carries, from the
    /// updates of the call and every update received so far (this call's
    /// included).
    type Responder = dyn Fn(&[OperationUpdate], &[OperationUpdate]) -> Vec<Operation> + Send + Sync;

    /// A test `ExecutionClient` that answers each checkpoint call with the
    /// operations its responder returns, optionally after a delay of tokio
    /// time, and records every call.
    pub(crate) struct ScriptedClient {
        respond: Box<Responder>,
        delay: Option<Duration>,
        /// Notified before the first call returns, when set.
        first_call_gate: Option<Arc<tokio::sync::Notify>>,
        calls: Mutex<Vec<(String, Vec<OperationUpdate>)>>,
        tokens: Mutex<u32>,
    }

    impl ScriptedClient {
        /// A client whose responses carry what `respond` returns.
        pub(crate) fn new(
            respond: impl Fn(&[OperationUpdate], &[OperationUpdate]) -> Vec<Operation>
            + Send
            + Sync
            + 'static,
        ) -> Self {
            Self {
                respond: Box::new(respond),
                delay: None,
                first_call_gate: None,
                calls: Mutex::new(Vec::new()),
                tokens: Mutex::new(0),
            }
        }

        /// A client whose responses carry nothing.
        pub(crate) fn empty() -> Self {
            Self::new(|_, _| Vec::new())
        }

        /// Answers each call after `delay` of tokio time.
        pub(crate) fn with_delay(mut self, delay: Duration) -> Self {
            self.delay = Some(delay);
            self
        }

        /// Holds the first call's response until `gate` is notified.
        pub(crate) fn with_first_call_gate(mut self, gate: Arc<tokio::sync::Notify>) -> Self {
            self.first_call_gate = Some(gate);
            self
        }

        /// Every call's checkpoint token and updates, in call order.
        pub(crate) fn calls(&self) -> Vec<(String, Vec<OperationUpdate>)> {
            self.calls.lock().expect("lock").clone()
        }

        /// Every update received, in call order.
        pub(crate) fn updates(&self) -> Vec<OperationUpdate> {
            self.calls().into_iter().flat_map(|(_, u)| u).collect()
        }

        /// The number of checkpoint calls received.
        pub(crate) fn call_count(&self) -> usize {
            self.calls.lock().expect("lock").len()
        }

        /// Whether an update of `name` with `action` was received.
        pub(crate) fn received(
            &self,
            name: &str,
            action: &aws_sdk_lambda::types::OperationAction,
        ) -> bool {
            self.updates()
                .iter()
                .any(|u| u.name() == Some(name) && u.action() == action)
        }
    }

    impl ExecutionClient for ScriptedClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            let (operations, first) = {
                let mut calls = self.calls.lock().expect("lock");
                let mut history: Vec<OperationUpdate> =
                    calls.iter().flat_map(|(_, u)| u.iter().cloned()).collect();
                history.extend(updates.iter().cloned());
                let operations = (self.respond)(&updates, &history);
                calls.push((checkpoint_token.to_owned(), updates));
                (operations, calls.len() == 1)
            };
            let token = {
                let mut tokens = self.tokens.lock().expect("lock");
                *tokens += 1;
                format!("t{tokens}")
            };
            let delay = self.delay;
            let gate = if first {
                self.first_call_gate.clone()
            } else {
                None
            };
            Box::pin(async move {
                if let Some(gate) = gate {
                    gate.notified().await;
                }
                if let Some(delay) = delay {
                    tokio::time::sleep(delay).await;
                }
                Ok(CheckpointOutput::new(Some(token), operations, None))
            })
        }

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

    /// Polls `f` once with the calling task's context, and returns.
    pub(crate) async fn poll_once<F: Future>(mut f: Pin<&mut F>) {
        std::future::poll_fn(|cx| {
            // The handle stays pending: the tests that call this await it
            // later.
            let _ = f.as_mut().poll(cx);
            std::task::Poll::Ready(())
        })
        .await;
    }

    /// One request a [`RefreshClient`] answers.
    pub(crate) struct RefreshRequest<'a> {
        /// The request's updates.
        pub(crate) updates: &'a [OperationUpdate],
        /// Every update received so far, this request's included.
        pub(crate) history: &'a [OperationUpdate],
        /// The 1-based number of this request among the requests with no
        /// updates. 0 for a request with updates.
        pub(crate) empty_number: usize,
        /// The tokio time since the client was created, when the response
        /// is built.
        pub(crate) now: Duration,
        /// The wall-clock time when the client was created.
        pub(crate) base: std::time::SystemTime,
    }

    impl RefreshRequest<'_> {
        /// The timestamp `in_` after the request's tokio time, in the
        /// wall-clock time the SDK reads under paused tokio time: the
        /// client's creation time plus the tokio time since.
        pub(crate) fn timestamp_in(&self, in_: Duration) -> aws_smithy_types::DateTime {
            aws_smithy_types::DateTime::from(self.base + self.now + in_)
        }
    }

    /// Decides the response to one request.
    type RefreshResponder =
        dyn Fn(&RefreshRequest<'_>) -> Result<Vec<Operation>, ExecutionClientError> + Send + Sync;

    /// A test `ExecutionClient` for the refresh scheduler. It records the
    /// tokio time of every call and of every answer to a call with no
    /// updates, delays the answer to such a call by a fixed time, and
    /// builds each response when it answers.
    pub(crate) struct RefreshClient {
        respond: Box<RefreshResponder>,
        empty_delay: Duration,
        start: tokio::time::Instant,
        base: std::time::SystemTime,
        calls: Mutex<Vec<(Duration, Vec<OperationUpdate>)>>,
        empty_answers: Mutex<Vec<Duration>>,
        tokens: Mutex<u32>,
    }

    impl RefreshClient {
        /// A client whose responses `respond` builds. Create it inside the
        /// test's runtime: its clock starts here.
        pub(crate) fn new(
            respond: impl Fn(&RefreshRequest<'_>) -> Result<Vec<Operation>, ExecutionClientError>
            + Send
            + Sync
            + 'static,
        ) -> Self {
            Self {
                respond: Box::new(respond),
                empty_delay: Duration::ZERO,
                start: tokio::time::Instant::now(),
                base: std::time::SystemTime::now(),
                calls: Mutex::new(Vec::new()),
                empty_answers: Mutex::new(Vec::new()),
                tokens: Mutex::new(0),
            }
        }

        /// Answers each call with no updates after `delay` of tokio time.
        pub(crate) fn with_empty_delay(mut self, delay: Duration) -> Self {
            self.empty_delay = delay;
            self
        }

        /// The tokio time since the client was created.
        pub(crate) fn elapsed(&self) -> Duration {
            self.start.elapsed()
        }

        /// The tokio time of each call with no updates, in call order.
        pub(crate) fn empty_calls(&self) -> Vec<Duration> {
            self.calls
                .lock()
                .expect("lock")
                .iter()
                .filter(|(_, updates)| updates.is_empty())
                .map(|(at, _)| *at)
                .collect()
        }

        /// The tokio time of each answer to a call with no updates.
        pub(crate) fn empty_answers(&self) -> Vec<Duration> {
            self.empty_answers.lock().expect("lock").clone()
        }

        /// The tokio time of the first call that carried an update of
        /// `name` with `action`.
        pub(crate) fn time_of(
            &self,
            name: &str,
            action: &aws_sdk_lambda::types::OperationAction,
        ) -> Option<Duration> {
            self.calls
                .lock()
                .expect("lock")
                .iter()
                .find(|(_, updates)| named(updates, name, action).is_some())
                .map(|(at, _)| *at)
        }

        /// Every update received, in call order.
        pub(crate) fn updates(&self) -> Vec<OperationUpdate> {
            self.calls
                .lock()
                .expect("lock")
                .iter()
                .flat_map(|(_, u)| u.iter().cloned())
                .collect()
        }

        /// Whether an update of `name` with `action` was received.
        pub(crate) fn received(
            &self,
            name: &str,
            action: &aws_sdk_lambda::types::OperationAction,
        ) -> bool {
            self.time_of(name, action).is_some()
        }
    }

    impl ExecutionClient for RefreshClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            let (history, empty_number) = {
                let mut calls = self.calls.lock().expect("lock");
                calls.push((self.start.elapsed(), updates.clone()));
                let history: Vec<OperationUpdate> =
                    calls.iter().flat_map(|(_, u)| u.iter().cloned()).collect();
                let empty_number = if updates.is_empty() {
                    calls.iter().filter(|(_, u)| u.is_empty()).count()
                } else {
                    0
                };
                (history, empty_number)
            };
            let token = {
                let mut tokens = self.tokens.lock().expect("lock");
                *tokens += 1;
                format!("t{tokens}")
            };
            Box::pin(async move {
                if empty_number > 0 && !self.empty_delay.is_zero() {
                    tokio::time::sleep(self.empty_delay).await;
                }
                let now = self.start.elapsed();
                let operations = (self.respond)(&RefreshRequest {
                    updates: &updates,
                    history: &history,
                    empty_number,
                    now,
                    base: self.base,
                })?;
                if empty_number > 0 {
                    self.empty_answers.lock().expect("lock").push(now);
                }
                Ok(CheckpointOutput::new(Some(token), operations, None))
            })
        }

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

    /// A root context on `client`, with an empty checkpoint log, whose
    /// Lambda deadline is 0 (none).
    pub(crate) fn refresh_ctx(client: &Arc<RefreshClient>) -> crate::DurableContext {
        crate::DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(crate::engine::CheckpointLog::empty()),
            Arc::clone(client) as Arc<dyn ExecutionClient>,
            "t0".to_owned(),
        )
    }

    /// The record of a callback whose START is `start`, with `status`, its
    /// callback ID and `result`.
    pub(crate) fn callback_record(
        start: &OperationUpdate,
        status: OperationStatus,
        result: Option<&str>,
    ) -> Operation {
        let mut details = aws_sdk_lambda::types::CallbackDetails::builder().callback_id("cb-1");
        if let Some(result) = result {
            details = details.result(result);
        }
        operation_like(start, status)
            .callback_details(details.build())
            .build()
            .expect("all required fields set")
    }

    /// Answers the START of every callback among `updates` with `STARTED`
    /// and its callback ID.
    pub(crate) fn callback_starts(updates: &[OperationUpdate]) -> Vec<Operation> {
        updates
            .iter()
            .filter(|u| {
                u.r#type() == &aws_sdk_lambda::types::OperationType::Callback
                    && u.action() == &aws_sdk_lambda::types::OperationAction::Start
            })
            .map(|start| callback_record(start, OperationStatus::Started, None))
            .collect()
    }

    /// Asserts that `actual` is `expected` within 50 ms. The end times a
    /// response carries are wall-clock times taken when the response is
    /// built, so a delay computed from one can be off by the real time a
    /// test takes between two steps.
    #[track_caller]
    pub(crate) fn assert_near(actual: Duration, expected: Duration) {
        let diff = actual.abs_diff(expected);
        assert!(
            diff <= Duration::from_millis(50),
            "expected {expected:?}, got {actual:?}"
        );
    }

    /// Asserts that `actual` holds one time per entry of `expected`, each
    /// within 50 ms (see [`assert_near`]).
    #[track_caller]
    pub(crate) fn assert_times(actual: &[Duration], expected: &[Duration]) {
        assert_eq!(
            actual.len(),
            expected.len(),
            "expected times {expected:?}, got {actual:?}"
        );
        for (a, e) in actual.iter().zip(expected) {
            assert_near(*a, *e);
        }
    }

    /// A root context on `client`, with an empty checkpoint log.
    pub(crate) fn scripted_ctx(client: &Arc<ScriptedClient>) -> crate::DurableContext {
        crate::DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(crate::engine::CheckpointLog::empty()),
            Arc::clone(client) as Arc<dyn ExecutionClient>,
            "t0".to_owned(),
        )
    }

    /// An operation record with the identity of `update` (its ID, type,
    /// sub-type, name and parent) and `status`, as a checkpoint response
    /// carries it.
    pub(crate) fn operation_like(
        update: &OperationUpdate,
        status: OperationStatus,
    ) -> aws_sdk_lambda::types::builders::OperationBuilder {
        let mut builder = Operation::builder()
            .id(update.id())
            .r#type(update.r#type().clone())
            .status(status)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0));
        if let Some(sub_type) = update.sub_type() {
            builder = builder.sub_type(sub_type);
        }
        if let Some(name) = update.name() {
            builder = builder.name(name);
        }
        if let Some(parent) = update.parent_id() {
            builder = builder.parent_id(parent);
        }
        builder
    }

    /// The first update in `updates` named `name` with `action`.
    pub(crate) fn named<'a>(
        updates: &'a [OperationUpdate],
        name: &str,
        action: &aws_sdk_lambda::types::OperationAction,
    ) -> Option<&'a OperationUpdate> {
        updates
            .iter()
            .find(|u| u.name() == Some(name) && u.action() == action)
    }

    /// Drives `handler` on `ctx` through [`drive_invocation`], with
    /// `remaining` as the time left.
    pub(crate) async fn drive_handler<F, Fut>(
        ctx: crate::DurableContext,
        remaining: Option<Duration>,
        handler: F,
    ) -> Result<InvocationOutcome, Box<dyn std::any::Any + Send + 'static>>
    where
        F: FnOnce(crate::DurableContext) -> Fut,
        Fut: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
    {
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let handler = Box::pin(handler(ctx));
        drive_outcome(handler, ownership, coordinator, root, remaining).await
    }

    /// Records the level and message of every event while installed as
    /// the thread's default subscriber.
    #[derive(Clone, Default)]
    pub(crate) struct EventMessages(Arc<Mutex<Vec<(tracing::Level, String)>>>);

    struct MessageVisitor(String);

    impl tracing::field::Visit for MessageVisitor {
        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
            if field.name() == "message" {
                self.0 = format!("{value:?}");
            }
        }
    }

    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for EventMessages {
        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            let mut visitor = MessageVisitor(String::new());
            event.record(&mut visitor);
            self.0
                .lock()
                .expect("lock")
                .push((*event.metadata().level(), visitor.0));
        }
    }

    impl EventMessages {
        /// Installs a capture as the thread's default subscriber until the
        /// returned guard drops.
        pub(crate) fn install() -> (Self, tracing::subscriber::DefaultGuard) {
            use tracing_subscriber::layer::SubscriberExt as _;
            let capture = Self::default();
            let subscriber = tracing_subscriber::registry().with(capture.clone());
            (capture, test_tracing::install_test_subscriber(subscriber))
        }

        /// The messages of the events at `level`, in emission order.
        pub(crate) fn at(&self, level: tracing::Level) -> Vec<String> {
            self.0
                .lock()
                .expect("lock")
                .iter()
                .filter(|(l, _)| *l == level)
                .map(|(_, m)| m.clone())
                .collect()
        }

        /// The number of `operation_replayed` events.
        pub(crate) fn replayed(&self) -> usize {
            self.at(tracing::Level::DEBUG)
                .iter()
                .filter(|m| *m == crate::observability::event_names::OPERATION_REPLAYED)
                .count()
        }
    }

    /// Turns an operation error into the handler's wire error.
    #[expect(clippy::needless_pass_by_value)]
    // reason: it is passed to `map_err`, which hands over the error.
    pub(crate) fn wire_err(err: crate::OperationError) -> crate::error::WireError {
        crate::error::WireError::new(None::<String>, Some(format!("{err:#}")))
    }

    /// One checkpoint request a [`LatencyClient`] received.
    #[derive(Clone)]
    pub(crate) struct LatencyRequest {
        /// The tokio time since the client was created, when it received
        /// the request.
        pub(crate) received: Duration,
        /// The tokio time when it answered the request. `None` until then.
        pub(crate) answered: Option<Duration>,
        /// The request's updates.
        pub(crate) updates: Vec<OperationUpdate>,
    }

    /// A test `ExecutionClient` that answers each checkpoint call
    /// `latency` of tokio time after it receives it, and records the time
    /// of each request and of each answer.
    ///
    /// It answers a `START` with a `STARTED` record of the operation, so
    /// the checkpoint log holds the record the service would return. With
    /// `fail_start`, it answers a request that carries a `START` with a
    /// non-retryable error instead.
    pub(crate) struct LatencyClient {
        latency: Duration,
        fail_start: bool,
        start: tokio::time::Instant,
        requests: Arc<Mutex<Vec<LatencyRequest>>>,
        tokens: Mutex<u32>,
    }

    impl LatencyClient {
        /// A client that answers after `latency`. Create it inside the
        /// test's runtime: its clock starts here.
        pub(crate) fn new(latency: Duration) -> Self {
            Self {
                latency,
                fail_start: false,
                start: tokio::time::Instant::now(),
                requests: Arc::new(Mutex::new(Vec::new())),
                tokens: Mutex::new(0),
            }
        }

        /// Answers a request that carries a `START` with a non-retryable
        /// error.
        pub(crate) fn failing_start(mut self) -> Self {
            self.fail_start = true;
            self
        }

        /// The tokio time since the client was created.
        pub(crate) fn elapsed(&self) -> Duration {
            self.start.elapsed()
        }

        /// Every request received, in order.
        pub(crate) fn requests(&self) -> Vec<LatencyRequest> {
            self.requests.lock().expect("lock").clone()
        }

        /// The first request that carries an update with `action`.
        pub(crate) fn request_with(
            &self,
            action: &aws_sdk_lambda::types::OperationAction,
        ) -> Option<LatencyRequest> {
            self.requests()
                .into_iter()
                .find(|r| r.updates.iter().any(|u| u.action() == action))
        }

        /// Whether any request carried a `SUCCEED`, `RETRY` or `FAIL`
        /// update.
        pub(crate) fn received_outcome(&self) -> bool {
            use aws_sdk_lambda::types::OperationAction;
            self.requests()
                .iter()
                .flat_map(|r| r.updates.clone())
                .any(|u| {
                    matches!(
                        u.action(),
                        OperationAction::Succeed | OperationAction::Retry | OperationAction::Fail
                    )
                })
        }
    }

    impl ExecutionClient for LatencyClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            use aws_sdk_lambda::types::OperationAction;
            let index = {
                let mut requests = self.requests.lock().expect("lock");
                requests.push(LatencyRequest {
                    received: self.start.elapsed(),
                    answered: None,
                    updates: updates.clone(),
                });
                requests.len() - 1
            };
            let token = {
                let mut tokens = self.tokens.lock().expect("lock");
                *tokens += 1;
                format!("t{tokens}")
            };
            Box::pin(async move {
                tokio::time::sleep(self.latency).await;
                if let Some(request) = self.requests.lock().expect("lock").get_mut(index) {
                    request.answered = Some(self.start.elapsed());
                }
                let starts: Vec<&OperationUpdate> = updates
                    .iter()
                    .filter(|u| u.action() == &OperationAction::Start)
                    .collect();
                if self.fail_start && !starts.is_empty() {
                    return Err(ExecutionClientError::new_non_retryable("START rejected"));
                }
                let operations = starts
                    .into_iter()
                    .map(|u| {
                        operation_like(u, OperationStatus::Started)
                            .build()
                            .expect("all required fields set")
                    })
                    .collect();
                Ok(CheckpointOutput::new(Some(token), operations, None))
            })
        }

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

    /// A root context on `client`, with an empty checkpoint log.
    /// `buffer_window` is `None` for direct writes (batching off), and
    /// `Some(delay)` for batching with `checkpoint_delay(delay)`.
    pub(crate) fn latency_ctx(
        client: &Arc<LatencyClient>,
        buffer_window: Option<Duration>,
    ) -> crate::DurableContext {
        crate::DurableContext::new_root_with_client_and_defaults(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(crate::engine::CheckpointLog::empty()),
            Arc::clone(client) as Arc<dyn ExecutionClient>,
            "t0".to_owned(),
            buffer_window,
            0,
            None,
        )
    }
}

#[cfg(test)]
// Tests deliberately spawn foreign (unblessed) tasks to exercise runtime
// behavior; production spawning is confined to the src/task.rs gateway.
#[expect(clippy::disallowed_methods)]
mod tests {
    use super::test_support::drive_ok;
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

    // Suspension drops the future at the await point

    /// A guard that sets a flag when dropped: proves the future was
    /// dropped at the await point.
    struct DropGuard {
        dropped: Arc<AtomicBool>,
    }

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

    /// A capture receives an event whose callsite a thread without a default
    /// subscriber reached first. Without the dispatchers that the
    /// `test-tracing` initializer keeps, that first use caches
    /// `Interest::never()`, and the capture misses the second event.
    #[test]
    fn capture_sees_callsite_first_reached_without_thread_default() {
        fn probe() {
            tracing::info!("capture-probe");
        }
        let (capture, _guard) = test_support::EventMessages::install();
        std::thread::spawn(probe)
            .join()
            .expect("the probe thread does not panic");
        assert_eq!(capture.at(tracing::Level::INFO), Vec::<String>::new());
        probe();
        assert_eq!(capture.at(tracing::Level::INFO), ["capture-probe"]);
    }

    /// A root context whose checkpoint calls carry nothing back, so a wait
    /// started on it stays waiting.
    fn waiting_ctx() -> crate::DurableContext {
        let client = Arc::new(test_support::ScriptedClient::empty());
        test_support::scripted_ctx(&client)
    }

    #[tokio::test]
    async fn suspension_drops_future_at_await_point() {
        let ctx = waiting_ctx();
        let drop_observed = Arc::new(AtomicBool::new(false));
        let after_await_ran = Arc::new(AtomicBool::new(false));

        let drop_clone = Arc::clone(&drop_observed);
        let after_clone = Arc::clone(&after_await_ran);
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let _guard = DropGuard {
                    dropped: drop_clone,
                };

                // A wait that nothing completes: the invocation suspends
                // and the driver drops this future.
                let _ = ctx.wait(Duration::from_secs(30)).await;

                // This code must NEVER run: the future is dropped above.
                after_clone.store(true, Ordering::SeqCst);
                Ok("should not reach".to_owned())
            },
            ownership,
            coordinator,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            drop_observed.load(Ordering::SeqCst),
            "future was not dropped at the await point"
        );
        assert!(
            !after_await_ran.load(Ordering::SeqCst),
            "code after the suspension point must not run"
        );
    }

    // Suspension is unswallowable (no catchable error)

    #[tokio::test]
    async fn suspension_unswallowable_by_catch_all() {
        let ctx = waiting_ctx();
        let after_catch_ran = Arc::new(AtomicBool::new(false));
        let after_clone = Arc::clone(&after_catch_ran);
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                // User tries a "catch-all" pattern: wrapping in a closure
                // that catches panics. This cannot catch future-drop.
                let result: Result<String, crate::error::WireError> = async {
                    let _ = ctx.wait(Duration::from_secs(30)).await;
                    Ok("survived".to_owned())
                }
                .await;

                // If somehow the suspension was catchable, this would run:
                after_clone.store(true, Ordering::SeqCst);
                result
            },
            ownership,
            coordinator,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !after_catch_ran.load(Ordering::SeqCst),
            "catch-all must not intercept suspension — future is dropped"
        );
    }

    // PENDING outcome surfaces to the driver caller

    #[tokio::test]
    async fn pending_outcome_surfaces_to_caller() {
        let ctx = waiting_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let _ = ctx.wait(Duration::from_secs(30)).await;
                Ok("unreachable".to_owned())
            },
            ownership,
            coordinator,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
    }

    // Normal completion

    #[tokio::test]
    async fn driver_returns_complete_on_success() {
        let ctx = crate::DurableContext::test_context();
        let signal = Arc::clone(ctx.coordinator());

        let outcome = drive_ok(
            ctx.clone(),
            async move { Ok::<_, crate::error::WireError>("done".to_owned()) },
            Arc::clone(ctx.task_ownership()),
            Arc::clone(&signal),
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
    }

    #[tokio::test]
    async fn driver_returns_failed_on_error() {
        let ctx = crate::DurableContext::test_context();
        let signal = Arc::clone(ctx.coordinator());

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                Err(crate::error::WireError::new(
                    Some("Error".to_owned()),
                    Some("boom".to_owned()),
                ))
            },
            Arc::clone(ctx.task_ownership()),
            Arc::clone(&signal),
        )
        .await;

        let InvocationOutcome::Failed { error } = outcome else {
            unreachable!("expected Failed, got {outcome:?}");
        };
        assert_eq!(error.error_type(), Some("Error"));
        assert_eq!(error.error_message(), Some("boom"));
    }

    // Resume: replayed operations return frozen results

    #[tokio::test]
    async fn resume_replays_frozen_results_without_re_executing() {
        // Simulate a resume invocation: checkpoint log has a result for
        // operation "1" (keyed by its wire ID), so the engine should
        // return the frozen value without calling the step body.
        let execution_count = Arc::new(AtomicU32::new(0));
        let exec_clone = Arc::clone(&execution_count);

        let wire_key = crate::engine::compute_wire_id_public("1");
        let log = Arc::new(CheckpointLog::from_records(vec![(
            wire_key.clone(),
            CheckpointRecord {
                id: wire_key,
                status: CheckpointStatus::Succeeded,
                result: Some(r#""frozen_value""#.to_owned()),
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )]));

        let engine = EngineState::new_root(Arc::clone(&log));

        // Simulate what the engine does on resume: check if replaying at
        // the operation's position.
        let op_id = engine.mint_id();
        let is_replay = engine.is_replaying_at(op_id.positional());

        let result = if is_replay {
            // Replay path: return frozen result without executing.
            let wire = crate::engine::compute_wire_id_public(op_id.positional());
            let record = log.get(&wire);
            record.unwrap().result.clone()
        } else {
            // Live path: execute the body (should NOT happen here).
            exec_clone.fetch_add(1, Ordering::SeqCst);
            Some(r#""live_value""#.to_owned())
        };

        assert_eq!(result, Some(r#""frozen_value""#.to_owned()));
        assert_eq!(
            execution_count.load(Ordering::SeqCst),
            0,
            "step body must NOT execute during replay"
        );
    }

    // Task ownership: foreign task fails fast

    #[tokio::test]
    async fn ownership_check_rejects_foreign_task() {
        // Must create ownership inside a spawned task where try_id()
        // returns Some: the #[tokio::test] root runs in block_on which
        // has no task ID.
        let result = tokio::spawn(async {
            let ownership = Arc::new(TaskOwnership::new_current());
            let ownership_clone = Arc::clone(&ownership);

            // Spawn a DIFFERENT task and try the ownership check there.
            let handle = tokio::spawn(async move { ownership_clone.check_current_task() });

            handle.await.unwrap()
        })
        .await;

        let inner_result = result.unwrap();
        assert!(inner_result.is_err());
        let msg = inner_result.unwrap_err();
        assert!(
            msg.contains("Use .spawn()"),
            "error message should guide users: {msg}"
        );
    }

    // Task ownership: owning task succeeds

    #[tokio::test]
    async fn ownership_check_allows_owning_task() {
        // Run inside a spawned task so try_id() returns Some.
        let result = tokio::spawn(async {
            let ownership = TaskOwnership::new_current();
            ownership.check_current_task()
        })
        .await;

        let inner = result.unwrap();
        assert!(inner.is_ok(), "owning task should pass: {inner:?}");
    }

    // Task ownership: .spawn() exemption (blessed tasks)

    #[tokio::test]
    async fn ownership_spawn_exemption_blesses_task() {
        // Create ownership in a spawned task, then spawn a child and bless it.
        let result = tokio::spawn(async {
            let ownership = Arc::new(TaskOwnership::new_current());
            let ownership_clone = Arc::clone(&ownership);

            // Simulate what .spawn() does: launch a task and bless it.
            let handle = tokio::spawn(async move {
                let task_id = tokio::task::id();
                ownership_clone.bless_task(task_id);
                ownership_clone.check_current_task()
            });

            handle.await.unwrap()
        })
        .await;

        let inner = result.unwrap();
        assert!(
            inner.is_ok(),
            "blessed task should pass ownership check: {inner:?}"
        );
    }

    // Task ownership: production topology (inline under block_on)

    /// Reproduces the REAL production topology: handler awaited inline
    /// under `block_on` (NOT inside `tokio::spawn`). `#[tokio::test]`
    /// runs in `block_on`, so `try_id()` is `None`: matching production.
    #[tokio::test]
    async fn ownership_root_context_allows_inline_operations() {
        // Context created inline (try_id() == None): production path.
        let ownership = TaskOwnership::new_current();
        assert!(
            matches!(ownership.owner, Owner::Thread(_)),
            "sanity: #[tokio::test] root runs in block_on with no task ID"
        );
        // Operation invoked inline on the owner thread: should pass.
        let result = ownership.check_current_task();
        assert!(
            result.is_ok(),
            "inline operation on the owner thread should pass: {result:?}"
        );
        // Operation invoked on another thread with no task ID: refused.
        let ownership = Arc::new(ownership);
        let other = Arc::clone(&ownership);
        let result = std::thread::spawn(move || other.check_current_task())
            .join()
            .unwrap();
        assert!(
            result.is_err_and(|msg| msg.contains("does not own the context")),
            "a thread that does not own the context must be refused"
        );
    }

    /// A context created on a task refuses a caller with no task ID, even
    /// on the thread that ran the owner task.
    #[test]
    fn ownership_task_context_refuses_callers_without_a_task() {
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let ownership = rt.block_on(async {
            tokio::spawn(async { Arc::new(TaskOwnership::new_current()) })
                .await
                .unwrap()
        });
        assert!(matches!(ownership.owner, Owner::Task(_)));
        assert!(ownership.check_current_task().is_err());
    }

    /// Production topology: a durable operation invoked from a bare user
    /// `tokio::spawn` (NOT blessed) MUST be rejected.
    #[tokio::test]
    async fn ownership_root_context_rejects_unblessed_spawn() {
        // Context created inline (try_id() == None): production path.
        let ownership = Arc::new(TaskOwnership::new_current());
        assert!(
            matches!(ownership.owner, Owner::Thread(_)),
            "sanity: root runs in block_on with no task ID"
        );
        let ownership_clone = Arc::clone(&ownership);

        // User tokio::spawn, NOT blessed.
        let handle = tokio::spawn(async move { ownership_clone.check_current_task() });

        let inner = handle.await.unwrap();
        assert!(
            inner.is_err(),
            "unblessed spawned task must be rejected in root-context mode"
        );
        let msg = inner.unwrap_err();
        assert!(
            msg.contains("Use .spawn()"),
            "error message should guide users: {msg}"
        );
    }

    /// Production topology: SDK-blessed spawns (`.spawn()`, combinators)
    /// still work in root-context mode.
    #[tokio::test]
    async fn ownership_root_context_allows_blessed_spawn() {
        // Context created inline (try_id() == None): production path.
        let ownership = Arc::new(TaskOwnership::new_current());
        assert!(
            matches!(ownership.owner, Owner::Thread(_)),
            "sanity: root runs in block_on with no task ID"
        );
        let ownership_clone = Arc::clone(&ownership);

        // Simulate what .spawn() / combinators do: spawn and bless.
        let handle = tokio::spawn(async move {
            let task_id = tokio::task::id();
            ownership_clone.bless_task(task_id);
            ownership_clone.check_current_task()
        });

        let inner = handle.await.unwrap();
        assert!(
            inner.is_ok(),
            "blessed task in root-context mode should pass: {inner:?}"
        );
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: test module
mod suspension_containment_and_task_ownership {
    use super::InvocationOutcome;
    use super::test_support::drive_ok;
    use crate::client::{ExecutionClient, InMemoryExecutionClient, TestResponse};
    use crate::context::DurableContext;
    use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};
    use aws_sdk_lambda::types::OperationAction;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    fn live_ctx(client: Arc<InMemoryExecutionClient>) -> DurableContext {
        DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client as Arc<dyn ExecutionClient>,
            "token0".to_owned(),
        )
    }

    fn succeeded_record(wire: &str) -> CheckpointRecord {
        CheckpointRecord {
            id: wire.to_owned(),
            status: CheckpointStatus::Succeeded,
            result: None,
            error_type: None,
            error_message: None,
            error_data: None,
            stack_trace: None,
            attempt: 0,
            invoke_result: None,
            invoke_error_type: None,
            invoke_error_message: None,
            invoke_error_data: None,
            invoke_stack_trace: None,
            replay_children: false,
            callback_id: None,
            op_type: None,
            sub_type: None,
            due_at: None,
            op_name: None,
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        }
    }

    // 1. Suspension never lets following user code run
    // Each op is awaited and its (never-produced) result ignored; the side
    // effect after the await MUST NOT run and the invocation MUST be Pending.

    #[tokio::test]
    async fn wait_suspend_does_not_run_following_code() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let _ = ctx_h.wait(Duration::from_secs(30)).await;
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !ran.load(Ordering::SeqCst),
            "code after a suspended wait ran"
        );
    }

    #[tokio::test]
    async fn invoke_suspend_does_not_run_following_code() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let _ = ctx_h
                    .invoke::<serde_json::Value>("target-fn", "input".to_owned())
                    .await;
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !ran.load(Ordering::SeqCst),
            "code after a suspended invoke ran"
        );
    }

    #[tokio::test]
    async fn step_retry_suspend_does_not_run_following_code() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                // Body fails; the default retry strategy schedules a retry,
                // which suspends (parks) on the backend timer.
                let _ = ctx_h
                    .step(|_| async { Err::<i32, crate::BoxError>("boom".into()) })
                    .name("retrying")
                    .await;
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !ran.load(Ordering::SeqCst),
            "code after a suspended step retry ran"
        );
    }

    #[tokio::test]
    async fn wait_for_condition_suspend_does_not_run_following_code() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let _ = ctx_h
                    .wait_for_condition(|_ctx, state: i32| async move { Ok(state + 1) }, 0)
                    .wait_strategy_fn(|_state: i32, _attempt| {
                        crate::wait_for_condition::WaitDecision::continue_with(Duration::from_secs(
                            1,
                        ))
                    })
                    .await;
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !ran.load(Ordering::SeqCst),
            "code after a suspended wfc ran"
        );
    }

    #[tokio::test]
    async fn callback_suspend_does_not_run_following_code() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let Ok(cb) = ctx_h.create_callback::<serde_json::Value>().await else {
                    return Err(crate::error::WireError::new(
                        Some("E".to_owned()),
                        Some("create failed".to_owned()),
                    ));
                };
                // Awaiting a pending callback result suspends.
                let _ = cb.result().await;
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !ran.load(Ordering::SeqCst),
            "code after a suspended callback ran"
        );
    }

    // 2. A replayed completed wait returns Ok and following code runs

    #[tokio::test]
    async fn replayed_completed_wait_returns_ok_and_continues() {
        let wire = crate::engine::compute_wire_id_public("1");
        let log = Arc::new(CheckpointLog::from_records(vec![(
            wire.clone(),
            succeeded_record(&wire),
        )]));
        let ctx = DurableContext::new_root(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            log,
        );
        let signal = Arc::clone(ctx.coordinator());
        let ran = Arc::new(AtomicBool::new(false));
        let ran_c = Arc::clone(&ran);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                ctx_h
                    .wait(Duration::from_secs(30))
                    .await
                    .expect("replayed completed wait returns Ok");
                ran_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert!(
            ran.load(Ordering::SeqCst),
            "code after a replayed wait must run"
        );
    }

    // 3. Checkpoint failures are not catchable

    /// A checkpoint API failure is never yielded to the handler as a
    /// catchable error (issue #43): the handler is dropped at its await
    /// point exactly as `suspend_now` drops it, so a catch around the
    /// operation cannot observe the failure or branch on it. A
    /// non-retryable failure fails the EXECUTION with the
    /// checkpoint-failure error type.
    #[tokio::test]
    async fn non_retryable_checkpoint_failure_uncatchable_fails_execution() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        client.enqueue_checkpoint_response(TestResponse::NonRetryableError("kaboom".to_owned()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let caught = Arc::new(AtomicBool::new(false));
        let caught_c = Arc::clone(&caught);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                // The live wait's START checkpoint fails non-retryably.
                // Pre-#43 this surfaced as a catchable Err; now the future
                // parks and the driver drops the handler, so neither branch
                // below runs.
                let r = ctx_h.wait(Duration::from_secs(5)).await;
                if r.is_err() {
                    caught_c.store(true, Ordering::SeqCst);
                }
                Ok::<_, crate::error::WireError>("handled".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert!(
            !caught.load(Ordering::SeqCst),
            "a checkpoint API failure must not be observable by a catch"
        );
        match outcome {
            InvocationOutcome::Failed { error } => {
                assert_eq!(
                    error.error_type(),
                    Some(crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE),
                    "a non-retryable checkpoint failure fails the execution \
                     with the unrecoverable-execution type"
                );
                assert!(
                    error.error_message().is_some_and(|m| m.contains("kaboom")),
                    "the service's rejection reason is preserved: {error:?}"
                );
            }
            other => panic!("expected a FAILED execution outcome, got {other:?}"),
        }
    }

    /// The retryable counterpart: a checkpoint failure that exhausted the
    /// client's internal retries fails the INVOCATION (a Lambda runtime
    /// error, so the service re-invokes: the interruption recovery path)
    /// rather than the execution, and is equally unobservable by a catch.
    #[tokio::test]
    async fn retryable_checkpoint_failure_uncatchable_fails_invocation() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        client.enqueue_checkpoint_response(TestResponse::RetryableError("throttled".to_owned()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let caught = Arc::new(AtomicBool::new(false));
        let caught_c = Arc::clone(&caught);
        let ctx_h = ctx.clone();
        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let r = ctx_h.wait(Duration::from_secs(5)).await;
                if r.is_err() {
                    caught_c.store(true, Ordering::SeqCst);
                }
                Ok::<_, crate::error::WireError>("handled".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;
        assert!(
            !caught.load(Ordering::SeqCst),
            "a checkpoint API failure must not be observable by a catch"
        );
        match outcome {
            InvocationOutcome::Fault { message, .. } => {
                assert!(
                    message.contains("throttled"),
                    "the exhausted failure's reason is preserved: {message}"
                );
            }
            other => panic!("expected an invocation Fault outcome, got {other:?}"),
        }
    }

    // 5. Dropping a .spawn() handle loses only the result: the task keeps
    // running until the tracker aborts it.

    #[tokio::test]
    async fn dropping_spawn_handle_keeps_task_running() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let started = Arc::new(AtomicBool::new(false));
        let reached_end = Arc::new(AtomicBool::new(false));
        let dropped = Arc::new(AtomicBool::new(false));
        {
            let s = Arc::clone(&started);
            let e = Arc::clone(&reached_end);
            let d = Arc::clone(&dropped);
            let handle = ctx
                .step(move |_| {
                    let s = Arc::clone(&s);
                    let e = Arc::clone(&e);
                    let d = Arc::clone(&d);
                    async move {
                        struct G(Arc<AtomicBool>);
                        impl Drop for G {
                            fn drop(&mut self) {
                                self.0.store(true, Ordering::SeqCst);
                            }
                        }
                        let _g = G(d);
                        s.store(true, Ordering::SeqCst);
                        std::future::pending::<()>().await;
                        e.store(true, Ordering::SeqCst);
                        Ok(1i32)
                    }
                })
                .name("bg")
                .spawn();
            // Let the spawned task run to its park point.
            for _ in 0..3 {
                tokio::task::yield_now().await;
            }
            assert!(
                started.load(Ordering::SeqCst),
                "spawned task should have started"
            );
            drop(handle);
        }
        for _ in 0..5 {
            tokio::task::yield_now().await;
        }
        assert!(
            !dropped.load(Ordering::SeqCst),
            "a dropped .spawn() handle does not cancel the task"
        );
        // The drive's teardown still stops it.
        let tasks = Arc::clone(ctx.coordinator().tasks());
        tasks.abort_all();
        tasks.wait_idle().await;
        assert!(dropped.load(Ordering::SeqCst), "abort_all stops the task");
        assert!(
            !reached_end.load(Ordering::SeqCst),
            "the stopped task does not reach its end"
        );
    }

    // 4 + 6. A spawned straggler (non-durable `pending()` body) holds the
    // invocation until the Lambda timeout fires. The timeout drops the
    // `drive_invocation` future, so the driver's cleanup never runs. Dropping
    // it drops the root task's `TrackedTask` handle, which aborts the root
    // task, and the drive's teardown guard, which aborts every tracked
    // operation task. Dropping the straggler's own handle would not stop
    // it. No SUCCEED checkpoint is made for the aborted straggler. The
    // bounded timeout simulates the Lambda platform's execution timeout
    // backstop.

    #[tokio::test]
    async fn straggler_is_aborted_by_timeout_no_succeed_checkpoint() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());

        let sib_started = Arc::new(AtomicBool::new(false));
        let sib_completed = Arc::new(AtomicBool::new(false));
        let sib_dropped = Arc::new(AtomicBool::new(false));

        let ctx_h = ctx.clone();
        let s = Arc::clone(&sib_started);
        let c = Arc::clone(&sib_completed);
        let d = Arc::clone(&sib_dropped);

        // Wrap in a timeout to simulate the Lambda execution timeout. The
        // straggler (a step body awaiting a non-durable pending future)
        // holds an activity permit, so the invocation does NOT report
        // Pending on its own. The Lambda timeout is the backstop that aborts
        // the straggler.
        let result = tokio::time::timeout(
            Duration::from_secs(2),
            drive_ok(
                ctx.clone(),
                async move {
                    // Sibling task: starts, then blocks on non-durable
                    // pending(). Its body never returns, so it is a
                    // "straggler".
                    let sib = ctx_h
                        .step(move |_| {
                            let s = Arc::clone(&s);
                            let c = Arc::clone(&c);
                            let d = Arc::clone(&d);
                            async move {
                                struct G(Arc<AtomicBool>);
                                impl Drop for G {
                                    fn drop(&mut self) {
                                        self.0.store(true, Ordering::SeqCst);
                                    }
                                }
                                let _g = G(d);
                                s.store(true, Ordering::SeqCst);
                                std::future::pending::<()>().await;
                                c.store(true, Ordering::SeqCst);
                                Ok(1i32)
                            }
                        })
                        .name("sibling")
                        .spawn();
                    // Let the sibling run to its park point.
                    for _ in 0..3 {
                        tokio::task::yield_now().await;
                    }
                    // The owner waits. The straggler still holds a permit, so
                    // the handler stays at this await point until the timeout
                    // fires and drops us.
                    let _ = ctx_h.wait(Duration::from_secs(30)).await;
                    let _ = sib.await;
                    Ok::<_, crate::error::WireError>("done".to_owned())
                },
                Arc::clone(ctx.task_ownership()),
                signal,
            ),
        )
        .await;

        // The timeout fired: the invocation never completed on its own
        // because the straggler held its permit.
        assert!(
            result.is_err(),
            "drive_invocation must NOT terminate on its own while a step body \
             runs; the Lambda timeout is the backstop"
        );

        // Let the runtime process the abort of the sibling task.
        for _ in 0..10 {
            tokio::task::yield_now().await;
        }
        // Give tokio a moment to run the drop paths.
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert!(
            sib_started.load(Ordering::SeqCst),
            "sibling should have started"
        );
        assert!(
            !sib_completed.load(Ordering::SeqCst),
            "sibling must not complete (its body is non-durable pending)"
        );
        assert!(
            sib_dropped.load(Ordering::SeqCst),
            "sibling task must be aborted when the timeout drops the handler"
        );
        let recorded = client.recorded_updates();
        assert!(
            recorded
                .iter()
                .all(|u| u.action() != &OperationAction::Succeed),
            "no operation should have checkpointed SUCCEED — the straggler \
             was aborted before reaching its terminal"
        );
    }

    // The drive is dropped while the root task is inside a poll on another
    // worker thread. Aborting the root does not interrupt that poll, and
    // the tracker has no live task, so the root can still start an
    // operation task after the drop. The teardown must stop it: the task
    // never runs, or it is aborted, and no work of the invocation remains.

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn root_spawn_after_drive_drop_is_stopped() {
        let ctx = live_ctx(Arc::new(InMemoryExecutionClient::new(Vec::new())));
        let coordinator = Arc::clone(ctx.coordinator());
        let (in_poll_tx, in_poll_rx) = std::sync::mpsc::channel::<()>();
        let (resume_tx, resume_rx) = std::sync::mpsc::channel::<()>();
        let body_started = Arc::new(AtomicBool::new(false));
        let body_dropped = Arc::new(AtomicBool::new(false));
        let spawned = Arc::new(AtomicBool::new(false));

        let ctx_h = ctx.clone();
        let started = Arc::clone(&body_started);
        let dropped = Arc::clone(&body_dropped);
        let after_spawn = Arc::clone(&spawned);
        let handler = async move {
            // Hold this worker inside the root's poll until the test has
            // dropped the drive.
            in_poll_tx.send(()).expect("the test waits for this signal");
            resume_rx.recv().expect("the test resumes the root");
            let handle = ctx_h
                .step(move |_| {
                    let started = Arc::clone(&started);
                    let dropped = Arc::clone(&dropped);
                    async move {
                        struct G(Arc<AtomicBool>);
                        impl Drop for G {
                            fn drop(&mut self) {
                                self.0.store(true, Ordering::SeqCst);
                            }
                        }
                        let _g = G(dropped);
                        started.store(true, Ordering::SeqCst);
                        std::future::pending::<()>().await;
                        Ok(1i32)
                    }
                })
                .name("late")
                .spawn();
            drop(handle);
            after_spawn.store(true, Ordering::SeqCst);
            std::future::pending::<Result<String, crate::error::WireError>>().await
        };

        let mut drive = Box::pin(super::drive_invocation(
            handler,
            crate::task::TaskContext::none(),
            Arc::clone(ctx.task_ownership()),
            Arc::clone(&coordinator),
            ctx.clone(),
            None,
        ));
        // One poll spawns the root, which a worker then polls.
        std::future::poll_fn(|cx| {
            assert!(drive.as_mut().poll(cx).is_pending());
            std::task::Poll::Ready(())
        })
        .await;
        in_poll_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("the root is inside its poll");
        assert_eq!(coordinator.phase(), super::Phase::Running);
        assert!(!coordinator.tasks().is_closed());
        drop(drive);
        // The teardown refuses every later spawn, and aborts a task whose
        // spawn took its permit before that.
        assert_eq!(coordinator.phase(), super::Phase::Finished);
        assert!(coordinator.tasks().is_closed());
        resume_tx.send(()).expect("the root waits for this signal");

        tokio::time::timeout(Duration::from_secs(5), async {
            while !spawned.load(Ordering::SeqCst) {
                tokio::time::sleep(Duration::from_millis(5)).await;
            }
        })
        .await
        .expect("the root reaches its spawn after the drop");
        // Give a spawned task time to be polled, if it was started.
        tokio::time::sleep(Duration::from_millis(50)).await;
        tokio::time::timeout(Duration::from_secs(5), coordinator.tasks().wait_idle())
            .await
            .expect("no operation task outlives the dropped drive");
        assert_eq!(coordinator.tasks().live(), 0);
        assert!(
            !body_started.load(Ordering::SeqCst) || body_dropped.load(Ordering::SeqCst),
            "a late operation task that ran was aborted"
        );
    }
}

#[cfg(test)]
mod scoped_suspension {
    use super::InvocationOutcome;
    use super::test_support::drive_ok;
    use crate::client::{ExecutionClient, InMemoryExecutionClient};
    use crate::context::DurableContext;
    use crate::engine::CheckpointLog;
    use crate::future::Branch;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::time::Duration;

    fn live_ctx(client: Arc<InMemoryExecutionClient>) -> DurableContext {
        DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client as Arc<dyn ExecutionClient>,
            "token0".to_owned(),
        )
    }

    /// Counts `WaitStarted` checkpoints (each carries `wait_options`).
    fn wait_starts(client: &InMemoryExecutionClient) -> usize {
        client
            .recorded_updates()
            .iter()
            .filter(|u| u.wait_options().is_some())
            .count()
    }

    // 1. Branch A waits while branch B has runnable work: B COMPLETES before
    //    the invocation reports Pending.
    #[tokio::test]
    async fn sibling_with_runnable_work_completes_before_invocation_suspends() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let b_ran = Arc::new(AtomicBool::new(false));
        let b_ran_c = Arc::clone(&b_ran);
        let ctx_h = ctx.clone();

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let flag = b_ran_c;
                let branches = vec![
                    Branch::new("A-wait", |cc: DurableContext| {
                        Box::pin(async move {
                            cc.wait(Duration::from_secs(30)).await?;
                            Ok(0_i32)
                        })
                    }),
                    Branch::new("B-step", move |cc: DurableContext| {
                        Box::pin(async move {
                            let v = cc.step(|_| async { Ok(7_i32) }).await?;
                            flag.store(true, Ordering::SeqCst);
                            Ok(v)
                        })
                    }),
                ];
                let _ = ctx_h.parallel(branches).await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            b_ran.load(Ordering::SeqCst),
            "sibling B must complete its runnable work before the invocation suspends"
        );
    }

    // 2. Two branches suspend: Pending only after BOTH parked (both reached
    //    WaitStarted).
    #[tokio::test]
    async fn two_branches_suspend_pending_after_both_parked() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let ctx_h = ctx.clone();

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let branches = vec![
                    Branch::new("a", |cc: DurableContext| {
                        Box::pin(async move {
                            cc.wait(Duration::from_secs(30)).await?;
                            Ok(0_i32)
                        })
                    }),
                    Branch::new("b", |cc: DurableContext| {
                        Box::pin(async move {
                            cc.wait(Duration::from_secs(30)).await?;
                            Ok(0_i32)
                        })
                    }),
                ];
                let _ = ctx_h.parallel(branches).await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_eq!(
            wait_starts(&client),
            2,
            "both branches must checkpoint WaitStarted before the invocation suspends"
        );
    }

    // 3. A suspended branch retains its slot: with max_concurrency=2 and four
    //    waiting branches, peak concurrent bodies equals the cap (not 4), and
    //    only cap-many branches ever start.
    #[tokio::test]
    async fn suspended_branches_retain_slots_peak_bounded_by_cap() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let active = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let ctx_h = ctx.clone();
        let active_h = Arc::clone(&active);
        let peak_h = Arc::clone(&peak);

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let mut branches = Vec::new();
                for i in 0..4 {
                    let active = Arc::clone(&active_h);
                    let peak = Arc::clone(&peak_h);
                    branches.push(Branch::new(format!("w{i}"), move |cc: DurableContext| {
                        Box::pin(async move {
                            let cur = active.fetch_add(1, Ordering::SeqCst) + 1;
                            peak.fetch_max(cur, Ordering::SeqCst);
                            cc.wait(Duration::from_secs(30)).await?;
                            Ok(0_i32)
                        })
                    }));
                }
                let _ = ctx_h.parallel(branches).max_concurrency(2).await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_eq!(
            peak.load(Ordering::SeqCst),
            2,
            "peak concurrent branches must equal the cap — suspended branches hold their slots"
        );
        assert!(
            active.load(Ordering::SeqCst) <= 2,
            "no more than cap-many branches may enter while others hold suspended slots"
        );
        assert_eq!(
            wait_starts(&client),
            2,
            "only the two slot-holding branches start; the other two never do"
        );
    }

    // 4. An eligible unstarted branch STARTS once a terminal completion frees
    //    a slot (contrast with test 3, where suspended branches hold slots).
    #[tokio::test]
    async fn slot_freed_by_completion_lets_next_branch_start() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let second_ran = Arc::new(AtomicBool::new(false));
        let second_h = Arc::clone(&second_ran);
        let ctx_h = ctx.clone();

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let flag = second_h;
                let branches = vec![
                    Branch::new("first", |cc: DurableContext| async move {
                        let v = cc.step(|_| async { Ok(1_i32) }).await?;
                        Ok(v)
                    }),
                    Branch::new("second", move |cc: DurableContext| {
                        Box::pin(async move {
                            let v = cc.step(|_| async { Ok(2_i32) }).await?;
                            flag.store(true, Ordering::SeqCst);
                            Ok(v)
                        })
                    }),
                ];
                let r = ctx_h.parallel(branches).max_concurrency(1).await;
                Ok::<_, crate::error::WireError>(format!("{}", r.is_ok()))
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Complete("true".to_owned()));
        assert!(
            second_ran.load(Ordering::SeqCst),
            "second branch must start after the first frees its slot"
        );
    }

    // 5 + 8. Nested map/parallel/child suspension propagates through child
    //         scopes to the root and reaches Pending WITHOUT hanging.
    #[tokio::test]
    async fn nested_coordinator_suspension_propagates_to_root_without_hang() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let ctx_h = ctx.clone();

        let fut = drive_ok(
            ctx.clone(),
            async move {
                let outer = vec![Branch::new("outer", |cc: DurableContext| {
                    Box::pin(async move {
                        // A child context whose step feeds a nested map whose
                        // single item waits: exercises child + coordinator
                        // scope propagation in one branch.
                        let inner = vec![Branch::new("inner-wait", |icc: DurableContext| {
                            Box::pin(async move {
                                icc.wait(Duration::from_secs(30)).await?;
                                Ok(0_i32)
                            })
                        })];
                        cc.parallel(inner)
                            .await
                            .map(|v: Vec<i32>| v.into_iter().sum::<i32>())
                            .map_err(Into::into)
                    })
                })];
                let _ = ctx_h.parallel(outer).await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        );

        let outcome = tokio::time::timeout(Duration::from_secs(5), fut)
            .await
            .expect("nested suspension must reach Pending, not hang");
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_eq!(
            wait_starts(&client),
            1,
            "the innermost wait must checkpoint WaitStarted"
        );
    }

    // 6. Early-completion threshold (min_successful) excludes a parked branch:
    //    the batch completes and the invocation does NOT suspend.
    #[tokio::test]
    async fn min_successful_completion_excludes_parked_branch() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let ctx_h = ctx.clone();

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                let branches = vec![
                    Branch::new("ok", |cc: DurableContext| async move {
                        let v = cc.step(|_| async { Ok(1_i32) }).await?;
                        Ok(v)
                    }),
                    Branch::new("waiter", |cc: DurableContext| {
                        Box::pin(async move {
                            cc.wait(Duration::from_secs(30)).await?;
                            Ok(2_i32)
                        })
                    }),
                ];
                let r = ctx_h
                    .parallel(branches)
                    .completion(
                        crate::builders::map_parallel::CompletionConfig::builder()
                            .min_successful(1)
                            .build()
                            .expect("valid completion config"),
                    )
                    .await;
                Ok::<_, crate::error::WireError>(format!("ok={}", r.is_ok()))
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        // Threshold met by "ok" → batch completes; the parked "waiter" is
        // excluded and the invocation does NOT suspend.
        assert_eq!(outcome, InvocationOutcome::Complete("ok=true".to_owned()));
    }

    // 7. No regression: a ROOT-level wait suspends the invocation immediately
    //    and following code does not run.
    #[tokio::test]
    async fn root_level_wait_suspends_invocation_immediately() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let after = Arc::new(AtomicBool::new(false));
        let after_c = Arc::clone(&after);
        let ctx_h = ctx.clone();

        let outcome = drive_ok(
            ctx.clone(),
            async move {
                ctx_h.wait(Duration::from_secs(30)).await.map_err(|e| {
                    crate::error::WireError::new(Some("W".to_owned()), Some(e.to_string()))
                })?;
                after_c.store(true, Ordering::SeqCst);
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            Arc::clone(ctx.task_ownership()),
            signal,
        )
        .await;

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            !after.load(Ordering::SeqCst),
            "code after a root-level wait must not run"
        );
    }
}

//
// `.spawn()` used to let a waiting operation inside a top-level `.spawn()`
// suspend the invocation while a sibling spawned task was still running, which
// aborted the sibling after it had already checkpointed STARTED. The
// invocation coordinator now suspends only when no SDK work can make progress.
//
// These tests encode the CORRECT behaviour and run as part of `make check`.
#[cfg(test)]
mod spawn_scope_regressions {
    use super::InvocationOutcome;
    use super::test_support::drive_ok;
    use crate::client::{ExecutionClient, InMemoryExecutionClient};
    use crate::context::DurableContext;
    use crate::engine::CheckpointLog;
    use aws_sdk_lambda::types::OperationAction;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    /// Upper bound on either test: a suspension-scoping defect must show up as
    /// a FAILED assertion, never as a hung test run.
    const BOUND: Duration = Duration::from_secs(5);

    fn live_ctx(client: Arc<InMemoryExecutionClient>) -> DurableContext {
        DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client as Arc<dyn ExecutionClient>,
            "token0".to_owned(),
        )
    }

    /// True if the client recorded a terminal (Succeed) checkpoint for the
    /// operation named `name`.
    fn succeeded(client: &InMemoryExecutionClient, name: &str) -> bool {
        client
            .recorded_updates()
            .iter()
            .any(|u| matches!(u.action(), OperationAction::Succeed) && u.name() == Some(name))
    }

    /// `wait.spawn()` beside `step.spawn()`: the spawned wait parks, but the
    /// spawned step is still runnable, so the invocation must stay alive until
    /// the step reaches its terminal checkpoint and only then report Pending.
    #[tokio::test]
    async fn spawned_step_reaches_terminal_checkpoint_before_pending() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let body_done = Arc::new(AtomicBool::new(false));
        let done = Arc::clone(&body_done);
        let ctx_h = ctx.clone();

        let outcome = tokio::time::timeout(
            BOUND,
            drive_ok(
                ctx.clone(),
                async move {
                    // Parks: no timer result is available on a first invocation.
                    let wait = ctx_h.wait(Duration::from_secs(10)).spawn();
                    // Runnable, and slower than the wait's park so the ordering
                    // under test is deterministic.
                    let work = ctx_h
                        .step(move |_| {
                            let done = Arc::clone(&done);
                            async move {
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                done.store(true, Ordering::SeqCst);
                                Ok(7_i32)
                            }
                        })
                        .name("work")
                        .spawn();
                    let _ = work.await;
                    let _ = wait.await;
                    Ok::<_, crate::error::WireError>("done".to_owned())
                },
                Arc::clone(ctx.task_ownership()),
                signal,
            ),
        )
        .await
        .expect("drive_invocation must terminate within the bound, not hang");

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            body_done.load(Ordering::SeqCst),
            "the spawned step body must run to completion before the invocation \
             suspends; a parked spawned sibling must not abort it"
        );
        assert!(
            succeeded(&client, "work"),
            "the spawned step must reach its terminal Succeed checkpoint before \
             the invocation reports Pending; otherwise its STARTED checkpoint \
             re-executes the body on resume and duplicates side effects"
        );
    }

    /// The documented composition: `tokio::join!` over a spawned wait and a
    /// spawned step. Same guarantee as above, reached through `join!`.
    #[tokio::test]
    async fn joined_spawned_wait_and_step_lets_the_step_finish() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let body_done = Arc::new(AtomicBool::new(false));
        let done = Arc::clone(&body_done);
        let ctx_h = ctx.clone();

        let outcome = tokio::time::timeout(
            BOUND,
            drive_ok(
                ctx.clone(),
                async move {
                    let wait = ctx_h.wait(Duration::from_secs(10)).spawn();
                    let work = ctx_h
                        .step(move |_| {
                            let done = Arc::clone(&done);
                            async move {
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                done.store(true, Ordering::SeqCst);
                                Ok(7_i32)
                            }
                        })
                        .name("work")
                        .spawn();
                    let (_timer, _result) = tokio::join!(wait, work);
                    Ok::<_, crate::error::WireError>("done".to_owned())
                },
                Arc::clone(ctx.task_ownership()),
                signal,
            ),
        )
        .await
        .expect("drive_invocation must terminate within the bound, not hang");

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            body_done.load(Ordering::SeqCst),
            "join! over a spawned wait and a spawned step must not abort the step"
        );
        assert!(
            succeeded(&client, "work"),
            "the joined spawned step must reach its terminal Succeed checkpoint \
             before the invocation reports Pending"
        );
    }

    /// A spawned wait waits, then the owner performs a non-spawned sequential
    /// step. The sequential step must complete and checkpoint Succeed. The
    /// handler then resolves, so the invocation completes with its result
    /// while the dropped wait's record stays `STARTED`.
    #[tokio::test]
    async fn spawned_wait_parks_then_owner_does_sequential_step() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let step_done = Arc::new(AtomicBool::new(false));
        let done = Arc::clone(&step_done);
        let ctx_h = ctx.clone();

        let outcome = tokio::time::timeout(
            BOUND,
            drive_ok(
                ctx.clone(),
                async move {
                    // Spawn a wait: it parks immediately (no timer result on
                    // first invocation). Hold the handle so dropping it
                    // does not abort the task, but never await it.
                    let _wait = ctx_h.wait(Duration::from_secs(10)).spawn();

                    // Yield once so the spawned wait task has a chance to run
                    // and register its wait. The yield runs under a held
                    // activity permit: a bare yield while an operation waits
                    // is a point where the invocation may suspend.
                    ctx_h.hold_activity(tokio::task::yield_now()).await;

                    // Now do a NON-SPAWNED sequential step. If the spawned
                    // wait already flagged ROOT, the driver will drop us here.
                    let _result = ctx_h
                        .step(move |_| {
                            let done = Arc::clone(&done);
                            async move {
                                done.store(true, Ordering::SeqCst);
                                Ok(42_i32)
                            }
                        })
                        .name("sequential_work")
                        .await;

                    // Handler completes normally: the invocation completes
                    // with its result.
                    Ok::<_, crate::error::WireError>("done".to_owned())
                },
                Arc::clone(ctx.task_ownership()),
                signal,
            ),
        )
        .await
        .expect("drive_invocation must terminate within the bound, not hang");

        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert!(
            step_done.load(Ordering::SeqCst),
            "the non-spawned step must complete before Pending; a parked spawn \
             must not pre-empt the owner's sequential work"
        );
        assert!(
            succeeded(&client, "sequential_work"),
            "the sequential step must reach its terminal Succeed checkpoint \
             before the invocation reports Pending"
        );
    }

    /// A spawned `try_join_all` containing a waiting wait input beside a
    /// runnable step sibling. The combinator is itself spawned. The waiting
    /// input keeps the combinator pending, the runnable sibling spawned
    /// alongside must still complete, and only then does the invocation
    /// suspend, without a deadlock.
    #[tokio::test]
    async fn spawned_combinator_with_parking_input_does_not_deadlock() {
        let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
        let ctx = live_ctx(Arc::clone(&client));
        let signal = Arc::clone(ctx.coordinator());
        let sibling_done = Arc::new(AtomicBool::new(false));
        let done = Arc::clone(&sibling_done);
        let ctx_h = ctx.clone();

        let outcome = tokio::time::timeout(
            BOUND,
            drive_ok(
                ctx.clone(),
                async move {
                    // Parking input: a spawned wait (will park on first
                    // invocation since no timer has elapsed).
                    let parking_wait = ctx_h.wait(Duration::from_mins(1)).spawn();
                    // The combinator contains the parking input alongside a
                    // step that resolves immediately.
                    let instant_step = ctx_h.step(|_| async { Ok(()) }).name("inner").future();
                    // Spawn the combinator: this registers the combinator on
                    // root scope. The defect made the parking input also park
                    // root, causing a deadlock.
                    let combo = ctx_h.try_join_all([parking_wait, instant_step]).spawn();

                    // Runnable sibling spawned on root beside the combinator.
                    let sibling = ctx_h
                        .step(move |_| {
                            let d = Arc::clone(&done);
                            async move {
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                d.store(true, Ordering::SeqCst);
                                Ok(42_i32)
                            }
                        })
                        .name("sibling")
                        .spawn();

                    let _ = tokio::join!(combo, sibling);
                    Ok::<_, crate::error::WireError>("done".to_owned())
                },
                Arc::clone(ctx.task_ownership()),
                signal,
            ),
        )
        .await
        .expect(
            "drive_invocation must terminate within the bound; \
             a deadlock from the spawned combinator defect would hang here",
        );

        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            sibling_done.load(Ordering::SeqCst),
            "the runnable sibling must complete before the invocation \
             suspends; the combinator's suspension must not abort it"
        );
        assert!(
            succeeded(&client, "sibling"),
            "the sibling must reach its terminal Succeed checkpoint \
             before the invocation reports Pending"
        );
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: the handler panics under test and test assertions
mod task_gateway {
    use super::{InvocationOutcome, drive_outcome};
    use crate::client::{ExecutionClient, InMemoryExecutionClient};
    use crate::context::DurableContext;
    use crate::engine::CheckpointLog;
    use crate::future::DurableFuture;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    fn live_ctx() -> DurableContext {
        DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::new(InMemoryExecutionClient::new(Vec::new())) as Arc<dyn ExecutionClient>,
            "token0".to_owned(),
        )
    }

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

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

    /// Spawns a step whose body holds a drop guard and awaits `pending()`.
    fn spawn_holding_step(ctx: &DurableContext, dropped: &Arc<AtomicBool>) -> DurableFuture<()> {
        let dropped = Arc::clone(dropped);
        ctx.step(move |_| {
            let dropped = Arc::clone(&dropped);
            async move {
                let _guard = DropFlag(dropped);
                std::future::pending::<()>().await;
                Ok(())
            }
        })
        .name("hold")
        .spawn()
    }

    async fn yield_three_times() {
        for _ in 0..3 {
            tokio::task::yield_now().await;
        }
    }

    /// A spawned step body still mid-await when the handler resolves is
    /// dropped by the drive's cleanup before `drive_invocation` returns, and
    /// the invocation completes with the handler's result.
    #[tokio::test]
    async fn aborted_spawned_body_drops_before_invocation_returns() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let dropped = Arc::new(AtomicBool::new(false));
        let handler_dropped = Arc::clone(&dropped);
        let outcome = drive_outcome(
            async move {
                let _wait = ctx.wait(Duration::from_secs(10)).name("timer").spawn();
                let _step = spawn_holding_step(&ctx, &handler_dropped);
                yield_three_times().await;
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            ownership,
            signal,
            root,
            None,
        )
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert!(
            dropped.load(Ordering::SeqCst),
            "the step body must be dropped before the invocation returns"
        );
    }

    /// A handler panic returns its payload only after every tracked task
    /// has unwound.
    #[tokio::test]
    async fn handler_panic_returns_payload_after_cleanup() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let dropped = Arc::new(AtomicBool::new(false));
        let handler_dropped = Arc::clone(&dropped);
        let outcome = drive_outcome(
            async move {
                let _step = spawn_holding_step(&ctx, &handler_dropped);
                yield_three_times().await;
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        let Err(payload) = outcome else {
            panic!("expected the handler panic, got {outcome:?}");
        };
        assert_eq!(payload.downcast_ref::<&str>(), Some(&"handler boom"));
        assert!(dropped.load(Ordering::SeqCst), "the step body was dropped");
        assert_eq!(tasks.live(), 0);
    }

    /// After a handler panic, the driver also aborts a task whose handle
    /// the handler moved out of its own future.
    #[tokio::test]
    async fn handler_panic_aborts_task_whose_handle_left_the_handler() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let dropped = Arc::new(AtomicBool::new(false));
        let handler_dropped = Arc::clone(&dropped);
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let handler_escaped = Arc::clone(&escaped);
        let outcome = drive_outcome(
            async move {
                let step = spawn_holding_step(&ctx, &handler_dropped);
                *handler_escaped.lock().expect("lock") = Some(step);
                yield_three_times().await;
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        assert!(outcome.is_err(), "expected the handler panic");
        assert!(
            escaped.lock().expect("lock").is_some(),
            "the test still holds the handle"
        );
        assert!(dropped.load(Ordering::SeqCst), "the step body was dropped");
        assert_eq!(tasks.live(), 0);
    }

    /// A handler that panics while a `.spawn()`ed wait is registered returns
    /// the panic payload, not `Pending`.
    #[tokio::test]
    async fn handler_panic_with_parked_spawn_returns_payload() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let parked_signal = Arc::clone(&signal);
        let outcome = drive_outcome(
            async move {
                let _wait = ctx.wait(Duration::from_secs(10)).name("timer").spawn();
                // Held activity keeps the handler runnable while it waits
                // for the registration.
                ctx.hold_activity(async {
                    for _ in 0..1000 {
                        if parked_signal.live_waits() == 1 {
                            break;
                        }
                        tokio::task::yield_now().await;
                    }
                })
                .await;
                assert_eq!(parked_signal.live_waits(), 1, "the wait is registered");
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        let Err(payload) = outcome else {
            panic!("expected the handler panic, got {outcome:?}");
        };
        assert_eq!(payload.downcast_ref::<&str>(), Some(&"handler boom"));
        assert_eq!(tasks.live(), 0);
    }

    /// A handler that panics while a wait registration is live returns the
    /// panic payload.
    #[tokio::test]
    async fn handler_panic_after_suspend_request_returns_payload() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let handler_signal = Arc::clone(&signal);
        let outcome = drive_outcome(
            async move {
                let _ctx = ctx;
                let _registration =
                    handler_signal.register_test_wait("op", std::task::Waker::noop());
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        let Err(payload) = outcome else {
            panic!("expected the handler panic, got {outcome:?}");
        };
        assert_eq!(payload.downcast_ref::<&str>(), Some(&"handler boom"));
        assert_eq!(tasks.live(), 0);
    }

    /// A recorded fatal error takes precedence over a handler panic.
    #[tokio::test]
    async fn fatal_error_wins_over_handler_panic() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let handler_signal = Arc::clone(&signal);
        let outcome = drive_outcome(
            async move {
                let _ctx = ctx;
                handler_signal.record_fatal("Fatal".to_owned(), "mismatch".to_owned());
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await
        .expect("the fatal error takes precedence over the panic");
        assert_eq!(
            outcome,
            InvocationOutcome::Failed {
                error: crate::error::WireError::new(
                    Some("Fatal".to_owned()),
                    Some("mismatch".to_owned()),
                ),
            }
        );
    }

    /// Panics with an [`InnerPanicPayload`] when dropped.
    pub(super) struct NestedPanicPayload;

    impl Drop for NestedPanicPayload {
        fn drop(&mut self) {
            std::panic::panic_any(InnerPanicPayload);
        }
    }

    /// Panics when dropped.
    pub(super) struct InnerPanicPayload;

    impl Drop for InnerPanicPayload {
        fn drop(&mut self) {
            panic!("inner payload drop");
        }
    }

    /// Records a fatal error on the invocation's coordinator when it is
    /// dropped.
    struct FatalOnDrop(Arc<crate::coordinator::InvocationCoordinator>);

    impl Drop for FatalOnDrop {
        fn drop(&mut self) {
            self.0
                .record_fatal("Fatal".to_owned(), "mismatch during cleanup".to_owned());
        }
    }

    /// A fatal error that a tracked task records while the driver cleans up
    /// after a handler panic still takes precedence over that panic. The
    /// handler moves the step's handle out of its own future, so only the
    /// driver's `abort_all` drops the step body, after the drive observed
    /// the panic. Dropping the body records the fatal error.
    #[tokio::test(flavor = "current_thread")]
    async fn fatal_recorded_during_panic_cleanup_wins_over_panic() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let body_signal = Arc::clone(&signal);
        let started = Arc::new(AtomicBool::new(false));
        let body_started = Arc::clone(&started);
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let handler_escaped = Arc::clone(&escaped);
        let check_signal = Arc::clone(&signal);
        let outcome = drive_outcome(
            async move {
                let step = ctx
                    .step(move |_| {
                        let guard = FatalOnDrop(Arc::clone(&body_signal));
                        let started = Arc::clone(&body_started);
                        async move {
                            let _guard = guard;
                            started.store(true, Ordering::SeqCst);
                            std::future::pending::<()>().await;
                            Ok(())
                        }
                    })
                    .name("hold")
                    .spawn();
                *handler_escaped.lock().expect("lock") = Some(step);
                yield_three_times().await;
                assert!(check_signal.fatal_error().is_none(), "no fatal yet");
                panic!("handler boom");
            },
            ownership,
            signal,
            root,
            None,
        )
        .await
        .expect("the fatal error recorded during cleanup takes precedence over the panic");
        assert!(started.load(Ordering::SeqCst), "the step body started");
        assert_eq!(
            outcome,
            InvocationOutcome::Failed {
                error: crate::error::WireError::new(
                    Some("Fatal".to_owned()),
                    Some("mismatch during cleanup".to_owned()),
                ),
            }
        );
        assert_eq!(tasks.live(), 0);
    }

    /// Runs its closure on the invocation's coordinator when it is dropped.
    struct OnDrop(
        Arc<crate::coordinator::InvocationCoordinator>,
        Arc<dyn Fn(&crate::coordinator::InvocationCoordinator) + Send + Sync>,
    );

    impl Drop for OnDrop {
        fn drop(&mut self) {
            (self.1)(&self.0);
        }
    }

    /// Drives a handler that panics with a [`NestedPanicPayload`] while a
    /// step body holds an [`OnDrop`] running `on_cleanup`. Only the
    /// driver's `abort_all` drops the body, after the drive observed the
    /// handler panic, as in `fatal_recorded_during_panic_cleanup_wins_over_panic`.
    async fn drive_nested_handler_panic_with_cleanup(
        on_cleanup: Arc<dyn Fn(&crate::coordinator::InvocationCoordinator) + Send + Sync>,
    ) -> (
        Result<InvocationOutcome, Box<dyn std::any::Any + Send + 'static>>,
        usize,
    ) {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let body_signal = Arc::clone(&signal);
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let handler_escaped = Arc::clone(&escaped);
        let outcome = drive_outcome(
            async move {
                let step = ctx
                    .step(move |_| {
                        let guard = OnDrop(Arc::clone(&body_signal), Arc::clone(&on_cleanup));
                        async move {
                            let _guard = guard;
                            std::future::pending::<()>().await;
                            Ok(())
                        }
                    })
                    .name("hold")
                    .spawn();
                *handler_escaped.lock().expect("lock") = Some(step);
                yield_three_times().await;
                std::panic::panic_any(NestedPanicPayload);
            },
            ownership,
            signal,
            root,
            None,
        )
        .await;
        (outcome, tasks.live())
    }

    /// A fatal error recorded during the cleanup takes precedence over a
    /// handler panic whose payload panics on drop with a payload that
    /// panics on drop again. The driver drops the handler's payload inside
    /// a catch and leaks the nested payload, so no panic escapes.
    #[tokio::test(flavor = "current_thread")]
    async fn fatal_during_cleanup_wins_over_nested_panicking_handler_payload() {
        let (outcome, live) = drive_nested_handler_panic_with_cleanup(Arc::new(|coordinator| {
            coordinator.record_fatal("Fatal".to_owned(), "during cleanup".to_owned());
        }))
        .await;
        let Ok(InvocationOutcome::Failed { error }) = &outcome else {
            panic!("expected the fatal outcome, got {outcome:?}");
        };
        assert_eq!(error.error_message(), Some("during cleanup"));
        assert_eq!(live, 0);
    }

    /// A handler that returns a value while a wait registration is live
    /// completes with that value: the resolved handler decides the outcome.
    #[tokio::test]
    async fn handler_value_with_live_registration_completes() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let handler_signal = Arc::clone(&signal);
        let outcome = drive_outcome(
            async move {
                let _ctx = ctx;
                let _registration =
                    handler_signal.register_test_wait("op", std::task::Waker::noop());
                Ok::<_, crate::error::WireError>("done".to_owned())
            },
            ownership,
            signal,
            root,
            None,
        )
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
    }

    /// The handler runs on a blessed task of its own, and its blessing is
    /// removed once the drive ends.
    #[tokio::test]
    async fn handler_runs_as_blessed_operation_task() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let outcome = drive_outcome(
            async move {
                let on_task = tokio::task::try_id().is_some();
                let value = ctx
                    .step(|_| async { Ok(1_i32) })
                    .name("s")
                    .await
                    .map_err(|e| {
                        crate::error::WireError::new(None::<String>, Some(e.to_string()))
                    })?;
                Ok::<_, crate::error::WireError>(format!("{on_task}:{value}"))
            },
            Arc::clone(&ownership),
            signal,
            root,
            None,
        )
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("true:1".to_owned()));
        assert_eq!(ownership.blessed_count(), 0);
    }

    /// The root task is not counted on the tracker, so a handler that waits
    /// for idle does not wait for itself.
    #[tokio::test]
    async fn wait_idle_in_handler_does_not_wait_for_handler() {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let signal = Arc::clone(ctx.coordinator());
        let root = ctx.clone();
        let tasks = Arc::clone(signal.tasks());
        let outcome = drive_outcome(
            async move {
                let step = ctx.step(|_| async { Ok(1_i32) }).name("quick").spawn();
                let _ = step.await;
                let idle = tokio::time::timeout(Duration::from_secs(1), tasks.wait_idle()).await;
                Ok::<_, crate::error::WireError>(idle.is_ok().to_string())
            },
            ownership,
            signal,
            root,
            None,
        )
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("true".to_owned()));
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: test assertions
mod coordinator_suspension {
    use super::test_support::{
        EventMessages, ScriptedClient, drive_handler, named, operation_like, scripted_ctx, wire_err,
    };
    use super::{InvocationOutcome, UNTRACKED_DEADLINE_WARNING};
    use crate::coordinator::{PermitKind, Phase};
    use crate::engine::CheckpointStatus;
    use aws_sdk_lambda::types::{OperationAction, OperationStatus};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::time::Duration;

    /// Waits, inside the handler's held activity, until `condition` holds,
    /// polling every 10 ms of tokio time, at most 1,000 times.
    async fn until(ctx: &crate::DurableContext, condition: impl Fn() -> bool) -> bool {
        ctx.hold_activity(async {
            for _ in 0..1000 {
                if condition() {
                    return true;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            false
        })
        .await
    }

    /// A client that, on the call carrying the step named `step`'s SUCCEED,
    /// also carries the operation named `waiting` with `status`.
    fn completes_on_step_succeed(
        step: &'static str,
        waiting: &'static str,
        status: OperationStatus,
    ) -> ScriptedClient {
        ScriptedClient::new(move |updates, history| {
            if named(updates, step, &OperationAction::Succeed).is_none() {
                return Vec::new();
            }
            named(history, waiting, &OperationAction::Start)
                .map(|start| {
                    operation_like(start, status.clone())
                        .build()
                        .expect("all required fields set")
                })
                .into_iter()
                .collect()
        })
    }

    /// A step body that returns once the client received the START of the
    /// operation named `waiting`, so the response that completes it comes
    /// after its registration.
    async fn after_start_of(
        client: &Arc<ScriptedClient>,
        waiting: &str,
    ) -> Result<u32, crate::BoxError> {
        for _ in 0..1000 {
            if client.received(waiting, &OperationAction::Start) {
                return Ok(2);
            }
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
        Err("the waiting operation never started".into())
    }

    #[tokio::test(start_paused = true)]
    async fn lone_wait_suspends_at_once() {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            ctx.wait(Duration::from_secs(1)).await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_eq!(client.call_count(), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn untracked_await_does_not_suspend_and_warns() {
        let (capture, _guard) = EventMessages::install();
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let drive = drive_handler(ctx, Some(Duration::from_secs(2)), |_ctx| async move {
            tokio::time::sleep(Duration::from_secs(3600)).await;
            Ok("done".to_owned())
        });
        let timed = tokio::time::timeout(Duration::from_secs(5), drive).await;
        assert!(timed.is_err(), "the untracked await does not suspend");
        assert_eq!(
            capture.at(tracing::Level::WARN),
            vec![UNTRACKED_DEADLINE_WARNING.to_owned()]
        );
    }

    /// A deadline that passes while SDK work runs logs nothing.
    #[tokio::test(start_paused = true)]
    async fn deadline_during_tracked_work_does_not_warn() {
        let (capture, _guard) = EventMessages::install();
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let outcome = drive_handler(ctx, Some(Duration::from_secs(1)), |ctx| async move {
            ctx.step(|_| async {
                tokio::time::sleep(Duration::from_secs(2)).await;
                Ok(1_u32)
            })
            .await
            .map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_eq!(capture.at(tracing::Level::WARN), Vec::<String>::new());
    }

    #[tokio::test(start_paused = true)]
    async fn sibling_response_completes_wait_in_invocation() {
        let (events, _guard) = EventMessages::install();
        let client = Arc::new(completes_on_step_succeed(
            "s",
            "w",
            OperationStatus::Succeeded,
        ));
        let ctx = scripted_ctx(&client);
        let body_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(1)).name("w").spawn();
            ctx.step(move |_| async move { after_start_of(&body_client, "w").await })
                .name("s")
                .await
                .map_err(wire_err)?;
            w.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_eq!(events.replayed(), 0, "a resumed wait emits no replay event");
    }

    #[tokio::test(start_paused = true)]
    async fn buffered_checkpoint_holds_permit_until_merged() {
        let client = Arc::new(completes_on_step_succeed(
            "s",
            "w",
            OperationStatus::Succeeded,
        ));
        let ctx = crate::DurableContext::new_root_with_client_and_coalescer(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(crate::engine::CheckpointLog::empty()),
            Arc::clone(&client) as Arc<dyn crate::client::ExecutionClient>,
            "t0".to_owned(),
            crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::from_millis(50)),
        );
        let body_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(1)).name("w").spawn();
            ctx.step(move |_| async move { after_start_of(&body_client, "w").await })
                .name("s")
                .await
                .map_err(wire_err)?;
            w.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
    }

    /// A root context on `client` whose writes wait out a coalescing window
    /// of one hour, with `log` as the checkpoint log.
    fn hour_window_ctx(
        client: &Arc<ScriptedClient>,
        log: crate::engine::CheckpointLog,
    ) -> crate::DurableContext {
        crate::DurableContext::new_root_with_client_and_coalescer(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(log),
            Arc::clone(client) as Arc<dyn crate::client::ExecutionClient>,
            "t0".to_owned(),
            crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::from_secs(3600)),
        )
    }

    #[tokio::test(start_paused = true)]
    async fn completion_preempts_window_of_dropped_contributor() {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = hour_window_ctx(&client, crate::engine::CheckpointLog::empty());
        let coordinator = Arc::clone(ctx.coordinator());
        let started = tokio::time::Instant::now();
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(10)).name("w").spawn();
            let buffered = ctx
                .hold_activity(async {
                    for _ in 0..1000 {
                        if ctx.coordinator().permits(PermitKind::Checkpoint) == 1 {
                            return true;
                        }
                        tokio::task::yield_now().await;
                    }
                    false
                })
                .await;
            if !buffered {
                return Err(crate::error::WireError::new(
                    None::<String>,
                    Some("the START of w was never buffered"),
                ));
            }
            drop(w);
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert!(
            started.elapsed() < Duration::from_secs(60),
            "completion waited {:?} of the window",
            started.elapsed()
        );
        assert!(
            client.received("w", &OperationAction::Start),
            "the buffered START is flushed"
        );
        assert_eq!(coordinator.tasks().live(), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn waiting_operation_preempts_window() {
        let client = Arc::new(ScriptedClient::empty());
        let wait_id = crate::engine::compute_wire_id_public("1");
        let log = crate::engine::CheckpointLog::from_records(vec![(
            wait_id.clone(),
            crate::engine::CheckpointRecord::with_status(&wait_id, CheckpointStatus::Started),
        )]);
        let ctx = hour_window_ctx(&client, log);
        let started = tokio::time::Instant::now();
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(10)).name("w").spawn();
            ctx.step(|_| async { Ok(1_u32) })
                .name("s")
                .await
                .map_err(wire_err)?;
            w.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            started.elapsed() < Duration::from_secs(60),
            "the step's writes waited {:?} of the window",
            started.elapsed()
        );
        assert!(client.received("s", &OperationAction::Succeed));
    }

    #[tokio::test(start_paused = true)]
    async fn wait_resumed_maps_terminal_status() {
        let client = Arc::new(completes_on_step_succeed("s", "w", OperationStatus::Failed));
        let ctx = scripted_ctx(&client);
        let body_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(1)).name("w").spawn();
            ctx.step(move |_| async move { after_start_of(&body_client, "w").await })
                .name("s")
                .await
                .map_err(wire_err)?;
            let err = w.await.expect_err("the wait record failed");
            let crate::error::OperationErrorKind::Wait(wait_err) = err.kind() else {
                panic!("expected a wait error, got {err:?}");
            };
            let crate::error::WaitErrorKind::UnexpectedStatus(status) = wait_err.kind();
            Ok(status.status().to_owned())
        })
        .await
        .expect("the handler does not panic");
        assert_eq!(outcome, InvocationOutcome::Complete("FAILED".to_owned()));
    }

    #[tokio::test(start_paused = true)]
    async fn resolved_handler_completes_with_dropped_spawned_wait() {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let handler_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(Duration::from_secs(10)).name("w").spawn();
            let registered = ctx
                .hold_activity(async {
                    for _ in 0..1000 {
                        if handler_client.received("w", &OperationAction::Start)
                            && ctx.coordinator().live_waits() == 1
                        {
                            return true;
                        }
                        tokio::task::yield_now().await;
                    }
                    false
                })
                .await;
            if !registered {
                return Err(crate::error::WireError::new(
                    None::<String>,
                    Some("the wait never registered"),
                ));
            }
            // The dropped wait keeps waiting until the drive ends, which
            // stops it. The handler's result decides the outcome.
            drop(w);
            Ok(serde_json::to_string("done").expect("a string serializes"))
        })
        .await;
        assert!(
            matches!(&outcome, Ok(InvocationOutcome::Complete(v)) if v == "\"done\""),
            "unexpected outcome: {outcome:?}"
        );
        let w_updates: Vec<_> = client
            .updates()
            .into_iter()
            .filter(|u| u.name() == Some("w"))
            .collect();
        assert_eq!(w_updates.len(), 1, "only the START of w was written");
        assert_eq!(
            w_updates
                .first()
                .map(aws_sdk_lambda::types::OperationUpdate::action),
            Some(&OperationAction::Start)
        );
        assert_eq!(coordinator.tasks().live(), 0);
        assert_eq!(coordinator.live_waits(), 0);
    }

    /// The coordinator's counts after a drive: no task, permit or wait
    /// registration remains.
    fn assert_clean(coordinator: &crate::coordinator::InvocationCoordinator) {
        assert_eq!(coordinator.permits(PermitKind::Activity), 0);
        assert_eq!(coordinator.permits(PermitKind::Checkpoint), 0);
        assert_eq!(coordinator.live_waits(), 0);
        assert_eq!(coordinator.tasks().live(), 0);
    }

    /// Spawns a wait of an hour and a step whose body never returns.
    fn spawn_wait_and_stuck_step(
        ctx: &crate::DurableContext,
    ) -> (crate::DurableFuture<()>, crate::DurableFuture<()>) {
        let wait = ctx.wait(Duration::from_secs(3600)).name("w").spawn();
        let step = ctx
            .step(|_| async {
                std::future::pending::<()>().await;
                Ok(())
            })
            .name("stuck")
            .spawn();
        (wait, step)
    }

    #[tokio::test(start_paused = true)]
    async fn invocation_end_leaves_no_task_permit_or_registration() {
        // (a) The handler returns Ok.
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let _ops = spawn_wait_and_stuck_step(&ctx);
            ctx.hold_activity(tokio::time::sleep(Duration::from_millis(10)))
                .await;
            Ok("a".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("a".to_owned()));
        assert_clean(&coordinator);

        // (b) The handler drops both handles and returns Ok. The detached
        // step and wait keep running until the drive ends, which stops
        // them.
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            drop(spawn_wait_and_stuck_step(&ctx));
            ctx.hold_activity(tokio::time::sleep(Duration::from_millis(10)))
                .await;
            Ok("b".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("b".to_owned()));
        assert_clean(&coordinator);

        // (c) The handler returns Err.
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let _ops = spawn_wait_and_stuck_step(&ctx);
            ctx.hold_activity(tokio::time::sleep(Duration::from_millis(10)))
                .await;
            Err(crate::error::WireError::new(Some("E"), Some("c")))
        })
        .await
        .expect("no panic");
        assert!(matches!(outcome, InvocationOutcome::Failed { .. }));
        assert_clean(&coordinator);

        // (d) The handler panics.
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let _ops = spawn_wait_and_stuck_step(&ctx);
            ctx.hold_activity(tokio::time::sleep(Duration::from_millis(10)))
                .await;
            panic!("d");
        })
        .await;
        let Err(payload) = outcome else {
            panic!("expected the handler panic, got {outcome:?}");
        };
        assert_eq!(payload.downcast_ref::<&str>(), Some(&"d"));
        assert_clean(&coordinator);
    }

    #[tokio::test(start_paused = true)]
    async fn unawaited_finished_spawn_does_not_block_suspension() {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let start = tokio::time::Instant::now();
        let handler_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, Some(Duration::from_mins(15)), |ctx| async move {
            let _h = ctx.step(|_| async { Ok(1_u32) }).name("h").spawn();
            let tasks = Arc::clone(ctx.coordinator().tasks());
            let exited = until(&ctx, || {
                handler_client.received("h", &OperationAction::Succeed) && tasks.live() == 0
            })
            .await;
            if !exited {
                return Err(crate::error::WireError::new(
                    None::<String>,
                    Some("h never ended"),
                ));
            }
            ctx.wait(Duration::from_secs(3600))
                .await
                .map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert!(
            start.elapsed() < Duration::from_secs(60),
            "the invocation suspended at once, not at the deadline"
        );
    }

    #[test]
    fn exhausted_budget_does_not_suspend_runnable_handler() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        runtime.block_on(async {
            let client = Arc::new(ScriptedClient::empty());
            let ctx = scripted_ctx(&client);
            let outcome = drive_handler(ctx, None, |ctx| async move {
                let _wait = ctx.wait(Duration::from_secs(3600)).name("w").spawn();
                let coordinator = Arc::clone(ctx.coordinator());
                let registered = until(&ctx, || coordinator.live_waits() == 1).await;
                if !registered {
                    return Err(crate::error::WireError::new(
                        None::<String>,
                        Some("no wait"),
                    ));
                }
                let sibling = ctx.step(|_| async { Ok(1_u32) }).name("sibling").spawn();
                let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<u32>();
                for value in 0..20_000 {
                    tx.send(value).expect("the receiver is alive");
                }
                drop(tx);
                let mut received = 0_u32;
                while rx.recv().await.is_some() {
                    received += 1;
                }
                sibling.await.map_err(wire_err)?;
                ctx.step(|_| async { Ok(2_u32) })
                    .name("after")
                    .await
                    .map_err(wire_err)?;
                Ok(received.to_string())
            })
            .await
            .expect("no panic");
            assert_eq!(outcome, InvocationOutcome::Complete("20000".to_owned()));
            assert!(client.received("after", &OperationAction::Succeed));
        });
    }

    #[tokio::test(start_paused = true)]
    async fn detached_write_in_flight_at_finish_completes() {
        let client = Arc::new(
            ScriptedClient::new(|updates, _| {
                named(updates, "quick", &OperationAction::Succeed)
                    .map(|succeed| {
                        operation_like(succeed, OperationStatus::Succeeded)
                            .build()
                            .expect("all required fields set")
                    })
                    .into_iter()
                    .collect()
            })
            .with_delay(Duration::from_millis(500)),
        );
        let ctx = scripted_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let log_ctx = ctx.clone();
        let handler_client = Arc::clone(&client);
        let start = tokio::time::Instant::now();
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let h = ctx.step(|_| async { Ok(1_u32) }).name("quick").spawn();
            let sent = until(&ctx, || {
                handler_client.received("quick", &OperationAction::Succeed)
            })
            .await;
            if !sent {
                return Err(crate::error::WireError::new(
                    None::<String>,
                    Some("no SUCCEED"),
                ));
            }
            drop(h);
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert!(start.elapsed() >= Duration::from_millis(500));
        assert_eq!(
            log_ctx.checkpoint_status_view("1").map(|v| v.status),
            Some(CheckpointStatus::Succeeded),
            "the in-flight write's response was merged"
        );
        assert_eq!(coordinator.tasks().live(), 0);
    }

    /// Runs the scenario of `root_yield_now_is_a_boundary_on_every_runtime`
    /// once and returns its outcome and whether `after` ran.
    async fn yield_with_live_wait() -> (InvocationOutcome, bool) {
        let client = Arc::new(ScriptedClient::empty());
        let ctx = scripted_ctx(&client);
        let after_ran = Arc::new(AtomicBool::new(false));
        let handler_ran = Arc::clone(&after_ran);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let _wait = ctx.wait(Duration::from_secs(3600)).name("w").spawn();
            let coordinator = Arc::clone(ctx.coordinator());
            let ready = ctx
                .hold_activity(async {
                    for _ in 0..10_000 {
                        if coordinator.live_waits() == 1
                            && coordinator.permits(PermitKind::Activity) == 2
                            && coordinator.permits(PermitKind::Checkpoint) == 0
                        {
                            return true;
                        }
                        tokio::task::yield_now().await;
                    }
                    false
                })
                .await;
            if !ready {
                return Err(crate::error::WireError::new(
                    None::<String>,
                    Some("not ready"),
                ));
            }
            tokio::task::yield_now().await;
            ctx.step(move |_| async move {
                handler_ran.store(true, Ordering::SeqCst);
                Ok(1_u32)
            })
            .name("after")
            .await
            .map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        (outcome, after_ran.load(Ordering::SeqCst))
    }

    #[test]
    fn root_yield_now_is_a_boundary_on_every_runtime() {
        let current = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let multi = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(4)
            .enable_all()
            .build()
            .expect("runtime");
        for _ in 0..100 {
            let (outcome, after_ran) = current.block_on(yield_with_live_wait());
            assert_eq!(
                outcome,
                InvocationOutcome::Pending,
                "current-thread runtime"
            );
            assert!(!after_ran, "current-thread runtime");

            let (outcome, after_ran) = multi.block_on(yield_with_live_wait());
            assert_eq!(outcome, InvocationOutcome::Pending, "multi-thread block_on");
            assert!(!after_ran, "multi-thread block_on");

            let (outcome, after_ran) = multi
                .block_on(async { spawned(yield_with_live_wait()).await })
                .expect("the spawned scenario does not panic");
            assert_eq!(outcome, InvocationOutcome::Pending, "multi-thread task");
            assert!(!after_ran, "multi-thread task");
        }
    }

    /// Runs `future` on its own tokio task.
    #[expect(clippy::disallowed_methods)]
    // reason: the scenario must run on a task of the multi-thread runtime,
    // outside the SDK's gateway.
    fn spawned<F>(future: F) -> tokio::task::JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        tokio::spawn(future)
    }

    #[tokio::test(start_paused = true)]
    async fn phase_is_finished_after_every_drive() {
        let ctx = scripted_ctx(&Arc::new(ScriptedClient::empty()));
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |_ctx| async move { Ok("done".to_owned()) })
            .await
            .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_eq!(coordinator.phase(), Phase::Finished);
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: test assertions
mod refresh_scheduler {
    use super::InvocationOutcome;
    use super::test_support::{
        RefreshClient, RefreshRequest, assert_near, assert_times, callback_record, callback_starts,
        drive_handler, named, operation_like, poll_once, refresh_ctx, wire_err,
    };
    use crate::BoxError;
    use crate::builders::wait_for_condition::WaitDecision;
    use crate::client::ExecutionClientError;
    use crate::coordinator::PermitKind;
    use crate::engine::CheckpointStatus;
    use aws_sdk_lambda::types::{
        ChainedInvokeDetails, Operation, OperationAction, OperationStatus, OperationUpdate,
        StepDetails, WaitDetails,
    };
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    const fn secs(s: u64) -> Duration {
        Duration::from_secs(s)
    }

    const fn millis(ms: u64) -> Duration {
        Duration::from_millis(ms)
    }

    /// A wait record of `start` with `status`, whose scheduled end is
    /// `end_in` from now when `end_in` is `Some`.
    fn wait_record(
        req: &RefreshRequest<'_>,
        start: &OperationUpdate,
        status: OperationStatus,
        end_in: Option<Duration>,
    ) -> Operation {
        let mut builder = operation_like(start, status);
        if let Some(end_in) = end_in {
            builder = builder.wait_details(
                WaitDetails::builder()
                    .scheduled_end_timestamp(req.timestamp_in(end_in))
                    .build(),
            );
        }
        builder.build().expect("all required fields set")
    }

    /// An invoke record of `start` with `status` and `result`.
    fn invoke_record(
        start: &OperationUpdate,
        status: OperationStatus,
        result: Option<&str>,
    ) -> Operation {
        let mut details = ChainedInvokeDetails::builder();
        if let Some(result) = result {
            details = details.result(result);
        }
        operation_like(start, status)
            .chained_invoke_details(details.build())
            .build()
            .expect("all required fields set")
    }

    /// A `wait_for_condition` record of `update` with `status`, carrying
    /// the update's payload as the state and, when `next_in` is `Some`, a
    /// next attempt `next_in` from now.
    fn condition_record(
        req: &RefreshRequest<'_>,
        update: &OperationUpdate,
        status: OperationStatus,
        payload: Option<&str>,
        next_in: Option<Duration>,
    ) -> Operation {
        let mut details = StepDetails::builder().attempt(1);
        if let Some(payload) = payload {
            details = details.result(payload);
        }
        if let Some(next_in) = next_in {
            details = details.next_attempt_timestamp(req.timestamp_in(next_in));
        }
        operation_like(update, status)
            .step_details(details.build())
            .build()
            .expect("all required fields set")
    }

    /// The first update of `name` with `action` among the request's
    /// updates.
    fn this<'a>(
        req: &'a RefreshRequest<'_>,
        name: &str,
        action: &OperationAction,
    ) -> Option<&'a OperationUpdate> {
        named(req.updates, name, action)
    }

    /// The first update of `name` with `action` received so far.
    fn ever<'a>(
        req: &'a RefreshRequest<'_>,
        name: &str,
        action: &OperationAction,
    ) -> Option<&'a OperationUpdate> {
        named(req.history, name, action)
    }

    /// A step that sleeps `d` of tokio time.
    fn sleeping_step(
        ctx: &crate::DurableContext,
        name: &str,
        d: Duration,
    ) -> crate::DurableFuture<u32> {
        ctx.step(move |_| async move {
            tokio::time::sleep(d).await;
            Ok(1_u32)
        })
        .name(name)
        .future()
    }

    /// A spawned step that sleeps `d` of tokio time.
    fn spawned_sleeping_step(
        ctx: &crate::DurableContext,
        name: &str,
        d: Duration,
    ) -> crate::DurableFuture<u32> {
        ctx.step(move |_| async move {
            tokio::time::sleep(d).await;
            Ok(1_u32)
        })
        .name(name)
        .spawn()
    }

    /// The test-3 handler: branch A waits 5 s and runs step `a`, branch B
    /// runs a step of 60 s.
    async fn parallel_wait_then_step(ctx: crate::DurableContext) -> Result<String, BoxError> {
        let branches: Vec<crate::Branch<u32>> = vec![
            crate::Branch::new("A", |child: crate::DurableContext| async move {
                child.wait(secs(5)).name("w").await?;
                let a = child.step(|_| async { Ok(1_u32) }).name("a").await?;
                Ok(a)
            }),
            crate::Branch::new("B", |child: crate::DurableContext| async move {
                let b = child
                    .step(|_| async {
                        tokio::time::sleep(secs(60)).await;
                        Ok(2_u32)
                    })
                    .name("b")
                    .await?;
                Ok(b)
            }),
        ];
        let results = ctx.parallel(branches).name("p").await?;
        Ok(format!("{results:?}"))
    }

    /// The client of test 3: the wait's START carries an end 5 s ahead,
    /// and the first refresh finds it `SUCCEEDED`. Every other update is
    /// answered with the status it records, so the log holds every
    /// operation's final status.
    fn test3_client() -> RefreshClient {
        RefreshClient::new(|req| {
            let mut ops: Vec<Operation> = req
                .updates
                .iter()
                .map(|u| {
                    let status = match u.action() {
                        OperationAction::Succeed => OperationStatus::Succeeded,
                        OperationAction::Fail => OperationStatus::Failed,
                        _ => OperationStatus::Started,
                    };
                    let end_in = (u.name() == Some("w")).then_some(secs(5));
                    wait_record(req, u, status, end_in)
                })
                .collect();
            if req.empty_number == 1
                && let Some(start) = ever(req, "w", &OperationAction::Start)
            {
                ops.push(wait_record(req, start, OperationStatus::Succeeded, None));
            }
            Ok(ops)
        })
    }

    #[tokio::test(start_paused = true)]
    async fn parallel_wait_then_step_finishes_in_one_invocation() {
        let client = Arc::new(test3_client());
        let ctx = refresh_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            parallel_wait_then_step(ctx)
                .await
                .map_err(|e| crate::error::WireError::new(None::<String>, Some(e.to_string())))
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("[1, 2]".to_owned()));
        assert_times(&client.empty_calls(), &[secs(5)]);
        assert_near(
            client
                .time_of("a", &OperationAction::Start)
                .expect("a started"),
            secs(5),
        );
    }

    /// Runs the callback scenario of test 4: a callback result started with
    /// `spawn_result()` and polled once, and a step of `step` beside it.
    /// Returns the outcome; the handler returns the callback's value.
    async fn callback_beside_step(
        client: &Arc<RefreshClient>,
        remaining: Option<Duration>,
        step: Duration,
    ) -> InvocationOutcome {
        let ctx = refresh_ctx(client);
        drive_handler(ctx, remaining, move |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            sleeping_step(&ctx, "s", step).await.map_err(wire_err)?;
            h.await.map_err(wire_err)
        })
        .await
        .expect("no panic")
    }

    /// A client that answers the callback START, and completes the callback
    /// with `"ok"` on the first refresh when `complete` is set.
    fn callback_client(complete: bool) -> RefreshClient {
        RefreshClient::new(move |req| {
            let mut ops = callback_starts(req.updates);
            if complete
                && req.empty_number == 1
                && let Some(start) = ever(req, "cb", &OperationAction::Start)
            {
                ops.push(callback_record(
                    start,
                    OperationStatus::Succeeded,
                    Some("\"ok\""),
                ));
            }
            Ok(ops)
        })
    }

    #[tokio::test(start_paused = true)]
    async fn callback_refresh_continues_in_invocation() {
        let client = Arc::new(callback_client(true));
        let outcome = callback_beside_step(&client, None, secs(3)).await;
        assert_eq!(outcome, InvocationOutcome::Complete("ok".to_owned()));
        assert_times(&client.empty_calls(), &[secs(1)]);
    }

    /// Runs a spawned invoke, polled once, beside a step of 5 s, and returns
    /// the outcome; the handler returns the invoke's value.
    async fn invoke_beside_step(client: &Arc<RefreshClient>) -> InvocationOutcome {
        let ctx = refresh_ctx(client);
        drive_handler(ctx, None, |ctx| async move {
            let mut h = std::pin::pin!(ctx.invoke::<u32>("target", 1_u32).name("inv").spawn());
            poll_once(h.as_mut()).await;
            sleeping_step(&ctx, "s", secs(5)).await.map_err(wire_err)?;
            let value = h.await.map_err(wire_err)?;
            Ok(value.to_string())
        })
        .await
        .expect("no panic")
    }

    #[tokio::test(start_paused = true)]
    async fn invoke_refresh_backs_off() {
        let client = Arc::new(RefreshClient::new(|req| {
            let Some(start) = ever(req, "inv", &OperationAction::Start) else {
                return Ok(Vec::new());
            };
            Ok(match req.empty_number {
                1 | 2 => vec![invoke_record(start, OperationStatus::Started, None)],
                3 => vec![invoke_record(start, OperationStatus::Succeeded, Some("7"))],
                _ => Vec::new(),
            })
        }));
        let outcome = invoke_beside_step(&client).await;
        assert_eq!(outcome, InvocationOutcome::Complete("7".to_owned()));
        assert_times(&client.empty_calls(), &[secs(1), secs(2), secs(4)]);
    }

    #[tokio::test(start_paused = true)]
    async fn changed_status_restarts_schedule() {
        let client = Arc::new(RefreshClient::new(|req| {
            let Some(start) = ever(req, "inv", &OperationAction::Start) else {
                return Ok(Vec::new());
            };
            Ok(match req.empty_number {
                1 => vec![invoke_record(start, OperationStatus::Pending, None)],
                2 => vec![invoke_record(start, OperationStatus::Succeeded, Some("7"))],
                _ => Vec::new(),
            })
        }));
        let outcome = invoke_beside_step(&client).await;
        assert_eq!(outcome, InvocationOutcome::Complete("7".to_owned()));
        assert_times(&client.empty_calls(), &[secs(1), secs(2)]);
    }

    /// The check future of [`condition`].
    type CheckFuture = std::future::Ready<Result<i32, BoxError>>;

    /// A `wait_for_condition` that continues with 1 s until its state is at
    /// least 2. Each check records the tokio time it ran at in `checks`.
    fn condition(
        ctx: &crate::DurableContext,
        start: tokio::time::Instant,
        checks: &Arc<Mutex<Vec<Duration>>>,
    ) -> crate::builders::WaitForConditionBuilder<
        i32,
        impl Fn(crate::StepContext, i32) -> CheckFuture + Send + Sync + 'static,
        CheckFuture,
        crate::serdes::JsonSerdes,
        crate::builders::wait_for_condition::WithWaitStrategy<i32>,
    > {
        let checks = Arc::clone(checks);
        ctx.wait_for_condition(
            move |_ctx, state: i32| {
                checks.lock().expect("lock").push(start.elapsed());
                std::future::ready(Ok::<i32, BoxError>(state + 1))
            },
            0,
        )
        .wait_strategy_fn(|state: i32, _attempt| {
            if state >= 2 {
                WaitDecision::complete()
            } else {
                WaitDecision::continue_with(secs(1))
            }
        })
        .name("cond")
    }

    /// Answers a condition RETRY with `PENDING` and a next attempt 1 s
    /// ahead, and the refresh numbered `ready_on` with `READY`.
    fn condition_client(ready_on: usize) -> RefreshClient {
        RefreshClient::new(move |req| {
            let mut ops = Vec::new();
            if let Some(retry) = this(req, "cond", &OperationAction::Retry) {
                ops.push(condition_record(
                    req,
                    retry,
                    OperationStatus::Pending,
                    retry.payload(),
                    Some(secs(1)),
                ));
            }
            if req.empty_number == ready_on
                && let Some(retry) = ever(req, "cond", &OperationAction::Retry)
            {
                ops.push(condition_record(
                    req,
                    retry,
                    OperationStatus::Ready,
                    retry.payload(),
                    None,
                ));
            }
            Ok(ops)
        })
    }

    #[tokio::test(start_paused = true)]
    async fn condition_check_refreshes_at_next_attempt() {
        let client = Arc::new(condition_client(1));
        let ctx = refresh_ctx(&client);
        let start = tokio::time::Instant::now();
        let checks = Arc::new(Mutex::new(Vec::new()));
        let handler_checks = Arc::clone(&checks);
        let outcome = drive_handler(ctx, None, move |ctx| async move {
            let mut h = std::pin::pin!(condition(&ctx, start, &handler_checks).spawn());
            poll_once(h.as_mut()).await;
            sleeping_step(&ctx, "s", secs(3)).await.map_err(wire_err)?;
            let state = h.await.map_err(wire_err)?;
            Ok(state.to_string())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("2".to_owned()));
        let checks = checks.lock().expect("lock").clone();
        assert_times(&checks, &[secs(0), secs(1)]);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_wakes_ready_operations_in_sorted_order() {
        let end = std::time::SystemTime::now() + secs(1);
        let client = Arc::new(RefreshClient::new(move |req| {
            let mut ops = Vec::new();
            for name in ["w1", "w2"] {
                if let Some(start) = this(req, name, &OperationAction::Start) {
                    ops.push(
                        operation_like(start, OperationStatus::Started)
                            .wait_details(
                                WaitDetails::builder()
                                    .scheduled_end_timestamp(aws_smithy_types::DateTime::from(end))
                                    .build(),
                            )
                            .build()
                            .expect("all required fields set"),
                    );
                }
                if req.empty_number == 1
                    && let Some(start) = ever(req, name, &OperationAction::Start)
                {
                    ops.push(wait_record(req, start, OperationStatus::Succeeded, None));
                }
            }
            Ok(ops)
        }));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w1 = ctx.wait(secs(1)).name("w1").spawn();
            let w2 = ctx.wait(secs(1)).name("w2").spawn();
            let s = spawned_sleeping_step(&ctx, "s", secs(3));
            let (a, b) = tokio::join!(w1, w2);
            a.map_err(wire_err)?;
            b.map_err(wire_err)?;
            s.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_eq!(client.empty_calls().len(), 1);
        let updates = client.updates();
        let mut expected: Vec<String> = ["w1", "w2"]
            .iter()
            .map(|n| {
                named(&updates, n, &OperationAction::Start)
                    .expect("the wait started")
                    .id()
                    .to_owned()
            })
            .collect();
        expected.sort();
        assert_eq!(coordinator.wake_log(), expected);
    }

    #[tokio::test(start_paused = true)]
    async fn lone_wait_starts_no_refresh() {
        let client = Arc::new(RefreshClient::new(|_| Ok(Vec::new())));
        let ctx = refresh_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            ctx.wait(secs(1)).await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Pending);
        tokio::time::sleep(secs(60)).await;
        assert_eq!(client.empty_calls(), Vec::<Duration>::new());
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_in_flight_finishes_and_readies_first() {
        let client = Arc::new(
            RefreshClient::new(|req| {
                let mut ops = Vec::new();
                if let Some(start) = this(req, "w", &OperationAction::Start) {
                    ops.push(wait_record(
                        req,
                        start,
                        OperationStatus::Started,
                        Some(secs(1)),
                    ));
                }
                if req.empty_number == 1
                    && let Some(start) = ever(req, "w", &OperationAction::Start)
                {
                    ops.push(wait_record(req, start, OperationStatus::Succeeded, None));
                }
                Ok(ops)
            })
            .with_empty_delay(secs(1)),
        );
        let ctx = refresh_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let w = ctx.wait(secs(1)).name("w").spawn();
            let s = spawned_sleeping_step(&ctx, "s", millis(1500));
            w.await.map_err(wire_err)?;
            s.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_times(&client.empty_answers(), &[secs(2)]);
    }

    #[tokio::test(start_paused = true)]
    async fn no_refresh_within_one_second_of_deadline() {
        let client = Arc::new(callback_client(true));
        let outcome = callback_beside_step(&client, Some(millis(1500)), secs(3)).await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_eq!(client.empty_calls(), Vec::<Duration>::new());
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_stops_under_one_second_left() {
        let client = Arc::new(callback_client(false));
        let outcome = callback_beside_step(&client, Some(millis(2500)), secs(3)).await;
        assert_eq!(outcome, InvocationOutcome::Pending);
        assert_times(&client.empty_calls(), &[secs(1)]);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_failure_keeps_classification() {
        // A retryable failure fails the invocation.
        let client = Arc::new(RefreshClient::new(|req| {
            if req.empty_number > 0 {
                return Err(ExecutionClientError::from_retryable(
                    "throttled refresh".to_owned(),
                ));
            }
            Ok(callback_starts(req.updates))
        }));
        let outcome = callback_beside_step(&client, None, secs(3)).await;
        let InvocationOutcome::Fault { message, .. } = &outcome else {
            panic!("expected a fault, got {outcome:?}");
        };
        assert_eq!(
            message,
            "[Unrecoverable Invocation] Checkpoint failed: throttled refresh"
        );
        assert_eq!(client.empty_calls().len(), 1, "no refresh after a failure");

        // A non-retryable failure fails the execution.
        let rejected = ExecutionClientError::new_non_retryable("rejected refresh");
        let expected = crate::error::checkpoint_execution_failure_wire(&rejected);
        let client = Arc::new(RefreshClient::new(move |req| {
            if req.empty_number > 0 {
                return Err(rejected.clone());
            }
            Ok(callback_starts(req.updates))
        }));
        let outcome = callback_beside_step(&client, None, secs(3)).await;
        let InvocationOutcome::Failed { error } = &outcome else {
            panic!("expected a failed execution, got {outcome:?}");
        };
        assert_eq!(error.error_type(), expected.error_type());
        assert_eq!(client.empty_calls().len(), 1, "no refresh after a failure");
    }

    /// A pending callback whose result is spawned and polled once, beside
    /// 3 s of activity that writes no checkpoint, then awaited.
    async fn callback_beside_activity(ctx: crate::DurableContext) -> InvocationOutcome {
        drive_handler(ctx, None, |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            ctx.hold_activity(tokio::time::sleep(secs(3))).await;
            h.await.map_err(wire_err)
        })
        .await
        .expect("no panic")
    }

    /// A refresh failure under checkpoint batching is recorded where the
    /// response arrives, on the detached flush task, for the refresh's
    /// first due registration. No later write observes the failed batch,
    /// so without that record the invocation would suspend on the callback
    /// instead.
    #[tokio::test(start_paused = true)]
    async fn batched_refresh_failure_keeps_classification() {
        let batched_ctx = |client: &Arc<RefreshClient>| {
            crate::DurableContext::new_root_with_client_and_coalescer(
                "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
                lambda_runtime::Context::default(),
                Arc::new(crate::engine::CheckpointLog::empty()),
                Arc::clone(client) as Arc<dyn crate::client::ExecutionClient>,
                "t0".to_owned(),
                crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
            )
        };

        // A retryable failure fails the invocation.
        let client = Arc::new(RefreshClient::new(|req| {
            if req.empty_number > 0 {
                return Err(ExecutionClientError::from_retryable(
                    "throttled refresh".to_owned(),
                ));
            }
            Ok(callback_starts(req.updates))
        }));
        let outcome = callback_beside_activity(batched_ctx(&client)).await;
        let InvocationOutcome::Fault { message, .. } = &outcome else {
            panic!("expected a fault, got {outcome:?}");
        };
        assert_eq!(
            message,
            "[Unrecoverable Invocation] Checkpoint failed: throttled refresh"
        );

        // A non-retryable failure fails the execution.
        let rejected = ExecutionClientError::new_non_retryable("rejected refresh");
        let expected = crate::error::checkpoint_execution_failure_wire(&rejected);
        let client = Arc::new(RefreshClient::new(move |req| {
            if req.empty_number > 0 {
                return Err(rejected.clone());
            }
            Ok(callback_starts(req.updates))
        }));
        let outcome = callback_beside_activity(batched_ctx(&client)).await;
        let InvocationOutcome::Failed { error } = &outcome else {
            panic!("expected a failed execution, got {outcome:?}");
        };
        assert_eq!(error.error_type(), expected.error_type());
    }

    /// The payload of a `panic!` or a failed `assert!` with a message.
    fn panic_message(payload: &(dyn std::any::Any + Send)) -> Option<&str> {
        payload
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| payload.downcast_ref::<&str>().copied())
    }

    /// The checkpoint client panics during a refresh under checkpoint
    /// batching, the default. The refresh is written by a detached flush
    /// task, whose outcome has no reader, while the scheduler waits for
    /// the batch holding its permit. The task gateway records the panic,
    /// which ends the drive although the batch is never published. So the
    /// drive ends, cleans up, and returns the original payload. The
    /// virtual-time timeout bounds the test if the drive hangs.
    #[tokio::test(start_paused = true)]
    async fn batched_client_panic_fails_invocation() {
        let client = Arc::new(RefreshClient::new(|req| {
            assert!(req.empty_number == 0, "batched refresh client panic");
            Ok(callback_starts(req.updates))
        }));
        let ctx = crate::DurableContext::new_root_with_client_and_coalescer(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(crate::engine::CheckpointLog::empty()),
            Arc::clone(&client) as Arc<dyn crate::client::ExecutionClient>,
            "t0".to_owned(),
            crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
        );
        let coordinator = Arc::clone(ctx.coordinator());
        let ended = tokio::time::timeout(
            secs(600),
            drive_handler(ctx, None, |ctx| async move {
                let cb = ctx
                    .create_callback::<String>()
                    .name("cb")
                    .await
                    .map_err(wire_err)?;
                let mut h = std::pin::pin!(cb.spawn_result());
                poll_once(h.as_mut()).await;
                ctx.hold_activity(tokio::time::sleep(secs(3))).await;
                h.await.map_err(wire_err)
            }),
        )
        .await
        .expect("the drive ends");
        let Err(payload) = ended else {
            panic!("expected the client panic, got {ended:?}");
        };
        assert_eq!(
            panic_message(payload.as_ref()),
            Some("batched refresh client panic")
        );
        assert_eq!(coordinator.tasks().live(), 0);
        assert_eq!(coordinator.live_waits(), 0);
        assert_times(&client.empty_calls(), &[secs(1)]);
    }

    /// A kept panic ends a drive whose handler holds an activity permit
    /// and never resolves, and the driver returns its payload.
    #[tokio::test(start_paused = true)]
    async fn kept_panic_ends_the_drive() {
        let client = Arc::new(callback_client(false));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let ended = tokio::time::timeout(
            secs(600),
            drive_handler(ctx, None, |ctx| async move {
                assert!(
                    ctx.coordinator()
                        .record_panic(Box::new("detached boom"))
                        .is_none()
                );
                ctx.hold_activity(std::future::pending::<()>()).await;
                Ok("unreachable".to_owned())
            }),
        )
        .await
        .expect("the drive ends");
        let Err(payload) = ended else {
            panic!("expected the kept panic, got {ended:?}");
        };
        assert_eq!(panic_message(payload.as_ref()), Some("detached boom"));
        assert_eq!(coordinator.tasks().live(), 0);
    }

    /// A fatal error takes precedence over a panic recorded after it, as
    /// it does over every other ending. The panic payload is dropped, and a
    /// panic from its destructor is discarded.
    #[tokio::test(start_paused = true)]
    async fn fatal_takes_precedence_over_kept_panic() {
        struct PanicsOnDrop;
        impl Drop for PanicsOnDrop {
            #[expect(clippy::panic)]
            // reason: the test checks that the driver discards a panic
            // from the payload's destructor.
            fn drop(&mut self) {
                panic!("payload drop");
            }
        }
        let client = Arc::new(callback_client(false));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let ended = drive_handler(ctx, None, |ctx| async move {
            ctx.coordinator()
                .record_invocation_fault("FatalFirst", "fatal first".to_owned());
            assert!(
                ctx.coordinator()
                    .record_panic(Box::new(PanicsOnDrop))
                    .is_none()
            );
            Ok("done".to_owned())
        })
        .await;
        let Ok(InvocationOutcome::Fault { message, .. }) = &ended else {
            panic!("expected the fatal outcome, got {ended:?}");
        };
        assert!(message.contains("fatal first"), "{message}");
        assert!(!coordinator.has_panic());
    }

    /// The kept panic's payload panics on drop with a payload that panics
    /// on drop again. The driver discards the first destructor panic and
    /// leaks its payload, so the fatal outcome still returns.
    #[tokio::test(start_paused = true)]
    async fn fatal_takes_precedence_over_nested_panicking_kept_payload() {
        let client = Arc::new(callback_client(false));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let ended = drive_handler(ctx, None, |ctx| async move {
            ctx.coordinator()
                .record_invocation_fault("FatalFirst", "fatal first".to_owned());
            assert!(
                ctx.coordinator()
                    .record_panic(Box::new(super::task_gateway::NestedPanicPayload))
                    .is_none()
            );
            Ok("done".to_owned())
        })
        .await;
        let Ok(InvocationOutcome::Fault { message, .. }) = &ended else {
            panic!("expected the fatal outcome, got {ended:?}");
        };
        assert!(message.contains("fatal first"), "{message}");
        assert!(!coordinator.has_panic());
    }

    /// The handler returns while a refresh is in flight, without
    /// checkpoint batching. The driver drops the scheduler at once, so
    /// only the write task can record the failure. A retryable failure
    /// must still fail the invocation, and a non-retryable one the
    /// execution, instead of the handler's `Complete`.
    #[tokio::test(start_paused = true)]
    async fn refresh_failure_in_flight_when_handler_returns_keeps_classification() {
        async fn run(failure: ExecutionClientError) -> (InvocationOutcome, Arc<RefreshClient>) {
            let client = Arc::new(
                RefreshClient::new(move |req| {
                    if req.empty_number > 0 {
                        return Err(failure.clone());
                    }
                    Ok(callback_starts(req.updates))
                })
                .with_empty_delay(millis(500)),
            );
            let ctx = refresh_ctx(&client);
            let coordinator = Arc::clone(ctx.coordinator());
            let outcome = drive_handler(ctx, None, |ctx| async move {
                let cb = ctx
                    .create_callback::<String>()
                    .name("cb")
                    .await
                    .map_err(wire_err)?;
                let mut h = std::pin::pin!(cb.spawn_result());
                poll_once(h.as_mut()).await;
                ctx.hold_activity(tokio::time::sleep(millis(1200))).await;
                Ok("done".to_owned())
            })
            .await
            .expect("no panic");
            assert_eq!(coordinator.tasks().live(), 0);
            (outcome, client)
        }

        let (outcome, client) = run(ExecutionClientError::from_retryable(
            "throttled refresh".to_owned(),
        ))
        .await;
        let InvocationOutcome::Fault { message, .. } = &outcome else {
            panic!("expected a fault, got {outcome:?}");
        };
        assert!(message.contains("throttled refresh"), "got {message}");
        assert_times(&client.empty_calls(), &[secs(1)]);

        let rejected = ExecutionClientError::new_non_retryable("rejected refresh");
        let expected = crate::error::checkpoint_execution_failure_wire(&rejected);
        let (outcome, client) = run(rejected).await;
        let InvocationOutcome::Failed { error } = &outcome else {
            panic!("expected a failed execution, got {outcome:?}");
        };
        assert_eq!(error.error_type(), expected.error_type());
        assert_times(&client.empty_calls(), &[secs(1)]);
    }

    /// The panic payload of the unbatched refresh tests below.
    struct RefreshPanic(u32);

    /// Drives a handler that returns while an unbatched refresh is in
    /// flight, after recording a fatal error when `fatal` is set. The
    /// checkpoint client panics with `RefreshPanic(7)` after the handler
    /// returned, so the driver has already dropped the scheduler, and with
    /// it the refresh's receiver.
    async fn drive_unbatched_refresh_panic_after_return(
        fatal: bool,
    ) -> (
        Result<InvocationOutcome, Box<dyn std::any::Any + Send + 'static>>,
        Arc<crate::coordinator::InvocationCoordinator>,
    ) {
        let client = Arc::new(
            RefreshClient::new(|req| {
                if req.empty_number > 0 {
                    std::panic::panic_any(RefreshPanic(7));
                }
                Ok(callback_starts(req.updates))
            })
            .with_empty_delay(millis(500)),
        );
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, move |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            ctx.hold_activity(tokio::time::sleep(millis(1200))).await;
            if fatal {
                ctx.coordinator()
                    .record_invocation_fault("FatalFirst", "fatal first".to_owned());
            }
            Ok("done".to_owned())
        })
        .await;
        (outcome, coordinator)
    }

    /// The checkpoint client panics during an unbatched refresh after the
    /// handler returned, so the driver has already dropped the scheduler.
    /// The task gateway records the panic of the detached write task on
    /// the coordinator, and the drive returns that payload instead of the
    /// handler's `Complete`.
    #[tokio::test(start_paused = true)]
    async fn unbatched_refresh_panic_after_handler_returns() {
        let (outcome, coordinator) = drive_unbatched_refresh_panic_after_return(false).await;
        let Err(payload) = outcome else {
            panic!("expected the refresh panic, got {outcome:?}");
        };
        assert_eq!(payload.downcast_ref::<RefreshPanic>().map(|p| p.0), Some(7));
        assert_eq!(coordinator.tasks().live(), 0);
    }

    /// A fatal error recorded before the unbatched refresh panic still
    /// takes precedence over it.
    #[tokio::test(start_paused = true)]
    async fn fatal_wins_over_unbatched_refresh_panic_after_handler_returns() {
        let (outcome, coordinator) = drive_unbatched_refresh_panic_after_return(true).await;
        let Ok(InvocationOutcome::Fault { message, .. }) = &outcome else {
            panic!("expected the fatal outcome, got {outcome:?}");
        };
        assert!(message.contains("fatal first"), "{message}");
        assert!(!coordinator.has_panic());
        assert_eq!(coordinator.tasks().live(), 0);
    }

    /// The handler panics while a batched refresh is in flight. The driver
    /// drops the scheduler, and so the refresh's caller, when the handler
    /// panics, and the end-of-invocation flush point never runs after a
    /// panic. So only the flusher that publishes the batch's failure can
    /// record it. Its classification must win over the handler's panic.
    #[tokio::test(start_paused = true)]
    async fn batched_refresh_failure_when_handler_panics_keeps_classification() {
        async fn run(failure: ExecutionClientError) -> InvocationOutcome {
            let client = Arc::new(
                RefreshClient::new(move |req| {
                    if req.empty_number > 0 {
                        return Err(failure.clone());
                    }
                    Ok(callback_starts(req.updates))
                })
                .with_empty_delay(millis(500)),
            );
            let ctx = crate::DurableContext::new_root_with_client_and_coalescer(
                "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
                lambda_runtime::Context::default(),
                Arc::new(crate::engine::CheckpointLog::empty()),
                Arc::clone(&client) as Arc<dyn crate::client::ExecutionClient>,
                "t0".to_owned(),
                crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
            );
            let coordinator = Arc::clone(ctx.coordinator());
            let outcome = drive_handler(ctx, None, |ctx| async move {
                let cb = ctx
                    .create_callback::<String>()
                    .name("cb")
                    .await
                    .map_err(wire_err)?;
                let mut h = std::pin::pin!(cb.spawn_result());
                poll_once(h.as_mut()).await;
                ctx.hold_activity(tokio::time::sleep(millis(1200))).await;
                panic!("handler panic beside a refresh");
            })
            .await
            .expect("the refresh failure wins over the handler panic");
            assert_eq!(coordinator.tasks().live(), 0);
            assert_times(&client.empty_calls(), &[secs(1)]);
            outcome
        }

        let outcome = run(ExecutionClientError::from_retryable(
            "throttled refresh".to_owned(),
        ))
        .await;
        let InvocationOutcome::Fault { message, .. } = &outcome else {
            panic!("expected a fault, got {outcome:?}");
        };
        assert!(message.contains("throttled refresh"), "got {message}");

        let rejected = ExecutionClientError::new_non_retryable("rejected refresh");
        let expected = crate::error::checkpoint_execution_failure_wire(&rejected);
        let outcome = run(rejected).await;
        let InvocationOutcome::Failed { error } = &outcome else {
            panic!("expected a failed execution, got {outcome:?}");
        };
        assert_eq!(error.error_type(), expected.error_type());
    }

    /// The checkpoint client panics during an unbatched refresh while the
    /// handler runs. The task gateway records the panic of the detached
    /// write task, and the scheduler waits on a channel that never carries
    /// it. The driver must still run its cleanup, so no task outlives the
    /// drive, and then return the original payload.
    #[tokio::test(start_paused = true)]
    async fn refresh_client_panic_cleans_up_and_propagates() {
        let client = Arc::new(RefreshClient::new(|req| {
            assert!(req.empty_number == 0, "refresh client panic");
            Ok(callback_starts(req.updates))
        }));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        let ended = drive_handler(ctx, None, |ctx| async move {
            let step = spawned_sleeping_step(&ctx, "s", secs(3));
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            step.await.map_err(wire_err)?;
            h.await.map_err(wire_err)
        })
        .await;
        let Err(payload) = ended else {
            panic!("expected the client panic, got {ended:?}");
        };
        let message = payload
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| payload.downcast_ref::<&str>().copied());
        assert_eq!(message, Some("refresh client panic"));
        assert_eq!(coordinator.tasks().live(), 0);
        assert_eq!(coordinator.live_waits(), 0);
        assert_times(&client.empty_calls(), &[secs(1)]);
    }

    #[tokio::test(start_paused = true)]
    async fn no_refresh_after_invocation_ends() {
        let client = Arc::new(callback_client(false));
        let ctx = refresh_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            sleeping_step(&ctx, "s", millis(2500))
                .await
                .map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        tokio::time::sleep(secs(120)).await;
        assert_times(&client.empty_calls(), &[secs(1), secs(2)]);
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_in_flight_when_handler_returns_completes() {
        let client = Arc::new(
            RefreshClient::new(|req| {
                let mut ops = callback_starts(req.updates);
                if req.empty_number > 0
                    && req.now >= millis(1400)
                    && let Some(start) = ever(req, "cb", &OperationAction::Start)
                {
                    ops.push(callback_record(
                        start,
                        OperationStatus::Succeeded,
                        Some("\"ok\""),
                    ));
                }
                Ok(ops)
            })
            .with_empty_delay(millis(500)),
        );
        let ctx = refresh_ctx(&client);
        let log_ctx = ctx.clone();
        let coordinator = Arc::clone(ctx.coordinator());
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            ctx.hold_activity(tokio::time::sleep(millis(1200))).await;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        let returned = client.elapsed();
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_times(&client.empty_answers(), &[millis(1500)]);
        assert!(returned >= millis(1500), "returned at {returned:?}");
        let cb_id = named(&client.updates(), "cb", &OperationAction::Start)
            .expect("the callback started")
            .id()
            .to_owned();
        assert_eq!(
            log_ctx.refresh_view(&cb_id).map(|(status, _)| status),
            Some(CheckpointStatus::Succeeded)
        );
        assert_eq!(coordinator.tasks().live(), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn new_earlier_registration_rearms_scheduler() {
        let client = Arc::new(RefreshClient::new(|req| {
            let mut ops = callback_starts(req.updates);
            if let Some(start) = this(req, "w", &OperationAction::Start) {
                ops.push(wait_record(
                    req,
                    start,
                    OperationStatus::Started,
                    Some(millis(300)),
                ));
            }
            if req.empty_number == 1
                && let Some(start) = ever(req, "w", &OperationAction::Start)
            {
                ops.push(wait_record(req, start, OperationStatus::Succeeded, None));
            }
            Ok(ops)
        }));
        let ctx = refresh_ctx(&client);
        let waited = Arc::new(Mutex::new(None));
        let handler_waited = Arc::clone(&waited);
        let handler_client = Arc::clone(&client);
        let outcome = drive_handler(ctx, None, move |ctx| async move {
            let s = spawned_sleeping_step(&ctx, "s", secs(10));
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            let mut h = std::pin::pin!(cb.spawn_result());
            poll_once(h.as_mut()).await;
            tokio::time::sleep(millis(200)).await;
            let result = ctx.wait(secs(1)).name("w").await;
            *handler_waited.lock().expect("lock") =
                Some((result.is_ok(), handler_client.elapsed()));
            s.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        let first = *client.empty_calls().first().expect("a refresh was sent");
        assert_near(first, millis(500));
        let (ok, at) = waited.lock().expect("lock").expect("the wait returned");
        assert!(ok, "the wait returns Ok(())");
        assert_near(at, millis(500));
    }

    #[tokio::test(start_paused = true)]
    async fn retired_earliest_registration_rearms_scheduler() {
        let client = Arc::new(RefreshClient::new(|req| {
            let mut ops = callback_starts(req.updates);
            if let Some(start) = this(req, "w", &OperationAction::Start) {
                ops.push(wait_record(
                    req,
                    start,
                    OperationStatus::Started,
                    Some(secs(3)),
                ));
            }
            if req.empty_number == 1
                && let Some(start) = ever(req, "w", &OperationAction::Start)
            {
                ops.push(wait_record(req, start, OperationStatus::Succeeded, None));
            }
            Ok(ops)
        }));
        let ctx = refresh_ctx(&client);
        let outcome = drive_handler(ctx, None, |ctx| async move {
            let s = spawned_sleeping_step(&ctx, "s", secs(10));
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            // A lazy result future, polled once, registers the wait.
            // Dropping it retires the registration. (Dropping the handle of
            // `spawn_result()` would not: the wait keeps running.)
            let mut cb_h = cb.result();
            poll_once(std::pin::Pin::new(&mut cb_h)).await;
            let w = ctx.wait(secs(3)).name("w").spawn();
            let (waited, ()) = tokio::join!(w, async move {
                tokio::time::sleep(millis(500)).await;
                drop(cb_h);
            });
            waited.map_err(wire_err)?;
            s.await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_times(&client.empty_calls(), &[secs(3)]);
    }

    /// The kinds of operation tests 21 and 22 start with `.spawn()` or
    /// `spawn_result()`.
    #[derive(Debug, Clone, Copy)]
    enum Spawned {
        Wait,
        Callback,
        Invoke,
        Condition,
    }

    impl Spawned {
        /// The name the operation gets.
        fn name(self) -> &'static str {
            match self {
                Self::Wait => "w",
                Self::Callback => "cb",
                Self::Invoke => "inv",
                Self::Condition => "cond",
            }
        }

        /// A client whose responses start the operation, and make it ready
        /// on the first refresh.
        fn client(self) -> RefreshClient {
            RefreshClient::new(move |req| {
                let mut ops = callback_starts(req.updates);
                if let Some(start) = this(req, "w", &OperationAction::Start) {
                    ops.push(wait_record(
                        req,
                        start,
                        OperationStatus::Started,
                        Some(secs(1)),
                    ));
                }
                if let Some(retry) = this(req, "cond", &OperationAction::Retry) {
                    ops.push(condition_record(
                        req,
                        retry,
                        OperationStatus::Pending,
                        retry.payload(),
                        Some(secs(1)),
                    ));
                }
                if req.empty_number == 1 {
                    let ready = match self {
                        Self::Wait => ever(req, "w", &OperationAction::Start)
                            .map(|s| wait_record(req, s, OperationStatus::Succeeded, None)),
                        Self::Callback => ever(req, "cb", &OperationAction::Start).map(|s| {
                            callback_record(s, OperationStatus::Succeeded, Some("\"ok\""))
                        }),
                        Self::Invoke => ever(req, "inv", &OperationAction::Start)
                            .map(|s| invoke_record(s, OperationStatus::Succeeded, Some("7"))),
                        Self::Condition => ever(req, "cond", &OperationAction::Retry).map(|r| {
                            condition_record(req, r, OperationStatus::Ready, r.payload(), None)
                        }),
                    };
                    ops.extend(ready);
                }
                Ok(ops)
            })
        }

        /// Starts the operation on `ctx` and returns its handle, whose
        /// value is rendered as a string.
        async fn start(
            self,
            ctx: &crate::DurableContext,
            checks: &Arc<Mutex<Vec<Duration>>>,
        ) -> Result<crate::DurableFuture<String>, crate::error::WireError> {
            Ok(match self {
                Self::Wait => {
                    let h = ctx.wait(secs(1)).name("w").spawn();
                    crate::DurableFuture::from_async(
                        async move { h.await.map(|()| "()".to_owned()) },
                    )
                }
                Self::Callback => {
                    let cb = ctx
                        .create_callback::<String>()
                        .name("cb")
                        .await
                        .map_err(wire_err)?;
                    cb.spawn_result()
                }
                Self::Invoke => {
                    let h = ctx.invoke::<u32>("target", 1_u32).name("inv").spawn();
                    crate::DurableFuture::from_async(async move { h.await.map(|v| v.to_string()) })
                }
                Self::Condition => {
                    let h = condition(ctx, tokio::time::Instant::now(), checks).spawn();
                    crate::DurableFuture::from_async(async move { h.await.map(|v| v.to_string()) })
                }
            })
        }

        /// The value the handle resolves with once the operation is ready.
        fn value(self) -> &'static str {
            match self {
                Self::Wait => "()",
                Self::Callback => "ok",
                Self::Invoke => "7",
                Self::Condition => "2",
            }
        }
    }

    /// A wait, an invoke and a callback result start refreshing only after
    /// their handle is first polled.
    #[tokio::test(start_paused = true)]
    async fn unawaited_spawned_operation_is_not_refreshed() {
        for kind in [Spawned::Wait, Spawned::Callback, Spawned::Invoke] {
            let client = Arc::new(kind.client());
            let ctx = refresh_ctx(&client);
            let coordinator = Arc::clone(ctx.coordinator());
            let seen = Arc::new(Mutex::new(None));
            let handler_seen = Arc::clone(&seen);
            let handler_client = Arc::clone(&client);
            let checks = Arc::new(Mutex::new(Vec::new()));
            let outcome = drive_handler(ctx, None, move |ctx| async move {
                // The wrapper future is never polled, so its handle is not.
                let _h = kind.start(&ctx, &checks).await?;
                let live = ctx
                    .hold_activity(async {
                        for _ in 0..1000 {
                            if handler_client.received(kind.name(), &OperationAction::Start)
                                && ctx.coordinator().live_waits() == 1
                            {
                                return Some(ctx.coordinator().live_waits());
                            }
                            tokio::task::yield_now().await;
                        }
                        None
                    })
                    .await;
                *handler_seen.lock().expect("lock") = Some(live);
                sleeping_step(&ctx, "s", secs(3)).await.map_err(wire_err)?;
                Ok("done".to_owned())
            })
            .await
            .expect("no panic");
            let live = seen.lock().expect("lock").expect("the handler ran");
            assert_eq!(live, Some(1), "{kind:?}: the operation is a live wait");
            assert_eq!(
                client.empty_calls(),
                Vec::<Duration>::new(),
                "{kind:?}: no refresh"
            );
            assert_eq!(
                outcome,
                InvocationOutcome::Complete("done".to_owned()),
                "{kind:?}"
            );
            assert_eq!(coordinator.live_waits(), 0, "{kind:?}");
        }
    }

    /// A `wait_for_condition` started with `.spawn()` arms its refresh when
    /// it registers its wait, so its next check runs when the delay ends
    /// although nothing polls its handle.
    #[tokio::test(start_paused = true)]
    async fn unawaited_spawned_condition_is_refreshed() {
        let client = Arc::new(Spawned::Condition.client());
        let ctx = refresh_ctx(&client);
        let checks = Arc::new(Mutex::new(Vec::new()));
        let handler_checks = Arc::clone(&checks);
        let outcome = drive_handler(ctx, None, move |ctx| async move {
            // The handle is kept and never polled.
            let _h = Spawned::Condition.start(&ctx, &handler_checks).await?;
            sleeping_step(&ctx, "s", secs(3)).await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
        assert_times(&checks.lock().expect("lock"), &[secs(0), secs(1)]);
        assert!(
            !client.empty_calls().is_empty(),
            "the condition is refreshed"
        );
    }

    /// Dropping the handle of `Callback::spawn_result()` keeps the result
    /// wait registered.
    #[tokio::test(start_paused = true)]
    async fn dropped_callback_spawn_result_keeps_waiting() {
        let client = Arc::new(Spawned::Callback.client());
        let ctx = refresh_ctx(&client);
        let seen = Arc::new(Mutex::new(None));
        let handler_seen = Arc::clone(&seen);
        let outcome = drive_handler(ctx, None, move |ctx| async move {
            let cb = ctx
                .create_callback::<String>()
                .name("cb")
                .await
                .map_err(wire_err)?;
            drop(cb.spawn_result());
            let live = ctx
                .hold_activity(async {
                    for _ in 0..1000 {
                        if ctx.coordinator().live_waits() == 1 {
                            break;
                        }
                        tokio::task::yield_now().await;
                    }
                    ctx.coordinator().live_waits()
                })
                .await;
            *handler_seen.lock().expect("lock") = Some(live);
            sleeping_step(&ctx, "s", secs(1)).await.map_err(wire_err)?;
            Ok("done".to_owned())
        })
        .await
        .expect("no panic");
        assert_eq!(*seen.lock().expect("lock"), Some(1), "the wait stays live");
        assert_eq!(outcome, InvocationOutcome::Complete("done".to_owned()));
    }

    /// A wait, an invoke and a callback result start refreshing at the
    /// first poll of their handle. A condition refreshes from its
    /// registration (see `unawaited_spawned_condition_is_refreshed`).
    #[tokio::test(start_paused = true)]
    async fn spawned_operation_refresh_starts_at_first_poll() {
        for kind in [Spawned::Wait, Spawned::Callback, Spawned::Invoke] {
            let client = Arc::new(kind.client());
            let ctx = refresh_ctx(&client);
            let resolved = Arc::new(Mutex::new(None));
            let handler_resolved = Arc::clone(&resolved);
            let handler_client = Arc::clone(&client);
            let checks = Arc::new(Mutex::new(Vec::new()));
            let outcome = drive_handler(ctx, None, move |ctx| async move {
                let h = kind.start(&ctx, &checks).await?;
                let s = spawned_sleeping_step(&ctx, "s", secs(4));
                tokio::time::sleep(secs(2)).await;
                let value = h.await.map_err(wire_err)?;
                *handler_resolved.lock().expect("lock") = Some(handler_client.elapsed());
                s.await.map_err(wire_err)?;
                Ok(value)
            })
            .await
            .expect("no panic");
            let expected_at = match kind {
                Spawned::Wait | Spawned::Condition => secs(2),
                Spawned::Callback | Spawned::Invoke => secs(3),
            };
            assert_eq!(
                outcome,
                InvocationOutcome::Complete(kind.value().to_owned()),
                "{kind:?}"
            );
            let first = *client.empty_calls().first().expect("a refresh was sent");
            assert_near(first, expected_at);
            let at = resolved.lock().expect("lock").expect("the handle resolved");
            assert_near(at, expected_at);
        }
    }

    /// The scheduler of a drive whose only work holds no permit sends
    /// nothing. A recorded fatal error keeps the phase `Running` with a due
    /// registration and no permit, the one state in which the coordinator
    /// refuses the scheduler's permit while the scheduler is polled.
    #[tokio::test(start_paused = true)]
    async fn refused_scheduler_permit_sends_nothing() {
        let client = Arc::new(RefreshClient::new(|_| Ok(Vec::new())));
        let ctx = refresh_ctx(&client);
        let coordinator = Arc::clone(ctx.coordinator());
        coordinator.record_fatal("Fatal".to_owned(), "stop".to_owned());
        let _wait = coordinator
            .register_test_wait("op", std::task::Waker::noop())
            .expect("running");
        let mut scheduler = std::pin::pin!(super::refresh_scheduler(ctx));
        let polled = tokio::time::timeout(secs(30), scheduler.as_mut()).await;
        assert!(polled.is_err(), "the scheduler stays pending");
        assert_eq!(client.empty_calls(), Vec::<Duration>::new());
        assert_eq!(coordinator.permits(PermitKind::Scheduler), 0);
    }

    #[cfg(feature = "test-util")]
    #[tokio::test(start_paused = true)]
    async fn replay_after_suspension_matches_in_process() {
        // In process: the wait continues inside the one invocation.
        let client = Arc::new(test3_client());
        let ctx = refresh_ctx(&client);
        let log_ctx = ctx.clone();
        let outcome = drive_handler(ctx, None, |ctx| async move {
            parallel_wait_then_step(ctx)
                .await
                .map_err(|e| crate::error::WireError::new(None::<String>, Some(e.to_string())))
        })
        .await
        .expect("no panic");
        let InvocationOutcome::Complete(in_process) = outcome else {
            panic!("expected Complete, got {outcome:?}");
        };
        let mut seen: Vec<String> = Vec::new();
        let mut in_process_ops = Vec::new();
        for update in client.updates() {
            if seen.contains(&update.id().to_owned()) {
                continue;
            }
            seen.push(update.id().to_owned());
            let (status, _) = log_ctx.refresh_view(update.id()).expect("recorded");
            in_process_ops.push((
                update.name().map(str::to_owned),
                update.r#type().as_str().to_owned(),
                status,
            ));
        }

        // Through LocalRunner, which suspends at the wait and replays.
        let result = crate::test_util::LocalRunner::new()
            .run(
                |(): (), ctx: crate::DurableContext| parallel_wait_then_step(ctx),
                (),
            )
            .await
            .expect("the run finishes");
        assert!(result.invocation_count() > 1, "LocalRunner suspended");
        assert_eq!(
            result.output().map(String::as_str),
            Some(in_process.as_str())
        );
        let replayed_ops: Vec<_> = result
            .operations()
            .iter()
            .map(|op| {
                let status = match op.status() {
                    crate::OperationStatus::Succeeded => CheckpointStatus::Succeeded,
                    crate::OperationStatus::Failed => CheckpointStatus::Failed,
                    other => CheckpointStatus::Unknown(format!("{other:?}")),
                };
                (
                    op.name().map(str::to_owned),
                    op.kind().wire_str().to_owned(),
                    status,
                )
            })
            .collect();
        assert_eq!(replayed_ops, in_process_ops);
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: handlers and destructors panic under test, and test assertions
mod panic_owner {
    //! The invocation coordinator owns every invocation-failing panic, and
    //! the driver resumes the first one after its cleanup.

    use super::{InvocationOutcome, drive_outcome, drive_with_scheduler};
    use crate::client::{
        CheckpointOutput, ExecutionClient, ExecutionClientError, GetStateOutput,
        InMemoryExecutionClient,
    };
    use crate::context::DurableContext;
    use crate::coordinator::InvocationCoordinator;
    use crate::engine::CheckpointLog;
    use crate::future::DurableFuture;
    use crate::task::TrackedJoinSet;
    use aws_sdk_lambda::types::OperationUpdate;
    use std::any::Any;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::task::{Context, Poll};
    use std::time::Duration;

    type Payload = Box<dyn Any + Send + 'static>;
    type Driven = Result<InvocationOutcome, Payload>;

    fn ctx_with(client: Arc<dyn ExecutionClient>) -> DurableContext {
        DurableContext::new_root_with_client(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            client,
            "token0".to_owned(),
        )
    }

    fn live_ctx() -> DurableContext {
        ctx_with(Arc::new(InMemoryExecutionClient::new(Vec::new())))
    }

    /// A panic payload identified by its number. It counts its drops, so a
    /// test can check that a payload was dropped through `discard_panic`.
    struct Tagged(u32, Arc<AtomicUsize>);

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

    /// Panics with `Tagged(n)`, whose drops `drops` counts.
    fn panic_tagged(n: u32, drops: &Arc<AtomicUsize>) -> ! {
        std::panic::panic_any(Tagged(n, Arc::clone(drops)))
    }

    /// A new drop counter.
    fn counter() -> Arc<AtomicUsize> {
        Arc::new(AtomicUsize::new(0))
    }

    /// The number of a [`Tagged`] payload, or `None` for another type.
    fn tag(payload: &(dyn Any + Send)) -> Option<u32> {
        payload.downcast_ref::<Tagged>().map(|p| p.0)
    }

    /// The tag of the panic the drive returned. Fails on any other outcome.
    fn returned_tag(driven: &Driven) -> Option<u32> {
        let Err(payload) = driven else {
            panic!("expected a panic, got {driven:?}");
        };
        tag(payload.as_ref())
    }

    /// Panics with `Tagged(n)` when dropped.
    struct PanicsOnDrop(u32, Arc<AtomicUsize>);

    impl Drop for PanicsOnDrop {
        fn drop(&mut self) {
            panic_tagged(self.0, &self.1);
        }
    }

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

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

    /// Yields, holding an activity permit, until `done` holds. Fails after
    /// 1,000 yields.
    async fn until(ctx: &DurableContext, done: impl Fn() -> bool) {
        ctx.hold_activity(async {
            for _ in 0..1000 {
                if done() {
                    return;
                }
                tokio::task::yield_now().await;
            }
            panic!("the condition did not hold within 1,000 yields");
        })
        .await;
    }

    /// Drives `handler` on `ctx` and returns the drive's result and the
    /// number of live tasks after it.
    async fn drive<F, Fut>(ctx: DurableContext, handler: F) -> (Driven, usize)
    where
        F: FnOnce(DurableContext) -> Fut,
        Fut: Future<Output = Result<String, crate::error::WireError>> + Send + 'static,
    {
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());
        let tasks = Arc::clone(coordinator.tasks());
        let root = ctx.clone();
        let driven = drive_outcome(handler(ctx), ownership, coordinator, root, None).await;
        (driven, tasks.live())
    }

    /// Spawns a step whose body holds `guard` and stays pending, and sets
    /// `started` once the body runs.
    fn spawn_holding<G: Send + 'static>(
        ctx: &DurableContext,
        name: &str,
        guard: G,
        started: &Arc<AtomicBool>,
    ) -> DurableFuture<()> {
        let guard = Arc::new(Mutex::new(Some(guard)));
        let started = Arc::clone(started);
        ctx.step(move |_| {
            let guard = guard.lock().expect("lock").take();
            let started = Arc::clone(&started);
            async move {
                let _guard = guard;
                started.store(true, Ordering::SeqCst);
                std::future::pending::<()>().await;
                Ok(())
            }
        })
        .name(name)
        .spawn()
    }

    /// Spawns a step whose body panics with `Tagged(n)`.
    fn spawn_panicking(
        ctx: &DurableContext,
        n: u32,
        drops: &Arc<AtomicUsize>,
    ) -> DurableFuture<()> {
        let drops = Arc::clone(drops);
        ctx.step(move |_| {
            let drops = Arc::clone(&drops);
            async move { panic_tagged(n, &drops) }
        })
        .name("boom")
        .spawn()
    }

    /// Test 6. The handler drops the handle of a step that panicked and
    /// returns `Ok`. The handle's drop records the unread panic.
    #[tokio::test]
    async fn dropped_handle_of_panicked_task_fails_invocation() {
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let step = spawn_panicking(&ctx, 6, &counter());
            let tasks = Arc::clone(ctx.coordinator().tasks());
            until(&ctx, || tasks.live() == 0).await;
            drop(step);
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(6));
        assert_eq!(live, 0);
    }

    /// Test 7. The handler moves the handle of a step that panicked into a
    /// value the test keeps, and returns `Ok`. The cleanup claims the
    /// unread panic.
    #[tokio::test]
    async fn escaped_handle_with_unread_panic_fails_invocation() {
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let kept = Arc::clone(&escaped);
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let step = spawn_panicking(&ctx, 7, &counter());
            let tasks = Arc::clone(ctx.coordinator().tasks());
            until(&ctx, || tasks.live() == 0).await;
            *kept.lock().expect("lock") = Some(step);
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(7));
        assert!(
            escaped.lock().expect("lock").is_some(),
            "the test still holds the handle"
        );
        assert_eq!(live, 0);
    }

    /// Test 8. The handler drops the handle of a pending step whose body
    /// panics when it is dropped, and returns. Dropping the handle does not
    /// stop the step. The drive's cleanup aborts it, which drops the body,
    /// and the gateway records that panic.
    #[tokio::test]
    async fn panic_while_aborting_dropped_task_fails_invocation() {
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let started = Arc::new(AtomicBool::new(false));
            let step = spawn_holding(&ctx, "hold", PanicsOnDrop(8, counter()), &started);
            until(&ctx, || started.load(Ordering::SeqCst)).await;
            drop(step);
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(8));
        assert_eq!(live, 0);
    }

    /// Test 9. A join set's item has delivered its panic to the queue, and
    /// the set drops without joining it.
    #[tokio::test]
    async fn queued_join_set_panic_fails_invocation() {
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let drops = counter();
            let mut set = TrackedJoinSet::<()>::new(Arc::clone(ctx.coordinator()));
            set.spawn(
                crate::task::TaskContext::none(),
                ctx.task_ownership(),
                async move { panic_tagged(9, &drops) },
            )
            .expect("runtime");
            let tasks = Arc::clone(ctx.coordinator().tasks());
            until(&ctx, || tasks.live() == 0).await;
            drop(set);
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(9));
        assert_eq!(live, 0);
    }

    /// Stays pending, sets its flag at its first poll, and panics with
    /// `Tagged(n)` when dropped.
    struct PendingThenDropPanics {
        started: Arc<AtomicBool>,
        _guard: PanicsOnDrop,
    }

    impl Future for PendingThenDropPanics {
        type Output = ();

        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
            self.started.store(true, Ordering::SeqCst);
            Poll::Pending
        }
    }

    /// Test 10. A join set drops while its item is pending, and the item's
    /// future panics when the abort drops it.
    #[tokio::test]
    async fn join_set_panic_after_drop_fails_invocation() {
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let started = Arc::new(AtomicBool::new(false));
            let mut set = TrackedJoinSet::<()>::new(Arc::clone(ctx.coordinator()));
            set.spawn(
                crate::task::TaskContext::none(),
                ctx.task_ownership(),
                PendingThenDropPanics {
                    started: Arc::clone(&started),
                    _guard: PanicsOnDrop(10, counter()),
                },
            )
            .expect("runtime");
            until(&ctx, || started.load(Ordering::SeqCst)).await;
            drop(set);
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(10));
        assert_eq!(live, 0);
    }

    /// Records a fatal error when dropped.
    struct FatalOnDrop(Arc<InvocationCoordinator>);

    impl Drop for FatalOnDrop {
        fn drop(&mut self) {
            self.0
                .record_fatal("Fatal".to_owned(), "during cleanup".to_owned());
        }
    }

    /// Test 4. The handler panics; during the cleanup a task records a
    /// fatal error. The fatal outcome wins, and the handler's payload is
    /// dropped through `discard_panic`.
    #[tokio::test(flavor = "current_thread")]
    async fn fatal_after_panic_wins() {
        let drops = counter();
        let handler_drops = Arc::clone(&drops);
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let kept = Arc::clone(&escaped);
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let started = Arc::new(AtomicBool::new(false));
            let guard = FatalOnDrop(Arc::clone(ctx.coordinator()));
            *kept.lock().expect("lock") = Some(spawn_holding(&ctx, "hold", guard, &started));
            until(&ctx, || started.load(Ordering::SeqCst)).await;
            assert!(ctx.coordinator().fatal_error().is_none(), "no fatal yet");
            panic_tagged(4, &handler_drops)
        })
        .await;
        let Ok(InvocationOutcome::Failed { error }) = &driven else {
            panic!("expected the fatal outcome, got {driven:?}");
        };
        assert_eq!(error.error_message(), Some("during cleanup"));
        assert_eq!(drops.load(Ordering::SeqCst), 1, "the payload was dropped");
        assert_eq!(live, 0);
    }

    /// Test 5. A fatal error is recorded, then the handler panics. The
    /// fatal outcome wins, and the payload is dropped through
    /// `discard_panic`.
    #[tokio::test]
    async fn fatal_before_panic_wins() {
        let drops = counter();
        let handler_drops = Arc::clone(&drops);
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            ctx.coordinator()
                .record_fatal("Fatal".to_owned(), "first".to_owned());
            panic_tagged(5, &handler_drops)
        })
        .await;
        let Ok(InvocationOutcome::Failed { error }) = &driven else {
            panic!("expected the fatal outcome, got {driven:?}");
        };
        assert_eq!(error.error_message(), Some("first"));
        assert_eq!(drops.load(Ordering::SeqCst), 1, "the payload was dropped");
        assert_eq!(live, 0);
    }

    /// Test 18. The handler panics with A. The cleanup then aborts a
    /// pending task whose future panics with B when dropped. A is
    /// resumed, and B is dropped through `discard_panic`.
    #[tokio::test(flavor = "current_thread")]
    async fn first_recorded_panic_wins() {
        let a_drops = counter();
        let b_drops = counter();
        let (handler_a, handler_b) = (Arc::clone(&a_drops), Arc::clone(&b_drops));
        let escaped: Arc<Mutex<Option<DurableFuture<()>>>> = Arc::new(Mutex::new(None));
        let kept = Arc::clone(&escaped);
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let started = Arc::new(AtomicBool::new(false));
            let guard = PanicsOnDrop(182, handler_b);
            *kept.lock().expect("lock") = Some(spawn_holding(&ctx, "hold", guard, &started));
            until(&ctx, || started.load(Ordering::SeqCst)).await;
            panic_tagged(181, &handler_a)
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(181));
        assert_eq!(b_drops.load(Ordering::SeqCst), 1, "B was dropped");
        assert_eq!(
            a_drops.load(Ordering::SeqCst),
            0,
            "A is returned, not dropped"
        );
        assert_eq!(live, 0);
    }

    /// Test 19. The handler returns `Ok`. One task the cleanup aborts
    /// panics when dropped; another holds a drop flag. The cleanup goes on
    /// after the panic, so the second task is dropped too.
    #[tokio::test]
    async fn cleanup_continues_after_a_panic() {
        let flag = Arc::new(AtomicBool::new(false));
        let handler_flag = Arc::clone(&flag);
        let escaped: Arc<Mutex<Vec<DurableFuture<()>>>> = Arc::new(Mutex::new(Vec::new()));
        let kept = Arc::clone(&escaped);
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let first = Arc::new(AtomicBool::new(false));
            let second = Arc::new(AtomicBool::new(false));
            let a = spawn_holding(&ctx, "panics", PanicsOnDrop(19, counter()), &first);
            let b = spawn_holding(&ctx, "flag", DropFlag(handler_flag), &second);
            kept.lock().expect("lock").extend([a, b]);
            until(&ctx, || {
                first.load(Ordering::SeqCst) && second.load(Ordering::SeqCst)
            })
            .await;
            Ok("done".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(19));
        assert!(flag.load(Ordering::SeqCst), "the second task was dropped");
        assert_eq!(live, 0);
    }

    /// Test 20. The handler future holds a value that panics when the
    /// cleanup drops the root task, after the drive ended by suspension.
    #[tokio::test]
    async fn root_drop_panic_during_cleanup_fails_invocation() {
        let (driven, live) = drive(live_ctx(), |ctx| async move {
            let _guard = PanicsOnDrop(20, counter());
            ctx.wait(Duration::from_secs(10))
                .name("timer")
                .await
                .map_err(|err| {
                    crate::error::WireError::new(None::<String>, Some(err.to_string()))
                })?;
            Ok("unreachable".to_owned())
        })
        .await;
        assert_eq!(returned_tag(&driven), Some(20));
        assert_eq!(live, 0);
    }

    /// A test scheduler that panics with `Tagged(n)` at its first poll.
    struct PanickingScheduler(u32);

    impl Future for PanickingScheduler {
        type Output = ();

        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
            panic_tagged(self.0, &counter())
        }
    }

    /// A test scheduler that stays pending and panics with `Tagged(n)` when
    /// dropped.
    struct DropPanickingScheduler {
        _guard: PanicsOnDrop,
    }

    impl Future for DropPanickingScheduler {
        type Output = ();

        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
            Poll::Pending
        }
    }

    /// Drives a handler that holds a step and returns once the step runs,
    /// with `scheduler` polled in place of the refresh scheduler.
    async fn drive_with<S: Future<Output = ()>>(
        scheduler: S,
        wait_forever: bool,
    ) -> (Driven, usize, bool) {
        let ctx = live_ctx();
        let ownership = Arc::clone(ctx.task_ownership());
        let coordinator = Arc::clone(ctx.coordinator());
        let tasks = Arc::clone(coordinator.tasks());
        let dropped = Arc::new(AtomicBool::new(false));
        let body_dropped = Arc::clone(&dropped);
        let handler = async move {
            let started = Arc::new(AtomicBool::new(false));
            let _step = spawn_holding(&ctx, "hold", DropFlag(body_dropped), &started);
            if wait_forever {
                ctx.hold_activity(std::future::pending::<()>()).await;
            }
            until(&ctx, || started.load(Ordering::SeqCst)).await;
            Ok("done".to_owned())
        };
        let driven = drive_with_scheduler(
            crate::task::TaskContext::none(),
            handler,
            ownership,
            coordinator,
            scheduler,
            None,
        )
        .await
        .map(|(outcome, _)| outcome);
        (driven, tasks.live(), dropped.load(Ordering::SeqCst))
    }

    /// Test 21. (a) The scheduler panics at its first poll while the
    /// handler's work is live; (b) a pending scheduler panics when the
    /// cleanup drops it after the handler returned. Each fails the
    /// invocation after the cleanup.
    #[tokio::test]
    async fn scheduler_poll_or_drop_panic_fails_after_cleanup() {
        let (driven, live, _) = drive_with(PanickingScheduler(211), true).await;
        assert_eq!(returned_tag(&driven), Some(211));
        assert_eq!(live, 0);

        let (driven, live, dropped) = drive_with(
            DropPanickingScheduler {
                _guard: PanicsOnDrop(212, counter()),
            },
            false,
        )
        .await;
        assert_eq!(returned_tag(&driven), Some(212));
        assert!(dropped, "the cleanup dropped the step after the panic");
        assert_eq!(live, 0);
    }

    /// A payload that holds a context, counts its drops, and panics when
    /// dropped with a payload whose destructor panics again.
    struct SelfReferential(Option<DurableContext>, Arc<AtomicUsize>);

    impl Drop for SelfReferential {
        fn drop(&mut self) {
            drop(self.0.take());
            self.1.fetch_add(1, Ordering::SeqCst);
            std::panic::panic_any(super::task_gateway::NestedPanicPayload);
        }
    }

    /// Polls `drive` until the handler was dropped and the drive is in its
    /// cleanup, waiting for a detached task.
    async fn poll_into_cleanup(
        drive: &mut Pin<Box<impl Future<Output = Driven>>>,
        coordinator: &InvocationCoordinator,
        handler_dropped: &AtomicBool,
    ) {
        for _ in 0..1000 {
            let polled = std::future::poll_fn(|cx| Poll::Ready(drive.as_mut().poll(cx))).await;
            assert!(polled.is_pending(), "the drive waits for the detached task");
            if handler_dropped.load(Ordering::SeqCst)
                && coordinator.phase() == crate::coordinator::Phase::Finished
            {
                return;
            }
            tokio::task::yield_now().await;
        }
        panic!("the drive did not reach its cleanup");
    }

    /// Test 3. A payload holds the only remaining `DurableContext` clone,
    /// so it keeps the coordinator alive. (a) It is recorded, and the drive
    /// is dropped before the arbitration: the guard drops it. (b) A
    /// detached task is in flight when the drive is dropped, and panics
    /// with it afterwards: the payload comes back to the task, which drops
    /// it. In both cases the payload is dropped once, no panic escapes, and
    /// the coordinator keeps nothing.
    #[tokio::test]
    async fn cancelled_drive_discards_self_referential_panic() {
        for late in [false, true] {
            let ctx = live_ctx();
            let ownership = Arc::clone(ctx.task_ownership());
            let coordinator = Arc::clone(ctx.coordinator());
            let root = ctx.clone();
            let drops = counter();
            let handler_drops = Arc::clone(&drops);
            let handler_dropped = Arc::new(AtomicBool::new(false));
            let flag = DropFlag(Arc::clone(&handler_dropped));
            let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
            let handler = async move {
                let _flag = flag;
                if late {
                    // The detached task takes the only context clone left
                    // after the drive is dropped.
                    let payload_ctx = ctx.clone();
                    let detached = async move {
                        drop(release_rx.await);
                        std::panic::panic_any(SelfReferential(Some(payload_ctx), handler_drops));
                    };
                    crate::task::spawn_detached(ctx.coordinator(), detached).expect("runtime");
                } else {
                    // A detached task keeps the cleanup waiting until the
                    // test releases it.
                    let detached = async move {
                        drop(release_rx.await);
                    };
                    crate::task::spawn_detached(ctx.coordinator(), detached).expect("runtime");
                    let payload = SelfReferential(Some(ctx.clone()), handler_drops);
                    assert!(ctx.coordinator().record_panic(Box::new(payload)).is_none());
                }
                drop(ctx);
                if late {
                    // The handler returns, so the cleanup waits for the
                    // detached task.
                    return Ok("done".to_owned());
                }
                std::future::pending::<Result<String, crate::error::WireError>>().await
            };
            let mut drive = Box::pin(drive_outcome(
                handler,
                ownership,
                Arc::clone(&coordinator),
                root,
                None,
            ));
            poll_into_cleanup(&mut drive, &coordinator, &handler_dropped).await;
            let dropped =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || drop(drive)));
            assert!(dropped.is_ok(), "no panic escapes the drop");
            release_tx.send(()).expect("the detached task waits");
            coordinator.tasks().wait_idle().await;
            assert_eq!(drops.load(Ordering::SeqCst), 1, "late = {late}");
            assert!(!coordinator.has_panic(), "late = {late}");
            assert!(coordinator.take_panic().is_none());
        }
    }

    /// A client whose checkpoint future panics with `Tagged(n)`, at its
    /// poll or, with `on_drop`, when it is dropped after it returned.
    #[derive(Debug)]
    struct PanickingClient {
        n: u32,
        on_drop: bool,
    }

    /// Returns a checkpoint output and panics with `Tagged(n)` when
    /// dropped.
    struct ReadyThenDropPanics(u32);

    impl Future for ReadyThenDropPanics {
        type Output = Result<CheckpointOutput, ExecutionClientError>;

        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
            Poll::Ready(Ok(CheckpointOutput {
                checkpoint_token: Some("token1".to_owned()),
                updated_operations: Vec::new(),
                next_marker: None,
            }))
        }
    }

    impl Drop for ReadyThenDropPanics {
        fn drop(&mut self) {
            panic_tagged(self.0, &counter());
        }
    }

    impl ExecutionClient for PanickingClient {
        fn checkpoint(
            &self,
            _arn: &str,
            _token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            let n = self.n;
            if self.on_drop {
                return Box::pin(ReadyThenDropPanics(n));
            }
            Box::pin(async move { panic_tagged(n, &counter()) })
        }

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

    /// Test 15. With checkpoint batching, the client's checkpoint future
    /// returns and then panics when the flusher drops it. The gateway
    /// records the flusher's panic.
    #[tokio::test]
    async fn detached_future_drop_panic_fails_invocation() {
        let ctx = DurableContext::new_root_with_client_and_coalescer(
            "arn:aws:lambda:us-east-1:1:function:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::new(PanickingClient {
                n: 15,
                on_drop: true,
            }) as Arc<dyn ExecutionClient>,
            "token0".to_owned(),
            crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
        );
        let (driven, live) = tokio::time::timeout(
            Duration::from_secs(10),
            drive(ctx, |ctx| async move {
                ctx.step(|_| async { Ok(1_u32) })
                    .name("s")
                    .await
                    .map_err(|err| {
                        crate::error::WireError::new(None::<String>, Some(err.to_string()))
                    })?;
                Ok("done".to_owned())
            }),
        )
        .await
        .expect("the drive ends");
        assert_eq!(returned_tag(&driven), Some(15));
        assert_eq!(live, 0);
    }

    /// Test 17. Without batching, an operation's write future is polled
    /// after its client panicked: it stays pending, because the write
    /// channel carries no payload. The drive returns the client's payload.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn write_waiter_stays_pending_when_client_panics() {
        let ctx = ctx_with(Arc::new(PanickingClient {
            n: 17,
            on_drop: false,
        }));
        let second_poll: Arc<Mutex<Option<bool>>> = Arc::new(Mutex::new(None));
        let observed = Arc::clone(&second_poll);
        let (driven, live) = tokio::time::timeout(
            Duration::from_secs(10),
            drive(ctx, |ctx| async move {
                let update = OperationUpdate::builder()
                    .id("w")
                    .r#type(aws_sdk_lambda::types::OperationType::Step)
                    .action(aws_sdk_lambda::types::OperationAction::Start)
                    .build()
                    .expect("valid update");
                let mut write = std::pin::pin!(ctx.checkpoint_updates(vec![update]));
                std::future::poll_fn(|cx| {
                    assert!(
                        write.as_mut().poll(cx).is_pending(),
                        "the write runs on its task"
                    );
                    // The write task runs on the other worker. Wait for its
                    // panic inside this poll, so the driver cannot end the
                    // drive between the two polls.
                    // `block_in_place` hands this worker's other tasks,
                    // the new write task among them, to another worker.
                    tokio::task::block_in_place(|| {
                        let start = std::time::Instant::now();
                        while !ctx.coordinator().has_panic() {
                            assert!(
                                start.elapsed() < Duration::from_secs(5),
                                "the client panics"
                            );
                            std::thread::sleep(Duration::from_millis(1));
                        }
                    });
                    *observed.lock().expect("lock") = Some(write.as_mut().poll(cx).is_pending());
                    Poll::Ready(())
                })
                .await;
                std::future::pending::<Result<String, crate::error::WireError>>().await
            }),
        )
        .await
        .expect("the drive ends");
        assert_eq!(
            *second_poll.lock().expect("lock"),
            Some(true),
            "the waiter stays pending"
        );
        assert_eq!(returned_tag(&driven), Some(17));
        assert_eq!(live, 0);
    }

    /// A test scheduler that stays pending. When the cleanup drops it, it
    /// waits until a probe task, spawned after the root task, has run.
    struct ProbeOnDrop(Arc<AtomicBool>);

    impl Future for ProbeOnDrop {
        type Output = ();

        fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
            Poll::Pending
        }
    }

    impl Drop for ProbeOnDrop {
        // The probe is spawned outside the SDK's gateway, so it queues
        // behind the root task on the runtime's inject queue.
        fn drop(&mut self) {
            let (tx, rx) = std::sync::mpsc::channel();
            drop(tokio::runtime::Handle::current().spawn(async move {
                tx.send(()).ok();
            }));
            // A timeout would leave the flag unset, which fails the test.
            if rx.recv_timeout(Duration::from_secs(10)).is_ok() {
                self.0.store(true, Ordering::SeqCst);
            }
        }
    }

    /// A panic recorded before the drive starts ends it before the handler
    /// runs. The runtime has one worker, and the driver runs on the
    /// `block_on` thread. So the root task and the probe both go to the
    /// runtime's inject queue, in that order, and the worker takes them in
    /// that order. The cleanup drops the scheduler before it aborts the
    /// root, and the scheduler's drop waits for the probe. So the worker
    /// has started the root task before the abort, and the handler stays
    /// unpolled only because the root cannot take a permit.
    #[test]
    fn panic_recorded_before_the_drive_leaves_the_handler_unpolled() {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .expect("runtime");
        let drops = counter();
        let polled = Arc::new(AtomicBool::new(false));
        let probe_ran = Arc::new(AtomicBool::new(false));
        let handler_polled = Arc::clone(&polled);
        let scheduler = ProbeOnDrop(Arc::clone(&probe_ran));
        let driven = runtime.block_on(async {
            let ctx = live_ctx();
            let ownership = Arc::clone(ctx.task_ownership());
            let coordinator = Arc::clone(ctx.coordinator());
            assert!(
                coordinator
                    .record_panic(Box::new(Tagged(119, Arc::clone(&drops))))
                    .is_none(),
                "the coordinator keeps the panic"
            );
            let handler = async move {
                handler_polled.store(true, Ordering::SeqCst);
                std::future::pending::<Result<String, crate::error::WireError>>().await
            };
            drive_with_scheduler(
                crate::task::TaskContext::none(),
                handler,
                ownership,
                coordinator,
                scheduler,
                None,
            )
            .await
            .map(|(outcome, _)| outcome)
        });
        assert!(probe_ran.load(Ordering::SeqCst), "the probe ran");
        assert!(
            !polled.load(Ordering::SeqCst),
            "the handler is never polled"
        );
        assert_eq!(returned_tag(&driven), Some(119));
    }
}

/// Tests of the answer to a checkpoint response without a token.
#[cfg(test)]
mod withdrawal_tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

    use aws_sdk_lambda::types::{
        Operation, OperationAction, OperationStatus as WireStatus, OperationType, OperationUpdate,
    };

    use super::test_support::EventMessages;
    use crate::client::{
        CheckpointOutput, ExecutionClient, ExecutionClientError, ExecutionClientErrorScope,
        GetStateOutput, InMemoryExecutionClient,
    };
    use crate::coordinator::{PermitKind, Phase, WITHDRAWAL_WARNING};
    use crate::engine::CheckpointLog;
    use crate::plugin::{
        HookFuture, HookWork, InvocationEndInfo, InvocationInfo, OperationChangeInfo,
        OperationInfo, Plugin, PluginFactory,
    };
    use crate::{BoxError, DurableContext, InvocationStatus, Options, WireError};

    const ARN: &str = "arn:aws:lambda:us-east-1:1:function:test";
    const REQUEST_ID: &str = "req-1";

    /// How [`WithdrawingClient`] answers one checkpoint request.
    #[derive(Clone)]
    enum Answer {
        /// As [`InMemoryExecutionClient`] answers it, with a token.
        Pass,
        /// `CheckpointOutput::new(None, vec![], None)`.
        Tokenless,
        /// No token, with these operations and this marker.
        TokenlessWith(Vec<Operation>, String),
        /// A transport error of this scope.
        Fail(ExecutionClientErrorScope),
    }

    /// Decides the answer to request `n` (1-based) with `updates`, and the
    /// tokio time to wait before it.
    type Script = dyn Fn(usize, &[OperationUpdate]) -> (Answer, Duration) + Send + Sync;

    /// A scripted `ExecutionClient` that records every call.
    struct WithdrawingClient {
        inner: InMemoryExecutionClient,
        script: Box<Script>,
        calls: Mutex<Vec<Vec<OperationUpdate>>>,
        get_state_calls: AtomicUsize,
        /// When set, every `get_state` call fails.
        get_state_fails: std::sync::atomic::AtomicBool,
    }

    impl WithdrawingClient {
        fn new(
            script: impl Fn(usize, &[OperationUpdate]) -> (Answer, Duration) + Send + Sync + 'static,
        ) -> Arc<Self> {
            Arc::new(Self {
                inner: InMemoryExecutionClient::new(Vec::new()),
                script: Box::new(script),
                calls: Mutex::new(Vec::new()),
                get_state_calls: AtomicUsize::new(0),
                get_state_fails: std::sync::atomic::AtomicBool::new(false),
            })
        }

        /// Answers request `n` without a token, and every other one as
        /// [`Answer::Pass`].
        fn tokenless_at(n: usize) -> Arc<Self> {
            Self::new(move |call, _| {
                if call == n {
                    (Answer::Tokenless, Duration::ZERO)
                } else {
                    (Answer::Pass, Duration::ZERO)
                }
            })
        }

        fn calls(&self) -> Vec<Vec<OperationUpdate>> {
            self.calls.lock().unwrap().clone()
        }

        fn updates(&self) -> Vec<OperationUpdate> {
            self.calls().into_iter().flatten().collect()
        }
    }

    impl ExecutionClient for WithdrawingClient {
        fn checkpoint(
            &self,
            execution_arn: &str,
            checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> std::pin::Pin<
            Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
        > {
            let number = {
                let mut calls = self.calls.lock().unwrap();
                calls.push(updates.clone());
                calls.len()
            };
            let (answer, delay) = (self.script)(number, &updates);
            let pass = matches!(answer, Answer::Pass).then(|| {
                self.inner
                    .checkpoint(execution_arn, checkpoint_token, updates)
            });
            Box::pin(async move {
                if !delay.is_zero() {
                    tokio::time::sleep(delay).await;
                }
                match answer {
                    Answer::Pass => match pass {
                        Some(pass) => pass.await,
                        None => unreachable!("a pass answer has a future"),
                    },
                    Answer::Tokenless => Ok(CheckpointOutput::new(None, vec![], None)),
                    Answer::TokenlessWith(operations, marker) => {
                        Ok(CheckpointOutput::new(None, operations, Some(marker)))
                    }
                    Answer::Fail(scope) => Err(ExecutionClientError::new(
                        scope,
                        "scripted checkpoint failure",
                    )),
                }
            })
        }

        fn get_state(
            &self,
            execution_arn: &str,
            checkpoint_token: &str,
            marker: Option<&str>,
        ) -> std::pin::Pin<
            Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
        > {
            self.get_state_calls.fetch_add(1, Ordering::SeqCst);
            if self.get_state_fails.load(Ordering::SeqCst) {
                return Box::pin(async {
                    Err(ExecutionClientError::new_non_retryable(
                        "scripted get_state failure",
                    ))
                });
            }
            self.inner
                .get_state(execution_arn, checkpoint_token, marker)
        }
    }

    /// What a [`RecordingPlugin`] saw.
    #[derive(Default)]
    struct Seen {
        ends: Vec<(InvocationStatus, Option<WireError>)>,
        operation_starts: usize,
        operation_ends: usize,
        changes: usize,
    }

    #[derive(Clone, Default)]
    struct RecordingFactory(Arc<Mutex<Seen>>);

    impl RecordingFactory {
        /// The end hook's status and error. Exactly one end hook ran.
        fn end(&self) -> (InvocationStatus, Option<WireError>) {
            let seen = self.0.lock().unwrap();
            assert_eq!(seen.ends.len(), 1, "one end hook");
            seen.ends.first().cloned().unwrap()
        }
    }

    impl PluginFactory for RecordingFactory {
        fn create_plugin(
            &self,
            _info: &InvocationInfo,
        ) -> Result<Option<Box<dyn Plugin>>, BoxError> {
            Ok(Some(Box::new(RecordingPlugin(Arc::clone(&self.0)))))
        }
    }

    struct RecordingPlugin(Arc<Mutex<Seen>>);

    impl Plugin for RecordingPlugin {
        fn on_operation_start(&self, _info: &OperationInfo) -> HookWork {
            self.0.lock().unwrap().operation_starts += 1;
            Ok(None)
        }

        fn on_operation_end(&self, _info: &OperationInfo) -> HookWork {
            self.0.lock().unwrap().operation_ends += 1;
            Ok(None)
        }

        fn on_operation_change(&self, _info: &OperationChangeInfo) -> HookWork {
            self.0.lock().unwrap().changes += 1;
            Ok(None)
        }

        fn on_invocation_end<'a>(&'a self, info: &'a InvocationEndInfo) -> HookFuture<'a> {
            self.0
                .lock()
                .unwrap()
                .ends
                .push((info.status(), info.execution_error().cloned()));
            Box::pin(std::future::ready(Ok(())))
        }
    }

    /// Runs `handler` behind `wrap` over `client` on a new execution, with
    /// checkpoint batching `batching` and `factory`, and returns the
    /// response.
    async fn run<F, Fut>(
        client: &Arc<WithdrawingClient>,
        batching: bool,
        factory: &RecordingFactory,
        handler: F,
    ) -> serde_json::Value
    where
        F: Fn(serde_json::Value, DurableContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<u32, BoxError>> + Send,
    {
        run_on(client, batching, factory, &[], handler).await
    }

    /// [`run`] on an execution whose state also holds `records`.
    async fn run_on<F, Fut>(
        client: &Arc<WithdrawingClient>,
        batching: bool,
        factory: &RecordingFactory,
        records: &[serde_json::Value],
        handler: F,
    ) -> serde_json::Value
    where
        F: Fn(serde_json::Value, DurableContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<u32, BoxError>> + Send,
    {
        run_result(client, batching, factory, records, handler)
            .await
            .expect("the invocation answers a response")
    }

    /// [`run_on`] that returns a Lambda error instead of failing.
    async fn run_result<F, Fut>(
        client: &Arc<WithdrawingClient>,
        batching: bool,
        factory: &RecordingFactory,
        records: &[serde_json::Value],
        handler: F,
    ) -> Result<serde_json::Value, lambda_runtime::Error>
    where
        F: Fn(serde_json::Value, DurableContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<u32, BoxError>> + Send,
    {
        let mut operations = vec![serde_json::json!({
            "Id": "root",
            "Type": "EXECUTION",
            "Status": "STARTED",
            "ExecutionDetails": { "InputPayload": "{}" }
        })];
        operations.extend_from_slice(records);
        let options = Options::builder()
            .execution_client(Arc::clone(client) as Arc<dyn ExecutionClient>)
            .checkpoint_batching(batching)
            .plugin(factory.clone())
            .build()
            .unwrap();
        let service = crate::wrap(handler, options);
        let mut lambda_ctx = lambda_runtime::Context::default();
        lambda_ctx.request_id = REQUEST_ID.to_owned();
        let event = lambda_runtime::LambdaEvent::new(
            crate::InvocationPayload(serde_json::json!({
                "DurableExecutionArn": ARN,
                "CheckpointToken": "t0",
                "InitialExecutionState": { "Operations": operations }
            })),
            lambda_ctx,
        );
        tokio::time::timeout(Duration::from_secs(60), service(event))
            .await
            .expect("the invocation ends")
            .map(|response| response.0)
    }

    /// Asserts that the last request `client` received carries `name`'s
    /// update with `action`: no request follows the failed one.
    fn last_request_has(client: &WithdrawingClient, name: &str, action: &OperationAction) {
        let calls = client.calls();
        let last = calls.last().expect("a request was sent");
        assert!(has(last, name, action), "{calls:?}");
    }

    /// Asserts the answer and the end of an invocation whose checkpoint
    /// write failed with a transport error of `scope`: a Lambda error and
    /// a `Retrying` end for `Invocation`, and `FAILED` with a `Failed` end
    /// for `Execution`, each with the failure's error.
    fn assert_failure_answer(
        scope: ExecutionClientErrorScope,
        response: Result<serde_json::Value, lambda_runtime::Error>,
        factory: &RecordingFactory,
    ) {
        let (status, error) = factory.end();
        let error = error.expect("the end carries the failure");
        if scope == ExecutionClientErrorScope::Invocation {
            let err = response.expect_err("the invocation fails");
            assert_eq!(status, InvocationStatus::Retrying);
            assert_eq!(
                error.error_type(),
                Some(crate::error::CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE)
            );
            assert_eq!(error.error_message(), Some(err.to_string().as_str()));
        } else {
            let response = response.expect("an envelope");
            assert_eq!(
                response
                    .pointer("/Status")
                    .and_then(serde_json::Value::as_str),
                Some("FAILED"),
                "{response}"
            );
            assert_eq!(status, InvocationStatus::Failed);
            assert_eq!(
                error.error_type(),
                Some(crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE)
            );
            assert_eq!(
                response
                    .pointer("/Error/ErrorType")
                    .and_then(serde_json::Value::as_str),
                Some(crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE)
            );
        }
        assert!(
            error
                .error_message()
                .is_some_and(|m| m.contains("scripted checkpoint failure")),
            "{error:?}"
        );
    }

    fn pending() -> serde_json::Value {
        serde_json::json!({ "Status": "PENDING" })
    }

    /// Whether `updates` hold an update of `name` with `action`.
    fn has(updates: &[OperationUpdate], name: &str, action: &OperationAction) -> bool {
        updates
            .iter()
            .any(|u| u.name() == Some(name) && u.action() == action)
    }

    fn no_fail(client: &WithdrawingClient) -> bool {
        client
            .updates()
            .iter()
            .all(|u| u.action() != &OperationAction::Fail)
    }

    /// A root context on `client`, without buffering.
    fn direct_ctx(client: &Arc<WithdrawingClient>) -> DurableContext {
        DurableContext::new_root_with_client(
            ARN.to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::clone(client) as Arc<dyn ExecutionClient>,
            "t0".to_owned(),
        )
    }

    fn step_start(id: &str) -> OperationUpdate {
        OperationUpdate::builder()
            .id(id)
            .r#type(OperationType::Step)
            .action(OperationAction::Start)
            .build()
            .unwrap()
    }

    #[tokio::test]
    async fn tokenless_direct_checkpoint_answers_pending() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            Ok(ctx.step(|_| async { Ok(1_u32) }).name("a").await?)
        })
        .await;
        assert_eq!(response, pending());
        assert_eq!(client.calls().len(), 1);
        assert!(no_fail(&client));
        assert_eq!(factory.end(), (InvocationStatus::Pending, None));
    }

    #[tokio::test]
    async fn tokenless_buffered_checkpoint_answers_pending() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, true, &factory, |_event, ctx| async move {
            let a = ctx.step(|_| async { Ok(1_u32) }).name("a").spawn();
            let b = ctx.step(|_| async { Ok(2_u32) }).name("b").spawn();
            Ok(a.await? + b.await?)
        })
        .await;
        assert_eq!(response, pending());
        let calls = client.calls();
        assert_eq!(calls.len(), 1, "{calls:?}");
        let first = calls.first().unwrap();
        assert!(has(first, "a", &OperationAction::Start), "{first:?}");
        assert!(has(first, "b", &OperationAction::Start), "{first:?}");
        assert!(no_fail(&client));
        assert_eq!(factory.end(), (InvocationStatus::Pending, None));
    }

    #[tokio::test]
    async fn tokenless_latch_blocks_later_checkpoints() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            let a = ctx.step(|_| async { Ok(1_u32) }).name("a").spawn();
            let b = ctx.step(|_| async { Ok(2_u32) }).name("b").spawn();
            Ok(a.await? + b.await?)
        })
        .await;
        assert_eq!(response, pending());
        let calls = client.calls();
        assert_eq!(calls.len(), 1, "{calls:?}");
        assert!(has(calls.first().unwrap(), "a", &OperationAction::Start));
        assert!(!has(&client.updates(), "b", &OperationAction::Start));
    }

    #[tokio::test]
    async fn tokenless_emits_lifecycle_events_not_plugin_hooks() {
        let (messages, _guard) = EventMessages::install();
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            Ok(ctx
                .step(|_| async { Ok(1_u32) })
                .name("a")
                .semantics(crate::StepSemantics::AtMostOncePerRetry)
                .await?)
        })
        .await;
        assert_eq!(response, pending());
        let started = messages
            .at(tracing::Level::INFO)
            .into_iter()
            .chain(messages.at(tracing::Level::DEBUG))
            .filter(|m| m == crate::observability::event_names::OPERATION_STARTED)
            .count();
        assert_eq!(started, 1, "the accepted START emits its event");
        let seen = factory.0.lock().unwrap();
        assert_eq!(seen.changes, 0, "no on_operation_change");
        assert_eq!(seen.operation_starts, 0, "no operation start hook");
        assert_eq!(seen.operation_ends, 0, "no operation end hook");
    }

    /// One recorded event: its level, target and fields.
    type Recorded = (tracing::Level, String, Vec<(String, String)>);

    /// Records every event's level, target and fields.
    #[derive(Clone, Default)]
    struct FieldsLayer(Arc<Mutex<Vec<Recorded>>>);

    struct FieldsVisitor(Vec<(String, String)>);

    impl tracing::field::Visit for FieldsVisitor {
        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
            self.0.push((field.name().to_owned(), format!("{value:?}")));
        }
    }

    impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for FieldsLayer {
        fn on_event(
            &self,
            event: &tracing::Event<'_>,
            _ctx: tracing_subscriber::layer::Context<'_, S>,
        ) {
            let mut visitor = FieldsVisitor(Vec::new());
            event.record(&mut visitor);
            let meta = event.metadata();
            self.0
                .lock()
                .unwrap()
                .push((*meta.level(), meta.target().to_owned(), visitor.0));
        }
    }

    #[tokio::test]
    async fn tokenless_warns_once_with_fields() {
        use tracing_subscriber::layer::SubscriberExt as _;
        let layer = FieldsLayer::default();
        let _guard = test_tracing::install_test_subscriber(
            tracing_subscriber::registry().with(layer.clone()),
        );
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            drop(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn());
            Ok(1)
        })
        .await;
        assert_eq!(response, pending());
        let warns: Vec<Recorded> = layer
            .0
            .lock()
            .unwrap()
            .iter()
            .filter(|(level, _, _)| *level == tracing::Level::WARN)
            .cloned()
            .collect();
        assert_eq!(warns.len(), 1, "{warns:?}");
        let (_, target, fields) = warns.first().unwrap();
        assert_eq!(target, "aws_durable_execution_sdk::coordinator");
        let field = |name: &str| {
            fields
                .iter()
                .find(|(n, _)| n == name)
                .map(|(_, v)| v.clone())
        };
        assert_eq!(field("executionArn").as_deref(), Some(ARN));
        assert_eq!(field("requestId").as_deref(), Some(REQUEST_ID));
        assert_eq!(field("message").as_deref(), Some(WITHDRAWAL_WARNING));
    }

    #[tokio::test(start_paused = true)]
    async fn tokenless_discards_new_state() {
        let state = Operation::builder()
            .id("other")
            .r#type(OperationType::Step)
            .status(WireStatus::Succeeded)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .build()
            .unwrap();
        let client = WithdrawingClient::new(move |_, _| {
            (
                Answer::TokenlessWith(vec![state.clone()], "marker".to_owned()),
                Duration::ZERO,
            )
        });
        let ctx = direct_ctx(&client);
        let write = ctx.submit_checkpoint_updates(vec![step_start("x")]);
        assert!(
            tokio::time::timeout(Duration::from_secs(5), write)
                .await
                .is_err(),
            "the caller never resolves"
        );
        assert!(ctx.coordinator().withdrawn());
        assert!(
            ctx.checkpoint_status_view("other").is_none()
                && ctx.checkpoint_status_view("x").is_none(),
            "the state is not merged"
        );
        assert_eq!(client.get_state_calls.load(Ordering::SeqCst), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn tokenless_leaves_queued_contributors_unresolved() {
        let client = WithdrawingClient::new(|n, _| {
            if n == 1 {
                (Answer::Tokenless, Duration::from_secs(1))
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let ctx = DurableContext::new_root_with_client_and_coalescer(
            ARN.to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::clone(&client) as Arc<dyn ExecutionClient>,
            "t0".to_owned(),
            crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
        );
        let first = ctx.submit_checkpoint_updates(vec![step_start("x")]);
        while client.calls().is_empty() {
            tokio::task::yield_now().await;
        }
        let second = ctx.submit_checkpoint_updates(vec![step_start("y")]);
        let (first, second) = tokio::join!(
            tokio::time::timeout(Duration::from_secs(5), first),
            tokio::time::timeout(Duration::from_secs(5), second),
        );
        assert!(first.is_err(), "the in-flight caller never resolves");
        assert!(second.is_err(), "the queued caller never resolves");
        assert!(ctx.coordinator().withdrawn());
        assert_eq!(client.calls().len(), 1, "the queued update is never sent");
    }

    /// The withdrawal drops the queued writes itself: a reserved write,
    /// which no writer would ever take while it is held, is dropped with
    /// its permit, unbuffered and buffered alike. It is never sent, even
    /// after its reservation is released.
    #[tokio::test(start_paused = true)]
    async fn withdrawal_drops_queued_and_held_writes() {
        for buffered in [false, true] {
            let client = WithdrawingClient::new(|n, _| {
                if n == 1 {
                    (Answer::Tokenless, Duration::from_secs(1))
                } else {
                    (Answer::Pass, Duration::ZERO)
                }
            });
            let ctx = if buffered {
                DurableContext::new_root_with_client_and_coalescer(
                    ARN.to_owned(),
                    lambda_runtime::Context::default(),
                    Arc::new(CheckpointLog::empty()),
                    Arc::clone(&client) as Arc<dyn ExecutionClient>,
                    "t0".to_owned(),
                    crate::checkpoint_coalescer::CheckpointCoalescer::new(Duration::ZERO),
                )
            } else {
                direct_ctx(&client)
            };
            let first = ctx.submit_checkpoint_updates(vec![step_start("x")]);
            while client.calls().is_empty() {
                tokio::task::yield_now().await;
            }
            let held = ctx.reserve_checkpoint_updates(vec![step_start("y")]);
            assert_eq!(ctx.coordinator().permits(PermitKind::Checkpoint), 2);
            assert!(
                tokio::time::timeout(Duration::from_secs(5), first)
                    .await
                    .is_err(),
                "the in-flight caller never resolves"
            );
            assert!(ctx.coordinator().withdrawn());
            assert_eq!(ctx.coordinator().phase(), Phase::Suspending);
            assert_eq!(
                ctx.coordinator().permits(PermitKind::Checkpoint),
                0,
                "buffered={buffered}: the held write was dropped with its permit"
            );
            let held = held.release();
            assert!(
                tokio::time::timeout(Duration::from_secs(5), held)
                    .await
                    .is_err(),
                "the held caller never resolves"
            );
            assert_eq!(client.calls().len(), 1, "the held write is never sent");
        }
    }

    /// Runs a handler that spawns steps `a` and `b` together, so both
    /// STARTs are queued before either is written. `a`'s START fails at
    /// once with a transport error of `scope`, and `b`'s START, queued
    /// behind it, would be answered without a token.
    async fn queued_client_error(
        scope: ExecutionClientErrorScope,
    ) -> (
        Arc<WithdrawingClient>,
        Result<serde_json::Value, lambda_runtime::Error>,
        RecordingFactory,
    ) {
        let client = WithdrawingClient::new(move |_, updates| {
            if has(updates, "a", &OperationAction::Start) {
                (Answer::Fail(scope), Duration::ZERO)
            } else if has(updates, "b", &OperationAction::Start) {
                (Answer::Tokenless, Duration::ZERO)
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run_result(&client, false, &factory, &[], |_event, ctx| async move {
            let a = ctx.step(|_| async { Ok(1_u32) }).name("a").spawn();
            let b = ctx.step(|_| async { Ok(2_u32) }).name("b").spawn();
            Ok(a.await? + b.await?)
        })
        .await;
        (client, response, factory)
    }

    /// A failed write drops the write queued behind it: `b`'s START is
    /// never sent, and the failure is the answer.
    #[tokio::test]
    async fn queued_write_behind_invocation_client_error_is_not_sent() {
        let scope = ExecutionClientErrorScope::Invocation;
        let (client, response, factory) = queued_client_error(scope).await;
        assert_eq!(client.calls().len(), 1, "only a's START");
        assert_failure_answer(scope, response, &factory);
    }

    #[tokio::test]
    async fn queued_write_behind_execution_client_error_is_not_sent() {
        let scope = ExecutionClientErrorScope::Execution;
        let (client, response, factory) = queued_client_error(scope).await;
        assert_eq!(client.calls().len(), 1, "only a's START");
        assert!(no_fail(&client), "no terminal FAIL is sent");
        assert_failure_answer(scope, response, &factory);
    }

    /// Answers the request that holds `a`'s START after a second, without
    /// a token.
    fn tokenless_start_of_a_after_a_second() -> Arc<WithdrawingClient> {
        WithdrawingClient::new(|_, updates| {
            if has(updates, "a", &OperationAction::Start) {
                (Answer::Tokenless, Duration::from_secs(1))
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        })
    }

    #[tokio::test]
    async fn pending_wins_over_handler_ok() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            drop(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn());
            Ok(1)
        })
        .await;
        assert_eq!(response, pending());
        assert!(
            client
                .updates()
                .iter()
                .all(|u| u.r#type() != &OperationType::Execution),
            "no EXECUTION update is sent"
        );
        assert_eq!(factory.end(), (InvocationStatus::Pending, None));
    }

    #[tokio::test]
    async fn pending_wins_over_handler_err() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            drop(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn());
            Err::<u32, BoxError>("boom".into())
        })
        .await;
        assert_eq!(response, pending());
        let (status, error) = factory.end();
        assert_eq!(status, InvocationStatus::Pending);
        assert_eq!(error.unwrap().error_message(), Some("boom"));
    }

    /// Runs `handler_err` (or a handler that returns `Ok(1)`) after it
    /// spawns steps `a` and `b` and drops both handles, without buffering.
    /// `a`'s START fails with an invocation-scoped transport error after a
    /// second, after the handler returned, and `b`'s START, queued behind
    /// it, would be answered without a token.
    async fn failed_after_handler(
        handler_err: bool,
    ) -> (
        Arc<WithdrawingClient>,
        Result<serde_json::Value, lambda_runtime::Error>,
        RecordingFactory,
    ) {
        let client = WithdrawingClient::new(|_, updates| {
            if has(updates, "a", &OperationAction::Start) {
                (
                    Answer::Fail(ExecutionClientErrorScope::Invocation),
                    Duration::from_secs(1),
                )
            } else if has(updates, "b", &OperationAction::Start) {
                (Answer::Tokenless, Duration::ZERO)
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run_result(
            &client,
            false,
            &factory,
            &[],
            move |_event, ctx| async move {
                drop(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn());
                drop(ctx.step(|_| async { Ok(2_u32) }).name("b").spawn());
                if handler_err {
                    return Err::<u32, BoxError>("boom".into());
                }
                Ok(1)
            },
        )
        .await;
        (client, response, factory)
    }

    #[tokio::test(start_paused = true)]
    async fn failure_after_handler_ok_decides_and_stops_later_writes() {
        let (client, response, factory) = failed_after_handler(false).await;
        assert_eq!(client.calls().len(), 1, "only a's START");
        assert_failure_answer(ExecutionClientErrorScope::Invocation, response, &factory);
    }

    #[tokio::test(start_paused = true)]
    async fn failure_after_handler_err_decides_and_stops_later_writes() {
        let (client, response, factory) = failed_after_handler(true).await;
        assert_eq!(client.calls().len(), 1, "only a's START");
        assert_failure_answer(ExecutionClientErrorScope::Invocation, response, &factory);
    }

    /// The failure of a write whose caller was stopped before the response
    /// came decides the outcome: the wait's START queued behind it is never
    /// sent.
    #[tokio::test(start_paused = true)]
    async fn failure_of_stopped_caller_decides_and_stops_later_writes() {
        let client = WithdrawingClient::new(|_, updates| {
            if has(updates, "a", &OperationAction::Start) {
                (
                    Answer::Fail(ExecutionClientErrorScope::Invocation),
                    Duration::from_secs(1),
                )
            } else if has(updates, "w", &OperationAction::Start) {
                (Answer::Tokenless, Duration::ZERO)
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run_result(&client, false, &factory, &[], |_event, ctx| async move {
            // The child's body returns while `a`'s START is in flight, so
            // its scope closes and stops `a` before the response.
            ctx.run_in_child_context(|child| async move {
                drop(child.step(|_| async { Ok(1_u32) }).name("a").spawn());
                tokio::time::sleep(Duration::from_millis(500)).await;
                Ok(0_u32)
            })
            .name("c")
            .await?;
            ctx.wait(Duration::from_secs(60)).name("w").await?;
            Ok(1)
        })
        .await;
        assert!(!has(&client.updates(), "w", &OperationAction::Start));
        last_request_has(&client, "a", &OperationAction::Start);
        assert_failure_answer(ExecutionClientErrorScope::Invocation, response, &factory);
    }

    /// Runs a handler that spawns step `a`, drops its handle, waits 1.5 s
    /// and returns `Err("boom")` when `handler_err`, else `Ok(1)`, without
    /// buffering. `a`'s SUCCEED fails with an execution-scoped transport
    /// error after a second.
    async fn stopped_write_failure(
        handler_err: bool,
    ) -> (
        Arc<WithdrawingClient>,
        Result<serde_json::Value, lambda_runtime::Error>,
        RecordingFactory,
    ) {
        let client = WithdrawingClient::new(|_, updates| {
            if has(updates, "a", &OperationAction::Succeed) {
                (
                    Answer::Fail(ExecutionClientErrorScope::Execution),
                    Duration::from_secs(1),
                )
            } else if has(updates, "a", &OperationAction::Fail) {
                (Answer::Tokenless, Duration::from_secs(2))
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run_result(
            &client,
            false,
            &factory,
            &[],
            move |_event, ctx| async move {
                drop(ctx.step(|_| async { Ok(1_u32) }).name("a").spawn());
                tokio::time::sleep(Duration::from_millis(1500)).await;
                if handler_err {
                    return Err::<u32, BoxError>("boom".into());
                }
                Ok(1)
            },
        )
        .await;
        (client, response, factory)
    }

    #[tokio::test(start_paused = true)]
    async fn failed_outcome_write_decides_over_handler_ok_and_sends_no_fail() {
        let (client, response, factory) = stopped_write_failure(false).await;
        assert!(no_fail(&client), "a's terminal FAIL is not sent");
        last_request_has(&client, "a", &OperationAction::Succeed);
        assert_failure_answer(ExecutionClientErrorScope::Execution, response, &factory);
    }

    #[tokio::test(start_paused = true)]
    async fn failed_outcome_write_decides_over_handler_err_and_sends_no_fail() {
        let (client, response, factory) = stopped_write_failure(true).await;
        assert!(no_fail(&client), "a's terminal FAIL is not sent");
        last_request_has(&client, "a", &OperationAction::Succeed);
        assert_failure_answer(ExecutionClientErrorScope::Execution, response, &factory);
    }

    /// Runs a handler whose step `a` SUCCEED fails with a transport error
    /// of `scope` after a second, while step `b`'s START waits behind it
    /// and would be answered without a token. Returns the client, the
    /// answer and the end.
    async fn earlier_client_error(
        scope: ExecutionClientErrorScope,
    ) -> (
        Arc<WithdrawingClient>,
        Result<serde_json::Value, lambda_runtime::Error>,
        RecordingFactory,
    ) {
        let client = WithdrawingClient::new(move |_, updates| {
            if has(updates, "a", &OperationAction::Succeed) {
                (Answer::Fail(scope), Duration::from_secs(1))
            } else if has(updates, "b", &OperationAction::Start) {
                (Answer::Tokenless, Duration::from_secs(1))
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run_result(&client, false, &factory, &[], |_event, ctx| async move {
            let a = ctx.step(|_| async { Ok(1_u32) }).name("a").spawn();
            tokio::time::sleep(Duration::from_millis(500)).await;
            let b = ctx.step(|_| async { Ok(2_u32) }).name("b").spawn();
            Ok(a.await? + b.await?)
        })
        .await;
        (client, response, factory)
    }

    #[tokio::test(start_paused = true)]
    async fn invocation_client_error_stops_the_write_waiting_behind_it() {
        let scope = ExecutionClientErrorScope::Invocation;
        let (client, response, factory) = earlier_client_error(scope).await;
        assert!(!has(&client.updates(), "b", &OperationAction::Start));
        last_request_has(&client, "a", &OperationAction::Succeed);
        assert_failure_answer(scope, response, &factory);
    }

    #[tokio::test(start_paused = true)]
    async fn execution_client_error_stops_the_write_waiting_behind_it() {
        let scope = ExecutionClientErrorScope::Execution;
        let (client, response, factory) = earlier_client_error(scope).await;
        assert!(!has(&client.updates(), "b", &OperationAction::Start));
        last_request_has(&client, "a", &OperationAction::Succeed);
        assert!(no_fail(&client), "no terminal FAIL is sent");
        assert_failure_answer(scope, response, &factory);
    }

    #[tokio::test(start_paused = true)]
    async fn pending_wins_over_context_validation_fatal() {
        let client = tokenless_start_of_a_after_a_second();
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            let cloned = ctx.clone();
            Ok(ctx
                .step(move |_| async move {
                    let inner = cloned.step(|_| async { Ok(2_u32) }).name("inner").await?;
                    Ok(inner)
                })
                .name("a")
                .await?)
        })
        .await;
        assert_eq!(response, pending());
        let (status, error) = factory.end();
        assert_eq!(status, InvocationStatus::Pending);
        let error = error.unwrap();
        assert_eq!(error.error_type(), Some("Error"));
        assert!(
            error
                .error_message()
                .is_some_and(|m| m.starts_with("context usage error")),
            "{error:?}"
        );
    }

    /// A serdes whose calls fail with a retryable error.
    struct FailingSerdes;

    impl crate::serdes::Serdes<u32> for FailingSerdes {
        fn serialize(
            &self,
            _value: u32,
            _context: crate::serdes::SerdesContext,
        ) -> impl Future<Output = Result<String, BoxError>> + Send {
            std::future::ready(Err(injected_serdes_failure()))
        }

        fn deserialize(
            &self,
            _wire: String,
            _context: crate::serdes::SerdesContext,
        ) -> impl Future<Output = Result<u32, BoxError>> + Send {
            std::future::ready(Err(injected_serdes_failure()))
        }
    }

    fn injected_serdes_failure() -> BoxError {
        Box::new(crate::serdes::RetryableSerdesError::new(
            "injected serdes failure",
        ))
    }

    /// Step `r`'s replayed result fails to deserialize while step `a`'s
    /// START is in flight. A step serializes its result only after its
    /// START is answered, so the fault comes from the replay.
    #[tokio::test(start_paused = true)]
    async fn pending_wins_over_serdes_fault() {
        let client = tokenless_start_of_a_after_a_second();
        let factory = RecordingFactory::default();
        let replayed = serde_json::json!({
            "Id": "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b",
            "Type": "STEP",
            "SubType": "Step",
            "Name": "r",
            "Status": "SUCCEEDED",
            "StepDetails": { "Attempt": 1, "Result": "1" }
        });
        let response = run_on(
            &client,
            false,
            &factory,
            &[replayed],
            |_event, ctx| async move {
                let replayed = ctx
                    .step(|_| async { Ok(1_u32) })
                    .name("r")
                    .serdes(FailingSerdes)
                    .future();
                drop(ctx.step(|_| async { Ok(2_u32) }).name("a").spawn());
                Ok(replayed.await?)
            },
        )
        .await;
        assert!(has(&client.updates(), "a", &OperationAction::Start));
        assert_eq!(response, pending());
        let (status, error) = factory.end();
        assert_eq!(status, InvocationStatus::Pending);
        let error = error.unwrap();
        assert_eq!(
            error.error_type(),
            Some(crate::error::SERDES_FAILED_ERROR_TYPE)
        );
        assert!(
            error
                .error_message()
                .is_some_and(|m| m.contains("injected serdes failure")),
            "{error:?}"
        );
    }

    #[tokio::test]
    async fn pure_withdrawal_end_hook_has_no_error() {
        let client = WithdrawingClient::tokenless_at(1);
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            ctx.step(|_| async { Ok(1_u32) }).name("a").await?;
            std::future::pending::<()>().await;
            Ok(1)
        })
        .await;
        assert_eq!(response, pending());
        assert_eq!(factory.end(), (InvocationStatus::Pending, None));
    }

    /// An `EXECUTION` update of the root execution with `action`.
    fn execution_update(action: &OperationAction) -> OperationUpdate {
        let builder = OperationUpdate::builder()
            .id("root")
            .r#type(OperationType::Execution)
            .action(action.clone());
        let builder = if *action == OperationAction::Fail {
            builder.error(
                aws_sdk_lambda::types::ErrorObject::builder()
                    .error_type("Boom")
                    .error_message("boom")
                    .build(),
            )
        } else {
            builder.payload("1")
        };
        builder.build().unwrap()
    }

    #[tokio::test]
    async fn execution_update_exempt_from_withdrawal() {
        for (action, status) in [
            (OperationAction::Succeed, WireStatus::Succeeded),
            (OperationAction::Fail, WireStatus::Failed),
        ] {
            let (messages, _guard) = EventMessages::install();
            let terminal = Operation::builder()
                .id("root")
                .r#type(OperationType::Execution)
                .status(status.clone())
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .build()
                .unwrap();
            let client = WithdrawingClient::new(move |_, _| {
                (
                    Answer::TokenlessWith(vec![terminal.clone()], String::new()),
                    Duration::ZERO,
                )
            });
            let ctx = direct_ctx(&client);
            let output = tokio::time::timeout(
                Duration::from_secs(5),
                ctx.checkpoint_updates_direct(vec![execution_update(&action)]),
            )
            .await
            .expect("the call resolves")
            .expect("the call returns Ok");
            assert_eq!(output.checkpoint_token(), None);
            assert!(
                output
                    .updated_operations
                    .iter()
                    .any(|op| op.r#type() == &OperationType::Execution && op.status() == &status),
                "the execution is terminal"
            );
            assert!(!ctx.coordinator().withdrawn(), "no latch is set");
            assert_eq!(ctx.coordinator().phase(), Phase::Running);
            assert_eq!(messages.at(tracing::Level::WARN), Vec::<String>::new());
        }
    }

    /// A tokenless response to an `EXECUTION` update returns `Ok` without
    /// fetching its pages, because the spent token is still in place: the
    /// response carries a marker, and `get_state` would fail.
    #[tokio::test]
    async fn execution_update_exempt_skips_pagination() {
        for action in [OperationAction::Succeed, OperationAction::Fail] {
            let client = WithdrawingClient::new(move |_, _| {
                (
                    Answer::TokenlessWith(Vec::new(), "marker".to_owned()),
                    Duration::ZERO,
                )
            });
            client.get_state_fails.store(true, Ordering::SeqCst);
            let ctx = direct_ctx(&client);
            let output = tokio::time::timeout(
                Duration::from_secs(5),
                ctx.checkpoint_updates_direct(vec![execution_update(&action)]),
            )
            .await
            .expect("the call resolves")
            .expect("the call returns Ok");
            assert_eq!(output.checkpoint_token(), None);
            assert!(!ctx.coordinator().withdrawn(), "no latch is set");
            assert_eq!(ctx.coordinator().phase(), Phase::Running);
            assert_eq!(
                client.get_state_calls.load(Ordering::SeqCst),
                0,
                "{action:?}: no get_state call"
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn refresh_checkpoint_withdrawn() {
        let client = WithdrawingClient::new(|_, updates| {
            if updates.is_empty() {
                (Answer::Tokenless, Duration::ZERO)
            } else {
                (Answer::Pass, Duration::ZERO)
            }
        });
        let factory = RecordingFactory::default();
        let response = run(&client, false, &factory, |_event, ctx| async move {
            let wait = ctx.wait(Duration::from_secs(1)).name("w").spawn();
            let step = ctx
                .step(|_| async {
                    tokio::time::sleep(Duration::from_secs(5)).await;
                    Ok(1_u32)
                })
                .name("s")
                .spawn();
            let (waited, value) = tokio::join!(wait, step);
            waited?;
            Ok(value?)
        })
        .await;
        assert_eq!(response, pending());
        let calls = client.calls();
        let refresh = calls
            .iter()
            .position(Vec::is_empty)
            .expect("a refresh was sent");
        assert_eq!(
            refresh + 1,
            calls.len(),
            "no checkpoint after the refresh: {calls:?}"
        );
        assert!(!has(&client.updates(), "s", &OperationAction::Succeed));
        assert_eq!(factory.end(), (InvocationStatus::Pending, None));
    }
}