1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
//! Context types for durable execution.
//!
//! [`DurableContext`] provides access to all durable operations.
//! [`StepContext`] is passed to step bodies and deliberately omits durable
//! operations: the type system enforces the "no nesting" rule at compile
//! time.
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use serde::{Serialize, de::DeserializeOwned};
use crate::BoxError;
use crate::builders::{
ChildBuilder, CreateCallbackBuilder, InvokeBuilder, JoinAllBuilder, MapBuilder,
ParallelBuilder, ParallelMixedBuilder, RaceBuilder, SelectOkBuilder, StepBuilder, Submitter,
TryJoinAllBuilder, WaitBuilder, WaitForCallbackBuilder, WaitForConditionBuilder,
WithRetryBuilder,
};
use crate::checkpoint_coalescer::{
Admission, BatchLimits, CheckpointBatch, CheckpointCoalescer, TrackedUpdate,
split_into_requests,
};
use crate::client::{
CheckpointOutput, ExecutionClient, ExecutionClientError, ExecutionClientErrorScope,
};
use crate::coordinator::{InvocationCoordinator, PermitKind};
use crate::driver::{FatalError, FatalSeverity, TaskOwnership};
use crate::engine::{
CheckpointLog, CheckpointRecord, CheckpointStatus, CheckpointStatusView, EngineState,
OperationId, TerminalReplaySnapshot,
};
use crate::error::{
NonDeterministicExecutionError, NonDeterministicExecutionErrorKind, OperationError,
OperationErrorKind, StepError, StepErrorKind,
};
use crate::future::{Branch, DurableFuture};
use aws_sdk_lambda::types::{OperationAction, OperationUpdate};
use tokio::sync::Mutex;
/// The changes one checkpoint call merged, for `on_operation_change`.
#[derive(Default)]
struct ChangeSet {
/// The wire IDs of the log records whose status changed, each once, in
/// merge order.
ids: Vec<String>,
/// The `EXECUTION` operations that changed the plugins' slot.
executions: Vec<crate::plugin::OperationInfo>,
}
/// A checkpoint write that has already started, and the future of its
/// result.
///
/// [`DurableContext::submit_checkpoint_updates`] starts the write before it
/// returns: the updates are admitted to the buffer, or enter the
/// [`DirectWriteQueue`]. Awaiting the value only waits for the result. Dropping it
/// does not cancel the write, because the batch flusher and the direct
/// write task do not depend on the caller. An at-least-once step uses this
/// to run its body while its `START` write is in flight.
pub(crate) struct SubmittedWrite {
result: std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send>,
>,
/// Set on the first poll (see [`SubmissionRecorder`]).
#[cfg(test)]
first_poll: Arc<std::sync::atomic::AtomicBool>,
/// The plugins and the log whose queued change sets the write delivers
/// when its result is ready (see [`Self::reported_by`]). `None` without
/// plugins, and once delivered.
report: Option<Box<WriteReport>>,
}
/// What a [`SubmittedWrite`] needs to deliver the change sets through its
/// own before it returns its result.
struct WriteReport {
plugins: Arc<crate::plugin::InvocationPlugins>,
log: Arc<CheckpointLog>,
/// The result, kept while the write waits for the deliveries.
ready: Option<Result<CheckpointOutput, ExecutionClientError>>,
/// The write's wait for the deliveries (see
/// [`InvocationPlugins::poll_changes_delivered`](crate::plugin::InvocationPlugins::poll_changes_delivered)).
wait: crate::plugin::DeliveryWait,
}
impl Drop for WriteReport {
/// A write dropped while it waits removes its waker registration.
fn drop(&mut self) {
self.plugins.cancel_wait(&mut self.wait);
}
}
impl SubmittedWrite {
fn new(
result: impl Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + 'static,
) -> Self {
Self {
result: Box::pin(result),
#[cfg(test)]
first_poll: Arc::new(std::sync::atomic::AtomicBool::new(false)),
report: None,
}
}
/// Makes the write deliver the queued change sets of `ctx`'s plugins
/// to `on_operation_change` once its result is ready, `Ok` or `Err`, on
/// the task that polls it to completion. A write dropped before that
/// delivers nothing: another drain point delivers its change set. Does
/// nothing without plugins.
fn reported_by(mut self, ctx: &DurableContext) -> Self {
self.report = ctx.shared_plugins().map(|plugins| {
Box::new(WriteReport {
plugins,
log: Arc::clone(&ctx.inner.engine.checkpoint_log),
ready: None,
wait: crate::plugin::DeliveryWait::default(),
})
});
self
}
/// A write whose result `receiver` delivers. A test builds the retained
/// `START` of an operation with it.
#[cfg(test)]
pub(crate) fn from_receiver(
receiver: tokio::sync::oneshot::Receiver<Result<CheckpointOutput, ExecutionClientError>>,
) -> Self {
Self::new(async move {
match receiver.await {
Ok(result) => result,
Err(_closed) => std::future::pending().await,
}
})
}
/// A rejected write: nothing is sent, and the result never resolves.
/// The rejected caller's task is being cancelled (see [`Admission`]).
fn rejected() -> Self {
Self::new(std::future::pending())
}
}
impl Future for SubmittedWrite {
type Output = Result<CheckpointOutput, ExecutionClientError>;
/// Returns the result once the change sets are delivered.
fn poll(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
let this = self.get_mut();
#[cfg(test)]
this.first_poll
.store(true, std::sync::atomic::Ordering::SeqCst);
let Some(report) = this.report.as_mut() else {
return this.result.as_mut().poll(cx);
};
let result = match report.ready.take() {
Some(result) => result,
None => std::task::ready!(this.result.as_mut().poll(cx)),
};
if report
.plugins
.poll_changes_delivered(&report.log, &mut report.wait, cx)
.is_pending()
{
report.ready = Some(result);
return std::task::Poll::Pending;
}
this.report = None;
std::task::Poll::Ready(result)
}
}
/// A checkpoint write whose position in the write order is fixed, but
/// that is not sent yet.
///
/// [`DurableContext::reserve_checkpoint_updates`] puts the updates into the
/// coalescer's open batch, or into the [`DirectWriteQueue`], before it
/// returns. A batch that holds a reserved write is not flushed, and later
/// entries of the queue wait behind it. So a later submission cannot reach
/// the service first. [`Self::release`] makes the write eligible to be
/// sent and returns its result future. Dropping the value releases it too.
///
/// The start step of an operation whose JS order is "queue START, then
/// fire `on_operation_start`" reserves START, fires the hook, then
/// releases START. So the hook returns before the START request is sent,
/// on any runtime, as in JS.
pub(crate) struct ReservedWrite {
write: SubmittedWrite,
/// What keeps the write from being sent. `None` once released, and for
/// a rejected write.
hold: Option<WriteHold>,
}
/// What [`ReservedWrite`] holds back.
enum WriteHold {
/// A hold on the coalescer's open batch.
Batch(Arc<CheckpointCoalescer>),
/// A held entry of the direct write queue.
Direct {
queue: Arc<DirectWriteQueue>,
id: u64,
},
}
impl WriteHold {
fn release(self) {
match self {
Self::Batch(coalescer) => coalescer.release_hold(),
Self::Direct { queue, id } => queue.release(id),
}
}
}
impl ReservedWrite {
/// A rejected reservation: nothing is held, and the result never
/// resolves (see [`SubmittedWrite::rejected`]).
fn rejected() -> Self {
Self {
write: SubmittedWrite::rejected(),
hold: None,
}
}
/// Makes the write eligible to be sent, and returns its result future.
/// It does not wait for the write.
pub(crate) fn release(mut self) -> SubmittedWrite {
// `self` is dropped when this returns, and the drop releases the
// hold.
std::mem::replace(&mut self.write, SubmittedWrite::rejected())
}
}
impl Drop for ReservedWrite {
/// A dropped reservation is released, so the writes queued behind it
/// are not blocked forever.
fn drop(&mut self) {
if let Some(hold) = self.hold.take() {
hold.release();
}
}
}
/// The test hook of the direct writer: for an entry's updates it returns
/// the `Notify` the writer awaits before it takes the checkpoint token, or
/// `None` to write at once.
#[cfg(test)]
pub(crate) type PreLockGate =
Arc<dyn Fn(&[OperationUpdate]) -> Option<Arc<tokio::sync::Notify>> + Send + Sync>;
/// The test hook that sees every admitted submission: its updates and the
/// first-poll flag of its [`SubmittedWrite`]. It runs before the write can
/// be sent: an ordinary write calls it before it joins the coalescer or
/// enters the [`DirectWriteQueue`], and a reservation calls it while its
/// entry is held.
#[cfg(test)]
pub(crate) type SubmissionRecorder =
Arc<dyn Fn(&[OperationUpdate], &Arc<std::sync::atomic::AtomicBool>) + Send + Sync>;
/// The test hook that each child-backed outcome path calls with the
/// operation's wire ID and the action it is about to write, just before it
/// awaits the operation's retained `START` write.
#[cfg(test)]
pub(crate) type SettlerEntryRecorder = Arc<dyn Fn(&str, OperationAction) + Send + Sync>;
/// The test hooks a [`DirectWriteQueue`] carries for every context of the
/// invocation.
#[cfg(test)]
#[derive(Default)]
struct TestHooks {
gate: Option<PreLockGate>,
submissions: Option<SubmissionRecorder>,
settler_entries: Option<SettlerEntryRecorder>,
}
/// The FIFO of the invocation's unbuffered checkpoint writes.
///
/// Without a coalescer, every write enters this queue under a synchronous
/// lock before the call that submits it returns. One detached task, the
/// direct writer, takes the entries in order, writes each one under the
/// `checkpoint_token` lock, and sends its result to the entry's
/// [`SubmittedWrite`]. So writes reach the service in submission order,
/// whichever task Tokio runs first. The root context and every child share
/// one queue, as they share `checkpoint_token`.
///
/// The writer runs while the queue has entries and ends when it is empty.
/// The next write starts a new one. A held entry (see [`ReservedWrite`])
/// stops the writer until it is released.
#[derive(Default)]
pub(crate) struct DirectWriteQueue {
state: std::sync::Mutex<DirectQueueState>,
/// Wakes the writer when a held entry is released.
released: tokio::sync::Notify,
/// The hooks tests install (see [`PreLockGate`],
/// [`SubmissionRecorder`] and [`SettlerEntryRecorder`]).
#[cfg(test)]
hooks: std::sync::Mutex<TestHooks>,
}
#[derive(Default)]
struct DirectQueueState {
entries: std::collections::VecDeque<DirectEntry>,
/// Whether a writer task is running. Set by the push that starts one,
/// cleared by the writer when it finds the queue empty.
writer_running: bool,
next_id: u64,
}
/// The result channel of a direct write. `None` means the write sent
/// nothing or failed: the admission check rejected it, the checkpoint
/// token was withdrawn, or this write or an earlier one failed. The
/// caller then never resolves.
type DirectResult = Option<Result<CheckpointOutput, ExecutionClientError>>;
/// One write of the [`DirectWriteQueue`].
struct DirectEntry {
id: u64,
/// Whether a [`ReservedWrite`] still holds the entry.
held: bool,
/// The context that submitted the write: its owners are admitted, and
/// its checkpoint log takes the response.
ctx: DurableContext,
updates: Vec<OperationUpdate>,
events: Vec<crate::tracing_layer::PendingTransitionEvent>,
/// The write's checkpoint permit, released after the result is sent.
permit: Option<crate::coordinator::Permit>,
/// The wire ID a refresh passes: a request with no update records its
/// failure for it (see [`DurableContext::checkpoint_refresh`]).
refresh_id: Option<String>,
sender: tokio::sync::oneshot::Sender<DirectResult>,
}
impl DirectWriteQueue {
fn lock(&self) -> std::sync::MutexGuard<'_, DirectQueueState> {
self.state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Releases the held entry `id`, and wakes the writer.
fn release(&self, id: u64) {
if let Some(entry) = self.lock().entries.iter_mut().find(|entry| entry.id == id) {
entry.held = false;
}
self.released.notify_waiters();
}
/// Takes the next entry once it is not held. Returns `None`, and marks
/// the writer stopped, when the queue is empty.
async fn next(&self) -> Option<DirectEntry> {
loop {
// `enable()` registers the waiter before the check, so a
// release between the check and the await still wakes it.
let mut released = std::pin::pin!(self.released.notified());
released.as_mut().enable();
{
let mut state = self.lock();
if state.entries.is_empty() {
state.writer_running = false;
return None;
}
if let Some(entry) = state.entries.pop_front_if(|entry| !entry.held) {
return Some(entry);
}
}
released.await;
}
}
/// Takes every queued entry, held ones included, so the caller drops
/// them without resolving their callers. The withdrawal of the
/// checkpoint token and a failed write call it (see
/// [`InvocationCoordinator::withdraw`] and
/// [`InvocationCoordinator::fail_write`]).
/// The writer finds the queue empty and stops. A released reservation
/// finds no entry and does nothing.
fn abandon_queued(&self) -> std::collections::VecDeque<DirectEntry> {
std::mem::take(&mut self.lock().entries)
}
/// Waits on the pre-lock gate for `updates`, when one is installed and
/// returns a `Notify` for them.
#[cfg(test)]
fn hooks(&self) -> std::sync::MutexGuard<'_, TestHooks> {
self.hooks
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
async fn pass_gate(&self, updates: &[OperationUpdate]) {
let gate = self.hooks().gate.clone();
if let Some(notify) = gate.and_then(|gate| gate(updates)) {
notify.notified().await;
}
}
}
/// The result future of a write that joined `batch`: it resolves when the
/// batch's flusher publishes the result.
fn batch_result(batch: Arc<CheckpointBatch>) -> SubmittedWrite {
SubmittedWrite::new(async move {
loop {
// `enable()` registers the waiter BEFORE the result check, so a
// publish landing between the check and the await still wakes
// us.
let mut notified = std::pin::pin!(batch.notified());
notified.as_mut().enable();
if let Some(result) = batch.result_clone() {
return result;
}
notified.await;
}
})
}
/// Marks the direct writer stopped when its task unwinds, so the next
/// write starts a new writer, which writes the entries still queued.
struct WriterUnwind(Arc<DirectWriteQueue>);
impl Drop for WriterUnwind {
fn drop(&mut self) {
if std::thread::panicking() {
self.0.lock().writer_running = false;
}
}
}
/// The direct writer: writes the queue's entries in order until it is
/// empty (see [`DirectWriteQueue`]).
async fn run_direct_writer(queue: Arc<DirectWriteQueue>) {
let _unwind = WriterUnwind(Arc::clone(&queue));
while let Some(entry) = queue.next().await {
#[cfg(test)]
queue.pass_gate(&entry.updates).await;
let DirectEntry {
ctx,
updates,
events,
permit,
refresh_id,
sender,
..
} = entry;
// A write that sent nothing or failed sends `None`, so the caller
// never resolves. A failure is recorded where the response arrives
// (see `DurableContext::write_locked`).
let written = match ctx
.checkpoint_direct_with_events(
updates,
&events,
Some(ctx.owners()),
refresh_id.as_deref(),
)
.await
{
Some(Ok(output)) => Some(Ok(output)),
None | Some(Err(_)) => None,
};
// A dropped receiver means the caller was cancelled, or the driver
// dropped the refresh scheduler when the drive ended: the write
// already happened, and its result has no reader. The caller's wake
// takes its own permit before the write's permit is released.
let _ = sender.send(written);
drop(permit);
}
}
/// The fatal error a failed checkpoint write records: a retryable failure
/// fails the invocation with the message of
/// [`checkpoint_invocation_failure_message`](crate::error::checkpoint_invocation_failure_message),
/// and a non-retryable failure fails the execution with the record of
/// [`checkpoint_execution_failure_wire`](crate::error::checkpoint_execution_failure_wire).
fn checkpoint_failure_fatal(err: &ExecutionClientError) -> FatalError {
if err.is_retryable() {
FatalError {
error_type: crate::error::CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE.to_owned(),
error_message: crate::error::checkpoint_invocation_failure_message(err),
severity: FatalSeverity::FailInvocation,
}
} else {
let wire = crate::error::checkpoint_execution_failure_wire(err);
FatalError {
error_type: wire.error_type().unwrap_or_default().to_owned(),
error_message: wire.error_message().unwrap_or_default().to_owned(),
severity: FatalSeverity::FailExecution,
}
}
}
/// Why a checkpoint write returned no output.
#[derive(Debug)]
pub(crate) enum WriteError {
/// The request failed with this error, and the failure is recorded
/// (see [`InvocationCoordinator::fail_write`]).
Failed(ExecutionClientError),
/// Nothing more is sent: the response had no token, the token was
/// withdrawn before the request was sent (see
/// [`InvocationCoordinator::withdraw`]), or an earlier write failed.
/// The write's callers never resolve.
Stopped,
}
/// The user-code body the SDK is polling on the current task.
///
/// [`DurableContext::claim_operation_id`] compares it with the context an
/// operation is called on.
#[derive(Debug, Clone)]
pub(crate) enum ActiveBody {
/// A body that runs on a `DurableContext`: the handler or a child body.
/// Holds that context's positional prefix ("" for the root).
Context(String),
/// A body that may not call durable operations: a step body or a
/// `wait_for_condition` check. Holds the operation's positional ID.
Step(String),
/// Plugin code: a wrap, or a start or end hook and its future. A
/// plugin observes operations, so a durable operation it called would
/// claim an ID that the handler's code did not create, and replay
/// would diverge.
Plugin,
/// The SDK derives the recorded error of a user function's outcome:
/// the error's `Display` and `source` run, which are user code. Holds
/// the operation's positional ID. An operation called there would
/// claim an ID on a live run only, since replay returns the recorded
/// error without deriving it again.
Outcome(String),
/// No body is active: the check does nothing. A plugin wrap's `next`
/// sets it when the code around the wrap had no value, so the code
/// inside sees exactly what it saw without the wrap.
Unset,
}
/// The body active now, or [`ActiveBody::Unset`] when none is.
pub(crate) fn current_body() -> ActiveBody {
ACTIVE_BODY
.try_with(ActiveBody::clone)
.unwrap_or(ActiveBody::Unset)
}
tokio::task_local! {
/// The body the SDK is polling. `LocalKey::scope` holds the value only
/// while the wrapped future is polled. So a parent future joined with a
/// child body on one task does not see the child's value, and a task
/// the SDK spawns starts without a value.
static ACTIVE_BODY: ActiveBody;
}
/// Polls `fut` with `body` as the active body.
///
/// Callers pass a future that calls the user closure inside it, so code
/// the closure runs before it returns its future is checked too.
pub(crate) fn run_body<F: Future>(body: ActiveBody, fut: F) -> impl Future<Output = F::Output> {
ACTIVE_BODY.scope(body, fut)
}
/// Calls `f` with `body` as the active body.
///
/// A step clones the user closure before each attempt. The clone runs the
/// captures' `Clone` implementations, which are user code. A terminal
/// record replays without cloning. So an operation claimed inside a clone
/// would claim an ID on a live attempt only. This scope makes such a claim
/// fail the execution with a context usage error instead.
pub(crate) fn run_body_sync<R>(body: ActiveBody, f: impl FnOnce() -> R) -> R {
ACTIVE_BODY.sync_scope(body, f)
}
/// The time left from `now` until `deadline_ms` (milliseconds since the
/// Unix epoch): `None` when the deadline is 0, `Duration::ZERO` once it
/// passed.
fn remaining_until(deadline_ms: u64, now: std::time::SystemTime) -> Option<Duration> {
if deadline_ms == 0 {
return None;
}
let deadline = std::time::UNIX_EPOCH + Duration::from_millis(deadline_ms);
Some(deadline.duration_since(now).unwrap_or(Duration::ZERO))
}
/// Shows a context prefix in a context usage error: `root` for the root.
pub(crate) fn display_prefix(prefix: &str) -> &str {
if prefix.is_empty() { "root" } else { prefix }
}
/// Returns the wire ID and payload of every `wait_for_condition` `RETRY`
/// among `updates`, in order.
fn wfc_retries(updates: &[OperationUpdate]) -> Vec<(String, Option<String>)> {
updates
.iter()
.filter(|update| {
*update.action() == OperationAction::Retry
&& update.sub_type() == Some(crate::wait_for_condition::WFC_SUB_TYPE)
})
.map(|update| (update.id().to_owned(), update.payload().map(str::to_owned)))
.collect()
}
/// Marks the record of `wire_id` `PENDING` with `payload` as its result,
/// after a `wait_for_condition` `RETRY` write whose response did not carry
/// the operation.
///
/// The service moves a retried operation to `PENDING`. A response that
/// does not carry the operation leaves the log at the status from before
/// the write. A waiting operation that read that status would take it for
/// the next status and run its next check at once. So the log takes the
/// status the service recorded. A record already `PENDING` is kept, and a
/// missing record stays missing. A response that carries the operation is
/// merged instead, so its status is kept.
fn mark_retry_pending(log: &CheckpointLog, wire_id: &str, payload: Option<&str>) {
log.update(wire_id, |record| {
if record.status != CheckpointStatus::Pending {
record.status = CheckpointStatus::Pending;
record.result = payload.map(str::to_owned);
}
});
}
/// Shared inner state for a durable execution context.
struct Inner {
execution_arn: String,
lambda_context: lambda_runtime::Context,
/// Engine state (ID counter + checkpoint log) for this context's
/// namespace.
engine: Arc<EngineState>,
/// The invocation coordinator, shared by every context of the
/// invocation and by the driver.
coordinator: Arc<InvocationCoordinator>,
/// Task-ownership detector: catches user `tokio::spawn` misuse.
task_ownership: Arc<TaskOwnership>,
/// Execution client for checkpointing (None in test contexts without a client).
execution_client: Option<Arc<dyn ExecutionClient>>,
/// Mutable checkpoint token rotated on each checkpoint call.
/// Uses `tokio::sync::Mutex` (not `std::sync::Mutex`) because the lock
/// must be held across `await` points in [`DurableContext::checkpoint_updates`],
/// serializing all concurrent checkpoint callers through one critical section.
checkpoint_token: Arc<Mutex<String>>,
/// Checkpoint-write coalescer, present only when
/// [`Options`](crate::Options) configured a `checkpoint_delay` and/or
/// `checkpoint_batching`. Shared with every child context so updates
/// from all namespaces coalesce into the same batches. A zero-window
/// batching coalescer is the default. `None` means every checkpoint
/// writes immediately, which needs `checkpoint_batching(false)` without
/// a `checkpoint_delay`.
coalescer: Option<Arc<CheckpointCoalescer>>,
/// The FIFO of unbuffered writes and its writer, shared by the root and
/// every child context, as `checkpoint_token` is (see
/// [`DirectWriteQueue`]).
direct: Arc<DirectWriteQueue>,
/// Cached parent wire ID: the SHA-256 hash of this context's prefix
/// (positional ID of the parent operation). `None` for root contexts.
parent_wire_id: Option<String>,
/// Abandoned owners of this invocation, shared by the root and every
/// context derived from it (see [`Admission`]).
admission: Arc<Admission>,
/// The owners this context runs in, outermost first: the wire IDs of
/// the non-virtual child contexts (batch items included) that enclose
/// it. Empty at the root. A checkpoint update from this context is
/// admitted only while none of them is abandoned.
owners: Arc<[String]>,
/// This namespace's `durable_execution` span. For a root context it is
/// the handler-level span wrapping the invocation; for a child context
/// (sequential child, map/parallel branch, callback body), recorded,
/// virtual or flat, it is a child of the span current when the context
/// is created, wrapping that child's body. [`DurableContext::mint_id`]
/// re-records its `isReplay` field after every operation claim minted
/// through this context, so replay-aware filters (see
/// `tracing_layer::ReplayFilterLayer`) can suppress log events emitted
/// while THIS namespace is replaying: the filter reads the SDK spans
/// from an event up to and including its nearest namespace span, and
/// stops there. Per-namespace spans are what keep
/// concurrent branches, each with its own replay high-water mark, from
/// clobbering each other's flag.
replay_span: tracing::Span,
/// The plugins of the invocation. The root context of a wrapped
/// invocation holds them, and every context derived from it shares
/// the same `Arc`. `None` without a registered plugin factory.
plugins: Option<Arc<crate::plugin::InvocationPlugins>>,
/// How many context levels this context sits below the root: 0 at the
/// root, plus 1 for each [`DurableContext::new_child`]. A Flat batch
/// item's context keeps the batch's level, and a virtual child's context
/// keeps its caller's level.
nesting_level: u32,
/// The invocation's
/// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth),
/// copied into every derived context.
preserve_child_depth: u32,
}
impl std::fmt::Debug for Inner {
/// Hand-written to keep `checkpoint_token`, a credential-like value,
/// out of log output, and to skip the engine/client/signal internals
/// that make a derived impl unreadable. See issue #30.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Inner")
.field("execution_arn", &self.execution_arn)
.field("parent_wire_id", &self.parent_wire_id)
.field("is_replaying", &self.engine.is_replaying())
.field("checkpoint_token", &"<redacted>")
.finish_non_exhaustive()
}
}
/// The durable execution context: a cheap-to-clone handle providing access
/// to all durable operations.
///
/// `DurableContext` is `Clone + Send + Sync` (backed by an `Arc`). Clone it
/// freely to share across async boundaries. Every durable operation method
/// except [`with_retry`](Self::with_retry) and the four combinators claims
/// its operation ID synchronously at the call site: polling order never
/// affects identity. A `with_retry` block with its own record claims its ID
/// when its builder becomes its future (`.await`, `.future()` or
/// `.spawn()`); a block with
/// [`without_child_context`](crate::builders::WithRetryBuilder::without_child_context)
/// claims none, and its first attempt claims the caller's next ID when it
/// starts. A combinator
/// ([`try_join_all`](Self::try_join_all), [`join_all`](Self::join_all),
/// [`select_ok`](Self::select_ok) and [`race`](Self::race)) claims its ID
/// when it is first awaited or polled, or when it is spawned. A combinator
/// that is dropped before that claims no ID and records nothing. A
/// combinator passed to another combinator must already have claimed its
/// ID: start it with `.spawn()` and pass the returned handle. A
/// still-unclaimed combinator input fails the execution with a context
/// usage error.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// // Access execution metadata
/// let arn = ctx.execution_arn();
/// let replaying = ctx.is_replaying();
///
/// // Perform a durable step
/// let result = ctx.step(|_| async { Ok("done".to_owned()) })
/// .name("example")
/// .await?;
/// Ok(result)
/// }
/// ```
#[derive(Clone)]
#[non_exhaustive]
pub struct DurableContext {
inner: Arc<Inner>,
/// The first-poll flag of the handle an operation started on its own
/// task returns. `None` on every context except the clone that starts
/// such an operation (see [`Self::with_awaited`]). Every wait
/// registration of an operation run on that clone carries the flag, so
/// the refresh scheduler skips it until the handle is first polled.
awaited: Option<Arc<std::sync::atomic::AtomicBool>>,
}
impl std::fmt::Debug for DurableContext {
/// Hand-written so `tracing::debug!(?ctx)` in a handler cannot leak the
/// checkpoint token into `CloudWatch` Logs: the token prints as
/// `"<redacted>"` and engine/client internals are skipped. See issue #30.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DurableContext")
.field("execution_arn", &self.inner.execution_arn)
.field("parent_wire_id", &self.inner.parent_wire_id)
.field("is_replaying", &self.inner.engine.is_replaying())
.field("checkpoint_token", &"<redacted>")
.finish_non_exhaustive()
}
}
impl DurableContext {
/// Builds a context for unit tests: a root context with an empty
/// checkpoint log and no execution client.
#[cfg(test)]
pub(crate) fn test_context() -> Self {
let execution_arn = String::from("arn:aws:lambda:us-east-1:123456789012:function:test");
let lambda_context = lambda_runtime::Context::default();
let engine = Arc::new(EngineState::new_root(Arc::new(CheckpointLog::empty())));
let replay_span = crate::tracing_layer::execution_span(
&execution_arn,
&lambda_context.request_id,
lambda_context.tenant_id.as_deref(),
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn,
lambda_context,
engine,
coordinator: InvocationCoordinator::new(),
task_ownership: Arc::new(TaskOwnership::new_current()),
execution_client: None,
checkpoint_token: Arc::new(Mutex::new(String::new())),
coalescer: None,
direct: Arc::new(DirectWriteQueue::default()),
parent_wire_id: None,
admission: Arc::new(Admission::new()),
owners: Arc::from(Vec::new()),
replay_span,
plugins: None,
nesting_level: 0,
preserve_child_depth: 0,
}),
awaited: None,
}
}
/// Creates a root context with the given execution state (test-only:
/// production roots are built by the handler wrapper with a client and
/// token via [`Self::new_root_with_client`]-equivalent wiring in
/// `lib.rs`).
#[cfg(test)]
pub(crate) fn new_root(
execution_arn: String,
lambda_context: lambda_runtime::Context,
checkpoint_log: Arc<CheckpointLog>,
) -> Self {
let engine = Arc::new(EngineState::new_root(checkpoint_log));
let replay_span = crate::tracing_layer::execution_span(
&execution_arn,
&lambda_context.request_id,
lambda_context.tenant_id.as_deref(),
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn,
lambda_context,
engine,
coordinator: InvocationCoordinator::new(),
task_ownership: Arc::new(TaskOwnership::new_current()),
execution_client: None,
checkpoint_token: Arc::new(Mutex::new(String::new())),
coalescer: None,
direct: Arc::new(DirectWriteQueue::default()),
parent_wire_id: None,
admission: Arc::new(Admission::new()),
owners: Arc::from(Vec::new()),
replay_span,
plugins: None,
nesting_level: 0,
preserve_child_depth: 0,
}),
awaited: None,
}
}
/// Creates a root context with a client and token (test-only harness
/// for exercising live-path operation execution against a test double).
#[cfg(test)]
pub(crate) fn new_root_with_client(
execution_arn: String,
lambda_context: lambda_runtime::Context,
checkpoint_log: Arc<CheckpointLog>,
client: Arc<dyn ExecutionClient>,
checkpoint_token: String,
) -> Self {
let engine = Arc::new(EngineState::new_root(checkpoint_log));
let replay_span = crate::tracing_layer::execution_span(
&execution_arn,
&lambda_context.request_id,
lambda_context.tenant_id.as_deref(),
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn,
lambda_context,
engine,
coordinator: InvocationCoordinator::new(),
task_ownership: Arc::new(TaskOwnership::new_current()),
execution_client: Some(client),
checkpoint_token: Arc::new(Mutex::new(checkpoint_token)),
coalescer: None,
direct: Arc::new(DirectWriteQueue::default()),
parent_wire_id: None,
admission: Arc::new(Admission::new()),
owners: Arc::from(Vec::new()),
replay_span,
plugins: None,
nesting_level: 0,
preserve_child_depth: 0,
}),
awaited: None,
}
}
/// Creates a root context with a client, token, and checkpoint
/// buffering window threaded in from
/// [`Options`](crate::Options) (internal). `checkpoint_buffer_window`
/// is `Some(Duration::ZERO)` for pure `checkpoint_batching` (the
/// default: no added delay; writes batch behind the single-writer
/// lock), `Some(window)` for a `checkpoint_delay` coalescing window,
/// and `None` for immediate writes, which need
/// `checkpoint_batching(false)` without a delay.
/// `preserve_child_depth` is the
/// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth)
/// of the invocation.
#[expect(clippy::too_many_arguments, reason = "one argument per root setting")]
pub(crate) fn new_root_with_client_and_defaults(
execution_arn: String,
lambda_context: lambda_runtime::Context,
checkpoint_log: Arc<CheckpointLog>,
client: Arc<dyn ExecutionClient>,
checkpoint_token: String,
checkpoint_buffer_window: Option<Duration>,
preserve_child_depth: u32,
plugins: Option<Arc<crate::plugin::InvocationPlugins>>,
) -> Self {
let engine = Arc::new(EngineState::new_root(checkpoint_log));
let replay_span = crate::tracing_layer::execution_span(
&execution_arn,
&lambda_context.request_id,
lambda_context.tenant_id.as_deref(),
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn,
lambda_context,
engine,
coordinator: InvocationCoordinator::new(),
task_ownership: Arc::new(TaskOwnership::new_current()),
execution_client: Some(client),
checkpoint_token: Arc::new(Mutex::new(checkpoint_token)),
coalescer: checkpoint_buffer_window.map(|d| Arc::new(CheckpointCoalescer::new(d))),
direct: Arc::new(DirectWriteQueue::default()),
parent_wire_id: None,
admission: Arc::new(Admission::new()),
owners: Arc::from(Vec::new()),
replay_span,
plugins,
nesting_level: 0,
preserve_child_depth,
}),
awaited: None,
}
}
/// Test-only root with an empty log, an in-memory client and the
/// plugin child operations depth `depth`, built through
/// [`Self::new_root_with_client_and_defaults`]. Returns the client, whose
/// recorded updates a test reads.
#[cfg(test)]
pub(crate) fn test_context_with_depth(
depth: u32,
) -> (Self, Arc<crate::client::InMemoryExecutionClient>) {
let client = Arc::new(crate::client::InMemoryExecutionClient::new(Vec::new()));
let ctx = Self::test_context_with_depth_and_client(
depth,
Arc::clone(&client) as Arc<dyn ExecutionClient>,
);
(ctx, client)
}
/// [`Self::test_context_with_depth`] with a caller-supplied client.
#[cfg(test)]
pub(crate) fn test_context_with_depth_and_client(
depth: u32,
client: Arc<dyn ExecutionClient>,
) -> Self {
Self::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client,
"token0".to_owned(),
None,
depth,
None,
)
}
/// Test-only root constructor that accepts an explicit
/// [`CheckpointCoalescer`], letting tests force small [`BatchLimits`]
/// so batch splitting is observable with a handful of updates.
#[cfg(test)]
pub(crate) fn new_root_with_client_and_coalescer(
execution_arn: String,
lambda_context: lambda_runtime::Context,
checkpoint_log: Arc<CheckpointLog>,
client: Arc<dyn ExecutionClient>,
checkpoint_token: String,
coalescer: CheckpointCoalescer,
) -> Self {
let engine = Arc::new(EngineState::new_root(checkpoint_log));
let replay_span = crate::tracing_layer::execution_span(
&execution_arn,
&lambda_context.request_id,
lambda_context.tenant_id.as_deref(),
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn,
lambda_context,
engine,
coordinator: InvocationCoordinator::new(),
task_ownership: Arc::new(TaskOwnership::new_current()),
execution_client: Some(client),
checkpoint_token: Arc::new(Mutex::new(checkpoint_token)),
coalescer: Some(Arc::new(coalescer)),
direct: Arc::new(DirectWriteQueue::default()),
parent_wire_id: None,
admission: Arc::new(Admission::new()),
owners: Arc::from(Vec::new()),
replay_span,
plugins: None,
nesting_level: 0,
preserve_child_depth: 0,
}),
awaited: None,
}
}
/// Creates the child context of the child operation at
/// `parent_positional_id`. `name` is that operation's name; the child's
/// span carries it as `operationName`, with the operation's wire ID as
/// `operationId`.
pub(crate) fn new_child(&self, parent_positional_id: &str, name: Option<&str>) -> Self {
let wire_id = crate::engine::compute_wire_id_public(parent_positional_id);
let engine = Arc::new(EngineState::new_child(
parent_positional_id,
Arc::clone(&self.inner.engine.checkpoint_log),
));
// The child namespace has its own replay high-water mark: nested
// operations can still be replaying while the parent is already
// live. Give it its own span, initialized from the CHILD engine's
// replay status; the child's mints keep it current, and the parent
// span keeps the value the parent's own mints gave it. The span is
// a child of the span current here, so a span a plugin entered
// around the code that creates this context is an ancestor of the
// child body's records. The replay filter decides by this span and
// the SDK operation spans inside this namespace, never by a parent
// namespace's span.
let replay_span = crate::tracing_layer::scoped_execution_span(
&self.inner.execution_arn,
&self.inner.lambda_context.request_id,
self.inner.lambda_context.tenant_id.as_deref(),
&wire_id,
name,
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn: self.inner.execution_arn.clone(),
lambda_context: self.inner.lambda_context.clone(),
engine,
coordinator: Arc::clone(&self.inner.coordinator),
task_ownership: Arc::clone(&self.inner.task_ownership),
execution_client: self.inner.execution_client.clone(),
checkpoint_token: Arc::clone(&self.inner.checkpoint_token),
coalescer: self.inner.coalescer.clone(),
direct: Arc::clone(&self.inner.direct),
parent_wire_id: Some(wire_id),
admission: Arc::clone(&self.inner.admission),
owners: self.owners_with(parent_positional_id),
replay_span,
plugins: self.inner.plugins.clone(),
nesting_level: self.inner.nesting_level.saturating_add(1),
preserve_child_depth: self.inner.preserve_child_depth,
}),
awaited: None,
}
}
/// Creates the context of the virtual child context at
/// `child_positional_id`, which this context claimed. It equals
/// [`Self::new_child`], except that its operations name this context's
/// parent as their parent, it keeps this context's nesting level, and
/// it runs in this context's owners: a virtual child writes no record,
/// so it is not an owner, and its scope never closes on its own. `name`
/// is the virtual operation's name; the child's span carries it as
/// `operationName`, with the virtual operation's wire ID as
/// `operationId`.
pub(crate) fn new_virtual_child(&self, child_positional_id: &str, name: Option<&str>) -> Self {
let wire_id = crate::engine::compute_wire_id_public(child_positional_id);
let engine = Arc::new(EngineState::new_child(
child_positional_id,
Arc::clone(&self.inner.engine.checkpoint_log),
));
// The virtual namespace has its own replay high-water mark, so it
// gets its own span, a child of the current span, as a child from
// `new_child` does. It carries the virtual operation's stable ID,
// and no record is written for it.
let replay_span = crate::tracing_layer::scoped_execution_span(
&self.inner.execution_arn,
&self.inner.lambda_context.request_id,
self.inner.lambda_context.tenant_id.as_deref(),
&wire_id,
name,
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn: self.inner.execution_arn.clone(),
lambda_context: self.inner.lambda_context.clone(),
engine,
coordinator: Arc::clone(&self.inner.coordinator),
task_ownership: Arc::clone(&self.inner.task_ownership),
execution_client: self.inner.execution_client.clone(),
checkpoint_token: Arc::clone(&self.inner.checkpoint_token),
coalescer: self.inner.coalescer.clone(),
direct: Arc::clone(&self.inner.direct),
parent_wire_id: self.inner.parent_wire_id.clone(),
admission: Arc::clone(&self.inner.admission),
owners: Arc::clone(&self.inner.owners),
replay_span,
plugins: self.inner.plugins.clone(),
nesting_level: self.inner.nesting_level,
preserve_child_depth: self.inner.preserve_child_depth,
}),
awaited: None,
}
}
/// Fails the virtual child context claimed at `op_id` when the log
/// holds a record at its ID: a virtual child writes no record, so a
/// record there was written by another operation, such as a non-virtual
/// child that the handler later switched to virtual. The error is a
/// `NonDeterministicExecution` mismatch, recorded as the invocation's
/// fatal error, whose claimed identity is `virtual Context` with
/// `sub_type` and `name`. Without a record it returns `Ok(())`.
pub(crate) fn reject_record_at_virtual_child(
&self,
op_id: &OperationId,
sub_type: &str,
name: Option<&str>,
) -> Result<(), OperationError> {
let Some(expected) = self.with_checkpoint_record(op_id.positional(), |record| {
format_op_identity(
record.op_type.as_deref().unwrap_or("Unknown"),
record.sub_type.as_deref(),
record.op_name.as_deref(),
)
}) else {
return Ok(());
};
Err(self.replay_mismatch_error(
op_id.wire(),
&expected,
"virtual Context",
Some(sub_type),
name,
))
}
/// Whether a context for the child namespace `child_positional_id`
/// would replay before its first claim: the first operation of that
/// namespace has a checkpoint record. It is the
/// [`Self::is_replaying`] a child context created now starts with.
pub(crate) fn namespace_is_replaying(&self, child_positional_id: &str) -> bool {
EngineState::new_child(
child_positional_id,
Arc::clone(&self.inner.engine.checkpoint_log),
)
.is_replaying()
}
/// Whether a context-backed record created on this context at `levels_below`
/// levels under it records `ReplayChildren` on its terminal update.
pub(crate) fn preserves_children(&self, levels_below: u32) -> bool {
let level = self.inner.nesting_level.saturating_add(levels_below);
level <= self.inner.preserve_child_depth
}
/// Mints the next operation ID (internal engine concern).
///
/// Also re-records THIS namespace's span `isReplay` flag: after each
/// claim, the namespace is replaying iff the NEXT operation to be
/// claimed in it has a checkpoint record. This keeps replay-aware log
/// filters (see `tracing_layer::ReplayFilterLayer`) in step with the
/// live replay status as each namespace crosses its own replay
/// high-water mark.
pub(crate) fn mint_id(&self) -> OperationId {
let id = self.inner.engine.mint_id();
self.inner.replay_span.record(
crate::tracing_layer::fields::IS_REPLAY,
self.inner.engine.is_replaying(),
);
id
}
/// Returns this context's positional prefix: `""` for the root context,
/// the positional ID of the operation that created it for a child.
pub(crate) fn prefix(&self) -> &str {
self.inner.engine.id_counter.prefix()
}
/// Claims the next operation ID for the public operation `method`, and
/// checks that the caller may claim it on this context.
///
/// The SDK records which body it is polling in [`ACTIVE_BODY`]. The
/// check compares that body with this context. The outcomes are:
///
/// - No body is active, or the body of this context is active: the
/// caller must own the context (see [`TaskOwnership`]). A task or
/// thread that does not own it fails the execution with a context
/// usage error.
/// - The body of another context is active: the execution fails with a
/// context usage error that names both contexts.
/// - A step body or a `wait_for_condition` check is active: the
/// execution fails with a context usage error that names the
/// operation.
/// - Plugin code is active: the SDK records a context usage error.
///
/// The failure is recorded as an execution-fatal error, which closes
/// checkpoint admission: no update requested after the record is
/// written, so an operation whose next update is refused keeps the last
/// state written. When it is recorded before the driver's arbitration,
/// the invocation answers `FAILED` on the first invocation. Only plugin code can record it
/// after the arbitration, either before `drive_invocation` returns or
/// after; such a record changes neither the response nor the
/// late-panic policy. Without the
/// check, the misuse surfaces one invocation later as a
/// non-determinism error that does not name the cause. The ID is
/// claimed in every case, so the caller builds its builder as usual.
///
/// Only the public operation methods call this. The SDK's own internal
/// claims (inside `wait_for_callback`) call [`Self::mint_id`], because
/// they run on the composite's context while a child body may be
/// active.
///
/// [`TaskOwnership`]: crate::driver::TaskOwnership
pub(crate) fn claim_operation_id(&self, method: &'static str) -> OperationId {
let message = ACTIVE_BODY
.try_with(|active| match active {
ActiveBody::Context(prefix) if prefix == self.prefix() => None,
ActiveBody::Context(prefix) => Some(format!(
"context usage error in \"{method}\": the operation was called on context \
\"{calling}\", but the SDK is running the body of context \"{active}\". \
Inside run_in_child_context, with_retry, map and parallel, call operations \
on the context passed to the closure.",
calling = display_prefix(self.prefix()),
active = display_prefix(prefix),
)),
ActiveBody::Step(id) => Some(format!(
"context usage error in \"{method}\": the operation was called inside the \
body of operation \"{id}\". A step body or a wait_for_condition check \
cannot call durable operations; use run_in_child_context to group \
operations."
)),
ActiveBody::Plugin => Some(format!(
"context usage error in \"{method}\": the operation was called inside \
plugin code. Plugin code cannot call durable operations."
)),
ActiveBody::Outcome(id) => Some(format!(
"context usage error in \"{method}\": the operation was called while the \
SDK records the outcome of operation \"{id}\". An error's Display and \
source cannot call durable operations."
)),
ActiveBody::Unset => None,
})
.ok()
.flatten();
let message = message.or_else(|| {
self.inner
.task_ownership
.check_current_task()
.err()
.map(|_| foreign_caller_message(method))
});
if let Some(message) = message {
self.coordinator().record_fatal("Error".to_owned(), message);
}
self.mint_id()
}
/// Returns this namespace's `durable_execution` span. The root task (for
/// a root context) or the child body's runner (for a child context)
/// enters it outside the plugin frames and wraps, so log events inherit
/// the execution ARN, request ID, and the namespace's live `isReplay`
/// flag, and a span a plugin enters around `next()` is its child.
pub(crate) fn replay_span(&self) -> tracing::Span {
self.inner.replay_span.clone()
}
/// Emits the
/// [`operation_replayed`](crate::observability::event_names::OPERATION_REPLAYED)
/// lifecycle event: the operation's recorded terminal outcome is being
/// returned without re-running it (see [`crate::observability`]).
///
/// `recorded_attempt` is the checkpoint record's retry count; the event
/// reports the 1-based attempt that produced the recorded outcome.
pub(crate) fn emit_operation_replayed(
&self,
wire_id: &str,
operation_name: Option<&str>,
operation_type: &str,
operation_sub_type: Option<&str>,
recorded_attempt: u32,
) {
crate::tracing_layer::operation_replayed_event(&crate::tracing_layer::OperationIdentity {
execution_arn: self.execution_arn(),
request_id: &self.lambda_context().request_id,
operation_id: wire_id,
operation_name,
operation_type,
operation_sub_type,
attempt: recorded_attempt.saturating_add(1),
});
}
/// FLAT-nesting counterpart of [`Self::new_child`]: a child that
/// reports `parent_wire_id_override` as its operations' parent (the
/// batch parent, not the virtual child). The child's span carries the
/// virtual child's wire ID as `operationId` and `name` as
/// `operationName`.
pub(crate) fn new_flat_child(
&self,
child_positional_id: &str,
parent_wire_id_override: &str,
name: Option<&str>,
) -> Self {
let engine = Arc::new(EngineState::new_child(
child_positional_id,
Arc::clone(&self.inner.engine.checkpoint_log),
));
// A flat branch has its own namespace and replay high-water mark,
// so it gets its own span, a child of the current span, as a child
// from `new_child` does. It carries the virtual child's stable ID,
// and no record is written for it.
let replay_span = crate::tracing_layer::scoped_execution_span(
&self.inner.execution_arn,
&self.inner.lambda_context.request_id,
self.inner.lambda_context.tenant_id.as_deref(),
&crate::engine::compute_wire_id_public(child_positional_id),
name,
engine.is_replaying(),
);
Self {
inner: Arc::new(Inner {
execution_arn: self.inner.execution_arn.clone(),
lambda_context: self.inner.lambda_context.clone(),
engine,
coordinator: Arc::clone(&self.inner.coordinator),
task_ownership: Arc::clone(&self.inner.task_ownership),
execution_client: self.inner.execution_client.clone(),
checkpoint_token: Arc::clone(&self.inner.checkpoint_token),
coalescer: self.inner.coalescer.clone(),
direct: Arc::clone(&self.inner.direct),
parent_wire_id: Some(parent_wire_id_override.to_owned()),
admission: Arc::clone(&self.inner.admission),
owners: self.owners_with(child_positional_id),
replay_span,
plugins: self.inner.plugins.clone(),
nesting_level: self.inner.nesting_level,
preserve_child_depth: self.inner.preserve_child_depth,
}),
awaited: None,
}
}
/// The scopes of this invocation: which are closed, and the tasks
/// started in each (see [`Admission`]).
pub(crate) fn admission(&self) -> &Arc<Admission> {
&self.inner.admission
}
/// The owners this context runs in, outermost first. Empty at the root.
pub(crate) fn owners(&self) -> &[String] {
&self.inner.owners
}
/// Returns at once when no owner of this context is abandoned, and
/// never returns otherwise (see [`Admission`]). Every operation
/// terminal awaits it before it runs the operation, so an abandoned
/// owner starts no operation and replays no recorded one.
pub(crate) async fn admit_operation(&self) {
if !self.admission().admits(self.owners()) {
std::future::pending::<()>().await;
}
}
/// This context's owners followed by the wire ID of `positional_id`:
/// the owners of a child context created for that operation.
fn owners_with(&self, positional_id: &str) -> Arc<[String]> {
self.inner
.owners
.iter()
.cloned()
.chain(std::iter::once(crate::engine::compute_wire_id_public(
positional_id,
)))
.collect()
}
/// Installs the direct writer's pre-lock gate (see [`PreLockGate`]).
/// The root context and every child share it.
#[cfg(test)]
pub(crate) fn set_pre_lock_gate(&self, gate: PreLockGate) {
self.inner.direct.hooks().gate = Some(gate);
}
/// Installs the submission recorder (see [`SubmissionRecorder`]). The
/// root context and every child share it.
#[cfg(test)]
pub(crate) fn set_submission_recorder(&self, recorder: SubmissionRecorder) {
self.inner.direct.hooks().submissions = Some(recorder);
}
/// Installs the settler-entry recorder (see [`SettlerEntryRecorder`]).
/// The root context and every child share it.
#[cfg(test)]
pub(crate) fn set_settler_entry_recorder(&self, recorder: SettlerEntryRecorder) {
self.inner.direct.hooks().settler_entries = Some(recorder);
}
/// Passes `updates` and `write`'s first-poll flag to the submission
/// recorder, when one is installed.
#[cfg(test)]
fn record_submission(&self, updates: &[OperationUpdate], write: &SubmittedWrite) {
let recorder = self.inner.direct.hooks().submissions.clone();
if let Some(recorder) = recorder
&& !updates.is_empty()
{
recorder(updates, &write.first_poll);
}
}
/// Waits for `start`, the retained `START` write of the child-backed
/// operation `wire_id`, before the operation writes its outcome
/// `action`. A failed `START` ends the invocation, as
/// [`Self::checkpoint_failure_unrecoverable`] describes, and the
/// outcome is never written. `None` means the operation's `START` was
/// recorded before this cycle.
pub(crate) async fn await_retained_start(
&self,
wire_id: &str,
start: Option<SubmittedWrite>,
action: OperationAction,
) -> Result<(), OperationError> {
#[cfg(test)]
{
let recorder = self.inner.direct.hooks().settler_entries.clone();
if let Some(recorder) = recorder {
recorder(wire_id, action.clone());
}
}
#[cfg(not(test))]
let _ = (wire_id, action);
if let Some(start) = start
&& let Err(err) = start.await
{
return self.checkpoint_failure_unrecoverable(err).await;
}
Ok(())
}
/// Buffers `updates` in the coalescer's open batch without starting a
/// flusher, so only a flush point writes them. Panics without
/// buffering.
#[cfg(test)]
pub(crate) fn buffer_unflushed(&self, updates: Vec<OperationUpdate>) {
let coalescer = self.inner.coalescer.as_ref().expect("a buffered context");
let tracked = self.track_updates(updates);
coalescer
.join(self.admission(), self.coordinator(), self.owners(), tracked)
.expect("the join is admitted");
}
/// The IDs of the updates that wait to be sent: those of the direct
/// write queue, then those of the coalescer's open batch.
#[cfg(test)]
pub(crate) fn queued_update_ids(&self) -> Vec<String> {
let mut ids: Vec<String> = self
.inner
.direct
.lock()
.entries
.iter()
.flat_map(|entry| entry.updates.iter().map(|u| u.id().to_owned()))
.collect();
if let Some(coalescer) = &self.inner.coalescer {
ids.extend(coalescer.pending_ids());
}
ids
}
/// The checkpoint token mutex, which a checkpoint call holds.
#[cfg(test)]
pub(crate) fn checkpoint_token_mutex(&self) -> Arc<Mutex<String>> {
Arc::clone(&self.inner.checkpoint_token)
}
/// The plugins of the invocation, shared by every context derived from
/// the root. `None` without a registered plugin factory.
pub(crate) fn plugins(&self) -> Option<&crate::plugin::InvocationPlugins> {
self.inner.plugins.as_deref()
}
/// Delivers the queued change sets of the plugins to
/// `on_operation_change`, and waits until every change set queued
/// before the call was delivered, also when another task delivers it
/// (see
/// [`InvocationPlugins::changes_delivered`](crate::plugin::InvocationPlugins::changes_delivered)).
/// So an operation that awaits this before it fires
/// `on_operation_start` or `on_operation_end` fires that hook after its
/// change. Does nothing without plugins. The caller must hold no
/// checkpoint lock.
pub(crate) async fn report_operation_changes(&self) {
if let Some(plugins) = self.plugins() {
plugins
.changes_delivered(&self.inner.engine.checkpoint_log)
.await;
}
}
/// [`Self::plugins`], shared: a user-function runner's own frame node
/// holds them.
pub(crate) fn shared_plugins(&self) -> Option<Arc<crate::plugin::InvocationPlugins>> {
self.inner.plugins.clone()
}
/// Returns the invocation coordinator, shared by every context of the
/// invocation.
pub(crate) fn coordinator(&self) -> &Arc<InvocationCoordinator> {
&self.inner.coordinator
}
/// Awaits `fut` while holding an activity permit, so the invocation
/// does not suspend while `fut` runs. When the coordinator refuses the
/// permit (the phase left `Running`), never resolves.
///
/// Wraps the step body, the `wait_for_condition` check and every serdes
/// call: work that can make progress without the SDK polling it.
pub(crate) async fn hold_activity<F: Future>(&self, fut: F) -> F::Output {
let Some(permit) = self.inner.coordinator.acquire(PermitKind::Activity) else {
return std::future::pending().await;
};
let output = fut.await;
drop(permit);
output
}
/// Resolves when the record of `wire_id` satisfies `ready`.
///
/// Registers a wait on its first poll, then reads the record. A missing
/// record is not ready. When the record is ready, the registration is
/// dropped and the future resolves. Otherwise it returns `Pending`; a
/// merged checkpoint response that carries the operation wakes it, and
/// each later poll updates the waker and reads the record again.
///
/// Registering before the read means a merge between the read and the
/// end of the poll still wakes the waiting task. When the coordinator
/// refuses the registration (the phase left `Running`), never resolves.
pub(crate) async fn wait_for_record(
&self,
wire_id: &str,
ready: fn(&CheckpointStatus) -> bool,
) {
let mut registration: Option<crate::coordinator::WaitRegistration> = None;
std::future::poll_fn(|cx| {
if let Some(live) = ®istration {
live.update_waker(cx.waker());
} else {
// The refresh schedule starts from the record's end time
// and status. A missing record is taken as `STARTED` with
// no end time.
let (status, due_at) = self
.refresh_view(wire_id)
.unwrap_or((CheckpointStatus::Started, None));
match self.inner.coordinator.register_wait(
wire_id,
due_at,
&status,
self.awaited.clone(),
cx.waker(),
) {
Some(live) => registration = Some(live),
None => return std::task::Poll::Pending,
}
}
let is_ready = self
.inner
.engine
.checkpoint_log
.status_view(wire_id)
.is_some_and(|view| ready(&view.status));
if is_ready {
registration = None;
std::task::Poll::Ready(())
} else {
if let Some(live) = ®istration {
live.resume_schedule();
}
std::task::Poll::Pending
}
})
.await;
// The response that readied the record queued its change set. It is
// delivered before the operation reads the record again, so it
// comes before the operation's end hook.
self.report_operation_changes().await;
}
/// The status and end time of the record of `wire_id`, as the refresh
/// scheduler reads them.
pub(crate) fn refresh_view(
&self,
wire_id: &str,
) -> Option<(CheckpointStatus, Option<std::time::SystemTime>)> {
self.inner
.engine
.checkpoint_log
.with_record(wire_id, |record| (record.status.clone(), record.due_at))
}
/// A clone of this context whose wait registrations carry `flag`, the
/// first-poll flag of the handle of an operation started on its own
/// task. The refresh scheduler skips those registrations until the
/// handle is first polled and sets the flag.
pub(crate) fn with_awaited(&self, flag: Arc<std::sync::atomic::AtomicBool>) -> Self {
Self {
inner: Arc::clone(&self.inner),
awaited: Some(flag),
}
}
/// Waits until the record of the operation at `positional_id` satisfies
/// `ready` (see [`Self::wait_for_record`]), then returns its view.
pub(crate) async fn wait_for_record_view(
&self,
positional_id: &str,
ready: fn(&CheckpointStatus) -> bool,
) -> CheckpointStatusView {
let wire_id = crate::engine::compute_wire_id_public(positional_id);
self.wait_for_record(&wire_id, ready).await;
#[expect(clippy::expect_used)]
// reason: `wait_for_record` resolves only once the record exists,
// and the checkpoint log never removes a record during an
// invocation.
self.checkpoint_status_view(positional_id)
.expect("a record that satisfied the wait is still in the log")
}
/// Returns the time left until the Lambda deadline: `None` when the
/// deadline is 0 (unknown), otherwise the deadline (milliseconds since
/// the Unix epoch) minus now, and `Duration::ZERO` once it passed.
pub(crate) fn remaining_time(&self) -> Option<Duration> {
remaining_until(
self.inner.lambda_context.deadline,
std::time::SystemTime::now(),
)
}
/// Returns a reference to the task-ownership tracker.
pub(crate) fn task_ownership(&self) -> &Arc<TaskOwnership> {
&self.inner.task_ownership
}
/// Checks task ownership and returns an `OperationError` if the caller
/// is not authorized. Used by every durable operation entry point.
pub(crate) fn enforce_task_ownership(&self) -> Result<(), OperationError> {
self.inner
.task_ownership
.check_current_task()
.map_err(|msg| {
self.coordinator()
.record_fatal("Error".to_owned(), foreign_caller_message("execute"));
OperationError::from_kind(OperationErrorKind::Step(StepError::new(
StepErrorKind::ExecutionFailed,
Some(msg.into()),
)))
})
}
/// Reads the checkpoint record for the given positional ID in place,
/// applying `f` under the log's read guard.
///
/// Returns `None` when no record exists. This (and the targeted
/// accessors below) replaces the removed full-record clone: `f` borrows
/// the stored record, so only what `f` returns is cloned. `f` must not
/// touch the checkpoint log (the read guard is held while it runs).
///
/// NOTE: The checkpoint log is keyed by wire ID (the hash), which is
/// what the backend returns in Operations[].Id. We look up by wire ID
/// computed from the positional ID.
pub(crate) fn with_checkpoint_record<R>(
&self,
positional_id: &str,
f: impl FnOnce(&CheckpointRecord) -> R,
) -> Option<R> {
let wire_id = crate::engine::compute_wire_id_public(positional_id);
self.inner.engine.checkpoint_log.with_record(&wire_id, f)
}
/// [`Self::with_checkpoint_record`], for the record stored under the
/// wire ID `wire_id`.
pub(crate) fn with_checkpoint_record_by_wire<R>(
&self,
wire_id: &str,
f: impl FnOnce(&CheckpointRecord) -> R,
) -> Option<R> {
self.inner.engine.checkpoint_log.with_record(wire_id, f)
}
/// Returns the compact view (status, attempt,
/// `replay_children`) of the checkpoint record for the given positional
/// ID, without cloning any of the record's owned strings.
pub(crate) fn checkpoint_status_view(
&self,
positional_id: &str,
) -> Option<CheckpointStatusView> {
let wire_id = crate::engine::compute_wire_id_public(positional_id);
self.inner.engine.checkpoint_log.status_view(&wire_id)
}
/// Returns whether a checkpoint record exists for the given positional
/// ID, without cloning anything.
///
/// Production operation paths read record presence through
/// [`Self::checkpoint_view_validated`] (which also validates identity);
/// this direct form is retained for unit tests.
#[cfg(test)]
pub(crate) fn has_checkpoint_record(&self, positional_id: &str) -> bool {
let wire_id = crate::engine::compute_wire_id_public(positional_id);
self.inner.engine.checkpoint_log.contains(&wire_id)
}
/// Returns the recorded result payload for the given positional ID,
/// cloning only that one string.
///
/// `None` means either no record exists or the record carries no
/// result: callers that need to distinguish should use
/// [`Self::with_checkpoint_record`].
pub(crate) fn checkpoint_result_payload(&self, positional_id: &str) -> Option<String> {
self.with_checkpoint_record(positional_id, |record| record.result.clone())
.flatten()
}
/// Returns the backend-assigned callback ID for the given positional
/// ID, cloning only that one string.
pub(crate) fn checkpoint_callback_id(&self, positional_id: &str) -> Option<String> {
self.with_checkpoint_record(positional_id, |record| record.callback_id.clone())
.flatten()
}
/// Returns the recorded wire failure record for the given positional
/// ID, cloning only the failure strings. `None` means no record
/// exists.
pub(crate) fn checkpoint_wire_error(
&self,
positional_id: &str,
) -> Option<crate::error::WireError> {
self.with_checkpoint_record(positional_id, |record| {
crate::error::WireError::new(record.error_type.clone(), record.error_message.clone())
.with_error_data(record.error_data.clone())
.with_stack_trace(record.stack_trace.clone().unwrap_or_default())
})
}
/// Returns the terminal-replay projection (status, `replay_children`,
/// and the result/error strings) of the checkpoint record for the
/// given positional ID, cloning only those payload strings.
///
/// This is what the map/parallel replay helpers consume when
/// reconstructing a terminal batch or child item; the record's invoke,
/// callback, attempt, ID, and identity fields are never cloned. `None`
/// means no record exists.
pub(crate) fn checkpoint_terminal_replay(
&self,
positional_id: &str,
) -> Option<TerminalReplaySnapshot> {
self.with_checkpoint_record(positional_id, |record| TerminalReplaySnapshot {
status: record.status.clone(),
replay_children: record.replay_children,
result: record.result.clone(),
error_message: record.error_message.clone(),
error_type: record.error_type.clone(),
error_data: record.error_data.clone(),
stack_trace: record.stack_trace.clone(),
})
}
/// Validates the claimed operation identity against the checkpoint
/// record and returns the compact status view, in a single read-guard
/// pass: the common preamble of every operation's replay check.
///
/// Returns `Ok(None)` when no record exists (live position, nothing to
/// validate), `Ok(Some(view))` when the identity matches, and the
/// `NonDeterministicExecution` error (also recorded on the fatal slot,
/// exactly as [`Self::validate_replay_identity`] does) on mismatch,
/// or when the record carries a [`CheckpointStatus::Unknown`] status
/// this SDK version cannot interpret, in which case the error names
/// the raw status. Nothing is cloned on the match path beyond the
/// status itself.
pub(crate) fn checkpoint_view_validated(
&self,
positional_id: &str,
wire_id: &str,
claimed_type: &str,
claimed_sub_type: Option<&str>,
claimed_name: Option<&str>,
) -> Result<Option<CheckpointStatusView>, OperationError> {
let Some((mismatch, view)) = self.with_checkpoint_record(positional_id, |record| {
(
replay_identity_mismatch(record, claimed_type, claimed_sub_type, claimed_name),
CheckpointStatusView {
status: record.status.clone(),
attempt: record.attempt,
replay_children: record.replay_children,
},
)
}) else {
return Ok(None);
};
if let Some(expected) = mismatch {
// Built (and the fatal slot written) OUTSIDE the read guard.
return Err(self.replay_mismatch_error(
wire_id,
&expected,
claimed_type,
claimed_sub_type,
claimed_name,
));
}
if let CheckpointStatus::Unknown(raw) = &view.status {
// A status this SDK cannot interpret must never be acted on:
// guessing non-terminal re-runs completed work, and guessing
// terminal fabricates an outcome that was never recorded. Fail
// the execution naming the raw status (issue #45).
return Err(self.unrecognized_status_error(wire_id, raw));
}
Ok(Some(view))
}
/// Eagerly validates a claimed operation's replay identity against the
/// checkpoint log, BEFORE the operation future first runs.
///
/// Builders call this when they are finalized into a
/// [`crate::DurableFuture`] (`.future()`, `.spawn()`, or `.await` via
/// `IntoFuture`). Validating at finalization instead of first poll makes
/// fatal propagation scheduler-independent: a short-circuiting combinator
/// (`select_ok`, `race`, `try_join_all`) aborts losers as soon as a
/// winner settles, so a mismatching constituent might otherwise never be
/// polled and the mismatch never recorded. The fatal slot is written
/// synchronously here (inside [`Self::validate_replay_identity`]), so the
/// invocation driver fails the execution with the dedicated error no
/// matter which sibling settles first.
///
/// A position with no checkpoint record is live (nothing to validate),
/// and a matching identity is a no-op: an unchanged handler behaves
/// identically.
pub(crate) fn preflight_replay_identity(
&self,
op_id: &OperationId,
claimed_type: &str,
claimed_sub_type: Option<&str>,
claimed_name: Option<&str>,
) -> Result<(), OperationError> {
// An abandoned owner replays no operation, so its claim is not
// checked against history. A mismatch here would record a fatal
// error and resolve the future. Skipping the check leaves the
// future to the admission check in `DurableFuture::for_operation`,
// which never resolves it. An owner abandoned after this check is
// stopped there too.
if !self.admission().admits(self.owners()) {
return Ok(());
}
self.checkpoint_view_validated(
op_id.positional(),
op_id.wire(),
claimed_type,
claimed_sub_type,
claimed_name,
)?;
Ok(())
}
/// Validates that the claimed operation's identity matches the
/// checkpoint record. On mismatch, returns a
/// `NonDeterministicExecution` error.
///
/// `claimed_type` is the operation type string the SDK sends to the
/// backend (e.g. `Step`, `Wait`, `Context`, `ChainedInvoke`,
/// `Callback`).
///
/// `claimed_sub_type` is the sub-type (e.g. `Step`, `Wait`, `Map`,
/// `RunInChildContext`) or `None` for operations without a sub-type.
///
/// `claimed_name` is the user-supplied `.name("...")` or `None`.
///
/// Production paths validate through [`Self::checkpoint_view_validated`]
/// (one read-guard pass, no record clone); this record-taking form is
/// retained as the direct unit-test harness for the identity-matching
/// rules both share.
#[cfg(test)]
pub(crate) fn validate_replay_identity(
&self,
record: &CheckpointRecord,
wire_id: &str,
claimed_type: &str,
claimed_sub_type: Option<&str>,
claimed_name: Option<&str>,
) -> Result<(), OperationError> {
match replay_identity_mismatch(record, claimed_type, claimed_sub_type, claimed_name) {
None => Ok(()),
Some(expected) => Err(self.replay_mismatch_error(
wire_id,
&expected,
claimed_type,
claimed_sub_type,
claimed_name,
)),
}
}
/// Builds the `NonDeterministicExecution` mismatch error and records it
/// on the shared fatal slot.
///
/// A replay identity mismatch is execution-fatal: recording it on the
/// shared slot makes the invocation driver fail the execution with the
/// dedicated error even if the returned `Err` is swallowed on its way
/// up: stored as a rejected outcome by `join_all`, out-raced by a
/// sibling's success in `select_ok`, stringified through a
/// child-context boundary, or tolerated by a map/parallel completion
/// config.
fn replay_mismatch_error(
&self,
wire_id: &str,
expected: &str,
claimed_type: &str,
claimed_sub_type: Option<&str>,
claimed_name: Option<&str>,
) -> OperationError {
let err = OperationError::from_kind(OperationErrorKind::NonDeterministicExecution(
NonDeterministicExecutionError::from_kind(
NonDeterministicExecutionErrorKind::OperationMismatch(
crate::error::OperationMismatch::new(
wire_id,
expected,
format_op_identity(claimed_type, claimed_sub_type, claimed_name),
),
),
),
));
self.inner.coordinator.record_fatal(
"NonDeterministicExecutionError".to_owned(),
crate::error::chain_string(&err),
);
err
}
/// Builds the execution-fatal error for a checkpoint record whose
/// status this SDK version does not recognize, recording it on the
/// shared fatal slot (issue #45).
///
/// Exactly like [`Self::replay_mismatch_error`], the fatal-slot write
/// makes the invocation driver fail the execution with the dedicated
/// error even if the returned `Err` is swallowed on its way up. The
/// error message carries the raw status verbatim, so the operator can
/// see which service-side status the SDK build predates.
pub(crate) fn unrecognized_status_error(&self, wire_id: &str, raw: &str) -> OperationError {
let err = OperationError::from_kind(OperationErrorKind::NonDeterministicExecution(
NonDeterministicExecutionError::from_kind(
NonDeterministicExecutionErrorKind::UnrecognizedStatus(
crate::error::UnrecognizedStatus::new(wire_id, raw),
),
),
));
self.inner.coordinator.record_fatal(
"NonDeterministicExecutionError".to_owned(),
crate::error::chain_string(&err),
);
err
}
/// What an operation does when its checkpoint write returned an
/// error. Never returns control to the caller, with one exception.
///
/// A failed write is recorded where its response arrives (see
/// [`InvocationCoordinator::fail_write`]), and its caller never
/// resolves. So the only error a write returns to its caller is the
/// one of a write that found no Tokio runtime and sent nothing (see
/// [`Self::write_direct_detached`]). The operation then returns the
/// error `.spawn()` returns without a runtime, at once, and nothing is
/// recorded. Any other error leaves the operation pending: the
/// recorded failure ends the drive, and the operation writes no
/// further update.
pub(crate) async fn checkpoint_failure_unrecoverable<T: NoRuntimeOutcome>(
&self,
err: ExecutionClientError,
) -> T {
if let Some(no_runtime) = std::error::Error::source(&err)
.and_then(|source| source.downcast_ref::<crate::task::NoRuntime>())
{
return T::no_runtime(*no_runtime);
}
std::future::pending::<T>().await
}
/// Records the failed checkpoint write of `op_wire_id` (see
/// [`InvocationCoordinator::fail_write`]): the write-failure latch,
/// and the classification in the fatal slot. The queued writes are
/// dropped. A retryable failure fails the invocation. A non-retryable
/// failure fails the execution with the record of
/// [`checkpoint_execution_failure_wire`](crate::error::checkpoint_execution_failure_wire).
///
/// [`Self::checkpoint_direct_with_events`] calls it, with the
/// checkpoint-token lock held, and no other code does.
fn record_write_failure(&self, op_wire_id: &str, err: &ExecutionClientError) {
if err.is_retryable() {
tracing::error!(
operation_id = %op_wire_id,
error = %err,
"retryable checkpoint failure exhausted retries; failing the invocation \
so the service re-invokes"
);
} else {
tracing::error!(
operation_id = %op_wire_id,
error = %err,
"non-retryable checkpoint failure; failing the execution"
);
}
self.inner
.coordinator
.fail_write(checkpoint_failure_fatal(err), || {
self.abandon_queued_writes();
});
}
/// Ends the invocation because a serdes call failed with a marked
/// error. Never resolves.
///
/// A serdes marks a transient failure with
/// [`RetryableSerdesError`](crate::serdes::RetryableSerdesError). The
/// failure records nothing: the invocation fails with a Lambda runtime
/// error, and the service invokes the function again. The next
/// invocation then repeats the failed serdes call. Like
/// [`Self::checkpoint_failure_unrecoverable`], the fault goes into the
/// fatal slot that every scope shares, so user code can neither catch
/// nor ignore it.
pub(crate) async fn serdes_fault<T>(
&self,
call: &'static str,
operation_id: &str,
name: Option<&str>,
err: BoxError,
) -> T {
let detail = crate::error::wire_message(&*err);
let message = match name {
Some(name) => {
format!("serdes {call} failed for operation \"{name}\" ({operation_id}): {detail}")
}
None => format!("serdes {call} failed for operation {operation_id}: {detail}"),
};
tracing::error!(
operation_id = %operation_id,
error = %detail,
"serdes {call} failed with a retryable error; failing the invocation so the \
service re-invokes"
);
self.inner
.coordinator
.record_invocation_fault(crate::error::SERDES_FAILED_ERROR_TYPE, message);
std::future::pending::<T>().await
}
/// Ends the invocation when `err` is marked with
/// `RetryableSerdesError`. Returns `err` unchanged otherwise.
///
/// Every call to a user [`Serdes`](crate::serdes::Serdes) passes its
/// error through this method before any other handling. So an
/// unmarked error takes the caller's permanent-failure path, and a
/// marked error never reaches it.
pub(crate) async fn route_serdes_error(
&self,
call: &'static str,
operation_id: &str,
name: Option<&str>,
err: BoxError,
) -> BoxError {
if crate::serdes::is_retryable_serdes_error(&*err) {
return self.serdes_fault(call, operation_id, name, err).await;
}
err
}
/// Checkpoints operation updates via the execution client.
///
/// When [`Options`](crate::Options) configured a `checkpoint_delay`
/// and/or `checkpoint_batching`, the updates join the shared coalescing
/// batch and this call resolves with the batch's result once it flushes
/// (after at most the configured delay, or earlier if a flush point
/// drains the buffer). Without either knob, the write happens
/// immediately via [`Self::checkpoint_updates_direct`].
pub(crate) async fn checkpoint_updates(
&self,
updates: Vec<OperationUpdate>,
) -> Result<CheckpointOutput, ExecutionClientError> {
self.submit_checkpoint_updates(updates).await
}
/// Starts the checkpoint write of [`Self::checkpoint_updates`] before
/// it returns, and returns the future of its result.
///
/// With buffering, the updates join the batch and take their checkpoint
/// permit under the buffer lock. Without it, they enter the
/// [`DirectWriteQueue`], whose writer sends them in submission order.
/// So the write keeps its place in the write order, and continues when
/// the returned value is dropped.
pub(crate) fn submit_checkpoint_updates(
&self,
updates: Vec<OperationUpdate>,
) -> SubmittedWrite {
self.checkpoint_with_urgency(updates, false)
}
/// Checkpoints operation updates, flushing the coalescing buffer
/// immediately instead of waiting out the delay window.
///
/// This is the "callback creation" flush point of the
/// [`checkpoint_delay`](crate::OptionsBuilder::checkpoint_delay)
/// contract: the caller needs the backend's response right away (the
/// service assigns the callback ID in it), so the batch, including any
/// previously buffered updates, which keeps write order intact, is
/// written now. Identical to [`Self::submit_checkpoint_updates`] when
/// no delay is configured.
///
/// The updates join the batch, or the direct write queue, before this
/// returns, as with [`Self::submit_checkpoint_updates`].
pub(crate) fn submit_checkpoint_updates_urgent(
&self,
updates: Vec<OperationUpdate>,
) -> SubmittedWrite {
self.checkpoint_with_urgency(updates, true)
}
/// Fixes the position of `updates` in the write order, as
/// [`Self::submit_checkpoint_updates`] does, but holds them back until
/// the returned [`ReservedWrite`] is released or dropped.
///
/// With buffering, the updates join the open batch, and the batch is
/// not flushed while the reservation holds it. Without buffering, they
/// enter the [`DirectWriteQueue`], and the writer waits at them. So no
/// request carries them, and no response is merged for them, before the
/// release.
pub(crate) fn reserve_checkpoint_updates(
&self,
updates: Vec<OperationUpdate>,
) -> ReservedWrite {
#[cfg(test)]
let recorded = updates.clone();
let tracked = self.track_updates(updates);
let Some(coalescer) = self.inner.coalescer.clone() else {
let (updates, events): (Vec<_>, Vec<_>) =
tracked.into_iter().map(|t| (t.update, t.event)).unzip();
let Some(permit) = self.inner.coordinator.acquire(PermitKind::Checkpoint) else {
return ReservedWrite::rejected();
};
let (write, id) = self.enqueue_direct(updates, events, Some(permit), None, true);
let write = write.reported_by(self);
#[cfg(test)]
if id.is_some() {
self.record_submission(&recorded, &write);
}
return ReservedWrite {
write,
hold: id.map(|id| WriteHold::Direct {
queue: Arc::clone(&self.inner.direct),
id,
}),
};
};
let Some(batch) = self.join_batch(&coalescer, tracked, false, None, true) else {
return ReservedWrite::rejected();
};
let write = batch_result(batch).reported_by(self);
#[cfg(test)]
self.record_submission(&recorded, &write);
ReservedWrite {
write,
hold: Some(WriteHold::Batch(coalescer)),
}
}
/// Sends one checkpoint with no updates for the refresh scheduler.
///
/// `first_wire_id` travels with the request: a failure of a request
/// with no update is recorded for it (see [`Self::record_write_failure`]).
/// The failure is recorded where the response arrives, on the detached
/// writer or flusher, so it decides the invocation's outcome even when
/// the driver dropped the scheduler, and so this future. A failed
/// refresh never resolves.
pub(crate) async fn checkpoint_refresh(&self, first_wire_id: &str) {
let write = if self.inner.coalescer.is_some() {
self.write_with_urgency(Vec::new(), true, Some(first_wire_id))
} else {
// No checkpoint permit: the scheduler's permit keeps the
// invocation open until the response is merged and the readied
// operations are woken. The write task is counted, so the
// drive's cleanup waits for it after the scheduler is dropped.
self.write_direct_detached(Vec::new(), Vec::new(), None, Some(first_wire_id.to_owned()))
};
// The task that sends the refresh delivers the change sets queued
// so far once the call returns. The scheduler runs inside a Tokio
// runtime, so the write never returns the error of a write that
// found none, and a failed refresh never resolves.
drop(write.reported_by(self).await);
}
/// Shared body of the buffered checkpoint paths: pairs each update
/// with its captured lifecycle-event metadata, then hands the pairs to
/// the write path, which emits each event as soon as the write that
/// persists its update succeeds. The write starts before this returns.
fn checkpoint_with_urgency(
&self,
updates: Vec<OperationUpdate>,
urgent: bool,
) -> SubmittedWrite {
// Lifecycle events (see `crate::observability`): every operation
// transition the SDK records passes through here, so this one site
// covers `operation_started` / `operation_succeeded` /
// `operation_failed` / `operation_retry_scheduled` for every
// operation type. The metadata is captured BEFORE the write (the
// checkpoint response mutates the log the attempt is derived from,
// and the updates themselves are consumed by it; the capture also
// snapshots this call's span so the event keeps its originating
// context). Ownership then travels WITH the update into the write
// path, the buffered flush task, not this possibly-cancelled
// future, emits the event, so a contributor dropped after joining
// a batch (a lost `race`/`select_ok` branch) cannot suppress
// telemetry for a transition the flush still persists, and events
// are emitted per persisted chunk rather than per batch. A rejected
// write records nothing, so it emits nothing.
let tracked = self.track_updates(updates);
self.write_with_urgency(tracked, urgent, None)
.reported_by(self)
}
/// Pairs each update with its lifecycle-event metadata, captured now
/// (see [`Self::checkpoint_with_urgency`]).
fn track_updates(&self, updates: Vec<OperationUpdate>) -> Vec<TrackedUpdate> {
updates
.into_iter()
.map(|update| {
// The current attempt is one past the recorded retry count,
// exactly as the step live path derives it.
let attempt = self
.inner
.engine
.checkpoint_log
.status_view(update.id())
.map_or(0, |view| view.attempt)
.saturating_add(1);
TrackedUpdate::capture(update, attempt)
})
.collect()
}
/// Dispatches a checkpoint write: joins the coalescing batch when one
/// is configured, otherwise writes directly. Under a non-zero delay, the
/// non-urgent join that opens a batch starts a detached flush that
/// waits out the window; an urgent contributor, or any contributor
/// under a zero-delay coalescer (pure `checkpoint_batching` mode),
/// requests the flush right away. Either way the flush task claims and
/// writes the batch under the coalescer's writer lock, so batching still
/// emerges while an earlier write is in flight.
///
/// Joining the batch transfers ownership of each update's lifecycle
/// event to the coalescer: the flush task that persists the update
/// emits it, so this future can be dropped mid-await without losing
/// telemetry for a transition the flush still records.
///
/// `refresh_id` applies only with buffering: the joined batch passes it
/// with its write (see [`Self::checkpoint_refresh`]).
///
/// The join or the direct write happens before this returns, so the
/// returned [`SubmittedWrite`] only waits for the result.
fn write_with_urgency(
&self,
updates: Vec<TrackedUpdate>,
urgent: bool,
refresh_id: Option<&str>,
) -> SubmittedWrite {
// The recorder sees the submission before it joins the coalescer
// or enters the queue, so before the writer can send it. The write
// built below takes the flag the recorder saw.
#[cfg(test)]
let flag = {
let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
let recorder = self.inner.direct.hooks().submissions.clone();
if let Some(recorder) = recorder
&& !updates.is_empty()
&& self.admission().admits(self.owners())
{
let submitted: Vec<OperationUpdate> =
updates.iter().map(|t| t.update.clone()).collect();
recorder(&submitted, &flag);
}
flag
};
#[cfg_attr(not(test), expect(unused_mut))] // reason: only the test build sets the flag
let mut write = self.write_with_urgency_unrecorded(updates, urgent, refresh_id);
#[cfg(test)]
{
write.first_poll = flag;
}
write
}
/// [`Self::write_with_urgency`] without the test submission recorder.
fn write_with_urgency_unrecorded(
&self,
updates: Vec<TrackedUpdate>,
urgent: bool,
refresh_id: Option<&str>,
) -> SubmittedWrite {
let Some(coalescer) = self.inner.coalescer.clone() else {
let (updates, events): (Vec<_>, Vec<_>) =
updates.into_iter().map(|t| (t.update, t.event)).unzip();
let Some(permit) = self.inner.coordinator.acquire(PermitKind::Checkpoint) else {
// The phase left `Running`, the checkpoint token was
// withdrawn, or a fatal error is recorded (a failed write
// records one): the write is rejected, as a write from an
// abandoned owner is.
return SubmittedWrite::rejected();
};
return self.write_direct_detached(updates, events, Some(permit), None);
};
match self.join_batch(&coalescer, updates, urgent, refresh_id, false) {
Some(batch) => batch_result(batch),
None => SubmittedWrite::rejected(),
}
}
/// Joins `updates` to the coalescer's open batch and schedules its
/// flush. With `reserve`, the join holds the batch until the hold is
/// released (see [`ReservedWrite`]). Returns `None` when admission
/// rejects the join.
fn join_batch(
&self,
coalescer: &Arc<CheckpointCoalescer>,
updates: Vec<TrackedUpdate>,
urgent: bool,
refresh_id: Option<&str>,
reserve: bool,
) -> Option<Arc<CheckpointBatch>> {
// Admission (see `Admission`): an update from an abandoned owner is
// rejected, and a rejected write never resolves. Its task is being
// cancelled. Returning `Ok` instead would let an operation continue
// as if its update were recorded. The admitted join holds a
// checkpoint permit until the batch's response is merged.
// After a fatal record, a failed write included, nothing more is
// admitted: the join's checkpoint permit is refused under the
// buffer lock (see `InvocationCoordinator::acquire`), so the write
// is rejected before it joins the buffer. A join admitted before
// the record stays in the buffer and is written.
let (batch, opened) = coalescer.join_owned(
self.admission(),
self.coordinator(),
self.owners(),
updates,
refresh_id,
reserve,
)?;
if urgent || coalescer.delay().is_zero() {
self.spawn_batch_flush(coalescer, &batch, Duration::ZERO);
} else if opened {
// The join that opened the batch arms its window on a detached
// task, so the batch is written even when every contributor is
// dropped before the window elapses.
self.spawn_batch_flush(coalescer, &batch, coalescer.delay());
}
Some(batch)
}
/// Writes one request's worth of tracked updates immediately and, if,
/// and only if, the checkpoint call that persists them succeeds, emits
/// each update's lifecycle event (inside the span captured with it).
/// This is the single site that pairs "the transition was persisted"
/// with "its telemetry was emitted": both the unbuffered path and every
/// chunk of a batched write funnel through it. The emission happens
/// inside [`Self::checkpoint_direct_with_events`], immediately after
/// the service accepts the write, before the fallible pagination
/// hydration that follows it, so a transition the service recorded
/// always emits its event even when hydrating the paginated state
/// fails afterwards.
///
/// Only the batch flusher calls this. Its updates were admitted when
/// they joined the buffer, so it skips the admission check.
async fn write_tracked_direct(
&self,
tracked: Vec<TrackedUpdate>,
) -> Result<CheckpointOutput, WriteError> {
let (updates, events): (Vec<_>, Vec<_>) =
tracked.into_iter().map(|t| (t.update, t.event)).unzip();
self.write_unchecked(updates, &events, None).await
}
/// Writes updates that skip the admission check: the batch flusher's.
/// `refresh_id` is the batch's (see [`Self::checkpoint_refresh`]).
async fn write_unchecked(
&self,
updates: Vec<OperationUpdate>,
events: &[crate::tracing_layer::PendingTransitionEvent],
refresh_id: Option<&str>,
) -> Result<CheckpointOutput, WriteError> {
#[expect(clippy::expect_used)]
// reason: with no owners to check, `checkpoint_direct_with_events`
// never rejects the write, so it always returns a result.
self.checkpoint_direct_with_events(updates, events, None, refresh_id)
.await
.expect("a write without an admission check is never rejected")
}
/// Writes updates directly, through the [`DirectWriteQueue`] and its
/// detached writer, after the admission check, and returns the result
/// to the caller.
///
/// `permit` is the write's checkpoint permit, held until the response is
/// merged, the operations it readied are woken, and the result is
/// handed to the caller. `None` is passed in two cases: after the drive
/// ended, and for an unbatched refresh, whose scheduler permit holds the
/// invocation open instead (see [`Self::checkpoint_refresh`]). In both
/// cases the cleanup's `wait_idle` waits for the counted writer.
///
/// The write runs on the writer's task because a cancelled caller must not
/// cancel an admitted request. A batch abandons its running items at
/// early completion and aborts their tasks. If an aborted item
/// cancelled a request the service had accepted, the checkpoint token
/// would not rotate, and the parent's next write would use a stale
/// token. The task is counted, so the invocation waits for it.
///
/// The outcomes are:
///
/// - No Tokio runtime is running: nothing is sent, and the caller gets
/// an invocation-scope error whose source is
/// [`NoRuntime`](crate::task::NoRuntime). An operation that receives
/// it returns the error `.spawn()` returns without a runtime (see
/// [`Self::checkpoint_failure_unrecoverable`]).
/// - The admission check rejects the write, the checkpoint token was
/// withdrawn, a fatal error was recorded before the caller took the
/// write's checkpoint permit, or a write failed, this one or an
/// earlier one: nothing more is sent, and the returned future never
/// resolves (see [`Admission`], [`InvocationCoordinator::acquire`]
/// and [`Self::record_write_failure`]).
/// - The checkpoint client panics: the task gateway records the panic on
/// the coordinator, which ends the drive. The channel carries no
/// payload, so the caller stays pending until the drive's cleanup
/// cancels it.
/// - Otherwise: the caller gets the write's output.
///
/// A refresh passes `refresh_id` (see [`Self::checkpoint_refresh`]).
///
/// The write enters the queue before this returns, so its position in
/// the write order is fixed, and the returned [`SubmittedWrite`] only
/// waits for the result.
fn write_direct_detached(
&self,
updates: Vec<OperationUpdate>,
events: Vec<crate::tracing_layer::PendingTransitionEvent>,
permit: Option<crate::coordinator::Permit>,
refresh_id: Option<String>,
) -> SubmittedWrite {
self.enqueue_direct(updates, events, permit, refresh_id, false)
.0
}
/// Appends a write to the [`DirectWriteQueue`] and starts the direct
/// writer when none runs. Returns the write's result future and, while
/// the entry is queued, its ID. A `held` entry is not written until
/// [`DirectWriteQueue::release`] releases it.
///
/// When no Tokio runtime is running, the writer cannot start: every
/// queued entry gets an invocation-scope error whose source is
/// [`NoRuntime`](crate::task::NoRuntime), and no ID is returned.
///
/// After a failed write nothing more is sent: the write is rejected
/// before it enters the queue, and no ID is returned.
fn enqueue_direct(
&self,
updates: Vec<OperationUpdate>,
events: Vec<crate::tracing_layer::PendingTransitionEvent>,
permit: Option<crate::coordinator::Permit>,
refresh_id: Option<String>,
held: bool,
) -> (SubmittedWrite, Option<u64>) {
let (sender, receiver) = tokio::sync::oneshot::channel();
let queue = &self.inner.direct;
let (id, start_writer) = {
#[cfg(test)]
crate::coordinator::race_points::reach(
crate::coordinator::race_points::RacePoint::DirectQueueLock,
);
let mut state = queue.lock();
// The latch is checked under the queue lock, and a failed
// write sets it before it drops the queue under the same lock.
// So an entry either is queued first and dropped, or is
// rejected here.
if self.inner.coordinator.write_failed() {
return (SubmittedWrite::rejected(), None);
}
let id = state.next_id;
state.next_id = state.next_id.wrapping_add(1);
state.entries.push_back(DirectEntry {
id,
held,
ctx: self.clone(),
updates,
events,
permit,
refresh_id,
sender,
});
let start_writer = !state.writer_running;
state.writer_running = true;
(id, start_writer)
};
let mut queued = Some(id);
if start_writer
&& let Err(no_runtime) = crate::task::spawn_detached(
self.coordinator(),
run_direct_writer(Arc::clone(queue)),
)
{
// The source marks the error, so that
// `checkpoint_failure_unrecoverable` returns the operation error
// `.spawn()` returns instead of failing the invocation.
let err = ExecutionClientError::with_source(
ExecutionClientErrorScope::Invocation,
no_runtime.to_string(),
no_runtime,
);
#[cfg(test)]
crate::coordinator::race_points::reach(
crate::coordinator::race_points::RacePoint::DirectNoRuntimeDrain,
);
// The latch is read under the queue lock, as at the entry
// above. A failed write sets it before it drops the queue under
// the same lock, so either the failure comes first and the
// drained entries are dropped unresolved, as the failure would
// drop them, or the drain comes first and the failure finds an
// empty queue.
let (drained, write_failed) = {
let mut state = queue.lock();
state.writer_running = false;
(
std::mem::take(&mut state.entries),
self.inner.coordinator.write_failed(),
)
};
if !write_failed {
for entry in drained {
// The receivers are this call's and those of callers
// that queued behind it on a thread without a runtime.
let _ = entry.sender.send(Some(Err(err.clone())));
}
}
queued = None;
}
// The writer is never aborted, so the sender is dropped unsent only
// when the checkpoint client panicked, or when a withdrawn
// checkpoint token or a failed write dropped the queued entry. The
// gateway recorded the panic, a withdrawal suspends the
// invocation, and a failed write ends the drive, so the caller
// stays pending until the cleanup cancels it.
let write = SubmittedWrite::new(async move {
match receiver.await {
Ok(Some(result)) => result,
Ok(None) | Err(_) => std::future::pending().await,
}
});
(write, queued)
}
/// Spawns a task that claims `batch` (if it is still the open batch)
/// and writes its buffered updates, publishing the result to every
/// contributor. The claim and the write both happen while holding the
/// coalescer's writer lock, so buffered writes are totally ordered and
/// a flush point that acquires the lock waits for this write to finish.
/// A write that sent nothing or failed publishes nothing, so the
/// batch's contributors never resolve: the checkpoint token was
/// withdrawn, or this write or an earlier one failed, and the failure
/// is recorded where its response arrived (see
/// [`Self::record_write_failure`]).
///
/// The write runs on its own task deliberately: a contributor dropped
/// mid-await (a lost `race`, a dropped `DurableFuture`) must not cancel
/// an in-flight batch write that other contributors are waiting on.
fn spawn_batch_flush(
&self,
coalescer: &Arc<CheckpointCoalescer>,
batch: &Arc<CheckpointBatch>,
delay: Duration,
) {
let ctx = self.clone();
let claim_from = Arc::clone(coalescer);
let coalescer = Arc::clone(coalescer);
let publish_to = Arc::clone(batch);
let batch = Arc::clone(batch);
// Detached mode of the task gateway (src/task.rs): this internal
// task runs no handler code and creates no durable operations, and it
// must survive a cancelled contributor. It is still counted, so the
// invocation waits for an in-flight write before it returns. The
// batch's checkpoint permits keep the invocation from suspending
// until the response is merged and published.
// A panic of the checkpoint client unwinds the flush, and nothing
// publishes the batch. The task gateway records the panic on the
// coordinator, which ends the drive. The contributors stay pending
// until the drive's cleanup cancels them.
let flush = async move {
if !delay.is_zero() {
// The window ends early when the invocation would suspend
// but for buffered writes, or when the drive ended. A
// counted task that slept out the whole window would keep
// a resolved handler from returning for up to the full
// `checkpoint_delay`, which has no upper bound.
ctx.coordinator().coalescing_window(delay).await;
}
let _writer = coalescer.writer_lock().lock().await;
if let Some((updates, permits)) = coalescer.take_batch_unheld(&batch).await {
// The merge already woke the operations the response
// readied. The contributors' wakes take their own permits
// before the batch's permits are released.
if let Ok(output) = ctx
.write_batched_updates(updates, coalescer.limits(), batch.refresh_id())
.await
{
batch.publish(Ok(output));
}
drop(permits);
}
};
let spawned = crate::task::spawn_detached(self.coordinator(), flush);
// No Tokio runtime is running on this thread, so nothing can write
// the batch: it is dropped from the buffer with its updates and
// permits, so no later flush sends it, and every contributor
// receives the error instead of waiting forever. Its source marks
// it, so an operation returns the error `.spawn()` returns without
// a runtime (see `checkpoint_failure_unrecoverable`). When another
// flusher already claimed the batch, that flusher publishes its
// result instead. Nothing was sent, and nothing is recorded. After
// a failed write the batch is not claimed and nothing is published
// (see `CheckpointCoalescer::claim_unspawned`).
let Err(no_runtime) = spawned else {
return;
};
#[cfg(test)]
crate::coordinator::race_points::reach(
crate::coordinator::race_points::RacePoint::BatchNoRuntimeClaim,
);
if let Some((updates, permits)) =
claim_from.claim_unspawned(&publish_to, self.coordinator())
{
drop(updates);
publish_to.publish(Err(ExecutionClientError::with_source(
ExecutionClientErrorScope::Invocation,
no_runtime.to_string(),
no_runtime,
)));
drop(permits);
}
}
/// Writes a sealed batch, splitting it into request-sized chunks that
/// respect the coalescer's [`BatchLimits`] (operation count and
/// estimated payload bytes) while preserving join order. Returns the
/// last chunk's output on success: backend-assigned fields from every
/// chunk are already merged into the checkpoint log. The first chunk
/// that sends nothing or fails stops the batch: the chunks after it are
/// not sent. `refresh_id` is the batch's (see
/// [`Self::checkpoint_refresh`]).
///
/// Each chunk's lifecycle events are emitted immediately after that
/// chunk's write succeeds (see [`Self::write_tracked_direct`]): a chunk
/// persisted before a later chunk fails still emits its events, so
/// telemetry stays faithful to what was actually recorded.
///
/// Callers must hold the coalescer's writer lock (see the invariants in
/// [`crate::checkpoint_coalescer`]).
async fn write_batched_updates(
&self,
updates: Vec<TrackedUpdate>,
limits: BatchLimits,
refresh_id: Option<String>,
) -> Result<CheckpointOutput, WriteError> {
if updates.is_empty() {
// A refresh joins with no update, and its request carries none.
return self
.write_unchecked(Vec::new(), &[], refresh_id.as_deref())
.await;
}
let mut last = None;
for chunk in split_into_requests(updates, &limits) {
last = Some(self.write_tracked_direct(chunk).await?);
}
#[expect(clippy::expect_used)]
// reason: a non-empty batch splits into at least one request.
Ok(last.expect("a non-empty batch has a request"))
}
/// Unconditionally drains the checkpoint coalescing buffer, writing any
/// pending batches now, and waits for any in-flight batch write to
/// finish before returning.
///
/// This is the "suspension" and "execution completion" flush point of
/// the [`checkpoint_delay`](crate::OptionsBuilder::checkpoint_delay) /
/// [`checkpoint_batching`](crate::OptionsBuilder::checkpoint_batching)
/// contract: the invocation wrapper calls it after the driver settles,
/// before reporting `PENDING`, `SUCCEEDED`, or `FAILED` to the service,
/// so a checkpoint that must land before the invocation ends is never
/// held back by the buffer. Because every claimed batch is written while
/// holding the coalescer's writer lock, acquiring that lock here makes
/// this a true barrier: a batch a delay timer already claimed cannot
/// still be in flight when this returns. A no-op when no buffering is
/// configured or the buffer is idle.
///
/// A write that sends nothing or fails stops the drain: the checkpoint
/// token was withdrawn, or this write or an earlier one failed, and
/// the failure is recorded where its response arrived (see
/// [`Self::record_write_failure`]). The batch's contributors never
/// resolve, and the rest of the buffer was dropped with the queued
/// writes.
pub(crate) async fn flush_pending_checkpoints(&self) {
let Some(coalescer) = self.inner.coalescer.clone() else {
return;
};
// Acquiring the writer lock waits out any in-flight batch write
// (batches are only claimed and written under it), then holding it
// across the drain keeps this flush ordered after those writes.
let _writer = coalescer.writer_lock().lock().await;
while let Some((batch, updates, permits)) = coalescer.take_any_unheld().await {
let written = self
.write_batched_updates(updates, coalescer.limits(), batch.refresh_id())
.await;
drop(permits);
match written {
Ok(output) => batch.publish(Ok(output)),
Err(_) => break,
}
}
}
/// Writes operation updates through the execution client immediately.
///
/// Serializes all concurrent callers through a single critical section:
/// the lock is held across the full read-token → API-call →
/// rotate-token sequence, and, when the response carries a pagination
/// marker, through the follow-up `get_state` fetch as well, so no
/// concurrent branch can rotate the token out from under the paginated
/// state read.
///
/// The write is admitted (see [`Admission`]) and runs on a detached
/// task (see [`Self::write_direct_detached`]).
#[cfg(test)]
pub(crate) async fn checkpoint_updates_direct(
&self,
updates: Vec<OperationUpdate>,
) -> Result<CheckpointOutput, ExecutionClientError> {
let Some(permit) = self.inner.coordinator.acquire(PermitKind::Checkpoint) else {
// The phase left `Running`, the checkpoint token was withdrawn,
// or a fatal error is recorded: the write is rejected, as a
// write from an abandoned owner is.
return std::future::pending().await;
};
let result = self
.write_direct_detached(updates, Vec::new(), Some(permit), None)
.await;
// The detached write task merged the response and dropped the
// token guard, so the caller's task delivers the change sets.
self.report_operation_changes().await;
result
}
/// A direct write after the drive ended, when no permit can be taken.
///
/// The drive's cleanup waited for every SDK task, so the write runs on
/// the caller's task, under the checkpoint-token lock. It returns its
/// result to the caller at once: [`WriteError::Stopped`] when the token
/// is or becomes withdrawn, or when a write failed before, and
/// [`WriteError::Failed`] when it fails itself.
pub(crate) async fn checkpoint_updates_after_drive(
&self,
updates: Vec<OperationUpdate>,
) -> Result<CheckpointOutput, WriteError> {
#[expect(clippy::expect_used)]
// reason: the root context's owners are empty, so the admission
// check never rejects the write, and it always returns a result.
self.checkpoint_direct_with_events(updates, &[], Some(self.owners()), None)
.await
.expect("a write from the root context is never rejected")
}
/// Body of [`Self::checkpoint_updates_direct`] that additionally owns
/// the lifecycle events paired with the updates. Each event is emitted
/// the moment `client.checkpoint` returns success, the point at which
/// the service has durably recorded the transitions, and **before**
/// the pagination hydration below, which can fail after the write
/// already persisted. Emitting first keeps telemetry faithful to what
/// was recorded: a rejected write emits nothing, and a persisted write
/// emits everything even when the follow-up `get_state` fetch fails.
///
/// With `Some(owners)`, the write is admitted while this call holds the
/// checkpoint-token lock. A rejected write sends nothing, emits no
/// event, does not rotate the token, and returns `None`. `None` skips
/// the check: the batch flusher passes it, because its updates were
/// admitted when they joined the buffer.
///
/// After the checkpoint token was withdrawn (see
/// [`InvocationCoordinator::withdraw`]), or after a failed write, the
/// call sends nothing and returns [`WriteError::Stopped`].
///
/// A failed call is recorded here (see [`Self::record_write_failure`]),
/// for the wire ID of the request's first update, or `refresh_id` for a
/// refresh, which sends none: the transport's error and the error of
/// the state read that follows an accepted paginated write, under the
/// checkpoint-token lock (see [`Self::write_locked`]), and a missing
/// execution client.
async fn checkpoint_direct_with_events(
&self,
updates: Vec<OperationUpdate>,
events: &[crate::tracing_layer::PendingTransitionEvent],
owners: Option<&[String]>,
refresh_id: Option<&str>,
) -> Option<Result<CheckpointOutput, WriteError>> {
let failure_id = updates
.first()
.map(|update| update.id().to_owned())
.or_else(|| refresh_id.map(str::to_owned))
.unwrap_or_default();
// Hold the async mutex across the entire checkpoint call to
// serialize concurrent branch checkpoints. This is the Rust
// equivalent of Go's sync.Mutex held across the blocking API call
// in checkpointer.checkpoint().
let token_guard = self.inner.checkpoint_token.lock().await;
if owners.is_some_and(|owners| !self.admission().admits(owners)) {
return None;
}
// Both latches are set under this lock, so a request that waited
// for the lock behind the withdrawn or failed one sees them here.
if self.inner.coordinator.withdrawn() || self.inner.coordinator.write_failed() {
return Some(Err(WriteError::Stopped));
}
let Some(client) = self.inner.execution_client.as_ref() else {
// Recorded under the checkpoint-token lock, as a failed call
// is, so it is ordered with every other write.
let err = ExecutionClientError::new_non_retryable("no execution client configured");
self.record_write_failure(&failure_id, &err);
drop(token_guard);
return Some(Err(WriteError::Failed(err)));
};
Some(
self.write_locked(client, token_guard, updates, events, &failure_id)
.await,
)
}
/// The write of [`Self::checkpoint_direct_with_events`], with the
/// checkpoint-token lock held. A failed call or a failed state read
/// after it is recorded for `failure_id` before the lock is released.
async fn write_locked(
&self,
client: &Arc<dyn ExecutionClient>,
mut token_guard: tokio::sync::MutexGuard<'_, String>,
updates: Vec<OperationUpdate>,
events: &[crate::tracing_layer::PendingTransitionEvent],
failure_id: &str,
) -> Result<CheckpointOutput, WriteError> {
let retried = wfc_retries(&updates);
// A tokenless response to a request with an `EXECUTION` update is
// not a withdrawal, as in the JS and Python SDKs.
let has_execution_update = updates
.iter()
.any(|update| update.r#type() == &aws_sdk_lambda::types::OperationType::Execution);
let output = match client
.checkpoint(&self.inner.execution_arn, &token_guard, updates)
.await
{
Ok(output) => output,
Err(err) => {
self.record_write_failure(failure_id, &err);
return Err(WriteError::Failed(err));
}
};
let next_token = output.checkpoint_token().map(ToOwned::to_owned);
let tokenless = next_token.is_none();
// The service has recorded the transitions: emit their lifecycle
// events now, before the fallible pagination hydration below can
// turn an already-persisted write into a caller-visible error.
for event in events {
event.emit(self.execution_arn(), &self.lambda_context().request_id);
}
match next_token {
// Rotate the token while still holding the lock.
Some(next_token) => *token_guard = next_token,
None if has_execution_update => {}
None => {
// The service accepts no further checkpoints from this
// invocation. The response's state is not merged, and the
// request's callers are not resolved. The latch is set
// under the token lock, the queued writes are dropped
// unresolved, and a request that already waits for the
// lock sees the latch before it is sent.
self.inner.coordinator.withdraw(
self.execution_arn(),
&self.lambda_context().request_id,
|| self.abandon_queued_writes(),
);
return Err(WriteError::Stopped);
}
}
// Merge updated operations into the checkpoint log so that
// subsequent reads (e.g. reading callback_id after START) see
// backend-assigned fields.
let mut merged: Vec<String> = Vec::new();
// The change set of this call, for `on_operation_change`: the wire
// IDs whose status changed, each once, and the `EXECUTION`
// operations that changed the plugins' slot. Only collected with
// plugins.
let mut change_set = ChangeSet::default();
if !output.updated_operations.is_empty() {
let changed_ids = crate::client::merge_operations_into_log(
&self.inner.engine.checkpoint_log,
&output.updated_operations,
);
self.collect_changes(&mut change_set, changed_ids, &output.updated_operations);
merged.extend(
output
.updated_operations
.iter()
.map(|op| op.id().to_owned()),
);
}
// If the checkpoint response is paginated, fetch remaining pages
// via get_state and merge them into the checkpoint log. The token
// lock stays held through this fetch: releasing it first would let
// a concurrent branch checkpoint and rotate the token, leaving this
// get_state call with a stale token. A tokenless response to an
// `EXECUTION` update left the spent token in place, so its pages
// are not fetched, as in the JS and Python SDKs.
if output.next_marker.is_some() && !tokenless {
let full_state = match crate::client::get_full_state(
client.as_ref(),
&self.inner.execution_arn,
&token_guard,
)
.await
{
Ok(full_state) => full_state,
Err(err) => {
// The response is merged already, so its changes are
// reported even though the pages failed.
self.queue_changes(change_set);
self.record_write_failure(failure_id, &err);
return Err(WriteError::Failed(err));
}
};
if !full_state.is_empty() {
let changed_ids = crate::client::merge_operations_into_log(
&self.inner.engine.checkpoint_log,
&full_state,
);
self.collect_changes(&mut change_set, changed_ids, &full_state);
merged.extend(full_state.iter().map(|op| op.id().to_owned()));
}
}
// Still under the token lock, so change sets queue in response
// order. No hook runs here: a drain point delivers them later.
self.queue_changes(change_set);
// A `wait_for_condition` RETRY the response did not carry: the log
// takes the status the service recorded. This runs under the token
// lock, so a later response, which carries a newer status, merges
// after it.
for (wire_id, payload) in &retried {
if !merged.iter().any(|id| id == wire_id) {
mark_retry_pending(
&self.inner.engine.checkpoint_log,
wire_id,
payload.as_deref(),
);
}
}
// The token is rotated and the response merged: release the lock,
// then wake every operation the response carries. The write's
// checkpoint permit is still held, so each woken operation holds
// its own permit before this write's permit is released.
drop(token_guard);
self.inner.coordinator.wake_operations(&merged);
Ok(output)
}
/// Drops every queued checkpoint write without resolving its caller:
/// the entries of the [`DirectWriteQueue`] and the coalescer's open
/// batch. Their permits are released after the queue locks are
/// released. The withdrawal of the checkpoint token and a failed write
/// call it (see [`InvocationCoordinator::withdraw`] and
/// [`InvocationCoordinator::fail_write`]).
fn abandon_queued_writes(&self) {
let direct = self.inner.direct.abandon_queued();
let batch = self
.inner
.coalescer
.as_ref()
.map(|coalescer| coalescer.abandon_pending());
drop(direct);
drop(batch);
}
/// Adds the changes of one merge to `change_set`: the wire IDs in
/// `changed_ids` not listed yet, and each `EXECUTION` operation of
/// `operations`, which replaces the plugins' slot and is a change when
/// the slot held no operation or one with another status. Does nothing
/// without plugins.
fn collect_changes(
&self,
change_set: &mut ChangeSet,
changed_ids: Vec<String>,
operations: &[aws_sdk_lambda::types::Operation],
) {
let Some(plugins) = self.plugins() else {
return;
};
for id in changed_ids {
if !change_set.ids.contains(&id) {
change_set.ids.push(id);
}
}
for info in operations
.iter()
.filter_map(crate::client::execution_info_from_operation)
{
if plugins.replace_execution(info.clone()) {
change_set.executions.retain(|held| held.id() != info.id());
change_set.executions.push(info);
}
}
}
/// Queues `change_set` for `on_operation_change` when it lists anything.
/// Each listed operation's info is built from its borrowed record, so
/// no record is cloned and the full log is not projected.
fn queue_changes(&self, change_set: ChangeSet) {
let Some(plugins) = self.plugins() else {
return;
};
let log = &self.inner.engine.checkpoint_log;
let mut updated: Vec<crate::plugin::OperationInfo> = change_set
.ids
.iter()
.filter_map(|id| {
log.with_record(id, |record| {
crate::plugin::OperationInfo::from_record(id, record)
})
})
.collect();
updated.extend(change_set.executions);
if !updated.is_empty() {
plugins.push_operation_change(updated);
}
}
/// Returns the parent wire ID if this is a child context.
pub(crate) fn parent_wire_id(&self) -> Option<&str> {
self.inner.parent_wire_id.as_deref()
}
/// Returns the attempt number for the given operation from the checkpoint
/// log (0 if no prior attempt recorded).
pub(crate) fn get_attempt(&self, op_id: &OperationId) -> u32 {
// On re-invocation after a RETRY, the backend returns the operation
// with step_details.attempt set to the last completed attempt number.
self.checkpoint_status_view(op_id.positional())
.map_or(0, |view| view.attempt)
}
/// Returns the execution ARN identifying this durable execution.
///
/// The ARN uniquely identifies the execution across invocations and is
/// stable for the lifetime of the orchestration.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// tracing::info!(arn = ctx.execution_arn(), "starting execution");
/// Ok(())
/// }
/// ```
pub fn execution_arn(&self) -> &str {
&self.inner.execution_arn
}
/// Returns a reference to the Lambda invocation context.
///
/// Provides access to the request ID, deadline, function ARN, and other
/// Lambda metadata for the current invocation.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// let request_id = &ctx.lambda_context().request_id;
/// tracing::info!(%request_id, "invoked");
/// Ok(())
/// }
/// ```
pub fn lambda_context(&self) -> &lambda_runtime::Context {
&self.inner.lambda_context
}
/// Returns whether the current invocation is in replay mode.
///
/// During replay, previously-checkpointed operation results are returned
/// without re-execution. Replay mode lasts while the next operation to
/// be claimed was already claimed by a prior invocation, including a
/// started-but-unfinished child context, map, or parallel parent that
/// the resumed invocation re-enters to replay its nested operations.
/// User code can use this flag to suppress duplicate side effects
/// (e.g., logging) during replay.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// if !ctx.is_replaying() {
/// tracing::info!("first execution, not replay");
/// }
/// Ok(())
/// }
/// ```
pub fn is_replaying(&self) -> bool {
self.inner.engine.is_replaying()
}
/// Creates a durable step operation.
///
/// The step body receives a [`StepContext`] and returns a result. The
/// result is checkpointed on success; on failure the retry strategy
/// determines whether to retry.
///
/// The step body is `FnOnce + Clone`. The SDK keeps the original closure
/// and calls a fresh clone of it for each attempt. Each capture follows
/// its type's `Clone` implementation: a cloned `Vec` or `String` has its
/// own contents, and a cloned `Arc` shares its allocation.
///
/// The operation ID is claimed synchronously at this call site.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let result = ctx.step(|_step_ctx| async {
/// Ok("computed value".to_owned())
/// }).name("compute")
/// .await?;
/// Ok(result)
/// }
/// ```
pub fn step<O, F, Fut>(&self, f: F) -> StepBuilder<O, F, Fut>
where
F: FnOnce(StepContext) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
O: Send + 'static,
{
let op_id = self.claim_operation_id("step");
// The closure is stored unerased; the single erasure point is the
// builder's `.future()` / `.await`, producing one DurableFuture box.
StepBuilder::new_internal(self.clone(), op_id, f)
}
/// Creates a durable wait (timer) operation.
///
/// The operation waits for the specified duration. The invocation
/// suspends during the wait only when no other SDK work can make
/// progress, and a wait that ends while other SDK work runs continues
/// in the same invocation. The wait is checkpointed, so replay does not
/// re-wait.
///
/// The duration is rounded up to whole seconds, so the wait never ends
/// early. A duration under one second, including [`Duration::ZERO`],
/// waits one second, because the service rejects a zero-second wait.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use std::time::Duration;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// ctx.wait(Duration::from_secs(60))
/// .name("cooldown")
/// .await?;
/// Ok(())
/// }
/// ```
pub fn wait(&self, duration: Duration) -> WaitBuilder {
// Round up to whole seconds. The service rejects `WaitSeconds: 0`,
// so the clamp raises a sub-second duration to one second.
#[expect(clippy::cast_possible_truncation)]
// reason: the clamp bounds the value to `1..=i32::MAX` before the cast to i32
let secs = (duration.as_secs_f64().ceil() as i64).clamp(1, i64::from(i32::MAX)) as i32;
let op_id = self.claim_operation_id("wait");
WaitBuilder::new_internal(self.clone(), op_id, secs)
}
/// Creates a durable invoke operation to call another durable function.
///
/// The output type `O` is the only type parameter: name it with
/// `ctx.invoke::<Receipt>(...)`, or let a typed binding or the
/// function's return type set it. The input needs only
/// `Serialize + Send + 'static`.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize)]
/// struct ChargeInput { amount: u64 }
///
/// #[derive(Serialize, Deserialize)]
/// struct Receipt { id: String }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let receipt = ctx.invoke::<Receipt>("payment-fn", ChargeInput { amount: 100 })
/// .name("charge")
/// .await?;
/// Ok(receipt.id)
/// }
/// ```
///
/// The returned builder's input type is opaque and borrows nothing, so a
/// builder stored in a binding works after the context it came from is
/// moved or dropped. The opaque type still names the `&self` lifetime,
/// so a function that takes the context by value cannot return the
/// un-awaited builder:
///
/// ```compile_fail,E0597
/// use aws_durable_execution_sdk as durable;
/// use durable::builders::InvokeBuilder;
///
/// fn charge(ctx: durable::DurableContext) -> InvokeBuilder<u32, impl serde::Serialize + Send + 'static> {
/// ctx.invoke::<u32>("payment-fn", 100_u32)
/// }
/// ```
///
/// Such a function returns `.future()` instead:
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// fn charge(ctx: durable::DurableContext) -> durable::DurableFuture<u32> {
/// ctx.invoke::<u32>("payment-fn", 100_u32).future()
/// }
/// ```
pub fn invoke<O>(
&self,
function_id: impl Into<String>,
input: impl Serialize + Send + 'static,
) -> InvokeBuilder<O, impl Serialize + Send + 'static>
where
O: Send + 'static,
{
let op_id = self.claim_operation_id("invoke");
// The input is carried TYPED into the builder: the payload serdes
// receives the owned value directly at execution time (a write-only
// transfer), so no intermediate representation is constructed here.
InvokeBuilder::new_internal(self.clone(), op_id, function_id.into(), input)
}
/// Creates a child context for fan-out / sub-orchestration.
///
/// The child closure receives its own [`DurableContext`] with an
/// independent operation-ID namespace. Use `.spawn()` for eager
/// (background) execution.
///
/// The body should run at least one durable operation. The child's
/// result is saved, so a replay returns it without running the body,
/// with three exceptions. A body that returns an error is not retried,
/// as a step is. A result over 256 KiB makes the body run again on
/// every replay, to rebuild the result; its record holds the payload of
/// [`ChildBuilder::summary`] instead. A context that
/// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth)
/// preserves also runs its body again on every replay. So put plain
/// computation in a step.
///
/// To change the error a child returns, call
/// [`map_err`](Result::map_err) on the awaited result.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let result = ctx.run_in_child_context(|child_ctx| async move {
/// let v = child_ctx.step(|_| async { Ok(42) }).await?;
/// Ok(v.to_string())
/// }).name("branch")
/// .await?;
/// Ok(result)
/// }
/// ```
pub fn run_in_child_context<O, F, Fut>(&self, f: F) -> ChildBuilder<O, F, Fut>
where
F: FnOnce(DurableContext) -> Fut + Send + 'static,
Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
O: Send + 'static,
{
let op_id = self.claim_operation_id("run_in_child_context");
// The closure is stored unerased; the child execution converts the
// BoxError into the internal child-error carrier at the boundary,
// and the single erasure point is the builder's `.future()` /
// `.await`, producing one DurableFuture box.
ChildBuilder::new_internal(self.clone(), op_id, f)
}
/// Runs a closure against a child context and retries the closure's
/// **overall** outcome as a unit.
///
/// Where a step's retry strategy re-runs one operation, `with_retry`
/// re-runs a whole block: if any operation in the block fails (or the
/// closure returns an error), the retry strategy decides whether to run
/// the entire block again. Each attempt receives a **fresh child
/// operation namespace**, so operations recorded by a failed attempt
/// are never replayed into the next one: every operation in the block
/// re-runs on retry. The block waits for the delay between attempts
/// (the backend owns the timer, exactly as step retries do). The
/// invocation suspends during that wait only when no other SDK work can
/// make progress, and a wait that ends while other SDK work runs
/// continues in the same invocation. The retry progress is derived from
/// checkpointed results, so it survives suspension and replays
/// deterministically.
///
/// The closure is `Fn` rather than `FnOnce` because the SDK calls it
/// once per attempt. It receives the attempt's context and the 1-based
/// attempt number, which is `N` in the attempt's name `attempt-N`. The
/// number is metadata for names and logs: a resumed attempt receives
/// the same number, and operation IDs do not depend on it. Configure
/// the policy with
/// [`retry_strategy`](WithRetryBuilder::retry_strategy) or
/// [`retry_strategy_config`](WithRetryBuilder::retry_strategy_config);
/// without one, the step default applies (6 total attempts with
/// exponential backoff). When retries exhaust, a block with its own
/// record fails with a [`ChildContextError`](crate::ChildContextError)
/// of kind `ChildFailed` whose source is the last attempt's
/// [`OperationError`](crate::OperationError).
/// [`without_child_context`](WithRetryBuilder::without_child_context)
/// runs the attempts in this context, without a record for the block;
/// on exhaustion such a block returns the last attempt's
/// `OperationError` unchanged, a `ChildContextError` of kind
/// `ChildFailed` whose source is the attempt body's error.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use aws_durable_execution_sdk::RetryDecision;
/// use std::time::Duration;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// // If either step fails, BOTH re-run on the next attempt.
/// let result = ctx.with_retry(|child, attempt| async move {
/// tracing::info!(attempt, "reserving and booking");
/// let quote = child
/// .step(|_| async { Ok("quote-17".to_owned()) })
/// .name("reserve-quote")
/// .await?;
/// let receipt = child
/// .step(move |_| async move { Ok(format!("booked:{quote}")) })
/// .name("book")
/// .await?;
/// Ok(receipt)
/// })
/// .name("reserve-and-book")
/// .retry_strategy(|_err, attempt| {
/// if attempt >= 3 {
/// RetryDecision::Stop
/// } else {
/// RetryDecision::retry(Duration::from_secs(5))
/// }
/// })
/// .await?;
/// Ok(result)
/// }
/// ```
pub fn with_retry<O, F, Fut>(&self, f: F) -> WithRetryBuilder<O, F, Fut>
where
F: Fn(DurableContext, u32) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
O: Send + 'static,
{
// The block claims its operation ID when the builder becomes its
// future, because only then is its mode known.
WithRetryBuilder::new_internal(self.clone(), f)
}
/// Creates a wait-for-condition operation that polls until a predicate
/// is satisfied.
///
/// The check function is called repeatedly with the current state, and
/// the configured strategy decides after each check whether to
/// complete, keep polling, or fail. Set one with
/// [`wait_strategy`](crate::builders::WaitForConditionBuilder::wait_strategy)
/// (a bounded [`WaitStrategy`](crate::builders::wait_for_condition::WaitStrategy)
/// configuration) or
/// [`wait_strategy_fn`](crate::builders::WaitForConditionBuilder::wait_strategy_fn)
/// (a custom closure). A strategy is required: the returned builder
/// cannot be awaited, converted with `.future()` or started with
/// `.spawn()` until one of the two setters has run.
///
/// The first check receives the initial state after a round trip
/// through the configured serdes, so it sees the same shape as a check
/// that resumes from a recorded state. The round trip runs before the
/// operation's first checkpoint: a serdes error marked with
/// [`RetryableSerdesError`](crate::serdes::RetryableSerdesError) ends
/// the invocation, and any other serdes error returns
/// `WaitForCondition(SerializationFailed)` without calling the check.
///
/// A check error fails the operation without a retry. It records the
/// type of a [`TypedError`](crate::TypedError) in its source chain, or
/// `Error` when there is none. The error kind follows the recorded
/// type, live and on replay: `WaitForCondition.MaxChecksExceeded` is
/// reported as `MaxChecksExceeded`, `SerializationError` as
/// `SerializationFailed`, and every other type as `CheckFailed`.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use durable::builders::wait_for_condition::WaitDecision;
/// use serde::{Deserialize, Serialize};
/// use std::time::Duration;
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct PollState { count: u32 }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// ctx.wait_for_condition(
/// |_step_ctx, state: PollState| async move {
/// Ok(PollState { count: state.count + 1 })
/// },
/// PollState { count: 0 },
/// ).name("poll-ready")
/// .wait_strategy_fn(|state: PollState, _attempt| {
/// if state.count >= 3 {
/// WaitDecision::complete()
/// } else {
/// WaitDecision::continue_with(Duration::from_secs(1))
/// }
/// })
/// .await?;
/// Ok(())
/// }
/// ```
pub fn wait_for_condition<S, F, Fut>(
&self,
check: F,
initial_state: S,
) -> WaitForConditionBuilder<S, F, Fut>
where
F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
S: Clone + Send + Sync + 'static,
{
let op_id = self.claim_operation_id("wait_for_condition");
WaitForConditionBuilder::new_internal(self.clone(), op_id, initial_state, check)
}
/// Creates a callback token for external completion.
///
/// The returned [`Callback`](crate::builders::callback::Callback) provides an ID that
/// external systems use to complete the operation, plus a
/// [`DurableFuture`] that resolves when the callback arrives.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Approval { approved: bool }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<bool, durable::BoxError> {
/// let cb = ctx.create_callback::<Approval>()
/// .name("approval")
/// .await?;
/// // Send cb.id() to an external system...
/// let approval = cb.result().await?;
/// Ok(approval.approved)
/// }
/// ```
pub fn create_callback<O>(&self) -> CreateCallbackBuilder<O>
where
O: Send + 'static,
{
let op_id = self.claim_operation_id("create_callback");
CreateCallbackBuilder::new_internal(self.clone(), op_id)
}
/// Creates a wait-for-callback operation that registers and waits for
/// an external callback in one step.
///
/// The submitter closure receives the callback ID as an owned
/// [`String`] and is responsible for delivering it to the external
/// system that will complete it.
///
/// The submitter is `FnOnce + Clone`. The SDK keeps the original closure
/// and calls a fresh clone of it for each attempt. Each capture follows
/// its type's `Clone` implementation: a cloned `Vec` or `String` has its
/// own contents, and a cloned `Arc` shares its allocation.
///
/// The output type `O` is the only type parameter: name it with
/// `ctx.wait_for_callback::<Approval>(..)`, or let a typed binding or the
/// function's return type set it. Every closure this method accepts
/// implements [`Submitter`](crate::builders::Submitter).
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct Approval { ok: bool }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<bool, durable::BoxError> {
/// let approval = ctx.wait_for_callback::<Approval>(
/// |_step_ctx, callback_id| async move {
/// // e.g., send callback_id to an approval queue
/// Ok(())
/// }
/// ).name("await-approval")
/// .await?;
/// Ok(approval.ok)
/// }
/// ```
///
/// The returned builder's submitter type is opaque and borrows nothing,
/// so a builder stored in a binding works after the context it came from
/// is moved or dropped. The opaque type still names the `&self`
/// lifetime, so a function that takes the context by value cannot return
/// the un-awaited builder:
///
/// ```compile_fail,E0597
/// use aws_durable_execution_sdk as durable;
/// use durable::builders::{Submitter, WaitForCallbackBuilder};
///
/// fn approval(ctx: durable::DurableContext) -> WaitForCallbackBuilder<String, impl Submitter> {
/// ctx.wait_for_callback::<String>(|_step_ctx, _callback_id| async { Ok(()) })
/// }
/// ```
///
/// Such a function returns `.future()` instead:
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// fn approval(ctx: durable::DurableContext) -> durable::DurableFuture<String> {
/// ctx.wait_for_callback::<String>(|_step_ctx, _callback_id| async { Ok(()) })
/// .future()
/// }
/// ```
pub fn wait_for_callback<O>(
&self,
submitter: impl Submitter,
) -> WaitForCallbackBuilder<O, impl Submitter>
where
O: Send + 'static,
{
let op_id = self.claim_operation_id("wait_for_callback");
WaitForCallbackBuilder::new_internal(self.clone(), op_id, submitter)
}
/// Creates a map operation that applies a function to each item in a
/// collection, with configurable concurrency.
///
/// Each item gets its own child context with an independent operation
/// namespace.
///
/// The closure should run at least one durable operation. Each item's
/// result is saved, so a replay returns it without running the
/// closure, with three exceptions. An item that returns an error is not
/// retried, as a step is. An item whose result is over 256 KiB runs
/// again on every replay, to rebuild the result. An item context that
/// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth)
/// preserves also runs again on every replay. So put plain computation
/// in a step.
///
/// When the whole batch result is over 256 KiB, the map records a
/// summary of its outcome instead. With
/// [`NestingMode::Normal`](crate::builders::map_parallel::NestingMode::Normal) replay reads each
/// item from its own record. A
/// [`NestingMode::Flat`](crate::builders::map_parallel::NestingMode::Flat) item has no record of
/// its own, so replay runs the items again to rebuild the result, even
/// when each item's result is small. [`MapBuilder::summary`] adds the
/// caller's own summary to that record.
///
/// The map claims one operation ID from this context when this method
/// is called. Its items are numbered inside the map: item `i` has the
/// ID of item `i` in the map's own namespace, whatever the item count,
/// the concurrency or the order in which items finish. So this
/// context's next operation gets this context's next ID.
///
/// A panic in an item propagates to the caller with its original
/// payload, and the SDK records nothing for it.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct Image { url: String }
///
/// #[derive(Serialize, Deserialize)]
/// struct Thumbnail { url: String }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// let images = vec![Image { url: "a.png".into() }, Image { url: "b.png".into() }];
/// let _thumbnails = ctx.map(images, |child_ctx, _img, _idx| async move {
/// let thumb = child_ctx
/// .step(|_| async { Ok(Thumbnail { url: "thumb.png".into() }) })
/// .await?;
/// Ok(thumb)
/// }).name("resize")
/// .max_concurrency(4)
/// .await?;
/// Ok(())
/// }
/// ```
///
/// The closure gets one item. JS passes the whole input array as a
/// fourth argument. To read other inputs, clone an `Arc<[I]>` of the
/// inputs into the closure:
///
/// ```no_run
/// use std::sync::Arc;
///
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// event: Vec<u32>,
/// ctx: durable::DurableContext,
/// ) -> Result<Vec<u32>, durable::BoxError> {
/// let all: Arc<[u32]> = event.clone().into();
/// let shares = ctx
/// .map(event, move |child, item, _idx| {
/// let all = Arc::clone(&all);
/// async move {
/// let share = child
/// .step(move |_| async move {
/// let total: u32 = all.iter().sum();
/// Ok(item * 100 / total.max(1))
/// })
/// .name("share")
/// .await?;
/// Ok(share)
/// }
/// })
/// .name("shares")
/// .await?;
/// Ok(shares)
/// }
/// ```
pub fn map<Items, I, O, F, Fut>(&self, items: Items, f: F) -> MapBuilder<I, O, F, Fut>
where
Items: IntoIterator<Item = I>,
F: Fn(DurableContext, I, usize) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
I: Send + 'static,
O: Send + 'static,
{
let op_id = self.claim_operation_id("map");
// The closure is stored unerased; at execution it is shared as
// `Arc<F>` and every item produces a concrete future, so the
// internal JoinSet holds unboxed futures. The single erasure point
// is the builder's `.future()` / `.await`, producing one
// DurableFuture box.
let items: Vec<I> = items.into_iter().collect();
MapBuilder::new_internal(self.clone(), op_id, items, f)
}
/// Creates a parallel operation that executes named branches
/// concurrently.
///
/// The parallel claims one operation ID from this context when this
/// method is called. Its branches are numbered inside the parallel:
/// branch `i` has the ID of item `i` in the parallel's own namespace,
/// as a [`map`](Self::map) item does.
///
/// A panic in a branch propagates to the caller with its original
/// payload, and the SDK records nothing for it.
///
/// Each branch should run at least one durable operation. Each branch's
/// result is saved, so a replay returns it without running the branch,
/// with three exceptions. A branch that returns an error is not
/// retried, as a step is. A branch whose result is over 256 KiB runs
/// again on every replay, to rebuild the result. A branch context that
/// [`plugin_child_operations_depth`](crate::OptionsBuilder::plugin_child_operations_depth)
/// preserves also runs again on every replay. So put plain computation
/// in a step.
///
/// When the whole batch result is over 256 KiB, the parallel records a
/// summary of its outcome instead. With
/// [`NestingMode::Normal`](crate::builders::map_parallel::NestingMode::Normal) replay reads each
/// branch from its own record. A
/// [`NestingMode::Flat`](crate::builders::map_parallel::NestingMode::Flat) branch has no record of
/// its own, so replay runs the branches again to rebuild the result, even
/// when each branch's result is small. [`ParallelBuilder::summary`] adds the
/// caller's own summary to that record.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// let branches = vec![
/// durable::Branch::new("a", |child_ctx: durable::DurableContext| async move {
/// let v = child_ctx.step(|_| async { Ok(1) }).await?;
/// Ok(v)
/// }),
/// ];
/// let _results: Vec<i32> = ctx.parallel(branches)
/// .name("fan-out")
/// .await?;
/// Ok(())
/// }
/// ```
pub fn parallel<Branches, O>(&self, branches: Branches) -> ParallelBuilder<O>
where
Branches: IntoIterator<Item = Branch<O>>,
O: Send + 'static,
{
let op_id = self.claim_operation_id("parallel");
let branch_tuples: Vec<_> = branches.into_iter().map(Branch::into_parts).collect();
ParallelBuilder::new_internal(self.clone(), op_id, branch_tuples)
}
/// Creates a parallel operation over branches whose results have
/// different types.
///
/// Each branch of `branches` returns its own type, and the
/// [`BranchHandle`](crate::BranchHandle) that
/// [`BranchSet::add`](crate::BranchSet::add) or
/// [`BranchSet::add_with_serdes`](crate::BranchSet::add_with_serdes)
/// returned gives that type back. The operation records the same
/// history as [`parallel`](Self::parallel) over branches with the same
/// names and outcomes: one parallel parent and one child context per
/// branch. Only the encoded branch values differ, because each branch
/// encodes its value with its own serdes.
///
/// `.await` returns the [`CompletionReason`](crate::builders::map_parallel::CompletionReason)
/// of the batch. It returns an error in exactly the cases where
/// `parallel(...).await` does, with the same error. When it returns,
/// each handle whose branch settled holds the branch's value or error.
/// A handle whose branch never started, or still ran when the batch
/// completed, holds no result. This holds whatever the parallel's own
/// outcome, including an error from a completion rule that fails the
/// batch. When the batch does not complete, for example because a
/// checkpoint write fails, no handle holds a result. With
/// [`spawn`](crate::builders::ParallelMixedBuilder::spawn), the handles
/// are filled when the returned future is awaited.
///
/// The operation ID is claimed when this method is called, as
/// [`parallel`](Self::parallel) claims it, and branch `i` has the ID of
/// item `i` in the batch's own namespace, as in `parallel`.
///
/// # Which form to use
///
/// - [`parallel`](Self::parallel), when every branch returns the same
/// type.
/// - [`parallel`](Self::parallel) over an enum, when the results are
/// cases of one type that the handler processes together. Use serde's
/// default (externally tagged) enum representation.
/// `#[serde(untagged)]` can decode a result into the wrong variant
/// when two variants accept the same JSON.
/// - `parallel_mixed`, when each branch returns its own type.
///
/// A panic in a branch propagates to the caller with its original
/// payload, the SDK records nothing for it, and no handle receives a
/// result.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use durable::serdes::SerdesContext;
/// use durable::{BoxError, BranchSet, Serdes};
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Reservation {
/// sku: String,
/// }
///
/// struct PaymentAuth {
/// code: u32,
/// }
///
/// // A serdes for `PaymentAuth` only.
/// struct PaymentSerdes;
///
/// impl Serdes<PaymentAuth> for PaymentSerdes {
/// async fn serialize(&self, value: PaymentAuth, _ctx: SerdesContext) -> Result<String, BoxError> {
/// Ok(value.code.to_string())
/// }
/// async fn deserialize(&self, wire: String, _ctx: SerdesContext) -> Result<PaymentAuth, BoxError> {
/// Ok(PaymentAuth { code: wire.parse()? })
/// }
/// }
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, BoxError> {
/// let mut branches = BranchSet::new();
/// let inventory = branches.add("inventory", |_ctx| async {
/// Ok(Reservation { sku: "sku-1".to_owned() })
/// });
/// let payment = branches.add_with_serdes("payment", PaymentSerdes, |_ctx| async {
/// Ok(PaymentAuth { code: 7 })
/// });
///
/// ctx.parallel_mixed(branches)
/// .name("process-order")
/// .max_concurrency(2)
/// .await?;
///
/// let inventory: Reservation = inventory.into_result()?;
/// let payment: PaymentAuth = payment.into_result()?;
/// Ok(format!("{}: {}", payment.code, inventory.sku))
/// }
/// ```
pub fn parallel_mixed(&self, branches: crate::BranchSet) -> ParallelMixedBuilder {
let op_id = self.claim_operation_id("parallel_mixed");
ParallelMixedBuilder::new_internal(self.clone(), op_id, branches)
}
/// Joins all futures, failing fast on the first error.
///
/// Returns `Vec<O>` on success, or the first `OperationError`
/// encountered.
///
/// The returned value has passed through the combinator's JSON
/// encoding: the SDK decodes the payload it recorded and returns that.
/// So the first run returns the value a replay returns, and data that
/// the value's serde form omits, such as a `#[serde(skip)]` field, is
/// absent on both paths.
///
/// When the combinator resolves, it cancels every input that is still
/// running. A cancelled input stops at its next `.await`.
///
/// # Oversized results
///
/// A combined result larger than 256 KiB is not stored in the
/// combinator's record. Replay then drives the inputs again. An input
/// whose own terminal record is inline replays without running again. An
/// input whose own terminal record has `ReplayChildren` runs its body
/// again to rebuild its value, and its recorded descendants replay.
///
/// # Empty input
///
/// Called with no futures, resolves to `Ok` with an empty `Vec`,
/// matching `futures::future::try_join_all`.
///
/// A panic in an input propagates to the caller with its original
/// payload, and the SDK records nothing for it.
///
/// # Operation ID
///
/// This method collects `futures` and claims no operation ID. An
/// operation that the iterator creates claims its ID during this
/// collection, so the inputs take their IDs before the combinator. The
/// combinator claims its own ID when it is first awaited or polled, or
/// when it is spawned, on this context. A combinator that is dropped
/// before that claims no ID and records nothing. An input that is itself
/// a combinator must already have claimed its ID: start it with
/// `.spawn()` and pass the returned handle. A still-unclaimed combinator
/// input fails the execution with a context usage error. Starting the
/// combinator inside the body of another context (a child context, a
/// `with_retry` attempt, a map item or a parallel branch) fails the
/// execution with a context usage error too.
///
/// # Start order
///
/// When the combinator runs, it begins the start phase of each
/// `.future()` input, in input order, before its own start step, as a
/// JS combinator awaits inputs that already run. An input whose JS form
/// queues its `START` at the call (a step, a wait, a child context,
/// `with_retry`, a map, a parallel or a `wait_for_callback`) queues it
/// then, so its first checkpoint comes before the combinator's, and a
/// start hook it fires when it queues `START` runs before the
/// combinator's. A start hook that waits for the `START` response (a
/// wait, a step under `AtMostOncePerRetry`) keeps that timing. A lazy
/// invoke or `wait_for_condition` is polled once, in input order,
/// before the combinator's start step, but the combinator does not wait
/// for its `START`. The combinator then queues its own `START`, fires
/// its start hook, and runs the inputs without waiting for the `START`
/// response; its `SUCCEED` or `FAIL` waits for it. On a `STARTED`,
/// `PENDING` or `READY` record it fires its replay start hook after the
/// inputs' start phases begin. A replay of a final record starts no
/// `.future()` input. A handle that `.spawn()` returned already runs
/// independently, and the combinator does not start it again.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// let a = ctx.step(|_| async { Ok(1) }).future();
/// let b = ctx.step(|_| async { Ok(2) }).future();
/// let _results: Vec<i32> = ctx.try_join_all([a, b])
/// .name("gather")
/// .await?;
/// Ok(())
/// }
/// ```
pub fn try_join_all<O>(
&self,
futures: impl IntoIterator<Item = DurableFuture<O>>,
) -> TryJoinAllBuilder<O>
where
O: Serialize + DeserializeOwned + Send + 'static,
{
TryJoinAllBuilder::new_internal(self.clone(), futures.into_iter().collect())
}
/// Joins all futures, collecting every outcome as a `Result`.
///
/// Never fails fast: all futures run to completion regardless of
/// individual errors. The output holds one `Result<O, OperationError>`
/// per input, in input order.
///
/// # Outer and inner errors
///
/// Awaiting returns `Result<Vec<Result<O, OperationError>>, OperationError>`,
/// and the two levels report different failures:
///
/// 1. The outer `Err` means the combinator itself failed, for example
/// replay nondeterminism. A failed checkpoint write never reaches
/// it: the write fails the invocation, and the combinator does not
/// resolve.
/// 2. An input that returns `Err` appears only as that input's inner
/// `Err`. The outer result is then `Ok`.
/// 3. A panicking input ends the invocation, as a panic does everywhere
/// else in the SDK. The SDK resumes the original panic payload. The
/// combinator writes no record and returns no result.
/// 4. Nothing cancels an input that `join_all` awaits. A combinator stops
/// an input only by dropping it, and `join_all` drops no input before
/// it settles.
///
/// An inner `Err` is a
/// [`OperationErrorKind::ChildContext`](crate::OperationErrorKind::ChildContext)
/// error of kind
/// [`ChildContextErrorKind::ChildFailed`](crate::ChildContextErrorKind::ChildFailed),
/// whose `wire()` carries the input's recorded failure (`error_type`,
/// message, `error_data`), on the first run and on replay. Match on the
/// `err.wire()` fields, not on the kind of the input that failed.
///
/// # Oversized results
///
/// A combined result larger than 256 KiB is not stored in the
/// combinator's record. Replay then drives the inputs again. An input
/// whose own terminal record is inline replays without running again. An
/// input whose own terminal record has `ReplayChildren` runs its body
/// again to rebuild its value, and its recorded descendants replay.
///
/// # Empty input
///
/// Called with no futures, resolves to `Ok` with an empty `Vec`,
/// matching `futures::future::join_all`.
///
/// # Operation ID
///
/// This method collects `futures` and claims no operation ID. An
/// operation that the iterator creates claims its ID during this
/// collection, so the inputs take their IDs before the combinator. The
/// combinator claims its own ID when it is first awaited or polled, or
/// when it is spawned, on this context. A combinator that is dropped
/// before that claims no ID and records nothing. An input that is itself
/// a combinator must already have claimed its ID: start it with
/// `.spawn()` and pass the returned handle. A still-unclaimed combinator
/// input fails the execution with a context usage error. Starting the
/// combinator inside the body of another context (a child context, a
/// `with_retry` attempt, a map item or a parallel branch) fails the
/// execution with a context usage error too.
///
/// # Start order
///
/// When the combinator runs, it begins the start phase of each
/// `.future()` input, in input order, before its own start step, as a
/// JS combinator awaits inputs that already run. An input whose JS form
/// queues its `START` at the call (a step, a wait, a child context,
/// `with_retry`, a map, a parallel or a `wait_for_callback`) queues it
/// then, so its first checkpoint comes before the combinator's, and a
/// start hook it fires when it queues `START` runs before the
/// combinator's. A start hook that waits for the `START` response (a
/// wait, a step under `AtMostOncePerRetry`) keeps that timing. A lazy
/// invoke or `wait_for_condition` is polled once, in input order,
/// before the combinator's start step, but the combinator does not wait
/// for its `START`. The combinator then queues its own `START`, fires
/// its start hook, and runs the inputs without waiting for the `START`
/// response; its `SUCCEED` or `FAIL` waits for it. On a `STARTED`,
/// `PENDING` or `READY` record it fires its replay start hook after the
/// inputs' start phases begin. A replay of a final record starts no
/// `.future()` input. A handle that `.spawn()` returned already runs
/// independently, and the combinator does not start it again.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
/// let a = ctx.step(|_| async { Ok(1) }).future();
/// let b = ctx.step(|_| async { Ok(2) }).future();
/// let outcomes: Vec<Result<i32, durable::OperationError>> = ctx
/// .join_all([a, b])
/// .name("collect")
/// .await?;
/// let succeeded = outcomes.iter().filter(|outcome| outcome.is_ok()).count();
/// assert_eq!(succeeded, 2);
/// Ok(())
/// }
/// ```
pub fn join_all<O>(
&self,
futures: impl IntoIterator<Item = DurableFuture<O>>,
) -> JoinAllBuilder<O>
where
O: Serialize + DeserializeOwned + Send + 'static,
{
JoinAllBuilder::new_internal(self.clone(), futures.into_iter().collect())
}
/// Returns the first successful result.
///
/// When the combinator resolves, it cancels every input that is still
/// running. A cancelled input stops at its next `.await`.
///
/// The returned value has passed through the combinator's JSON
/// encoding: the SDK decodes the payload it recorded and returns that.
/// So the first run returns the value a replay returns, and data that
/// the value's serde form omits, such as a `#[serde(skip)]` field, is
/// absent on both paths.
///
/// If every future fails, the operation fails with
/// [`CombinatorErrorKind::AllFailed`](crate::CombinatorErrorKind::AllFailed)
/// preserving each future's error (see [`CombinatorError::failures`](crate::CombinatorError::failures)).
///
/// # Oversized results
///
/// A winning value larger than 256 KiB is not stored in the
/// combinator's record. The record stores the winner's input index
/// instead. Replay then drives only the recorded winner again, and drops
/// every other input without running it. The winner replays without
/// running again when its own terminal record is inline. A winner whose
/// own terminal record has `ReplayChildren` runs its body again to
/// rebuild its value, and its recorded descendants replay.
///
/// # Empty input
///
/// Called with no futures, fails with
/// [`CombinatorErrorKind::EmptyInput`](crate::CombinatorErrorKind::EmptyInput):
/// there is no future that could succeed.
///
/// A panic in an input propagates to the caller with its original
/// payload, and the SDK records nothing for it.
///
/// # Operation ID
///
/// This method collects `futures` and claims no operation ID. An
/// operation that the iterator creates claims its ID during this
/// collection, so the inputs take their IDs before the combinator. The
/// combinator claims its own ID when it is first awaited or polled, or
/// when it is spawned, on this context. A combinator that is dropped
/// before that claims no ID and records nothing. An input that is itself
/// a combinator must already have claimed its ID: start it with
/// `.spawn()` and pass the returned handle. A still-unclaimed combinator
/// input fails the execution with a context usage error. Starting the
/// combinator inside the body of another context (a child context, a
/// `with_retry` attempt, a map item or a parallel branch) fails the
/// execution with a context usage error too.
///
/// # Start order
///
/// When the combinator runs, it begins the start phase of each
/// `.future()` input, in input order, before its own start step, as a
/// JS combinator awaits inputs that already run. An input whose JS form
/// queues its `START` at the call (a step, a wait, a child context,
/// `with_retry`, a map, a parallel or a `wait_for_callback`) queues it
/// then, so its first checkpoint comes before the combinator's, and a
/// start hook it fires when it queues `START` runs before the
/// combinator's. A start hook that waits for the `START` response (a
/// wait, a step under `AtMostOncePerRetry`) keeps that timing. A lazy
/// invoke or `wait_for_condition` is polled once, in input order,
/// before the combinator's start step, but the combinator does not wait
/// for its `START`. The combinator then queues its own `START`, fires
/// its start hook, and runs the inputs without waiting for the `START`
/// response; its `SUCCEED` or `FAIL` waits for it. On a `STARTED`,
/// `PENDING` or `READY` record it fires its replay start hook after the
/// inputs' start phases begin. A replay of a final record starts no
/// `.future()` input. A handle that `.spawn()` returned already runs
/// independently, and the combinator does not start it again.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let a = ctx.step(|_| async { Ok("fast".to_owned()) }).future();
/// let b = ctx.step(|_| async { Ok("slow".to_owned()) }).future();
/// let winner = ctx.select_ok([a, b])
/// .name("race-ok")
/// .await?;
/// Ok(winner)
/// }
/// ```
pub fn select_ok<O>(
&self,
futures: impl IntoIterator<Item = DurableFuture<O>>,
) -> SelectOkBuilder<O>
where
O: Serialize + DeserializeOwned + Send + 'static,
{
SelectOkBuilder::new_internal(self.clone(), futures.into_iter().collect())
}
/// Returns the first settled result, whether success or failure.
///
/// When the combinator resolves, it cancels every input that is still
/// running. A cancelled input stops at its next `.await`.
///
/// The returned value has passed through the combinator's JSON
/// encoding: the SDK decodes the payload it recorded and returns that.
/// So the first run returns the value a replay returns, and data that
/// the value's serde form omits, such as a `#[serde(skip)]` field, is
/// absent on both paths.
///
/// When the first settled outcome is a failure, the operation fails
/// with
/// [`CombinatorErrorKind::FirstSettledFailed`](crate::CombinatorErrorKind::FirstSettledFailed)
/// carrying the losing future's error as its source; the same variant
/// is produced live and on replay.
///
/// # Oversized results
///
/// A winning value larger than 256 KiB is not stored in the
/// combinator's record. The record stores the winner's input index
/// instead. Replay then drives only the recorded winner again, and drops
/// every other input without running it. The winner replays without
/// running again when its own terminal record is inline. A winner whose
/// own terminal record has `ReplayChildren` runs its body again to
/// rebuild its value, and its recorded descendants replay.
///
/// # Empty input
///
/// Called with no futures, fails with
/// [`CombinatorErrorKind::EmptyInput`](crate::CombinatorErrorKind::EmptyInput):
/// there is no future that could settle.
///
/// A panic in an input propagates to the caller with its original
/// payload, and the SDK records nothing for it.
///
/// # Operation ID
///
/// This method collects `futures` and claims no operation ID. An
/// operation that the iterator creates claims its ID during this
/// collection, so the inputs take their IDs before the combinator. The
/// combinator claims its own ID when it is first awaited or polled, or
/// when it is spawned, on this context. A combinator that is dropped
/// before that claims no ID and records nothing. An input that is itself
/// a combinator must already have claimed its ID: start it with
/// `.spawn()` and pass the returned handle. A still-unclaimed combinator
/// input fails the execution with a context usage error. Starting the
/// combinator inside the body of another context (a child context, a
/// `with_retry` attempt, a map item or a parallel branch) fails the
/// execution with a context usage error too.
///
/// # Start order
///
/// When the combinator runs, it begins the start phase of each
/// `.future()` input, in input order, before its own start step, as a
/// JS combinator awaits inputs that already run. An input whose JS form
/// queues its `START` at the call (a step, a wait, a child context,
/// `with_retry`, a map, a parallel or a `wait_for_callback`) queues it
/// then, so its first checkpoint comes before the combinator's, and a
/// start hook it fires when it queues `START` runs before the
/// combinator's. A start hook that waits for the `START` response (a
/// wait, a step under `AtMostOncePerRetry`) keeps that timing. A lazy
/// invoke or `wait_for_condition` is polled once, in input order,
/// before the combinator's start step, but the combinator does not wait
/// for its `START`. The combinator then queues its own `START`, fires
/// its start hook, and runs the inputs without waiting for the `START`
/// response; its `SUCCEED` or `FAIL` waits for it. On a `STARTED`,
/// `PENDING` or `READY` record it fires its replay start hook after the
/// inputs' start phases begin. A replay of a final record starts no
/// `.future()` input. A handle that `.spawn()` returned already runs
/// independently, and the combinator does not start it again.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let a = ctx.step(|_| async { Ok("first".to_owned()) }).future();
/// let b = ctx.step(|_| async { Ok("second".to_owned()) }).future();
/// let winner = ctx.race([a, b])
/// .name("fastest")
/// .await?;
/// Ok(winner)
/// }
/// ```
pub fn race<O>(&self, futures: impl IntoIterator<Item = DurableFuture<O>>) -> RaceBuilder<O>
where
O: Serialize + DeserializeOwned + Send + 'static,
{
RaceBuilder::new_internal(self.clone(), futures.into_iter().collect())
}
}
/// Context passed to step bodies.
///
/// `StepContext` deliberately does **not** expose any durable operations.
/// This provides compile-time enforcement of the rule that durable
/// operations cannot be nested inside step bodies: attempting to call
/// a durable operation method inside a step body is a type error.
///
/// Use `tracing` macros for logging inside steps: the SDK-created
/// operation span automatically attaches execution context fields.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
/// _event: serde_json::Value,
/// ctx: durable::DurableContext,
/// ) -> Result<String, durable::BoxError> {
/// let result = ctx.step(|step_ctx: durable::StepContext| async move {
/// // step_ctx has no durable operations: type-system enforced
/// tracing::info!("inside step");
/// Ok("done".to_owned())
/// }).await?;
/// Ok(result)
/// }
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct StepContext {
attempt: u32,
_private: (),
}
impl StepContext {
/// Creates a new step context (internal).
pub(crate) fn new(attempt: u32) -> Self {
Self {
attempt,
_private: (),
}
}
/// Returns the current attempt number, starting at 1 for the first
/// attempt.
pub fn attempt(&self) -> u32 {
self.attempt
}
}
/// Canonicalizes an operation type string to the service wire format via
/// [`aws_sdk_lambda::types::OperationType`].
///
/// Both envelope parsers store the wire token (`CHAINED_INVOKE`, the
/// `OperationType::as_str()` form). The SDK's own claimed types and older
/// fixtures use `PascalCase` (`ChainedInvoke`). A plain case-insensitive
/// comparison misses the underscore, so both spellings are converted to
/// `SCREAMING_SNAKE` and round-tripped through `OperationType` before
/// comparison. Unknown types canonicalize to their `SCREAMING_SNAKE` form,
/// which keeps genuine mismatches detectable.
pub(crate) fn canonical_op_type(raw: &str) -> String {
// PascalCase → SCREAMING_SNAKE: insert `_` at lower→upper boundaries,
// then uppercase. Already-wire values (all caps + underscores) pass
// through unchanged because they contain no lower→upper boundary.
let mut screaming = String::with_capacity(raw.len() + 4);
let mut prev_is_lower = false;
for ch in raw.chars() {
if ch.is_ascii_uppercase() && prev_is_lower {
screaming.push('_');
}
prev_is_lower = ch.is_ascii_lowercase();
screaming.push(ch.to_ascii_uppercase());
}
// Round-trip through the SDK enum so every known type lands on the
// exact canonical wire constant (`OperationType::as_str()`).
aws_sdk_lambda::types::OperationType::from(screaming.as_str())
.as_str()
.to_owned()
}
/// Compares a checkpoint record's stored identity against a claimed one.
///
/// Returns `None` when the identities match (or the record carries no
/// operation type), and `Some(expected)`, the stored identity
/// formatted for the mismatch error, when they differ. The comparisons
/// borrow the record, so the match path clones nothing; only the cold
/// mismatch path allocates. This is the shared core behind
/// `DurableContext::validate_replay_identity` and
/// `DurableContext::checkpoint_view_validated`.
fn replay_identity_mismatch(
record: &CheckpointRecord,
claimed_type: &str,
claimed_sub_type: Option<&str>,
claimed_name: Option<&str>,
) -> Option<String> {
// A record without a stored operation type has nothing to validate
// against, so the check skips it, as JS does. This is the ONLY
// lenient path; once a record carries identity, every field is
// compared in full.
let expected_type = record.op_type.as_deref()?;
let mismatch = || {
Some(format_op_identity(
expected_type,
record.sub_type.as_deref(),
record.op_name.as_deref(),
))
};
// Compare canonicalized types: the checkpoint log stores the wire
// token (e.g. `CHAINED_INVOKE`), while the claimed type can be
// PascalCase, so both sides canonicalize through `OperationType`
// before comparison.
if canonical_op_type(expected_type) != canonical_op_type(claimed_type) {
return mismatch();
}
// Sub-type is compared as a complete Option in both directions: a
// stored sub-type with no claimed sub-type (or the reverse) is a
// mismatch, not a skip. Otherwise a reordered same-type operation
// could consume the wrong checkpoint silently.
let sub_type_matches = match (record.sub_type.as_deref(), claimed_sub_type) {
(Some(expected), Some(claimed)) => expected.eq_ignore_ascii_case(claimed),
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
};
if !sub_type_matches {
return mismatch();
}
// Name is likewise compared as a complete Option in both directions.
// Adding or removing `.name(...)` between runs changes the operation's
// replay identity and must be flagged, for the same reason as above.
//
// Empty names are normalized to `None` on BOTH sides before the
// comparison: an empty name and no name are the same identity, so an
// operation named `""` whose record holds no `Name` still matches.
// Without normalization an UNCHANGED handler would be rejected on
// resume. Map items and parallel branches never claim an empty name:
// they claim the recorded name, which defaults to `map-item-{index}`
// or `parallel-branch-{index}`.
let claimed_name = claimed_name.filter(|n| !n.is_empty());
let expected_name = record.op_name.as_deref().filter(|n| !n.is_empty());
let name_matches = match (expected_name, claimed_name) {
(Some(expected), Some(claimed)) => expected == claimed,
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
};
if !name_matches {
return mismatch();
}
None
}
/// Formats an operation's identity as a human-readable string for error
/// messages (e.g. `"Step/Step named \"fetch-name\""` or `"Wait/Wait"`).
fn format_op_identity(op_type: &str, sub_type: Option<&str>, name: Option<&str>) -> String {
let mut s = String::with_capacity(64);
s.push_str(op_type);
if let Some(sub) = sub_type {
s.push('/');
s.push_str(sub);
}
if let Some(n) = name {
s.push_str(" named \"");
s.push_str(n);
s.push('"');
}
s
}
/// The value an operation returns when its direct checkpoint write found
/// no Tokio runtime (see `DurableContext::checkpoint_failure_unrecoverable`).
pub(crate) trait NoRuntimeOutcome {
/// The outcome for `no_runtime`.
fn no_runtime(no_runtime: crate::task::NoRuntime) -> Self;
}
impl<T> NoRuntimeOutcome for Result<T, OperationError> {
fn no_runtime(no_runtime: crate::task::NoRuntime) -> Self {
Err(crate::task::NoRuntime::operation_error(no_runtime))
}
}
/// For a call site whose function returns the operation error itself.
impl NoRuntimeOutcome for OperationError {
fn no_runtime(no_runtime: crate::task::NoRuntime) -> Self {
crate::task::NoRuntime::operation_error(no_runtime)
}
}
#[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::*;
use crate::client::{
GetStateOutput, InMemoryExecutionClient, TestResponse, operations_to_checkpoint_log,
};
use crate::engine::{CheckpointLog, CheckpointStatus};
use aws_sdk_lambda::types::Operation;
use std::sync::Arc;
/// A `TypedError` around a `RetryableSerdesError` is still marked, so
/// it ends the invocation, and the fault message holds the wrapped
/// chain without the type name.
#[tokio::test]
async fn typed_retryable_serdes_error_fault_omits_the_type_name() {
let typed = crate::TypedError::with_type(
"Throttled",
crate::serdes::RetryableSerdesError::new("mount timed out"),
);
assert!(crate::serdes::is_retryable_serdes_error(&typed));
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token0".to_owned(),
);
let fault_ctx = ctx.clone();
let outcome = crate::driver::test_support::outcome_of(
ctx.clone(),
Arc::clone(ctx.task_ownership()),
Arc::clone(ctx.coordinator()),
async move {
let _ = fault_ctx
.route_serdes_error("serialize", "op-1", Some("s"), Box::new(typed))
.await;
},
)
.await;
let crate::driver::InvocationOutcome::Fault {
error_type,
message,
} = outcome
else {
unreachable!("expected an invocation fault, got {outcome:?}");
};
assert_eq!(error_type, crate::error::SERDES_FAILED_ERROR_TYPE);
assert_eq!(
message,
"serdes serialize failed for operation \"s\" (op-1): \
retryable serdes failure: mount timed out"
);
}
/// The batch context, its Normal item context and its Flat item
/// context take their levels from the constructors: `new_child` adds 1
/// and `new_flat_child` keeps the level.
#[test]
fn nesting_levels_follow_constructors() {
let (root, _client) = DurableContext::test_context_with_depth(5);
let level = |ctx: &DurableContext| ctx.inner.nesting_level;
assert_eq!(level(&root), 0);
assert_eq!(root.inner.preserve_child_depth, 5);
let batch = root.new_child("1", None);
let normal = batch.new_child("1-1", None);
let flat = batch.new_flat_child("1-2", "parent", None);
assert_eq!((level(&batch), level(&normal), level(&flat)), (1, 2, 1));
let child = root.new_child("2", None);
let batch = child.new_child("2-1", None);
let normal = batch.new_child("2-1-1", None);
let flat = batch.new_flat_child("2-1-2", "parent", None);
assert_eq!((level(&batch), level(&normal), level(&flat)), (2, 3, 2));
for ctx in [&child, &batch, &normal, &flat] {
assert_eq!(
ctx.inner.preserve_child_depth, 5,
"every constructor copies the depth"
);
}
for ctx in [
DurableContext::test_context(),
DurableContext::new_root(
"arn".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
),
] {
assert_eq!((level(&ctx), ctx.inner.preserve_child_depth), (0, 0));
}
}
/// `new_virtual_child` keeps the caller's level and depth: 0 under the
/// root and 1 under a child of the root.
#[test]
fn virtual_child_keeps_nesting_level() {
let (root, _client) = DurableContext::test_context_with_depth(5);
let level = |ctx: &DurableContext| ctx.inner.nesting_level;
let under_root = root.new_virtual_child("1", None);
let child = root.new_child("2", None);
let under_child = child.new_virtual_child("2-1", None);
assert_eq!((level(&under_root), level(&under_child)), (0, 1));
for ctx in [&under_root, &under_child] {
assert_eq!(ctx.inner.preserve_child_depth, 5);
}
// The virtual child names its caller's parent and runs in its
// caller's owners.
assert_eq!(under_root.parent_wire_id(), None);
assert_eq!(under_root.owners(), [] as [String; 0]);
assert_eq!(under_child.parent_wire_id(), child.parent_wire_id());
assert_eq!(under_child.owners(), child.owners());
}
/// Each row of the issue's table: the context that creates the record,
/// asked with `levels_below` 1, against depths 0, 1, 2 and `u32::MAX`.
#[test]
fn preserves_children_table() {
let depths = [0, 1, 2, u32::MAX];
let row = |make: &dyn Fn(&DurableContext) -> DurableContext| -> Vec<bool> {
depths
.iter()
.map(|&depth| {
let (root, _client) = DurableContext::test_context_with_depth(depth);
make(&root).preserves_children(1)
})
.collect()
};
// A top-level child, map or parallel container: level 1.
assert_eq!(row(&|root| root.clone()), [false, true, true, true]);
// An item of a top-level map, Normal nesting: level 2.
assert_eq!(
row(&|root| root.new_child("1", None)),
[false, false, true, true]
);
// A child inside a Normal item: level 3.
assert_eq!(
row(&|root| root.new_child("1", None).new_child("1-1", None)),
[false, false, false, true]
);
// A child inside a Flat item of a top-level map: level 2.
assert_eq!(
row(&|root| root
.new_child("1", None)
.new_flat_child("1-1", "parent", None)),
[false, false, true, true]
);
// A child inside a top-level child: level 2.
assert_eq!(
row(&|root| root.new_child("1", None)),
[false, false, true, true]
);
// Additions saturate instead of overflowing.
let (root, _client) = DurableContext::test_context_with_depth(u32::MAX);
assert!(root.new_child("1", None).preserves_children(u32::MAX));
}
/// Test 19: each combinator method collects the operations its
/// iterator creates, which claim their IDs, and claims no ID itself.
#[test]
fn combinator_methods_collect_without_claiming() {
let ctx = DurableContext::new_root(
"arn:aws:lambda:us-east-1:1:function:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
);
// A lazy iterator: each step claims its ID when the combinator
// method collects it.
let inputs = || {
let ctx = &ctx;
(0..2).map(move |n| ctx.step(move |_| async move { Ok(n) }).future())
};
let try_join_all = ctx.try_join_all(inputs());
let join_all = ctx.join_all(inputs());
let select_ok = ctx.select_ok(inputs());
let race = ctx.race(inputs());
assert_eq!(
ctx.mint_id().positional(),
"9",
"the eight steps claimed 1 to 8, the combinators nothing"
);
drop((try_join_all, join_all, select_ok, race));
}
/// A claim outside any `run_body` scope checks only ownership, and the
/// owner thread passes it.
#[test]
fn claim_without_active_body_records_nothing() {
let ctx = DurableContext::test_context();
let id = ctx.claim_operation_id("step");
assert_eq!(id.positional(), "1");
assert!(ctx.coordinator().fatal_error().is_none());
}
/// A claim from a thread that does not own the context, with no body
/// active, records the ownership error and still claims the next ID.
/// The owner's claim before it records nothing.
#[test]
fn claim_from_foreign_thread_records_fatal() {
let ctx = DurableContext::test_context();
assert_eq!(ctx.claim_operation_id("step").positional(), "1");
assert!(ctx.coordinator().fatal_error().is_none());
let id = std::thread::scope(|scope| {
scope
.spawn(|| ctx.claim_operation_id("step"))
.join()
.expect("the claim does not panic")
});
assert_eq!(id.positional(), "2");
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "Error");
assert_eq!(fatal.error_message, foreign_caller_message("step"));
}
/// `enforce_task_ownership` passes for the owner thread and records
/// nothing. From a thread that does not own the context it returns an
/// `ExecutionFailed` step error and records the ownership error.
#[test]
fn enforce_task_ownership_refuses_foreign_thread() {
let ctx = DurableContext::test_context();
assert!(ctx.enforce_task_ownership().is_ok());
assert!(ctx.coordinator().fatal_error().is_none());
let result = std::thread::scope(|scope| {
scope
.spawn(|| ctx.enforce_task_ownership())
.join()
.expect("the check does not panic")
});
let err = result.expect_err("a foreign thread is refused");
assert!(matches!(
err.kind(),
OperationErrorKind::Step(step) if matches!(step.kind(), StepErrorKind::ExecutionFailed)
));
// The `StepError` is the operation error's source, and the ownership
// message is the step error's source.
let source = std::error::Error::source(&err)
.and_then(std::error::Error::source)
.map(ToString::to_string);
assert!(
source
.as_deref()
.is_some_and(|msg| msg.contains("which does not own the context")),
"unexpected source: {source:?}"
);
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "Error");
assert_eq!(fatal.error_message, foreign_caller_message("execute"));
}
/// A claim on the context whose body is active passes.
#[tokio::test]
async fn claim_in_own_body_records_nothing() {
let ctx = DurableContext::test_context();
let id = run_body(ActiveBody::Context(String::new()), async {
ctx.claim_operation_id("step")
})
.await;
assert_eq!(id.positional(), "1");
assert!(ctx.coordinator().fatal_error().is_none());
}
/// A claim on the context whose body is active, made by a raw task that
/// does not own the context, still runs the ownership check: the
/// matching body does not authorize the caller. It records the
/// ownership error and still claims the next ID.
#[tokio::test]
async fn claim_in_own_body_on_raw_task_records_fatal() {
let ctx = DurableContext::test_context();
assert_eq!(ctx.claim_operation_id("step").positional(), "1");
let foreign = ctx.clone();
let id = tokio::spawn(run_body(ActiveBody::Context(String::new()), async move {
foreign.claim_operation_id("step")
}))
.await
.expect("the claim does not panic");
assert_eq!(id.positional(), "2");
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "Error");
assert_eq!(fatal.error_message, foreign_caller_message("step"));
}
/// A claim on another context than the active body records message A
/// and still claims the ID.
#[tokio::test]
async fn claim_in_other_body_records_fatal() {
let ctx = DurableContext::test_context();
let id = run_body(ActiveBody::Context("3".to_owned()), async {
ctx.claim_operation_id("wait")
})
.await;
assert_eq!(id.positional(), "1");
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "Error");
assert_eq!(
fatal.error_message,
"context usage error in \"wait\": the operation was called on context \"root\", \
but the SDK is running the body of context \"3\". Inside run_in_child_context, \
with_retry, map and parallel, call operations on the context passed to the closure."
);
}
/// A claim inside a step body records message B.
#[tokio::test]
async fn claim_in_step_body_records_fatal() {
let ctx = DurableContext::test_context();
let _id = run_body(ActiveBody::Step("4".to_owned()), async {
ctx.claim_operation_id("map")
})
.await;
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "Error");
assert_eq!(
fatal.error_message,
"context usage error in \"map\": the operation was called inside the body of \
operation \"4\". A step body or a wait_for_condition check cannot call durable \
operations; use run_in_child_context to group operations."
);
}
/// Helper: builds a Step operation.
fn make_step_op(id: &str, result: &str) -> Operation {
Operation::builder()
.id(id)
.r#type(aws_sdk_lambda::types::OperationType::Step)
.status(aws_sdk_lambda::types::OperationStatus::Succeeded)
.start_timestamp(aws_smithy_types::DateTime::from_secs(0))
.step_details(
aws_sdk_lambda::types::StepDetails::builder()
.result(result)
.build(),
)
.build()
.unwrap()
}
/// Tests that `checkpoint_updates` paginates when the checkpoint response
/// has a `next_marker`: calling `get_state` to fetch all remaining
/// operations and merging them into the checkpoint log.
#[tokio::test]
async fn checkpoint_updates_paginates_on_marker() {
// The full state has 3 operations (what get_state returns).
let all_ops = vec![
make_step_op("step-1", "\"r1\""),
make_step_op("step-2", "\"r2\""),
make_step_op("step-3", "\"r3\""),
];
let client = Arc::new(InMemoryExecutionClient::new(all_ops));
// Enqueue a paginated checkpoint response: returns only step-1
// but signals more pages via next_marker.
let page1_ops = vec![make_step_op("step-1", "\"r1\"")];
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
page1_ops,
"page-2-token".to_owned(),
));
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::clone(&log),
client.clone(),
"initial-token".to_owned(),
);
// Perform a checkpoint with no updates (we just want to exercise pagination).
let result = ctx.checkpoint_updates(Vec::new()).await;
assert!(result.is_ok());
// The checkpoint log should now contain ALL operations from get_state.
assert!(log.get("step-1").is_some(), "step-1 must be in the log");
assert!(
log.get("step-2").is_some(),
"step-2 must be in the log (paginated)"
);
assert!(
log.get("step-3").is_some(),
"step-3 must be in the log (paginated)"
);
// get_state should have been called once for pagination.
let get_state_count = *client.get_state_call_count.lock().unwrap();
assert_eq!(
get_state_count, 1,
"get_state must be called for pagination"
);
}
/// Mock client for the concurrent pagination/token race test: every
/// `checkpoint` validates and rotates the token, always returns a
/// pagination marker, and `get_state` records whether the token it was
/// handed is still the client's CURRENT token.
#[derive(Debug)]
struct PaginatedTokenValidatingClient {
current_token: std::sync::Mutex<String>,
counter: std::sync::atomic::AtomicU32,
stale_checkpoint_tokens: std::sync::atomic::AtomicU32,
stale_get_state_tokens: std::sync::atomic::AtomicU32,
get_state_calls: std::sync::atomic::AtomicU32,
}
impl PaginatedTokenValidatingClient {
fn new(initial_token: &str) -> Self {
Self {
current_token: std::sync::Mutex::new(initial_token.to_owned()),
counter: std::sync::atomic::AtomicU32::new(0),
stale_checkpoint_tokens: std::sync::atomic::AtomicU32::new(0),
stale_get_state_tokens: std::sync::atomic::AtomicU32::new(0),
get_state_calls: std::sync::atomic::AtomicU32::new(0),
}
}
}
impl ExecutionClient for PaginatedTokenValidatingClient {
fn checkpoint(
&self,
_execution_arn: &str,
checkpoint_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
let submitted = checkpoint_token.to_owned();
Box::pin(async move {
// Widen the race window like the real network call would.
tokio::task::yield_now().await;
let mut current = self
.current_token
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *current != submitted {
self.stale_checkpoint_tokens
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
return Err(ExecutionClientError::non_retryable(format!(
"stale checkpoint token: expected {current}, got {submitted}"
)));
}
let n = self
.counter
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let next = format!("token-{}", n + 1);
current.clone_from(&next);
drop(current);
Ok(CheckpointOutput {
checkpoint_token: Some(next),
updated_operations: Vec::new(),
// Every response paginated: forces the marker-triggered
// get_state on every checkpoint.
next_marker: Some("more-pages".to_owned()),
})
})
}
fn get_state(
&self,
_execution_arn: &str,
checkpoint_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
let submitted = checkpoint_token.to_owned();
Box::pin(async move {
self.get_state_calls
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
// Yield so a concurrent branch would have every chance to
// checkpoint (and rotate the token) if the caller released
// the token lock too early.
tokio::task::yield_now().await;
tokio::task::yield_now().await;
let current = self
.current_token
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if *current != submitted {
self.stale_get_state_tokens
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
drop(current);
Ok(GetStateOutput::new(Vec::new(), None))
})
}
}
/// Regression test (issue #5): concurrent checkpoints whose responses
/// carry a pagination marker must perform the marker-triggered
/// `get_state` while STILL holding the checkpoint-token lock. If the
/// lock is dropped first, a concurrent branch checkpoints, consumes and
/// rotates the token, and the paginated `get_state` runs with a stale
/// token. The mock's `get_state` validates the token it receives
/// against the client's current token.
#[tokio::test]
async fn concurrent_paginated_checkpoints_get_state_uses_current_token() {
let client = Arc::new(PaginatedTokenValidatingClient::new("token-0"));
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
);
// Race several concurrent checkpoint_updates calls, each of which
// paginates. Every one must succeed (no stale checkpoint token) and
// every get_state must observe the then-current token.
let (r1, r2, r3, r4) = tokio::join!(
ctx.checkpoint_updates(Vec::new()),
ctx.checkpoint_updates(Vec::new()),
ctx.checkpoint_updates(Vec::new()),
ctx.checkpoint_updates(Vec::new()),
);
assert!(r1.is_ok(), "checkpoint 1 failed: {r1:?}");
assert!(r2.is_ok(), "checkpoint 2 failed: {r2:?}");
assert!(r3.is_ok(), "checkpoint 3 failed: {r3:?}");
assert!(r4.is_ok(), "checkpoint 4 failed: {r4:?}");
assert_eq!(
client
.get_state_calls
.load(std::sync::atomic::Ordering::SeqCst),
4,
"every paginated checkpoint must trigger a get_state"
);
assert_eq!(
client
.stale_checkpoint_tokens
.load(std::sync::atomic::Ordering::SeqCst),
0,
"no checkpoint may run with a stale token"
);
assert_eq!(
client
.stale_get_state_tokens
.load(std::sync::atomic::Ordering::SeqCst),
0,
"the marker-triggered get_state must run with the current token \
(token lock held through the paginated fetch)"
);
}
/// Tests that `checkpoint_updates` does NOT call `get_state` when there
/// is no pagination marker.
#[tokio::test]
async fn checkpoint_updates_no_pagination_when_no_marker() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
// Default response has no marker.
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
client.clone(),
"initial-token".to_owned(),
);
let result = ctx.checkpoint_updates(Vec::new()).await;
assert!(result.is_ok());
let get_state_count = *client.get_state_call_count.lock().unwrap();
assert_eq!(
get_state_count, 0,
"get_state must NOT be called without a marker"
);
}
/// Tests that the bootstrap pagination path works: when the initial
/// state has a `NextMarker`, `get_state` is called to fetch the full
/// operation set, and all operations appear in the checkpoint log.
#[tokio::test]
async fn bootstrap_pagination_fetches_all_pages() {
// Simulate a paginated initial state: page 1 has step-1,
// and get_state returns the full set (step-1 + step-2 + step-3).
let all_ops = vec![
make_step_op("step-1", "\"result-1\""),
make_step_op("step-2", "\"result-2\""),
make_step_op("step-3", "\"result-3\""),
];
let client: Arc<dyn ExecutionClient> = Arc::new(InMemoryExecutionClient::new(all_ops));
// The full log comes from get_state when the initial state is paginated.
let full_state = client.get_state("arn:test", "token", None).await;
assert!(full_state.is_ok());
let full_state = full_state.unwrap();
let log = operations_to_checkpoint_log(&full_state.operations);
assert!(log.get("step-1").is_some());
assert!(log.get("step-2").is_some());
assert!(log.get("step-3").is_some());
// Verify that the results are correct.
let r2 = log.get("step-2").unwrap();
assert_eq!(r2.result.as_deref(), Some("\"result-2\""));
assert_eq!(r2.status, CheckpointStatus::Succeeded);
}
// Non-determinism detection tests
#[test]
fn validate_replay_identity_passes_when_types_match() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Succeeded,
result: Some("42".to_owned()),
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
op_type: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: Some("my-step".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("my-step"));
assert!(result.is_ok());
}
// Targeted checkpoint accessors
/// Builds a context whose checkpoint log holds one record at positional
/// ID `"1"` (keyed by its wire ID, matching the production log shape).
fn ctx_with_record_at_1(record: CheckpointRecord) -> DurableContext {
let wire_id = crate::engine::compute_wire_id_public("1");
let log = Arc::new(CheckpointLog::from_records(vec![(wire_id, record)]));
DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
)
}
/// A record at a virtual child's ID fails with a recorded mismatch whose
/// claimed identity is `virtual Context`; a record without a type reads
/// as `Unknown`; no record passes.
#[test]
fn reject_record_at_virtual_child_messages() {
let record = |op_type: Option<&str>| CheckpointRecord {
id: "wire-1".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: op_type.map(str::to_owned),
sub_type: Some("RunInChildContext".to_owned()),
due_at: None,
op_name: Some("slot".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
for (op_type, expected) in [
(
Some("Context"),
"expected Context/RunInChildContext named \"slot\"",
),
(None, "expected Unknown/RunInChildContext named \"slot\""),
] {
let ctx = ctx_with_record_at_1(record(op_type));
let op_id = ctx.mint_id();
let err = ctx
.reject_record_at_virtual_child(&op_id, "RunInChildContext", Some("slot"))
.expect_err("a record at the slot");
let message = crate::error::chain_string(&err);
assert!(message.contains(expected), "{message}");
assert!(
message.contains("got virtual Context/RunInChildContext named \"slot\""),
"{message}"
);
let fatal = ctx.coordinator().fatal_error().expect("fatal recorded");
assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
let next = ctx.mint_id();
assert!(
ctx.reject_record_at_virtual_child(&next, "RunInChildContext", None)
.is_ok()
);
}
}
#[test]
fn checkpoint_view_validated_returns_view_on_identity_match() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Succeeded,
result: Some("42".to_owned()),
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 2,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: true,
callback_id: None,
op_type: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: Some("my-step".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
let result =
ctx.checkpoint_view_validated("1", "wire-1", "Step", Some("Step"), Some("my-step"));
assert!(result.is_ok());
let view = result.unwrap();
assert!(view.is_some());
let view = view.unwrap();
assert_eq!(view.status, CheckpointStatus::Succeeded);
assert_eq!(view.attempt, 2);
assert!(view.replay_children);
// No record at another position: Ok(None), nothing to validate.
let live = ctx.checkpoint_view_validated("2", "wire-2", "Step", Some("Step"), None);
assert!(matches!(live, Ok(None)));
}
#[test]
fn checkpoint_view_validated_errors_on_identity_mismatch() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".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: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
// Claimed as Wait but checkpointed as Step → the same
// NonDeterministicExecution error `validate_replay_identity` builds.
let result = ctx.checkpoint_view_validated("1", "wire-1", "Wait", Some("Wait"), None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(
err.kind(),
OperationErrorKind::NonDeterministicExecution(_)
));
let display = format!("{err:#}");
assert!(
display.contains("Step") && display.contains("Wait"),
"expected both identities in error: {display}"
);
}
/// Replay reaching a record whose status this SDK version does not
/// recognize must fail the execution naming the raw status (issue
/// #45), never return the view for the operation to act on.
#[test]
#[expect(clippy::panic)] // reason: test assertions over non_exhaustive kinds
fn checkpoint_view_validated_fails_execution_on_unrecognized_status() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Unknown("PAUSED".to_owned()),
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
op_type: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
assert!(
ctx.coordinator().fatal_error().is_none(),
"no fatal recorded before the replay check"
);
// Identity matches: the failure is the status, not the identity.
let result = ctx.checkpoint_view_validated("1", "wire-1", "Step", Some("Step"), None);
assert!(result.is_err());
let err = result.unwrap_err();
let OperationErrorKind::NonDeterministicExecution(nde) = err.kind() else {
panic!("expected NonDeterministicExecution, got {:?}", err.kind());
};
let NonDeterministicExecutionErrorKind::UnrecognizedStatus(details) = nde.kind() else {
panic!("expected UnrecognizedStatus, got {:?}", nde.kind());
};
assert_eq!(details.wire_id(), "wire-1");
assert_eq!(details.status(), "PAUSED");
let display = format!("{err:#}");
assert!(
display.contains("PAUSED"),
"error must name the raw status: {display}"
);
// The fatal slot is written so the invocation driver fails the
// execution even if the returned `Err` is swallowed downstream.
let fatal = ctx
.coordinator()
.fatal_error()
.expect("unrecognized status must record a fatal error");
assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
assert!(
fatal.error_message.contains("PAUSED"),
"fatal message must carry the raw status: {}",
fatal.error_message
);
}
/// A record with a recognized status and matching identity records no
/// fatal and returns the view: the #45 guard fires only on `Unknown`.
#[test]
fn checkpoint_view_validated_known_status_records_no_fatal() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::TimedOut,
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
op_type: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
let result = ctx.checkpoint_view_validated("1", "wire-1", "Step", Some("Step"), None);
assert!(matches!(result, Ok(Some(_))));
assert!(ctx.coordinator().fatal_error().is_none());
}
#[test]
fn targeted_getters_return_single_fields() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Failed,
result: Some(r#""state""#.to_owned()),
error_type: Some("SomeError".to_owned()),
error_message: Some("it broke".to_owned()),
error_data: None,
stack_trace: None,
attempt: 5,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: Some("cb-42".to_owned()),
op_type: None,
sub_type: None,
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
assert!(ctx.has_checkpoint_record("1"));
assert!(!ctx.has_checkpoint_record("2"));
assert_eq!(
ctx.checkpoint_result_payload("1").as_deref(),
Some(r#""state""#)
);
assert!(ctx.checkpoint_result_payload("2").is_none());
assert_eq!(ctx.checkpoint_callback_id("1").as_deref(), Some("cb-42"));
let wire = ctx.checkpoint_wire_error("1");
let wire = wire.expect("record 1 exists");
assert_eq!(wire.error_type(), Some("SomeError"));
assert_eq!(wire.error_message(), Some("it broke"));
assert!(ctx.checkpoint_wire_error("2").is_none());
let view = ctx.checkpoint_status_view("1");
assert!(view.is_some());
let view = view.unwrap();
assert_eq!(view.status, CheckpointStatus::Failed);
assert_eq!(view.attempt, 5);
}
#[test]
fn checkpoint_terminal_replay_projects_payload_and_error_fields() {
let ctx = ctx_with_record_at_1(CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Failed,
result: Some(r#""summary""#.to_owned()),
error_type: Some("BatchError".to_owned()),
error_message: Some("batch broke".to_owned()),
error_data: Some(r#"{"code":7}"#.to_owned()),
stack_trace: Some(vec!["frame-a".to_owned()]),
attempt: 3,
invoke_result: Some("never-projected".to_owned()),
invoke_error_type: Some("never-projected".to_owned()),
invoke_error_message: Some("never-projected".to_owned()),
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: true,
callback_id: Some("cb-99".to_owned()),
op_type: Some("Context".to_owned()),
sub_type: Some("Map".to_owned()),
due_at: None,
op_name: Some("batch".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
});
let snapshot = ctx.checkpoint_terminal_replay("1");
assert_eq!(
snapshot,
Some(TerminalReplaySnapshot {
status: CheckpointStatus::Failed,
replay_children: true,
result: Some(r#""summary""#.to_owned()),
error_message: Some("batch broke".to_owned()),
error_type: Some("BatchError".to_owned()),
error_data: Some(r#"{"code":7}"#.to_owned()),
stack_trace: Some(vec!["frame-a".to_owned()]),
})
);
// No record → no snapshot.
assert!(ctx.checkpoint_terminal_replay("2").is_none());
}
#[test]
fn validate_replay_identity_fails_on_type_mismatch() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".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: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
// Claimed as Wait but checkpointed as Step → error
let result = ctx.validate_replay_identity(&record, "wire-1", "Wait", Some("Wait"), None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(
err.kind(),
OperationErrorKind::NonDeterministicExecution(_)
));
let display = format!("{err:#}");
assert!(
display.contains("Step"),
"expected Step in error: {display}"
);
assert!(
display.contains("Wait"),
"expected Wait in error: {display}"
);
}
#[test]
fn validate_replay_identity_fails_on_subtype_mismatch() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".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: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
// Same op_type but different sub_type → error
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("WaitForCondition"), None);
assert!(result.is_err());
let err = result.unwrap_err();
assert!(matches!(
err.kind(),
OperationErrorKind::NonDeterministicExecution(_)
));
}
#[test]
fn validate_replay_identity_fails_on_name_mismatch() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".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: Some("Step".to_owned()),
sub_type: Some("Step".to_owned()),
due_at: None,
op_name: Some("fetch-user".to_owned()),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
// Same type but different name → error
let result = ctx.validate_replay_identity(
&record,
"wire-1",
"Step",
Some("Step"),
Some("fetch-order"),
);
assert!(result.is_err());
let err = result.unwrap_err();
let display = format!("{err:#}");
assert!(
display.contains("fetch-user"),
"expected name in error: {display}"
);
assert!(
display.contains("fetch-order"),
"expected claimed name in error: {display}"
);
}
#[test]
fn validate_replay_identity_skips_when_no_identity_stored() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Succeeded,
result: Some("1".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,
};
// Even though claimed type differs, validation passes because the
// record has no identity to compare against.
let result = ctx.validate_replay_identity(&record, "wire-1", "Wait", Some("Wait"), None);
assert!(result.is_ok());
}
#[test]
fn validate_replay_identity_case_insensitive_type_match() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".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: Some("STEP".to_owned()),
sub_type: Some("STEP".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
// Wire format uses UPPER_CASE: validation is case-insensitive.
let result = ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), None);
assert!(result.is_ok());
}
/// Regression test (issue #6): the inline JSON envelope path stores the
/// raw wire value `CHAINED_INVOKE` (with underscore) while the SDK
/// claims `ChainedInvoke` (`PascalCase`). A case-insensitive comparison
/// alone rejects every non-paginated replayed invoke as
/// non-deterministic; canonicalization must accept it.
#[test]
fn validate_replay_identity_inline_chained_invoke_replay_matches() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".to_owned(),
status: CheckpointStatus::Succeeded,
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: Some("\"ok\"".to_owned()),
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
// Exactly what parse_single_operation stores from the inline
// envelope: the raw wire `Type` value.
op_type: Some("CHAINED_INVOKE".to_owned()),
sub_type: Some("ChainedInvoke".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let result = ctx.validate_replay_identity(
&record,
"wire-1",
"ChainedInvoke",
Some("ChainedInvoke"),
None,
);
assert!(
result.is_ok(),
"inline CHAINED_INVOKE record must match claimed ChainedInvoke: {result:?}"
);
}
/// Canonicalization must not weaken detection: a genuinely different
/// type still mismatches after canonicalization.
#[test]
fn validate_replay_identity_canonicalized_types_still_mismatch() {
let log = Arc::new(CheckpointLog::empty());
let ctx = DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
);
let record = CheckpointRecord {
id: "wire-1".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: Some("CHAINED_INVOKE".to_owned()),
sub_type: Some("ChainedInvoke".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("ChainedInvoke"), None);
assert!(
result.is_err(),
"Step claimed against CHAINED_INVOKE record must mismatch"
);
}
/// Both spellings of every known operation type canonicalize to the
/// same wire constant, and unknown types stay distinguishable.
#[test]
fn canonical_op_type_bridges_wire_and_pascal_spellings() {
for (pascal, wire) in [
("Callback", "CALLBACK"),
("ChainedInvoke", "CHAINED_INVOKE"),
("Context", "CONTEXT"),
("Execution", "EXECUTION"),
("Step", "STEP"),
("Wait", "WAIT"),
] {
assert_eq!(
canonical_op_type(pascal),
canonical_op_type(wire),
"{pascal} and {wire} must canonicalize identically"
);
}
assert_ne!(
canonical_op_type("Step"),
canonical_op_type("ChainedInvoke"),
"distinct types must stay distinct"
);
}
/// Builds a checkpoint record carrying full identity fields for the
/// Some↔None conformance tests below.
fn record_with_identity(
op_type: Option<&str>,
sub_type: Option<&str>,
op_name: Option<&str>,
) -> CheckpointRecord {
CheckpointRecord {
id: "wire-1".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: op_type.map(ToOwned::to_owned),
sub_type: sub_type.map(ToOwned::to_owned),
due_at: None,
op_name: op_name.map(ToOwned::to_owned),
parent_id: None,
start_timestamp: None,
end_timestamp: None,
}
}
fn test_ctx() -> DurableContext {
DurableContext::new_root(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
)
}
#[test]
fn validate_replay_identity_fails_when_stored_name_removed() {
// Record was checkpointed with a name; the claim carries none.
// Removing `.name(...)` changes replay identity and must be flagged,
// otherwise a reordered unnamed same-type operation could consume
// this checkpoint silently.
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), Some("my-step"));
let result = ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), None);
let err = result.unwrap_err();
assert!(matches!(
err.kind(),
OperationErrorKind::NonDeterministicExecution(_)
));
let display = format!("{err:#}");
assert!(
display.contains("my-step"),
"expected stored name in error: {display}"
);
}
#[test]
fn validate_replay_identity_fails_when_name_added() {
// Record was checkpointed without a name (but with identity); the
// claim now carries one. The None↔Some direction is a mismatch too.
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), None);
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("new-name"));
let err = result.unwrap_err();
assert!(matches!(
err.kind(),
OperationErrorKind::NonDeterministicExecution(_)
));
let display = format!("{err:#}");
assert!(
display.contains("new-name"),
"expected claimed name in error: {display}"
);
}
#[test]
fn validate_replay_identity_fails_when_subtype_dropped() {
// Sub-type is compared as a complete Option in both directions.
let ctx = test_ctx();
let record = record_with_identity(Some("Context"), Some("Map"), None);
let result = ctx.validate_replay_identity(&record, "wire-1", "Context", None, None);
assert!(
result.is_err(),
"expected mismatch when stored sub-type is dropped from the claim"
);
// And the reverse direction: record without a sub-type, claim with one.
let record = record_with_identity(Some("Context"), None, None);
let result = ctx.validate_replay_identity(&record, "wire-1", "Context", Some("Map"), None);
assert!(
result.is_err(),
"expected mismatch when a sub-type is added to the claim"
);
}
#[test]
fn validate_replay_identity_untyped_record_skips_name_and_subtype() {
// A record genuinely lacking identity (no op_type) is the ONLY
// lenient path: nothing is compared, whatever the claim carries.
let ctx = test_ctx();
let record = record_with_identity(None, None, None);
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("any-name"));
assert!(result.is_ok());
}
#[test]
fn validate_replay_identity_empty_claimed_name_matches_stored_none() {
// An empty claimed name and a record with no `Name` are the same
// identity. An unchanged handler must NOT be rejected on resume.
let ctx = test_ctx();
let record = record_with_identity(Some("Context"), Some("MapIteration"), None);
let result = ctx.validate_replay_identity(
&record,
"wire-1",
"Context",
Some("MapIteration"),
Some(""),
);
assert!(
result.is_ok(),
"claimed empty name must match a stored None: {result:?}"
);
}
#[test]
fn validate_replay_identity_empty_stored_name_matches_claimed_none() {
// The reverse direction: a backend that stored an empty name string
// must match a claim carrying no name.
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), Some(""));
let result = ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), None);
assert!(
result.is_ok(),
"stored empty name must match a claimed None: {result:?}"
);
}
#[test]
fn validate_replay_identity_empty_name_still_mismatches_real_name() {
// Normalization must not weaken detection: an empty claim against a
// real stored name (and the reverse) is still a mismatch.
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), Some("real"));
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some(""));
assert!(
result.is_err(),
"empty claim vs stored 'real' must mismatch"
);
let record = record_with_identity(Some("Step"), Some("Step"), None);
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("real"));
assert!(
result.is_err(),
"claimed 'real' vs stored None must mismatch"
);
}
#[test]
fn validate_replay_identity_mismatch_records_fatal_error() {
// A mismatch must record the execution-fatal error on the shared
// suspension-signal slot so the invocation driver fails the execution
// even when the returned `Err` is swallowed downstream.
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), Some("alpha"));
assert!(
ctx.coordinator().fatal_error().is_none(),
"no fatal recorded before validation"
);
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("beta"));
assert!(result.is_err());
let fatal = ctx
.coordinator()
.fatal_error()
.expect("mismatch must record a fatal error");
assert_eq!(fatal.error_type, "NonDeterministicExecutionError");
assert!(
fatal.error_message.contains("alpha") && fatal.error_message.contains("beta"),
"fatal message must name both identities: {}",
fatal.error_message
);
}
#[test]
fn validate_replay_identity_pass_records_no_fatal() {
let ctx = test_ctx();
let record = record_with_identity(Some("Step"), Some("Step"), Some("same"));
let result =
ctx.validate_replay_identity(&record, "wire-1", "Step", Some("Step"), Some("same"));
assert!(result.is_ok());
assert!(
ctx.coordinator().fatal_error().is_none(),
"a passing validation must not record a fatal error"
);
}
// Debug redaction tests
#[test]
fn debug_output_redacts_checkpoint_token() {
let secret_token = "super-secret-credential-value-12345";
let log = Arc::new(CheckpointLog::empty());
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = DurableContext::new_root_with_client(
"arn:aws:lambda:us-east-1:123456789012:function:my-fn".to_owned(),
lambda_runtime::Context::default(),
log,
client,
secret_token.to_owned(),
);
let debug_output = format!("{ctx:?}");
// The actual token value MUST NOT appear in debug output.
assert!(
!debug_output.contains(secret_token),
"checkpoint_token value leaked in Debug output: {debug_output}"
);
// The redacted placeholder MUST appear.
assert!(
debug_output.contains("<redacted>"),
"expected '<redacted>' in Debug output: {debug_output}"
);
// Useful fields MUST be present.
assert!(
debug_output.contains("arn:aws:lambda:us-east-1:123456789012:function:my-fn"),
"expected execution_arn in Debug output: {debug_output}"
);
}
/// Every context derived from the root shares the root's plugins: the
/// child of `new_child` and the flat child of `new_flat_child`. The test
/// compares the `Arc`s by address.
#[test]
fn derived_contexts_share_the_root_plugins() {
let plugins = crate::plugin::test_support::invocation_plugins();
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::new(InMemoryExecutionClient::new(Vec::new())),
"token-0".to_owned(),
None,
0,
Some(Arc::clone(&plugins)),
);
let same = |ctx: &DurableContext| {
ctx.plugins()
.is_some_and(|shared| std::ptr::eq(shared, Arc::as_ptr(&plugins)))
};
assert!(same(&root), "the root holds the plugins");
let child = root.new_child("1", None);
assert!(same(&child), "new_child copies the plugins");
assert!(
same(&child.new_child("1-1", None)),
"a grandchild shares them"
);
assert!(
same(&root.new_flat_child("2", "parent", None)),
"new_flat_child copies the plugins"
);
assert!(
DurableContext::test_context().plugins().is_none(),
"a root constructor without the parameter sets none"
);
}
// Checkpoint coalescing tests
/// Builds a root context with a checkpoint-coalescing delay, backed by
/// the in-memory client.
fn coalescing_ctx(client: Arc<dyn ExecutionClient>, delay: Duration) -> DurableContext {
DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client,
"token-0".to_owned(),
Some(delay),
0,
None,
)
}
/// Helper: builds a bare step START update with the given wire ID.
fn make_update(id: &str) -> OperationUpdate {
OperationUpdate::builder()
.id(id.to_owned())
.r#type(aws_sdk_lambda::types::OperationType::Step)
.action(OperationAction::Start)
.build()
.expect("all required OperationUpdate fields set")
}
/// Without a Tokio runtime the batch flusher cannot start: every
/// contributor receives an invocation-scoped error instead of waiting
/// forever, and nothing is written.
#[test]
fn batch_flush_without_runtime_returns_invocation_error() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = coalescing_ctx(client.clone(), Duration::ZERO);
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
ctx.checkpoint_updates(vec![make_update("op-a")]).await
});
let std::task::Poll::Ready(Err(err)) = polled else {
unreachable!("expected an immediate error, got {polled:?}");
};
assert_eq!(err.scope(), ExecutionClientErrorScope::Invocation);
assert!(
err.to_string().contains(crate::task::NO_RUNTIME_MESSAGE),
"unexpected error: {err}"
);
assert!(client.recorded_updates().is_empty(), "nothing is written");
}
/// A flusher that cannot be spawned publishes nothing for a batch that
/// another flusher already claimed: that flusher publishes the
/// batch's result.
#[test]
fn unspawned_flush_of_a_claimed_batch_publishes_nothing() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = coalescing_ctx(client.clone(), Duration::from_secs(60));
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
let coalescer = Arc::clone(ctx.inner.coalescer.as_ref().expect("buffered"));
let (batch, _) = coalescer
.join(
ctx.admission(),
ctx.coordinator(),
ctx.owners(),
vec![TrackedUpdate::capture(make_update("op-a"), 1)],
)
.expect("admitted");
let claimed = coalescer.take_batch(&batch);
ctx.spawn_batch_flush(&coalescer, &batch, Duration::ZERO);
(claimed.is_some(), batch.result_clone().is_none())
});
assert!(
matches!(polled, std::task::Poll::Ready((true, true))),
"{polled:?}"
);
assert!(client.recorded_updates().is_empty(), "nothing is written");
}
/// Two concurrent checkpoint calls inside the delay window coalesce
/// into ONE client call carrying both updates.
#[tokio::test(start_paused = true)]
async fn coalesced_checkpoints_batch_into_one_call() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = coalescing_ctx(client.clone(), Duration::from_millis(50));
let (a, b) = tokio::join!(
ctx.checkpoint_updates(vec![make_update("op-a")]),
ctx.checkpoint_updates(vec![make_update("op-b")]),
);
assert!(a.is_ok(), "first coalesced caller succeeds");
assert!(b.is_ok(), "second coalesced caller succeeds");
let call_count = *client.checkpoint_call_count.lock().unwrap();
assert_eq!(call_count, 1, "both updates must share one API call");
let ids: Vec<String> = client
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect();
assert_eq!(
ids,
vec!["op-a".to_owned(), "op-b".to_owned()],
"the single call carries both updates in join order"
);
}
/// An urgent checkpoint (the callback-creation flush point) does not
/// wait out the delay window: it flushes immediately, carrying any
/// previously buffered updates with it.
#[tokio::test(start_paused = true)]
async fn urgent_checkpoint_flushes_without_waiting_the_window() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
// A window long enough that waiting it out would be visible in
// paused time.
let ctx = coalescing_ctx(client.clone(), Duration::from_hours(1));
let start = tokio::time::Instant::now();
ctx.submit_checkpoint_updates_urgent(vec![make_update("op-urgent")])
.await
.expect("urgent checkpoint succeeds");
assert_eq!(
start.elapsed(),
Duration::ZERO,
"urgent flush must not wait for the coalescing window"
);
let call_count = *client.checkpoint_call_count.lock().unwrap();
assert_eq!(call_count, 1);
}
/// `flush_pending_checkpoints` (the suspension / end-of-invocation
/// flush point) drains a buffered batch long before its window
/// elapses, and the buffered caller observes the flushed result.
#[tokio::test(start_paused = true)]
async fn flush_pending_checkpoints_drains_the_buffer() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = coalescing_ctx(client.clone(), Duration::from_hours(1));
let start = tokio::time::Instant::now();
let buffered = tokio::spawn({
let ctx = ctx.clone();
async move {
ctx.checkpoint_updates(vec![make_update("op-buffered")])
.await
}
});
// Let the spawned caller join the batch (well under the window).
tokio::time::sleep(Duration::from_millis(1)).await;
ctx.flush_pending_checkpoints().await;
let result = buffered.await.expect("buffered caller task completes");
assert!(result.is_ok(), "buffered caller observes the flush result");
assert!(
start.elapsed() < Duration::from_secs(1),
"flush must not wait for the one-hour window"
);
let call_count = *client.checkpoint_call_count.lock().unwrap();
assert_eq!(call_count, 1);
}
/// Without a configured delay, `checkpoint_updates` writes immediately:
/// one call per checkpoint, exactly the pre-knob behavior.
#[tokio::test(start_paused = true)]
async fn no_delay_checkpoints_write_immediately() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client.clone(),
"token-0".to_owned(),
);
let start = tokio::time::Instant::now();
ctx.checkpoint_updates(vec![make_update("op-1")])
.await
.expect("first write succeeds");
ctx.checkpoint_updates(vec![make_update("op-2")])
.await
.expect("second write succeeds");
assert_eq!(start.elapsed(), Duration::ZERO);
let call_count = *client.checkpoint_call_count.lock().unwrap();
assert_eq!(call_count, 2, "no coalescing without a configured delay");
}
/// A test client whose `checkpoint` calls block until released,
/// delegating to an [`InMemoryExecutionClient`] once the gate opens.
/// Lets tests hold a batched write "in flight" deterministically.
#[derive(Debug)]
struct GatedClient {
inner: InMemoryExecutionClient,
gate: tokio::sync::Semaphore,
/// Snapshot of update-ID lists, one entry per checkpoint call, in
/// call order.
calls: std::sync::Mutex<Vec<Vec<String>>>,
}
impl GatedClient {
fn new() -> Self {
Self {
inner: InMemoryExecutionClient::new(Vec::new()),
gate: tokio::sync::Semaphore::new(0),
calls: std::sync::Mutex::new(Vec::new()),
}
}
/// Allows one blocked (or future) checkpoint call to proceed.
fn release_one(&self) {
self.gate.add_permits(1);
}
fn call_ids(&self) -> Vec<Vec<String>> {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
}
impl ExecutionClient for GatedClient {
fn checkpoint(
&self,
execution_arn: &str,
checkpoint_token: &str,
updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
let arn = execution_arn.to_owned();
let token = checkpoint_token.to_owned();
Box::pin(async move {
// Block until the test releases the gate. The permit is
// consumed (forgotten) so each call needs its own release.
let permit = self.gate.acquire().await.map_err(|e| {
ExecutionClientError::non_retryable(format!("gate closed: {e}"))
})?;
permit.forget();
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(updates.iter().map(|u| u.id.clone()).collect());
self.inner.checkpoint(&arn, &token, updates).await
})
}
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.inner
.get_state(execution_arn, checkpoint_token, marker)
}
}
/// REGRESSION (flush contract): once a delay timer claims a batch and
/// its write is in flight, `flush_pending_checkpoints` must NOT return
/// until that write finishes: the wrapper reports
/// PENDING/SUCCEEDED/FAILED right after the flush, and an unawaited
/// in-flight checkpoint would cross that boundary.
#[tokio::test(start_paused = true)]
async fn flush_waits_for_in_flight_timer_claimed_batch() {
let client = Arc::new(GatedClient::new());
let ctx = coalescing_ctx(
Arc::clone(&client) as Arc<dyn ExecutionClient>,
Duration::from_millis(10),
);
// A buffered contributor: its delay timer fires at +10ms, claiming
// the batch and starting a write that blocks on the gate.
let contributor = tokio::spawn({
let ctx = ctx.clone();
async move {
ctx.checkpoint_updates(vec![make_update("op-in-flight")])
.await
}
});
// Advance past the window so the timer claims the batch and the
// write task blocks inside the gated client.
tokio::time::sleep(Duration::from_millis(20)).await;
// The end-of-invocation flush must now WAIT for that in-flight
// write. Prove it stays pending while the gate is closed: in
// paused time, the timeout can only fire because every task is
// blocked on the (non-timer) gate.
let mut flush = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.flush_pending_checkpoints().await }
});
let raced = tokio::time::timeout(Duration::from_mins(1), &mut flush).await;
assert!(
raced.is_err(),
"flush returned while the timer-claimed batch write was still in flight — \
the flush barrier is broken"
);
// Release the write; now both the contributor and the flush finish.
client.release_one();
flush.await.expect("flush task completes");
contributor
.await
.expect("contributor task completes")
.expect("contributor observes the published write");
assert_eq!(
client.call_ids(),
vec![vec!["op-in-flight".to_owned()]],
"exactly the claimed batch was written, once"
);
}
/// A test client that FAILS every checkpoint call retryably, holding
/// the FIRST call at a gate so the test can order a second batch's
/// queuing against the in-flight failing write. Calls after the first
/// fail immediately (no gate), so a regression that performs an extra
/// write shows up as an extra recorded call instead of a hang.
#[derive(Debug)]
struct GatedRetryableFailClient {
gate: tokio::sync::Semaphore,
first: std::sync::atomic::AtomicBool,
/// Snapshot of update-ID lists, one entry per checkpoint call, in
/// call order.
calls: std::sync::Mutex<Vec<Vec<String>>>,
}
impl GatedRetryableFailClient {
fn new() -> Self {
Self {
gate: tokio::sync::Semaphore::new(0),
first: std::sync::atomic::AtomicBool::new(true),
calls: std::sync::Mutex::new(Vec::new()),
}
}
/// Releases the gated first call so its rejection lands.
fn release_first(&self) {
self.gate.add_permits(1);
}
fn call_ids(&self) -> Vec<Vec<String>> {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
fn call_count(&self) -> usize {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.len()
}
}
impl ExecutionClient for GatedRetryableFailClient {
fn checkpoint(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async move {
self.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(updates.iter().map(|u| u.id.clone()).collect());
if self.first.swap(false, std::sync::atomic::Ordering::SeqCst) {
// Hold the first call in flight until the test
// releases it; the permit is consumed so a second
// call never blocks here.
if let Ok(permit) = self.gate.acquire().await {
permit.forget();
}
}
Err(ExecutionClientError::from_retryable(
"injected retryable checkpoint failure".to_owned(),
))
})
}
fn get_state(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
Err(ExecutionClientError::new_non_retryable(
"get_state not used in this test",
))
})
}
}
/// A flusher QUEUED behind a failing batch write performs no
/// checkpoint call. Batch A's write is in flight (held at the client's
/// gate) when batch B opens and queues its flusher on the writer lock;
/// A then fails retryably. The failure sets the latch and drops B's
/// batch, and B's flusher, which claimed nothing or reaches the
/// checkpoint-token lock after the latch, sends nothing and publishes
/// nothing. No contributor resolves, and the first failure is the
/// recorded one.
#[tokio::test(start_paused = true)]
async fn queued_batch_flush_after_retryable_failure_writes_nothing() {
let client = Arc::new(GatedRetryableFailClient::new());
let ctx = coalescing_ctx(
Arc::clone(&client) as Arc<dyn ExecutionClient>,
Duration::ZERO,
);
// Batch A: its zero-delay flusher claims the batch under the
// writer lock and starts the write, which is held at the gate.
let contributor_a = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.checkpoint_updates(vec![make_update("op-a")]).await }
});
while client.call_count() < 1 {
tokio::time::sleep(Duration::from_millis(1)).await;
}
// Batch B opens while A's write is in flight; its flusher queues
// on the writer lock behind A.
let contributor_b = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.checkpoint_updates(vec![make_update("op-b")]).await }
});
// Let B join the buffer and its flusher reach the writer lock.
tokio::time::sleep(Duration::from_millis(5)).await;
// A's held write now fails retryably; B's queued flusher runs
// right after, under the same writer lock.
client.release_first();
let both = async { tokio::join!(contributor_a, contributor_b) };
assert!(
tokio::time::timeout(Duration::from_secs(60), both)
.await
.is_err(),
"no contributor resolves"
);
assert_eq!(
client.call_ids(),
vec![vec!["op-a".to_owned()]],
"batch B causes no checkpoint call after batch A's failure"
);
assert!(ctx.queued_update_ids().is_empty(), "B's batch is dropped");
let first = ctx.coordinator().write_failure().expect("latched");
assert_eq!(
first.error_type,
crate::error::CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE
);
assert_eq!(
first.error_message,
"[Unrecoverable Invocation] Checkpoint failed: injected retryable checkpoint failure"
);
}
/// A retryable checkpoint failure records the fault JS gives it: the
/// type `CheckpointUnrecoverableInvocationError` and the message
/// `[Unrecoverable Invocation] Checkpoint failed: {m}`, and fails the
/// invocation.
#[test]
fn checkpoint_failure_fatal_of_a_retryable_error() {
let err = ExecutionClientError::new(ExecutionClientErrorScope::Invocation, "throttled");
let fatal = checkpoint_failure_fatal(&err);
assert_eq!(fatal.error_type, "CheckpointUnrecoverableInvocationError");
assert_eq!(
fatal.error_message,
"[Unrecoverable Invocation] Checkpoint failed: throttled"
);
assert!(matches!(fatal.severity, FatalSeverity::FailInvocation));
}
/// A fan-out exceeding one request's operation-count limit is split
/// into multiple ordered requests rather than one oversized call.
#[tokio::test(start_paused = true)]
async fn coalesced_fanout_splits_into_size_capped_requests() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let limits = BatchLimits {
max_operations: 2,
max_payload_bytes: usize::MAX,
};
let ctx = DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client.clone(),
"token-0".to_owned(),
CheckpointCoalescer::with_limits(Duration::from_millis(50), limits),
);
// Five contributors join one coalescing window.
let results = tokio::join!(
ctx.checkpoint_updates(vec![make_update("op-1")]),
ctx.checkpoint_updates(vec![make_update("op-2")]),
ctx.checkpoint_updates(vec![make_update("op-3")]),
ctx.checkpoint_updates(vec![make_update("op-4")]),
ctx.checkpoint_updates(vec![make_update("op-5")]),
);
for outcome in [results.0, results.1, results.2, results.3, results.4] {
assert!(outcome.is_ok(), "every contributor observes success");
}
let call_count = *client.checkpoint_call_count.lock().unwrap();
assert_eq!(
call_count, 3,
"five updates under a two-op cap must go out as 2+2+1 requests"
);
let ids: Vec<String> = client
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect();
assert_eq!(
ids,
vec!["op-1", "op-2", "op-3", "op-4", "op-5"],
"join order is preserved across the split requests"
);
}
/// Pure batching mode (zero window): checkpoints arriving while an
/// earlier write is in flight batch into ONE follow-up call, and no
/// artificial delay is added anywhere.
#[tokio::test(start_paused = true)]
async fn batching_mode_batches_writes_behind_in_flight_call() {
let client = Arc::new(GatedClient::new());
let ctx = coalescing_ctx(
Arc::clone(&client) as Arc<dyn ExecutionClient>,
Duration::ZERO,
);
// First checkpoint drives immediately and blocks in the client.
let first = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.checkpoint_updates(vec![make_update("op-first")]).await }
});
tokio::task::yield_now().await;
// Two more checkpoints arrive while the first write is in flight:
// they join the open batch behind the writer lock.
let second = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.checkpoint_updates(vec![make_update("op-second")]).await }
});
let third = tokio::spawn({
let ctx = ctx.clone();
async move { ctx.checkpoint_updates(vec![make_update("op-third")]).await }
});
// Let both join and block on the writer lock / gate.
tokio::time::sleep(Duration::from_millis(1)).await;
// Release both calls (first write, then the batched follow-up).
client.release_one();
client.release_one();
for task in [first, second, third] {
task.await
.expect("contributor task completes")
.expect("contributor observes success");
}
assert_eq!(
client.call_ids(),
vec![
vec!["op-first".to_owned()],
vec!["op-second".to_owned(), "op-third".to_owned()],
],
"the two checkpoints that arrived during the in-flight write \
must batch into one follow-up call"
);
}
// Lifecycle-event ownership regression tests
//
// The documented contract (`crate::observability`) guarantees that
// every transition the service records emits its lifecycle event.
// These tests pin the two ways the old contributor-owned emission
// violated that: a contributor dropped after joining a buffered batch,
// and a split batch whose earlier chunk persists before a later chunk
// fails.
/// A `MakeWriter` that captures subscriber output in a shared buffer.
#[derive(Clone)]
struct EventCaptureWriter(Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for EventCaptureWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if let Ok(mut inner) = self.0.lock() {
inner.extend_from_slice(buf);
}
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for EventCaptureWriter {
type Writer = EventCaptureWriter;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
/// Installs a JSON capture subscriber (all levels, flattened fields,
/// span list included) and returns the shared buffer plus the guard.
fn lifecycle_capture() -> (
Arc<std::sync::Mutex<Vec<u8>>>,
tracing::subscriber::DefaultGuard,
) {
use tracing_subscriber::layer::SubscriberExt as _;
let buffer = Arc::new(std::sync::Mutex::new(Vec::new()));
let fmt_layer = tracing_subscriber::fmt::layer()
.json()
.flatten_event(true)
.with_span_list(true)
.with_writer(EventCaptureWriter(Arc::clone(&buffer)));
let subscriber = tracing_subscriber::registry().with(fmt_layer);
let guard = test_tracing::install_test_subscriber(subscriber);
(buffer, guard)
}
/// Parses the captured output into the JSON lifecycle-event lines with
/// the given event name, returning each line's parsed JSON.
fn captured_lifecycle_events(
buffer: &Arc<std::sync::Mutex<Vec<u8>>>,
event_name: &str,
) -> Vec<serde_json::Value> {
let output = buffer.lock().map_or_else(
|_| String::new(),
|b| String::from_utf8_lossy(&b).to_string(),
);
output
.lines()
.filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
.filter(|v| {
v.get("message").and_then(serde_json::Value::as_str) == Some(event_name)
&& v.get("target").and_then(serde_json::Value::as_str)
== Some(crate::observability::TARGET)
})
.collect()
}
/// REGRESSION (event ownership, dropped contributor): a buffered
/// contributor dropped after joining a batch, explicitly supported for
/// `race`/`select_ok` losers, must not take its lifecycle events with
/// it. The flush task persists the update, so the write path must emit
/// the event, inside the span the contributor captured.
///
/// The scenario retries a few times because `tracing`'s global
/// max-level hint and callsite-interest caches are rebuilt whenever any
/// concurrently running test registers or drops a subscriber, and a
/// rebuild racing this test's `DEBUG`-level emission can drop the event
/// before it reaches this test's (thread-local) subscriber. The
/// persistence invariant is asserted on every attempt; a genuine
/// emission regression fails all attempts.
#[tokio::test(start_paused = true)]
async fn dropped_buffered_contributor_still_emits_events_for_persisted_updates() {
use crate::observability::event_names;
let mut emitted = false;
for _attempt in 0..5 {
let (buffer, _guard) = lifecycle_capture();
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = coalescing_ctx(client.clone(), Duration::from_hours(1));
// The contributor polls once inside its own span, far enough
// to capture its events and join the coalescing batch, then is
// dropped, exactly like a lost `race` branch.
{
let span = tracing::info_span!("contributor-span");
let _entered = span.enter();
let mut fut = Box::pin(ctx.checkpoint_updates(vec![make_update("op-dropped")]));
let mut poll_cx = std::task::Context::from_waker(std::task::Waker::noop());
assert!(
Future::poll(fut.as_mut(), &mut poll_cx).is_pending(),
"the buffered contributor must be awaiting the batch"
);
} // `fut` dropped here, before any flush.
// The end-of-invocation flush persists the batch anyway.
ctx.flush_pending_checkpoints().await;
let ids: Vec<String> = client
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect();
assert_eq!(
ids,
vec!["op-dropped".to_owned()],
"the dropped contributor's update must still be persisted"
);
let events = captured_lifecycle_events(&buffer, event_names::OPERATION_STARTED);
if events.is_empty() {
// A concurrent subscriber rebuild dropped the event before
// it reached this test's subscriber; retry the scenario.
continue;
}
let matching: Vec<&serde_json::Value> = events
.iter()
.filter(|v| {
v.get(crate::tracing_layer::fields::OPERATION_ID)
.and_then(serde_json::Value::as_str)
== Some("op-dropped")
})
.collect();
assert_eq!(
matching.len(),
1,
"the persisted transition must emit exactly one operation_started \
event even though its contributor was dropped; got {events:?}"
);
let spans = format!("{:?}", matching.first().and_then(|v| v.get("spans")));
assert!(
spans.contains("contributor-span"),
"the event must carry the originating contributor's span context, \
got spans: {spans}"
);
emitted = true;
break;
}
assert!(
emitted,
"no attempt emitted operation_started for the dropped contributor's \
persisted update — telemetry for a persisted transition was lost"
);
}
/// A client whose second (and any later) `checkpoint` call fails,
/// delegating the first to an [`InMemoryExecutionClient`]. Lets tests
/// persist an early batch chunk and then fail a later one.
#[derive(Debug)]
struct FailSecondCallClient {
inner: InMemoryExecutionClient,
calls: std::sync::Mutex<u32>,
}
impl FailSecondCallClient {
fn new() -> Self {
Self {
inner: InMemoryExecutionClient::new(Vec::new()),
calls: std::sync::Mutex::new(0),
}
}
}
impl ExecutionClient for FailSecondCallClient {
fn checkpoint(
&self,
execution_arn: &str,
checkpoint_token: &str,
updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
let arn = execution_arn.to_owned();
let token = checkpoint_token.to_owned();
Box::pin(async move {
let call_index = {
let mut calls = self
.calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*calls += 1;
*calls
};
if call_index >= 2 {
return Err(ExecutionClientError::new_non_retryable(
"injected failure on the second chunk",
));
}
self.inner.checkpoint(&arn, &token, updates).await
})
}
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.inner
.get_state(execution_arn, checkpoint_token, marker)
}
}
/// REGRESSION (event ownership, split batch): when a sealed batch splits
/// into several requests and an earlier request persists before a later
/// one fails, the persisted chunk's events must be emitted: the failure,
/// which leaves every contributor unresolved, must not suppress
/// telemetry for transitions the service actually recorded.
///
/// Retries for the same reason as
/// [`dropped_buffered_contributor_still_emits_events_for_persisted_updates`]:
/// concurrent tests rebuilding `tracing`'s global caches can race a
/// `DEBUG` emission. Hard invariants assert on every attempt.
#[tokio::test(start_paused = true)]
async fn split_batch_emits_events_for_chunks_persisted_before_a_failure() {
use crate::observability::event_names;
let mut emitted = false;
for _attempt in 0..5 {
let (buffer, _guard) = lifecycle_capture();
let client = Arc::new(FailSecondCallClient::new());
let limits = BatchLimits {
max_operations: 1,
max_payload_bytes: usize::MAX,
};
let ctx = DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
CheckpointCoalescer::with_limits(Duration::from_millis(50), limits),
);
// Two contributors share one batch; the one-op cap splits it
// into two requests. The first persists, the second fails.
let first = ctx.submit_checkpoint_updates(vec![make_update("op-persisted")]);
let second = ctx.submit_checkpoint_updates(vec![make_update("op-rejected")]);
until_write_failed(&ctx).await;
let fatal = ctx.coordinator().write_failure().expect("latched");
assert_eq!(
fatal.error_type,
crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE
);
let both = async { tokio::join!(first, second) };
assert!(
tokio::time::timeout(Duration::from_secs(5), both)
.await
.is_err(),
"no contributor resolves"
);
let ids: Vec<String> = client
.inner
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect();
assert_eq!(
ids,
vec!["op-persisted".to_owned()],
"exactly the first chunk was persisted"
);
let events = captured_lifecycle_events(&buffer, event_names::OPERATION_STARTED);
if events.is_empty() {
// A concurrent subscriber rebuild dropped the event before
// it reached this test's subscriber; retry the scenario.
continue;
}
let persisted: Vec<&serde_json::Value> = events
.iter()
.filter(|v| {
v.get(crate::tracing_layer::fields::OPERATION_ID)
.and_then(serde_json::Value::as_str)
== Some("op-persisted")
})
.collect();
assert_eq!(
persisted.len(),
1,
"the persisted chunk must emit its operation_started event \
despite the later chunk's failure; got {events:?}"
);
assert!(
!events.iter().any(|v| {
v.get(crate::tracing_layer::fields::OPERATION_ID)
.and_then(serde_json::Value::as_str)
== Some("op-rejected")
}),
"the rejected chunk recorded nothing, so it must emit nothing; \
got {events:?}"
);
emitted = true;
break;
}
assert!(
emitted,
"no attempt emitted operation_started for the persisted chunk — \
telemetry for a persisted transition was lost"
);
}
/// REGRESSION (event ownership, failed pagination hydration): the
/// checkpoint call can persist the transitions and *then* fail while
/// hydrating paginated state through `get_state`. The persisted
/// transitions' events must already be emitted by then, emission
/// happens immediately after the service accepts the write, before the
/// fallible pagination fetch, even though the write fails.
///
/// Retries for the same reason as
/// [`dropped_buffered_contributor_still_emits_events_for_persisted_updates`]:
/// concurrent tests rebuilding `tracing`'s global caches can race a
/// `DEBUG` emission. Hard invariants assert on every attempt.
#[tokio::test]
async fn persisted_checkpoint_emits_events_when_pagination_hydration_fails() {
use crate::observability::event_names;
let mut emitted = false;
for _attempt in 0..5 {
let (buffer, _guard) = lifecycle_capture();
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
// The write itself succeeds but signals more pages, and the
// follow-up get_state fetch fails.
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
Vec::new(),
"page-2-token".to_owned(),
));
client.fail_get_state("injected get_state failure");
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
);
let write = ctx.submit_checkpoint_updates(vec![make_update("op-hydration")]);
until_write_failed(&ctx).await;
let fatal = ctx.coordinator().write_failure().expect("latched");
assert_eq!(
fatal.error_type,
crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE
);
assert!(
tokio::time::timeout(Duration::from_millis(100), write)
.await
.is_err(),
"the write's caller never resolves"
);
let ids: Vec<String> = client
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect();
assert_eq!(
ids,
vec!["op-hydration".to_owned()],
"the transition was persisted before get_state failed"
);
let events = captured_lifecycle_events(&buffer, event_names::OPERATION_STARTED);
if events.is_empty() {
// A concurrent subscriber rebuild dropped the event before
// it reached this test's subscriber; retry the scenario.
continue;
}
let matching: Vec<&serde_json::Value> = events
.iter()
.filter(|v| {
v.get(crate::tracing_layer::fields::OPERATION_ID)
.and_then(serde_json::Value::as_str)
== Some("op-hydration")
})
.collect();
assert_eq!(
matching.len(),
1,
"the persisted transition must emit exactly one operation_started \
event even though pagination hydration failed; got {events:?}"
);
emitted = true;
break;
}
assert!(
emitted,
"no attempt emitted operation_started for the persisted transition — \
telemetry was suppressed by a failed pagination fetch"
);
}
/// Waits, for at most five seconds, until a write of `ctx` failed.
async fn until_write_failed(ctx: &DurableContext) {
tokio::time::timeout(Duration::from_secs(5), async {
while !ctx.coordinator().write_failed() {
tokio::time::sleep(Duration::from_millis(1)).await;
}
})
.await
.expect("a write failed");
}
// Checkpoint admission tests (abandoned owners).
/// The bound on every await in the admission tests. A rejected write
/// never resolves, so these awaits time out.
const ADMISSION_BOUND: Duration = Duration::from_secs(1);
/// A root context with batching on (`Some(Duration::ZERO)`), a
/// coalescing delay, or no buffering (`None`).
fn admission_root(
client: &Arc<InMemoryExecutionClient>,
window: Option<Duration>,
) -> DurableContext {
DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
window,
0,
None,
)
}
/// The wire IDs the client recorded, in order.
fn recorded_ids(client: &InMemoryExecutionClient) -> Vec<String> {
client
.recorded_updates()
.iter()
.map(|u| u.id.clone())
.collect()
}
/// Writes `id` from `item` after abandoning it, and asserts that the
/// write never resolves and that nothing is recorded.
async fn assert_abandoned_write_not_sent(window: Option<Duration>) {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, window);
let item = root.new_child("1", None);
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let written = tokio::time::timeout(
ADMISSION_BOUND,
item.checkpoint_updates(vec![make_update("u")]),
)
.await;
assert!(written.is_err(), "a rejected write never resolves");
assert!(client.recorded_updates().is_empty(), "nothing is sent");
}
#[tokio::test]
async fn abandoned_owner_update_is_not_sent_buffered() {
assert_abandoned_write_not_sent(Some(Duration::ZERO)).await;
}
#[tokio::test]
async fn abandoned_owner_update_is_not_sent_direct() {
assert_abandoned_write_not_sent(None).await;
}
#[tokio::test]
async fn abandoned_owner_direct_write_is_rejected() {
// Batching is on, but `checkpoint_updates_direct` skips the buffer.
// So this rejection comes from the check under the token lock.
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::ZERO));
let item = root.new_child("1", None);
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let written = tokio::time::timeout(
ADMISSION_BOUND,
item.checkpoint_updates_direct(vec![make_update("u")]),
)
.await;
assert!(written.is_err(), "a rejected direct write never resolves");
assert!(client.recorded_updates().is_empty(), "nothing is sent");
}
#[tokio::test]
async fn nested_owner_follows_its_outer_item() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::ZERO));
let item = root.new_child("1", None);
let inner = item.new_child("1-1", None);
assert_eq!(
inner.owners(),
[
crate::engine::compute_wire_id_public("1"),
crate::engine::compute_wire_id_public("1-1"),
],
"a nested context runs in its outer item, outermost first"
);
root.admission()
.abandon([crate::engine::compute_wire_id_public("1").as_str()]);
let written = tokio::time::timeout(
ADMISSION_BOUND,
inner.checkpoint_updates(vec![make_update("u")]),
)
.await;
assert!(written.is_err(), "the nested write never resolves");
assert!(client.recorded_updates().is_empty(), "nothing is sent");
}
#[tokio::test(start_paused = true)]
async fn admitted_update_precedes_parent_final_update() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::from_millis(50)));
let item = root.new_child("1", None);
let writer = tokio::spawn({
let item = item.clone();
async move { item.checkpoint_updates(vec![make_update("a")]).await }
});
// Yield until `a` is buffered. The delay window holds it there, so
// it is admitted but not yet sent when the item is abandoned.
let coalescer = Arc::clone(root.inner.coalescer.as_ref().expect("buffering is on"));
let mut yields = 0;
while coalescer.pending_len() == 0 {
assert!(yields < 1_000, "the item update was never buffered");
yields += 1;
tokio::task::yield_now().await;
}
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let parent = tokio::spawn({
let root = root.clone();
async move { root.checkpoint_updates(vec![make_update("p")]).await }
});
tokio::time::advance(Duration::from_millis(100)).await;
tokio::time::timeout(ADMISSION_BOUND, writer)
.await
.expect("the admitted write resolves")
.expect("the writer task completes")
.expect("the admitted write succeeds");
tokio::time::timeout(ADMISSION_BOUND, parent)
.await
.expect("the parent write resolves")
.expect("the parent task completes")
.expect("the parent write succeeds");
assert_eq!(
recorded_ids(&client),
["a", "p"],
"the admitted item update reaches the service before the parent's"
);
}
/// A client that holds its first checkpoint call until the test opens a
/// gate, and records the token and the update IDs of every call. Call
/// `n` returns the token `token-n`.
#[derive(Debug, Default)]
struct TokenGateClient {
entered: tokio::sync::Notify,
gate: tokio::sync::Notify,
calls: std::sync::Mutex<Vec<(String, Vec<String>)>>,
}
impl TokenGateClient {
fn calls(&self) -> Vec<(String, Vec<String>)> {
self.calls.lock().unwrap().clone()
}
}
impl ExecutionClient for TokenGateClient {
fn checkpoint(
&self,
_arn: &str,
token: &str,
updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
let token = token.to_owned();
Box::pin(async move {
let n = {
let mut calls = self.calls.lock().unwrap();
calls.push((token, updates.iter().map(|u| u.id.clone()).collect()));
calls.len()
};
if n == 1 {
self.entered.notify_one();
self.gate.notified().await;
}
Ok(CheckpointOutput {
checkpoint_token: Some(format!("token-{n}")),
updated_operations: Vec::new(),
next_marker: None,
})
})
}
fn get_state(
&self,
_arn: &str,
_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
Ok(GetStateOutput {
operations: Vec::new(),
next_marker: None,
})
})
}
}
#[tokio::test]
async fn admitted_direct_write_survives_cancelled_caller() {
let client = Arc::new(TokenGateClient::default());
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
None,
0,
None,
);
let item = root.new_child("1", None);
let entered = client.entered.notified();
let writer = tokio::spawn({
let item = item.clone();
async move { item.checkpoint_updates(vec![make_update("a")]).await }
});
tokio::time::timeout(ADMISSION_BOUND, entered)
.await
.expect("the client holds the item's write");
writer.abort();
assert!(
writer
.await
.expect_err("the caller was aborted")
.is_cancelled(),
"the caller is cancelled while its write is in flight"
);
client.gate.notify_one();
tokio::time::timeout(
ADMISSION_BOUND,
root.checkpoint_updates(vec![make_update("p")]),
)
.await
.expect("the parent write resolves")
.expect("the parent write succeeds");
assert_eq!(
client.calls(),
[
("token-0".to_owned(), vec!["a".to_owned()]),
("token-1".to_owned(), vec!["p".to_owned()]),
],
"the cancelled caller's write completed and rotated the token"
);
}
#[tokio::test]
async fn abandoned_owner_starts_no_operation() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::ZERO));
let item = root.new_child("1", None);
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flag = Arc::clone(&ran);
let stepped = tokio::time::timeout(
ADMISSION_BOUND,
item.step(move |_| async move {
flag.store(true, std::sync::atomic::Ordering::SeqCst);
Ok(1_u32)
})
.into_future(),
)
.await;
assert!(stepped.is_err(), "the operation never resolves");
assert!(
!ran.load(std::sync::atomic::Ordering::SeqCst),
"the step body never ran"
);
assert!(
client.recorded_updates().is_empty(),
"no update is recorded"
);
}
/// An abandoned owner does not even replay a recorded operation, which
/// writes nothing: the builder future is never polled past the check.
#[tokio::test]
async fn abandoned_owner_replays_no_operation() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let wire = crate::engine::compute_wire_id_public("1-1");
let record = CheckpointRecord {
id: wire.clone(),
status: CheckpointStatus::Succeeded,
result: Some("7".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 log = CheckpointLog::from_records(vec![(wire, record)]);
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(log),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
Some(Duration::ZERO),
0,
None,
);
let item = root.new_child("1", None);
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let stepped = tokio::time::timeout(
ADMISSION_BOUND,
item.step(|_| async { Ok(0_u32) }).into_future(),
)
.await;
assert!(
stepped.is_err(),
"the recorded step is not replayed for an abandoned owner: {stepped:?}"
);
}
/// A builder created before its owner is abandoned, and finalized after,
/// is not checked against a contradicting record. The record says the
/// operation was a wait, and the builder claims a step. For an owner that
/// is not abandoned, the same claim records a fatal error and resolves.
/// For the abandoned owner, nothing is recorded, nothing is written, and
/// the future never resolves.
#[tokio::test]
async fn abandoned_owner_skips_replay_preflight() {
let wait_record = |positional: &str| {
let wire = crate::engine::compute_wire_id_public(positional);
let record = CheckpointRecord {
id: wire.clone(),
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: Some("Wait".to_owned()),
sub_type: Some("Wait".to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
(wire, record)
};
let build_root = || {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let log = CheckpointLog::from_records(vec![wait_record("1-1")]);
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(log),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
Some(Duration::ZERO),
0,
None,
);
(client, root)
};
// Control: an owner that is not abandoned records the mismatch.
let (_, control_root) = build_root();
let control_item = control_root.new_child("1", None);
let control = tokio::time::timeout(
ADMISSION_BOUND,
control_item.step(|_| async { Ok(0_u32) }).into_future(),
)
.await
.expect("the mismatch resolves at once");
assert!(control.is_err(), "the mismatch is an error: {control:?}");
assert!(
control_item.coordinator().fatal_error().is_some(),
"the mismatch records a fatal error"
);
// The builder exists before the abandonment and is finalized after it.
let (client, root) = build_root();
let item = root.new_child("1", None);
let builder = item.step(|_| async { Ok(0_u32) });
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let stepped = tokio::time::timeout(ADMISSION_BOUND, builder.into_future()).await;
assert!(
stepped.is_err(),
"the abandoned owner's future never resolves: {stepped:?}"
);
assert!(
item.coordinator().fatal_error().is_none(),
"no fatal error is recorded for the abandoned owner"
);
assert!(
root.coordinator().fatal_error().is_none(),
"no fatal error reaches the root"
);
assert!(client.recorded_updates().is_empty(), "nothing is written");
}
/// An abandoned owner does not replay a recorded callback either. The
/// recorded `Started` callback resolves without a write, so only the
/// admission check at the terminal can hold it back.
#[tokio::test]
async fn abandoned_owner_replays_no_callback() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let wire = crate::engine::compute_wire_id_public("1-1");
let record = CheckpointRecord {
id: wire.clone(),
status: CheckpointStatus::Started,
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: Some("cb-1".to_owned()),
op_type: None,
sub_type: None,
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let log = Arc::new(CheckpointLog::from_records(vec![(wire, record)]));
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::clone(&log),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
Some(Duration::ZERO),
0,
None,
);
// The control: an owner that is not abandoned replays the callback.
let control = root.new_child("1", None);
let replayed = tokio::time::timeout(
ADMISSION_BOUND,
control.create_callback::<String>().into_future(),
)
.await
.expect("the recorded callback replays")
.expect("the replay succeeds");
assert_eq!(replayed.id(), "cb-1");
let item = root.new_child("1", None);
root.admission()
.abandon(item.owners().iter().map(String::as_str));
let created = tokio::time::timeout(
ADMISSION_BOUND,
item.create_callback::<String>().into_future(),
)
.await;
assert!(
created.is_err(),
"the recorded callback is not replayed for an abandoned owner"
);
assert!(client.recorded_updates().is_empty(), "nothing is sent");
}
#[tokio::test]
async fn admitted_owner_writes_as_before() {
for window in [Some(Duration::ZERO), None] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, window);
let item = root.new_child("1", None);
tokio::time::timeout(
ADMISSION_BOUND,
item.checkpoint_updates(vec![make_update("u")]),
)
.await
.expect("the write resolves")
.expect("the write succeeds");
assert_eq!(recorded_ids(&client), ["u"], "window {window:?}");
}
}
/// Without a Tokio runtime a direct write cannot start its task. The
/// caller gets the no-runtime error at once, and nothing is sent.
#[test]
fn direct_write_without_runtime_returns_invocation_error() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = admission_root(&client, None);
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
ctx.checkpoint_updates(vec![make_update("u")]).await
});
let std::task::Poll::Ready(Err(err)) = polled else {
unreachable!("expected an immediate error, got {polled:?}");
};
assert_eq!(err.scope(), ExecutionClientErrorScope::Invocation);
assert!(
err.to_string().contains(crate::task::NO_RUNTIME_MESSAGE),
"unexpected error: {err}"
);
assert!(
std::error::Error::source(&err)
.is_some_and(<dyn std::error::Error>::is::<crate::task::NoRuntime>),
"the error carries the no-runtime marker"
);
assert!(client.recorded_updates().is_empty(), "nothing is sent");
}
/// An operation whose direct write finds no Tokio runtime returns the
/// error `.spawn()` returns without a runtime, at once. Nothing is
/// sent, and no invocation fault is recorded.
#[test]
fn operation_without_runtime_returns_spawn_error() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let thread_client = Arc::clone(&client);
// The context is built on the polling thread, so that thread owns it.
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
let ctx = admission_root(&thread_client, None);
let signal = Arc::clone(ctx.coordinator());
(
ctx.step(|_| async { Ok(1_u32) }).into_future().await,
signal,
)
});
let std::task::Poll::Ready((Err(err), signal)) = polled else {
unreachable!("expected an immediate error, got {polled:?}");
};
let spawn_error = crate::task::NoRuntime::operation_error(crate::task::NoRuntime);
assert_eq!(format!("{err:#}"), format!("{spawn_error:#}"));
assert!(client.recorded_updates().is_empty(), "nothing is sent");
assert!(signal.fatal_error().is_none(), "no fault is recorded");
}
/// An operation whose buffered write finds no Tokio runtime returns
/// the error `.spawn()` returns without a runtime, at once: the batch
/// flusher cannot be spawned. Nothing is sent, and no fatal error is
/// recorded.
#[test]
fn buffered_write_without_runtime_returns_the_no_runtime_error() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let thread_client = Arc::clone(&client);
// The context is built on the polling thread, so that thread owns it.
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
let ctx = admission_root(&thread_client, Some(Duration::ZERO));
(ctx.step(|_| async { Ok(1_u32) }).into_future().await, ctx)
});
let std::task::Poll::Ready((Err(err), ctx)) = polled else {
unreachable!("expected an immediate error, got {polled:?}");
};
let spawn_error = crate::task::NoRuntime::operation_error(crate::task::NoRuntime);
assert_eq!(format!("{err:#}"), format!("{spawn_error:#}"));
assert!(client.recorded_updates().is_empty(), "nothing is sent");
assert!(
ctx.coordinator().fatal_error().is_none(),
"no fatal error is recorded"
);
// The failed write left the buffer, so a flush under a runtime
// sends nothing.
assert!(ctx.queued_update_ids().is_empty(), "the batch is dropped");
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(ctx.flush_pending_checkpoints());
assert!(
client.recorded_updates().is_empty(),
"the dropped batch is never sent"
);
assert!(ctx.coordinator().fatal_error().is_none());
}
/// After a failed write, a write on a thread without a Tokio runtime,
/// direct or buffered, is rejected before its writer is spawned: it
/// never resolves, and nothing is sent.
#[test]
fn write_after_failure_without_runtime_never_resolves() {
for window in [None, Some(Duration::ZERO)] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let thread_client = Arc::clone(&client);
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
let ctx = admission_root(&thread_client, window);
ctx.coordinator().fail_write(
FatalError {
error_type: "Failed".to_owned(),
error_message: "failed".to_owned(),
severity: FatalSeverity::FailExecution,
},
|| {},
);
ctx.checkpoint_updates(vec![make_update("u")]).await
});
assert!(polled.is_pending(), "window {window:?}: {polled:?}");
assert!(client.recorded_updates().is_empty(), "window {window:?}");
}
}
/// A write on a thread without a Tokio runtime, direct or buffered,
/// whose writer cannot be spawned, meets a failed write after it
/// entered its queue and before it hands out the `NoRuntime` error: the
/// thread sets the latch when it reaches that point, and the failure
/// does not drop the queue. The failure came first, so the write is
/// dropped unresolved, as the failure drops every queued write, and
/// nothing is sent.
#[test]
fn no_runtime_error_after_a_failed_write_is_not_published() {
use crate::coordinator::race_points::{self, RacePoint};
for (window, point) in [
(None, RacePoint::DirectNoRuntimeDrain),
(Some(Duration::ZERO), RacePoint::BatchNoRuntimeClaim),
] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let thread_client = Arc::clone(&client);
let fired = Arc::new(std::sync::atomic::AtomicBool::new(false));
let thread_fired = Arc::clone(&fired);
let polled = crate::task::test_support::poll_once_without_runtime(move || {
let ctx = admission_root(&thread_client, window);
let failing = ctx.clone();
race_points::set(move |reached| {
if reached == point {
thread_fired.store(true, std::sync::atomic::Ordering::SeqCst);
failing.coordinator().fail_write(
FatalError {
error_type: "Failed".to_owned(),
error_message: "failed".to_owned(),
severity: FatalSeverity::FailExecution,
},
|| {},
);
}
});
async move { ctx.checkpoint_updates(vec![make_update("u")]).await }
});
assert!(
fired.load(std::sync::atomic::Ordering::SeqCst),
"window {window:?}: the point is reached"
);
assert!(polled.is_pending(), "window {window:?}: {polled:?}");
assert!(client.recorded_updates().is_empty(), "window {window:?}");
}
}
/// A replayed `Started` child skips its START write, so its body runs
/// and its first write is the terminal `FAIL`. When that direct write
/// finds no Tokio runtime, the child returns the error `.spawn()`
/// returns without a runtime. Nothing is sent, and no invocation fault
/// is recorded.
#[test]
fn replayed_child_failure_without_runtime_returns_spawn_error() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let wire = crate::engine::compute_wire_id_public("1");
let record = CheckpointRecord {
id: wire.clone(),
status: CheckpointStatus::Started,
result: None,
error_type: None,
error_message: None,
error_data: None,
stack_trace: None,
attempt: 0,
invoke_result: None,
invoke_error_type: None,
invoke_error_message: None,
invoke_error_data: None,
invoke_stack_trace: None,
replay_children: false,
callback_id: None,
op_type: Some("Context".to_owned()),
sub_type: Some(crate::child::CHILD_SUB_TYPE.to_owned()),
due_at: None,
op_name: None,
parent_id: None,
start_timestamp: None,
end_timestamp: None,
};
let thread_client = Arc::clone(&client);
// The context is built on the polling thread, so that thread owns it.
let polled = crate::task::test_support::poll_once_without_runtime(move || async move {
let ctx = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::from_records(vec![(wire, record)])),
thread_client as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
None,
0,
None,
);
let signal = Arc::clone(ctx.coordinator());
let outcome = ctx
.run_in_child_context(|_child| async { Err::<u32, BoxError>("boom".into()) })
.into_future()
.await;
(outcome, signal)
});
let std::task::Poll::Ready((Err(err), signal)) = polled else {
unreachable!("expected an immediate error, got {polled:?}");
};
let spawn_error = crate::task::NoRuntime::operation_error(crate::task::NoRuntime);
assert_eq!(format!("{err:#}"), format!("{spawn_error:#}"));
assert!(client.recorded_updates().is_empty(), "nothing is sent");
assert!(signal.fatal_error().is_none(), "no fault is recorded");
}
/// A client whose checkpoint call panics.
#[derive(Debug)]
struct PanickingClient;
impl ExecutionClient for PanickingClient {
fn checkpoint(
&self,
_arn: &str,
_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
#[expect(clippy::panic)] // reason: the panic is the behavior under test
Box::pin(async { panic!("boom in checkpoint") })
}
fn get_state(
&self,
_arn: &str,
_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
Ok(GetStateOutput {
operations: Vec::new(),
next_marker: None,
})
})
}
}
/// Writes one update directly through `client`, and returns the
/// coordinator's kept panic after the write task stopped. The caller
/// must stay pending: the write channel carries no panic payload.
async fn direct_write_kept_panic(
client: Arc<dyn ExecutionClient>,
) -> Box<dyn std::any::Any + Send + 'static> {
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client,
"token-0".to_owned(),
None,
0,
None,
);
let coordinator = Arc::clone(root.coordinator());
let mut write = std::pin::pin!(root.checkpoint_updates(vec![make_update("u")]));
let waited = tokio::time::timeout(ADMISSION_BOUND, async {
tokio::select! {
_ = &mut write => false,
() = async {
// Wait until the write task has stopped, then poll the
// caller once more.
tokio::task::yield_now().await;
coordinator.tasks().wait_idle().await;
} => true,
}
})
.await
.expect("the write task stops");
assert!(waited, "the caller resolved");
let polled =
std::future::poll_fn(|cx| std::task::Poll::Ready(write.as_mut().poll(cx))).await;
assert!(
polled.is_pending(),
"the caller stays pending after the client panicked"
);
coordinator.take_panic().expect("the panic is kept")
}
/// An error source whose destructor panics with "source drop".
#[derive(Debug)]
struct DropPanickingSource;
impl std::fmt::Display for DropPanickingSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("drop-panicking source")
}
}
impl std::error::Error for DropPanickingSource {}
impl Drop for DropPanickingSource {
#[expect(clippy::panic)] // reason: the panic is the behavior under test
fn drop(&mut self) {
panic!("source drop");
}
}
/// A client whose checkpoint call waits for `release`, then fails with
/// an error whose source panics when dropped.
#[derive(Debug)]
struct GatedFailingClient {
release: tokio::sync::Notify,
}
impl ExecutionClient for GatedFailingClient {
fn checkpoint(
&self,
_arn: &str,
_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
self.release.notified().await;
Err(ExecutionClientError::with_source(
ExecutionClientErrorScope::Invocation,
"gated failure",
DropPanickingSource,
))
})
}
fn get_state(
&self,
_arn: &str,
_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
Ok(GetStateOutput {
operations: Vec::new(),
next_marker: None,
})
})
}
}
/// The caller of a direct write is dropped before the write returns,
/// and the write fails. The write task drops the client's error, and
/// the task gateway records the panic of its destructor on the
/// coordinator.
#[tokio::test]
async fn unread_direct_write_result_drop_panic_is_recorded() {
let client = Arc::new(GatedFailingClient {
release: tokio::sync::Notify::new(),
});
let root = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
None,
0,
None,
);
let coordinator = Arc::clone(root.coordinator());
let mut write = Box::pin(root.checkpoint_updates(vec![make_update("u")]));
let polled =
std::future::poll_fn(|cx| std::task::Poll::Ready(write.as_mut().poll(cx))).await;
assert!(polled.is_pending());
drop(write);
client.release.notify_one();
tokio::time::timeout(ADMISSION_BOUND, coordinator.tasks().wait_idle())
.await
.expect("the write task stops");
let payload = coordinator
.take_panic()
.expect("the destructor's panic is recorded");
assert_eq!(
crate::task::test_support::str_payload(payload.as_ref()),
Some("source drop")
);
}
/// A panic of the checkpoint client in a direct write's task is kept
/// by the coordinator with its original payload, and the caller stays
/// pending.
#[tokio::test]
async fn direct_write_panic_is_recorded_and_caller_stays_pending() {
let payload = direct_write_kept_panic(Arc::new(PanickingClient)).await;
assert_eq!(
crate::task::test_support::str_payload(payload.as_ref()),
Some("boom in checkpoint")
);
}
/// A checkpoint future that returns `Ready` and then panics in its
/// destructor.
struct ReadyThenDropPanic;
impl Future for ReadyThenDropPanic {
type Output = Result<CheckpointOutput, ExecutionClientError>;
fn poll(
self: std::pin::Pin<&mut Self>,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
std::task::Poll::Ready(Ok(CheckpointOutput {
checkpoint_token: Some("token-1".to_owned()),
updated_operations: Vec::new(),
next_marker: None,
}))
}
}
impl Drop for ReadyThenDropPanic {
#[expect(clippy::panic)] // reason: the panic is the behavior under test
fn drop(&mut self) {
panic!("boom in checkpoint drop");
}
}
/// A client whose checkpoint future panics in its destructor.
#[derive(Debug)]
struct DropPanickingClient;
impl ExecutionClient for DropPanickingClient {
fn checkpoint(
&self,
_arn: &str,
_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(ReadyThenDropPanic)
}
fn get_state(
&self,
_arn: &str,
_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async {
Ok(GetStateOutput {
operations: Vec::new(),
next_marker: None,
})
})
}
}
/// A panic from the destructor of a checkpoint future that returned
/// `Ready` is kept by the coordinator with its original payload, and the
/// caller of the direct write stays pending.
#[tokio::test]
async fn direct_write_drop_panic_is_recorded_and_caller_stays_pending() {
let payload = direct_write_kept_panic(Arc::new(DropPanickingClient)).await;
assert_eq!(
crate::task::test_support::str_payload(payload.as_ref()),
Some("boom in checkpoint drop")
);
}
#[tokio::test]
async fn child_context_owner_covers_its_descendants() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::ZERO));
let child = root.new_child("1", None);
root.admission()
.abandon([crate::engine::compute_wire_id_public("1").as_str()]);
let written = tokio::time::timeout(
ADMISSION_BOUND,
child.checkpoint_updates(vec![make_update("u")]),
)
.await;
assert!(written.is_err(), "the child's write never resolves");
tokio::time::timeout(
ADMISSION_BOUND,
root.checkpoint_updates(vec![make_update("p")]),
)
.await
.expect("the root write resolves")
.expect("the root write succeeds");
assert_eq!(recorded_ids(&client), ["p"], "only the root update is sent");
}
#[tokio::test]
async fn finished_child_rejects_escaped_descendant_write() {
use aws_sdk_lambda::types::OperationAction;
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = admission_root(&client, Some(Duration::ZERO));
let slot: Arc<std::sync::Mutex<Option<DurableFuture<u32>>>> =
Arc::new(std::sync::Mutex::new(None));
let release = Arc::new(tokio::sync::Notify::new());
let step_wire = crate::engine::compute_wire_id_public("1-1");
let child_wire = crate::engine::compute_wire_id_public("1");
let returned = tokio::time::timeout(ADMISSION_BOUND, {
let slot = Arc::clone(&slot);
let release = Arc::clone(&release);
let client = Arc::clone(&client);
let step_wire = step_wire.clone();
root.run_in_child_context(move |child| async move {
let handle = child
.step(move |_| async move {
release.notified().await;
Ok(7_u32)
})
.name("s")
.spawn();
*slot.lock().unwrap() = Some(handle);
let mut yields = 0;
while !client
.recorded_updates()
.iter()
.any(|u| u.id == step_wire && u.action == OperationAction::Start)
{
if yields == 1_000 {
return Err("the step START was never recorded".into());
}
yields += 1;
tokio::task::yield_now().await;
}
Ok(1_u32)
})
.into_future()
})
.await
.expect("the child returns")
.expect("the child succeeds");
assert_eq!(returned, 1);
release.notify_one();
let handle = slot
.lock()
.unwrap()
.take()
.expect("the body stored the handle");
let awaited = tokio::time::timeout(ADMISSION_BOUND, handle).await;
assert!(awaited.is_err(), "the escaped operation never resolves");
let updates = client.recorded_updates();
let has = |id: &str, action: OperationAction| {
updates.iter().any(|u| u.id == id && u.action == action)
};
assert!(
has(&step_wire, OperationAction::Start),
"s START is recorded"
);
assert!(
has(&child_wire, OperationAction::Succeed),
"the child's SUCCEED is recorded"
);
assert!(
!has(&step_wire, OperationAction::Succeed),
"s SUCCEED is never sent after the child returned"
);
}
// Tenant ID on the root and child spans.
/// Emits one record under the root span of a context built from a
/// Lambda context with `tenant_id`, and one under a child body's span,
/// and returns the span lists of the two records.
fn tenant_span_lists(
tenant_id: Option<&str>,
) -> (Vec<serde_json::Value>, Vec<serde_json::Value>) {
use crate::tracing_layer::tests::{json_records, json_span_subscriber, spans_of};
let buffer = Arc::new(std::sync::Mutex::new(Vec::new()));
let subscriber = json_span_subscriber(&buffer);
{
let _guard = test_tracing::install_test_subscriber(subscriber);
let mut lambda_context = lambda_runtime::Context::default();
lambda_context.tenant_id = tenant_id.map(str::to_owned);
let root = DurableContext::new_root(
"arn:test".to_owned(),
lambda_context,
Arc::new(CheckpointLog::empty()),
);
root.replay_span().in_scope(|| tracing::info!("in-root"));
let child = root.new_child("1", Some("child"));
child.replay_span().in_scope(|| tracing::info!("in-child"));
};
let records = json_records(&buffer);
(
spans_of(&records, "in-root"),
spans_of(&records, "in-child"),
)
}
#[test]
fn tenant_id_on_root_and_child_spans() {
use crate::tracing_layer::tests::has_field;
let tenant = serde_json::Value::String("t-1".to_owned());
let (root, child) = tenant_span_lists(Some("t-1"));
assert!(
has_field(&root, crate::tracing_layer::fields::TENANT_ID, &tenant),
"{root:?}"
);
assert!(
has_field(&child, crate::tracing_layer::fields::TENANT_ID, &tenant),
"{child:?}"
);
}
#[test]
fn no_tenant_id_without_tenant() {
use crate::tracing_layer::tests::any_field;
let (root, child) = tenant_span_lists(None);
assert!(
!any_field(&root, crate::tracing_layer::fields::TENANT_ID),
"{root:?}"
);
assert!(
!any_field(&child, crate::tracing_layer::fields::TENANT_ID),
"{child:?}"
);
// The record is still under the SDK's spans.
assert!(
any_field(&child, crate::tracing_layer::fields::OPERATION_ID),
"{child:?}"
);
}
}
#[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 coordinator_tests {
use super::{DurableContext, remaining_until};
use crate::client::ExecutionClient;
use crate::coordinator::{InvocationCoordinator, PermitKind, Phase};
use crate::driver::test_support::{ScriptedClient, operation_like};
use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};
use crate::task::test_support::{Schedule, ScheduleState};
use aws_sdk_lambda::types::{OperationAction, OperationStatus, OperationType, OperationUpdate};
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime};
fn ctx_with(log: Arc<CheckpointLog>, client: &Arc<ScriptedClient>) -> DurableContext {
DurableContext::new_root_with_client(
"arn:aws:lambda:us-east-1:1:function:test".to_owned(),
lambda_runtime::Context::default(),
log,
Arc::clone(client) as Arc<dyn ExecutionClient>,
"t0".to_owned(),
)
}
#[test]
fn remaining_time_cases() {
let now = SystemTime::now();
let now_ms = |offset: i64| {
let base = now
.duration_since(std::time::UNIX_EPOCH)
.expect("after the epoch")
.as_millis();
u64::try_from(i128::try_from(base).expect("fits") + i128::from(offset))
.expect("non-negative")
};
assert_eq!(remaining_until(0, now), None);
let ahead = remaining_until(now_ms(5_000), now).expect("a deadline");
assert!(ahead > Duration::from_secs(4) && ahead <= Duration::from_secs(5));
assert_eq!(remaining_until(now_ms(-1_000), now), Some(Duration::ZERO));
// The context reads its own Lambda deadline.
let ctx = DurableContext::test_context();
assert_eq!(ctx.remaining_time(), None, "the default deadline is 0");
}
/// A wait on a missing record starts its schedule as a `STARTED` record
/// with no end time: a first refresh after 1 s, and a backoff when the
/// refresh finds the record `STARTED`.
#[tokio::test(start_paused = true)]
async fn wait_for_record_without_record_starts_as_started() {
let ctx = DurableContext::test_context();
let coordinator = Arc::clone(ctx.coordinator());
let registered = tokio::time::Instant::now();
let wire = "missing".to_owned();
let mut wait = Box::pin(ctx.wait_for_record(&wire, |s| *s == CheckpointStatus::Succeeded));
let polled = futures_poll_once(wait.as_mut());
assert!(polled.is_pending());
assert_eq!(
coordinator.next_refresh_at(),
Some(registered + Duration::from_secs(1))
);
tokio::time::advance(Duration::from_secs(1)).await;
let crate::coordinator::DueRefresh::Due { keys, .. } =
coordinator.take_due(tokio::time::Instant::now())
else {
unreachable!("the registration is due");
};
let records =
std::collections::BTreeMap::from([(wire.clone(), (CheckpointStatus::Started, None))]);
coordinator.after_refresh(&keys, &records);
assert_eq!(
coordinator.next_refresh_at(),
Some(registered + Duration::from_secs(2)),
"an unchanged STARTED record backs off"
);
}
/// Polls `fut` once with a no-op waker.
fn futures_poll_once<F: Future + ?Sized>(
fut: std::pin::Pin<&mut F>,
) -> std::task::Poll<F::Output> {
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
fut.poll(&mut cx)
}
#[test]
fn wait_for_record_ready_before_registration() {
let wire = crate::engine::compute_wire_id_public("1");
let log = Arc::new(CheckpointLog::from_records(vec![(
wire.clone(),
CheckpointRecord::with_status(&wire, CheckpointStatus::Succeeded),
)]));
let client = Arc::new(ScriptedClient::empty());
let ctx = ctx_with(log, &client);
let coordinator = Arc::clone(ctx.coordinator());
let schedule = Schedule::idle(&coordinator);
let mut wait = Box::pin(ctx.wait_for_record(&wire, |s| *s != CheckpointStatus::Started));
assert!(schedule.poll(wait.as_mut()).is_ready());
assert_eq!(coordinator.live_waits(), 0);
assert_eq!(client.call_count(), 0);
}
/// What the readiness hook of the next test changes on its first call:
/// the log, the coordinator, and the wire ID.
type Hook = Option<(Arc<CheckpointLog>, Arc<InvocationCoordinator>, String)>;
thread_local! {
static HOOK: RefCell<Hook> = const { RefCell::new(None) };
}
/// On its first call: marks the record `SUCCEEDED`, wakes its
/// registration, as a merge between the read and the end of the poll
/// does, and returns `false`. Later calls: ready once the record left
/// `STARTED`.
fn merge_during_first_read(status: &CheckpointStatus) -> bool {
if let Some((log, coordinator, wire)) = HOOK.with(|hook| hook.borrow_mut().take()) {
log.insert(
wire.clone(),
CheckpointRecord::with_status(&wire, CheckpointStatus::Succeeded),
);
coordinator.wake_operations(&[wire]);
return false;
}
*status != CheckpointStatus::Started
}
#[test]
fn wait_for_record_merge_after_read_is_not_lost() {
let wire = crate::engine::compute_wire_id_public("1");
let log = Arc::new(CheckpointLog::from_records(vec![(
wire.clone(),
CheckpointRecord::with_status(&wire, CheckpointStatus::Started),
)]));
let client = Arc::new(ScriptedClient::empty());
let ctx = ctx_with(Arc::clone(&log), &client);
let coordinator = Arc::clone(ctx.coordinator());
HOOK.with(|hook| {
*hook.borrow_mut() = Some((Arc::clone(&log), Arc::clone(&coordinator), wire.clone()));
});
let schedule = Schedule::idle(&coordinator);
let mut wait = Box::pin(ctx.wait_for_record(&wire, merge_during_first_read));
assert!(schedule.poll(wait.as_mut()).is_pending());
assert_eq!(
schedule.state(),
ScheduleState::Queued,
"the wake during the poll keeps the task queued"
);
assert_eq!(coordinator.permits(PermitKind::Activity), 1);
assert_eq!(coordinator.phase(), Phase::Running);
assert!(schedule.poll(wait.as_mut()).is_ready());
assert_eq!(
client.call_count(),
0,
"no checkpoint call between the polls"
);
assert_eq!(coordinator.live_waits(), 0);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn direct_write_holds_token_lock_through_response_merge() {
let gate = Arc::new(tokio::sync::Notify::new());
let ctx_slot: Arc<std::sync::OnceLock<DurableContext>> =
Arc::new(std::sync::OnceLock::new());
let a_merged_at_b = Arc::new(AtomicBool::new(false));
let responder_ctx = Arc::clone(&ctx_slot);
let responder_flag = Arc::clone(&a_merged_at_b);
let client = Arc::new(
ScriptedClient::new(move |updates, history| {
if history.len() == updates.len() {
// A's call: the response carries operation `a`.
return updates
.iter()
.map(|u| {
operation_like(u, OperationStatus::Succeeded)
.build()
.expect("all required fields set")
})
.collect();
}
let merged = responder_ctx
.get()
.is_some_and(|ctx| ctx.has_checkpoint_record("1"));
responder_flag.store(merged, Ordering::SeqCst);
Vec::new()
})
.with_first_call_gate(Arc::clone(&gate)),
);
let ctx = ctx_with(Arc::new(CheckpointLog::empty()), &client);
ctx_slot.set(ctx.clone()).expect("set once");
let update = |positional: &str| {
OperationUpdate::builder()
.id(crate::engine::compute_wire_id_public(positional))
.r#type(OperationType::Step)
.sub_type("Step")
.action(OperationAction::Start)
.build()
.expect("all required fields set")
};
let a_ctx = ctx.clone();
let a_update = update("1");
let a = tokio::spawn(async move { a_ctx.checkpoint_updates_direct(vec![a_update]).await });
for _ in 0..1000 {
if client.call_count() == 1 {
break;
}
tokio::time::sleep(Duration::from_millis(1)).await;
}
assert_eq!(client.call_count(), 1, "A's call was received");
let b_ctx = ctx.clone();
let b_update = update("2");
let b = tokio::spawn(async move { b_ctx.checkpoint_updates_direct(vec![b_update]).await });
for _ in 0..100 {
tokio::task::yield_now().await;
}
assert_eq!(client.call_count(), 1, "B waits for A's merge");
gate.notify_one();
a.await.expect("A does not panic").expect("A succeeds");
b.await.expect("B does not panic").expect("B succeeds");
let calls = client.calls();
assert_eq!(calls.len(), 2);
assert_eq!(
calls.get(1).map(|(token, _)| token.as_str()),
Some("t1"),
"B's call carries the token A's response rotated in"
);
assert!(
a_merged_at_b.load(Ordering::SeqCst),
"operation a was merged before B's call was sent"
);
}
#[tokio::test]
async fn hold_activity_after_suspension_never_resolves() {
let ctx = DurableContext::test_context();
ctx.coordinator().finish();
let ran = Arc::new(AtomicBool::new(false));
let held = Arc::clone(&ran);
let waited = tokio::time::timeout(
Duration::from_millis(100),
ctx.hold_activity(async move { held.store(true, Ordering::SeqCst) }),
)
.await;
assert!(waited.is_err(), "the held future never resolves");
assert!(!ran.load(Ordering::SeqCst), "the work never ran");
}
#[tokio::test]
async fn direct_write_after_suspension_is_rejected() {
let client = Arc::new(ScriptedClient::empty());
let ctx = ctx_with(Arc::new(CheckpointLog::empty()), &client);
ctx.coordinator().finish();
let update = OperationUpdate::builder()
.id("u")
.r#type(OperationType::Step)
.action(OperationAction::Start)
.build()
.expect("all required fields set");
let written = tokio::time::timeout(
Duration::from_millis(100),
ctx.checkpoint_updates_direct(vec![update]),
)
.await;
assert!(written.is_err(), "the rejected write never resolves");
assert_eq!(client.call_count(), 0, "nothing was sent");
}
#[tokio::test]
async fn wait_for_record_after_suspension_never_resolves() {
let wire = crate::engine::compute_wire_id_public("1");
let log = Arc::new(CheckpointLog::from_records(vec![(
wire.clone(),
CheckpointRecord::with_status(&wire, CheckpointStatus::Succeeded),
)]));
let ctx = ctx_with(log, &Arc::new(ScriptedClient::empty()));
ctx.coordinator().finish();
let waited = tokio::time::timeout(
Duration::from_millis(100),
ctx.wait_for_record(&wire, |s| *s != CheckpointStatus::Started),
)
.await;
assert!(waited.is_err(), "a refused registration never resolves");
}
/// A `RETRY` update of `positional` with sub-type `sub_type`.
fn retry_update(positional: &str, sub_type: &str, payload: &str) -> OperationUpdate {
OperationUpdate::builder()
.id(crate::engine::compute_wire_id_public(positional))
.r#type(OperationType::Step)
.sub_type(sub_type)
.action(OperationAction::Retry)
.payload(payload)
.build()
.expect("all required fields set")
}
#[tokio::test]
async fn wfc_retry_keeps_status_the_response_carries() {
let wfc = crate::wait_for_condition::WFC_SUB_TYPE;
for (carried, expected) in [
(OperationStatus::Ready, CheckpointStatus::Ready),
(OperationStatus::Succeeded, CheckpointStatus::Succeeded),
(OperationStatus::Failed, CheckpointStatus::Failed),
] {
let wire = crate::engine::compute_wire_id_public("1");
let log = Arc::new(CheckpointLog::from_records(vec![(
wire.clone(),
CheckpointRecord::with_status(&wire, CheckpointStatus::Started),
)]));
let status = carried.clone();
let client = Arc::new(ScriptedClient::new(move |updates, _| {
updates
.iter()
.map(|u| {
operation_like(u, status.clone())
.build()
.expect("all required fields set")
})
.collect()
}));
let ctx = ctx_with(Arc::clone(&log), &client);
ctx.checkpoint_updates_direct(vec![retry_update("1", wfc, "1")])
.await
.expect("the write succeeds");
assert_eq!(
log.get(&wire).expect("present").status,
expected,
"a RETRY response that carries {carried:?} keeps it"
);
}
}
#[tokio::test]
async fn wfc_retry_omitted_from_response_is_pending() {
let wfc = crate::wait_for_condition::WFC_SUB_TYPE;
let ready = crate::engine::compute_wire_id_public("1");
let pending = crate::engine::compute_wire_id_public("2");
let step = crate::engine::compute_wire_id_public("3");
let succeeded = crate::engine::compute_wire_id_public("5");
let mut pending_record = CheckpointRecord::with_status(&pending, CheckpointStatus::Pending);
pending_record.result = Some("old".to_owned());
let log = Arc::new(CheckpointLog::from_records(vec![
(
ready.clone(),
CheckpointRecord::with_status(&ready, CheckpointStatus::Ready),
),
(pending.clone(), pending_record),
(
step.clone(),
CheckpointRecord::with_status(&step, CheckpointStatus::Started),
),
(
succeeded.clone(),
CheckpointRecord::with_status(&succeeded, CheckpointStatus::Started),
),
]));
let client = Arc::new(ScriptedClient::empty());
let ctx = ctx_with(Arc::clone(&log), &client);
ctx.checkpoint_updates_direct(vec![
retry_update("1", wfc, "next"),
retry_update("2", wfc, "new"),
retry_update("3", "Step", "x"),
retry_update("4", wfc, "x"),
OperationUpdate::builder()
.id(crate::engine::compute_wire_id_public("5"))
.r#type(OperationType::Step)
.sub_type(wfc)
.action(OperationAction::Succeed)
.payload("y")
.build()
.expect("all required fields set"),
])
.await
.expect("the write succeeds");
let record = log.get(&ready).expect("present");
assert_eq!(
record.status,
CheckpointStatus::Pending,
"a READY record from the previous cycle takes the PENDING the service recorded"
);
assert_eq!(record.result.as_deref(), Some("next"));
assert_eq!(
log.get(&pending).expect("present").result.as_deref(),
Some("old"),
"a record the service already marked PENDING is kept"
);
assert_eq!(
log.get(&step).expect("present").status,
CheckpointStatus::Started,
"a step RETRY is not a wait_for_condition RETRY"
);
assert_eq!(
log.get(&succeeded).expect("present").status,
CheckpointStatus::Started,
"a wait_for_condition SUCCEED is not a RETRY"
);
let missing = crate::engine::compute_wire_id_public("4");
assert!(
log.get(&missing).is_none(),
"a missing record stays missing"
);
}
}
/// The write order of unbuffered submissions and of reserved writes.
#[cfg(test)]
// The tests submit from a task on a runtime worker, which needs a spawn.
#[expect(clippy::disallowed_methods)]
mod write_order_tests {
use std::sync::Arc;
use std::time::Duration;
use aws_sdk_lambda::types::{OperationAction, OperationType, OperationUpdate};
use super::DurableContext;
use crate::client::{
CheckpointOutput, ExecutionClient, ExecutionClientError, GetStateOutput,
InMemoryExecutionClient,
};
use crate::engine::CheckpointLog;
fn start(id: &str) -> OperationUpdate {
OperationUpdate::builder()
.id(id.to_owned())
.r#type(OperationType::Step)
.action(OperationAction::Start)
.build()
.expect("all required OperationUpdate fields set")
}
/// A root context over `client`, with the coalescer `window` (`None`:
/// no coalescer, so every write is direct).
fn context(client: &Arc<InMemoryExecutionClient>, window: Option<Duration>) -> DurableContext {
DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
window,
0,
None,
)
}
fn ids(client: &InMemoryExecutionClient) -> Vec<String> {
client
.recorded_updates()
.iter()
.map(|u| u.id().to_owned())
.collect()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn unbuffered_submissions_reach_client_in_submission_order() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = context(&client, None);
tokio::spawn(async move {
let a = ctx.submit_checkpoint_updates(vec![start("A")]);
let b = ctx.submit_checkpoint_updates(vec![start("B")]);
a.await.expect("A is written");
b.await.expect("B is written");
})
.await
.expect("the submitting task completes");
assert_eq!(ids(&client), ["A", "B"]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn child_and_root_unbuffered_submissions_share_fifo() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = context(&client, None);
let hold_a = Arc::new(tokio::sync::Notify::new());
let gate_notify = Arc::clone(&hold_a);
root.set_pre_lock_gate(Arc::new(move |updates: &[OperationUpdate]| {
updates
.iter()
.any(|u| u.id() == "A")
.then(|| Arc::clone(&gate_notify))
}));
let child = root.new_child("1", None);
let a = child.submit_checkpoint_updates(vec![start("A")]);
let b = root.submit_checkpoint_updates(vec![start("B")]);
let deadline = tokio::time::Instant::now() + Duration::from_millis(500);
while tokio::time::Instant::now() < deadline {
assert!(
client.recorded_updates().is_empty(),
"a write reached the client while A was held: {:?}",
ids(&client)
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
hold_a.notify_one();
a.await.expect("A is written");
b.await.expect("B is written");
assert_eq!(ids(&client), ["A", "B"]);
}
#[tokio::test]
async fn dropping_reserved_write_releases_in_order() {
for window in [None, Some(Duration::ZERO)] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = context(&client, window);
let a = ctx.reserve_checkpoint_updates(vec![start("A")]);
let b = ctx.submit_checkpoint_updates(vec![start("B")]);
drop(a);
tokio::time::timeout(Duration::from_secs(2), b)
.await
.map_err(|_| format!("B is blocked behind the dropped A ({window:?})"))
.unwrap()
.expect("B is written");
assert_eq!(ids(&client), ["A", "B"], "{window:?}");
}
}
/// A released reservation is written in its place: before a write
/// submitted after it, and only once released.
#[tokio::test]
async fn released_reservation_is_written_before_later_submissions() {
for window in [None, Some(Duration::ZERO)] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = context(&client, window);
let a = ctx.reserve_checkpoint_updates(vec![start("A")]);
let b = ctx.submit_checkpoint_updates(vec![start("B")]);
tokio::time::sleep(Duration::from_millis(50)).await;
assert!(
client.recorded_updates().is_empty(),
"nothing is sent while A is held ({window:?})"
);
let a = a.release();
a.await.expect("A is written");
b.await.expect("B is written");
assert_eq!(ids(&client), ["A", "B"], "{window:?}");
}
}
/// A fatal record refuses a later update, and does not drop one that
/// was admitted before it: with no coalescer, a zero window and a 60 s
/// window, `A` is written and resolves, and `B` is never written and
/// never resolves.
#[tokio::test]
async fn fatal_record_keeps_admitted_writes() {
for window in [None, Some(Duration::ZERO), Some(Duration::from_secs(60))] {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = context(&client, window);
let a = ctx.submit_checkpoint_updates(vec![start("A")]);
ctx.coordinator()
.record_fatal("Error".to_owned(), "boom".to_owned());
let b = ctx.submit_checkpoint_updates(vec![start("B")]);
ctx.flush_pending_checkpoints().await;
tokio::time::timeout(Duration::from_secs(2), a)
.await
.map_err(|_| format!("A does not resolve ({window:?})"))
.unwrap()
.expect("A is written");
assert_eq!(ids(&client), ["A"], "{window:?}");
assert!(
tokio::time::timeout(Duration::from_millis(50), b)
.await
.is_err(),
"a refused write never resolves ({window:?})"
);
assert_eq!(ids(&client), ["A"], "{window:?}");
}
}
/// A reservation the admission or the coordinator rejects holds
/// nothing, sends nothing, and never resolves.
#[tokio::test]
async fn rejected_reservation_sends_nothing() {
for window in [None, Some(Duration::ZERO)] {
// The phase left `Running`: the coordinator refuses the permit.
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let ctx = context(&client, window);
ctx.coordinator().finish();
let write = ctx.reserve_checkpoint_updates(vec![start("A")]).release();
assert!(
tokio::time::timeout(Duration::from_millis(50), write)
.await
.is_err(),
"a refused reservation never resolves ({window:?})"
);
assert!(client.recorded_updates().is_empty(), "{window:?}");
}
// An abandoned owner: the batch join is rejected.
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let root = context(&client, Some(Duration::ZERO));
let child = root.new_child("1", None);
root.admission()
.abandon([crate::engine::compute_wire_id_public("1").as_str()]);
let write = child.reserve_checkpoint_updates(vec![start("A")]).release();
assert!(
tokio::time::timeout(Duration::from_millis(50), write)
.await
.is_err(),
"a rejected join never resolves"
);
assert_eq!(client.recorded_updates(), Vec::new());
}
/// A client that panics on a request carrying `A`, and records the IDs
/// of the other requests.
#[derive(Default)]
struct PanicsOnA(std::sync::Mutex<Vec<String>>);
impl ExecutionClient for PanicsOnA {
fn checkpoint(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
// The client panic under test.
assert!(!updates.iter().any(|u| u.id() == "A"), "client boom");
self.0
.lock()
.unwrap()
.extend(updates.iter().map(|u| u.id().to_owned()));
Box::pin(async {
Ok(CheckpointOutput::new(
Some("t".to_owned()),
Vec::new(),
None,
))
})
}
fn get_state(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async { Ok(GetStateOutput::new(Vec::new(), None)) })
}
}
/// A checkpoint client panic unwinds the direct writer. The next write
/// starts a new writer, so it is still sent.
#[tokio::test]
async fn write_after_writer_panic_starts_a_new_writer() {
let client = Arc::new(PanicsOnA::default());
let ctx = DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"token-0".to_owned(),
);
let a = ctx.submit_checkpoint_updates(vec![start("A")]);
assert!(
tokio::time::timeout(Duration::from_millis(50), a)
.await
.is_err(),
"the panicked write never resolves"
);
assert!(
ctx.coordinator().has_panic(),
"the gateway recorded the panic"
);
let b = ctx.submit_checkpoint_updates(vec![start("B")]);
tokio::time::timeout(Duration::from_secs(2), b)
.await
.expect("a new writer sends B")
.expect("B is written");
assert_eq!(*client.0.lock().unwrap(), ["B"]);
}
}
/// The context usage error for an operation claimed, spawned or executed on
/// a task or thread that does not own the context.
pub(crate) fn foreign_caller_message(method: &str) -> String {
format!(
"context usage error in \"{method}\": the operation was called on a task or thread \
that does not own the context. Start concurrent operations with .spawn(), map, \
parallel or a combinator, not with tokio::spawn or std::thread::spawn."
)
}
/// Tests of the change sets the write path queues for
/// `on_operation_change`, and of the points that deliver them.
#[cfg(test)]
mod change_hook_tests {
use super::{CheckpointCoalescer, DurableContext};
use crate::OperationStatus;
use crate::client::{ExecutionClient, InMemoryExecutionClient, TestResponse};
use crate::driver::test_support::{
RefreshClient, ScriptedClient, drive_handler, named, operation_like,
};
use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};
use crate::plugin::test_support::Changes;
use crate::plugin::{InvocationPlugins, OperationInfo, PluginFactory};
use aws_sdk_lambda::types::{
Operation, OperationAction, OperationStatus as WireStatus, OperationType, OperationUpdate,
};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
/// A root context on `client` over `log`, with `plugins`.
fn ctx_on(
client: Arc<dyn ExecutionClient>,
log: Arc<CheckpointLog>,
window: Option<Duration>,
plugins: Arc<InvocationPlugins>,
) -> DurableContext {
DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
client,
"t0".to_owned(),
window,
0,
Some(plugins),
)
}
/// A client whose response carries each update's operation, with the
/// status its action records.
fn echo_client() -> Arc<ScriptedClient> {
Arc::new(ScriptedClient::new(|updates, _history| {
updates
.iter()
.map(|u| {
let status = match u.action() {
OperationAction::Succeed => WireStatus::Succeeded,
OperationAction::Fail => WireStatus::Failed,
OperationAction::Retry => WireStatus::Pending,
_ => WireStatus::Started,
};
operation_like(u, status).build().expect("all fields set")
})
.collect()
}))
}
/// A step operation `id` with `status`.
fn step_op(id: &str, status: WireStatus) -> Operation {
Operation::builder()
.id(id)
.r#type(OperationType::Step)
.status(status)
.start_timestamp(aws_smithy_types::DateTime::from_secs(0))
.build()
.expect("all fields set")
}
/// A step `START` update of `id`.
fn start(id: &str) -> OperationUpdate {
OperationUpdate::builder()
.id(id)
.r#type(OperationType::Step)
.action(OperationAction::Start)
.build()
.expect("all fields set")
}
/// The change hook runs with the token mutex and the coalescer's writer
/// lock free, with and without batching.
#[tokio::test]
async fn change_hook_runs_outside_locks() {
type Locks = (
Arc<tokio::sync::Mutex<String>>,
Option<Arc<CheckpointCoalescer>>,
);
for window in [None, Some(Duration::ZERO)] {
let locks: Arc<OnceLock<Locks>> = Arc::default();
let free: Arc<Mutex<Vec<(bool, bool)>>> = Arc::default();
let mut recorder = Changes::default();
{
let locks = Arc::clone(&locks);
let free = Arc::clone(&free);
recorder.on_change = Some(Arc::new(move |_info| {
let (token, coalescer) = locks.get().expect("set before the run");
let token_free = token.try_lock().is_ok();
let writer_free = coalescer
.as_ref()
.is_none_or(|c| c.writer_lock().try_lock().is_ok());
free.lock().unwrap().push((token_free, writer_free));
}));
}
let ctx = ctx_on(
echo_client(),
Arc::new(CheckpointLog::empty()),
window,
recorder.plugins(),
);
locks
.set((ctx.checkpoint_token_mutex(), ctx.inner.coalescer.clone()))
.map_err(|_| "set twice")
.expect("set once");
drive_handler(ctx, None, |ctx| async move {
ctx.step(|_| async { Ok(1_u32) })
.name("s")
.await
.map(|v| v.to_string())
.map_err(|e| crate::error::WireError::new(None::<String>, Some(e.to_string())))
})
.await
.expect("no panic");
let free = free.lock().unwrap().clone();
assert!(!free.is_empty(), "window {window:?}: at least one call");
assert!(
free.iter().all(|&(token, writer)| token && writer),
"window {window:?}: {free:?}"
);
}
}
/// The retained `START` write of a default step, which its start step
/// reserved, delivers the `STARTED` change when the step awaits it: the
/// change is reported before the step sends its `SUCCEED`, with and
/// without batching.
#[tokio::test]
async fn retained_start_write_reports_its_change() {
for window in [None, Some(Duration::ZERO)] {
let recorder = Changes::default();
let seen: Arc<Mutex<Vec<(OperationAction, usize)>>> = Arc::default();
let client = {
let calls = Arc::clone(&recorder.calls);
let seen = Arc::clone(&seen);
Arc::new(ScriptedClient::new(move |updates, _history| {
let delivered = calls.lock().unwrap().len();
updates
.iter()
.map(|u| {
seen.lock().unwrap().push((u.action().clone(), delivered));
let status = if u.action() == &OperationAction::Succeed {
WireStatus::Succeeded
} else {
WireStatus::Started
};
operation_like(u, status).build().expect("all fields set")
})
.collect()
}))
};
let ctx = ctx_on(
client,
Arc::new(CheckpointLog::empty()),
window,
recorder.plugins(),
);
drive_handler(ctx, None, |ctx| async move {
ctx.step(|_| async { Ok(1_u32) })
.name("s")
.await
.map(|v| v.to_string())
.map_err(|e| crate::error::WireError::new(None::<String>, Some(e.to_string())))
})
.await
.expect("no panic");
let seen = seen.lock().unwrap().clone();
assert_eq!(
seen,
[(OperationAction::Start, 0), (OperationAction::Succeed, 1)],
"window {window:?}: {:?}",
recorder.timeline()
);
}
}
/// A context whose plugin's first change hook, for change set
/// `earlier`, is held open on another thread, and a completed write
/// whose own change set `own` is queued behind it.
struct HeldWrite {
ctx: DurableContext,
recorder: Changes,
write: std::pin::Pin<Box<super::SubmittedWrite>>,
release: std::sync::mpsc::Sender<()>,
holder: Option<std::thread::JoinHandle<()>>,
}
impl HeldWrite {
fn start() -> Self {
Self::start_with(Ok(crate::client::CheckpointOutput::new(
None,
Vec::new(),
None,
)))
}
/// As [`Self::start`], with `result` as the write's result.
fn start_with(
result: Result<crate::client::CheckpointOutput, crate::client::ExecutionClientError>,
) -> Self {
let (entered_tx, entered_rx) = std::sync::mpsc::channel::<()>();
let (release, release_rx) = std::sync::mpsc::channel::<()>();
let release_rx = Mutex::new(release_rx);
let first = std::sync::atomic::AtomicBool::new(true);
let recorder = Changes {
on_change: Some(Arc::new(move |_info| {
if first.swap(false, std::sync::atomic::Ordering::SeqCst) {
entered_tx.send(()).unwrap();
release_rx.lock().unwrap().recv().unwrap();
}
})),
..Changes::default()
};
let ctx = ctx_on(
Arc::new(InMemoryExecutionClient::new(Vec::new())),
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
let entry = |id: &str| {
vec![OperationInfo::from_record(
id,
&CheckpointRecord::with_status(id, CheckpointStatus::Started),
)]
};
let plugins = ctx.shared_plugins().expect("the context has plugins");
plugins.push_operation_change(entry("earlier"));
let holder = {
let ctx = ctx.clone();
std::thread::spawn(move || {
ctx.plugins()
.expect("the context has plugins")
.drain_operation_changes(&ctx.inner.engine.checkpoint_log);
})
};
entered_rx.recv().unwrap();
// The write's own response queued its change set.
plugins.push_operation_change(entry("own"));
let (sender, receiver) = tokio::sync::oneshot::channel();
let write = Box::pin(super::SubmittedWrite::from_receiver(receiver).reported_by(&ctx));
assert!(sender.send(result).is_ok(), "the write is waiting");
Self {
ctx,
recorder,
write,
release,
holder: Some(holder),
}
}
/// Waits until the holder delivered both change sets and returned.
fn join_holder(&mut self) {
self.holder
.take()
.expect("the holder is joined once")
.join()
.unwrap();
}
fn waiter_count(&self) -> usize {
self.ctx
.plugins()
.expect("the context has plugins")
.delivery_waiter_count()
}
}
/// A completed write whose change set another thread is still
/// delivering, held open by an earlier change hook, returns its
/// result only after that change set was delivered. So the operation
/// that awaits it fires its next hook after its change. Repeated
/// polls keep one waker registration, and the delivery wakes the
/// registered waker by itself: the test sees the wake before it polls
/// the write again.
#[test]
fn write_waits_for_change_delivered_by_another_task() {
let mut held = HeldWrite::start();
let (signal, signals) = crate::plugin::test_support::SignalWaker::new();
let waker = std::task::Waker::from(Arc::clone(&signal));
let mut cx = std::task::Context::from_waker(&waker);
for _ in 0..100 {
assert!(
held.write.as_mut().poll(&mut cx).is_pending(),
"the write waits while its change set is undelivered"
);
}
assert_eq!(held.waiter_count(), 1);
assert_eq!(held.recorder.updated_ids(), [["earlier"]]);
assert_eq!(signal.woken(), 0);
held.release.send(()).unwrap();
signals
.recv_timeout(Duration::from_secs(30))
.expect("a delivery woke the write's waker");
held.join_holder();
match held.write.as_mut().poll(&mut cx) {
std::task::Poll::Ready(result) => result.expect("the write succeeded"),
std::task::Poll::Pending => unreachable!("the write is ready once delivered"),
};
assert_eq!(held.recorder.updated_ids(), [["earlier"], ["own"]]);
assert_eq!(held.waiter_count(), 0);
}
/// A write dropped while it waits for a delivery removes its waker
/// registration.
#[test]
fn dropped_write_removes_its_registration() {
let mut held = HeldWrite::start();
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
assert!(held.write.as_mut().poll(&mut cx).is_pending());
assert_eq!(held.waiter_count(), 1);
held.write = Box::pin(super::SubmittedWrite::rejected());
assert_eq!(held.waiter_count(), 0);
held.release.send(()).unwrap();
held.join_holder();
assert_eq!(held.recorder.updated_ids(), [["earlier"], ["own"]]);
assert_eq!(held.waiter_count(), 0);
}
/// The operations maps and change infos one run of a step and a child
/// context builds, with `plugins` or without any.
async fn change_work_of_run(plugins: Option<Arc<InvocationPlugins>>) -> (usize, usize) {
let ctx = DurableContext::new_root_with_client_and_defaults(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
echo_client(),
"t0".to_owned(),
Some(Duration::ZERO),
0,
plugins,
);
let projections = crate::engine::projections();
let infos = crate::plugin::infos_from_records();
drive_handler(ctx, None, |ctx| async move {
let one = ctx.step(|_| async { Ok(1_u32) }).name("s").await;
let two = ctx
.run_in_child_context(|child| async move {
Ok(child.step(|_| async { Ok(2_u32) }).name("inner").await?)
})
.name("c")
.await;
Ok(format!("{one:?} {two:?}"))
})
.await
.expect("no panic");
(
crate::engine::projections() - projections,
crate::plugin::infos_from_records() - infos,
)
}
/// Without a plugin, the checkpoint responses of a run build no
/// operations map and no operation info. With one, the same run builds
/// both, so the counters observe the change work.
#[tokio::test]
async fn no_plugin_builds_no_change_info() {
assert_eq!(change_work_of_run(None).await, (0, 0));
let (projected, infos) = change_work_of_run(Some(Changes::default().plugins())).await;
assert!(projected > 0, "a plugin's run projects the log");
assert!(infos > 0, "a plugin's run builds infos");
}
/// A direct write delivers its change on the caller's task once the
/// detached write task returned the result. A write whose state read
/// failed never resolves, and records the failure: a drain point
/// delivers its change.
#[tokio::test]
async fn direct_write_reports_change_on_caller() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
client.enqueue_checkpoint_response(TestResponse::Success(vec![step_op(
"d",
WireStatus::Started,
)]));
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
vec![step_op("d", WireStatus::Succeeded)],
"page-2-token".to_owned(),
));
client.fail_get_state("injected get_state failure");
let recorder = Changes::default();
let ctx = ctx_on(
client,
Arc::new(CheckpointLog::empty()),
Some(Duration::ZERO),
recorder.plugins(),
);
ctx.checkpoint_updates_direct(vec![start("d")])
.await
.expect("the write succeeds");
assert_eq!(recorder.updated_ids(), [["d"]]);
let failed = ctx.checkpoint_updates_direct(vec![start("d")]);
assert!(
tokio::time::timeout(Duration::from_millis(100), failed)
.await
.is_err(),
"the failed write never resolves"
);
assert!(ctx.coordinator().write_failed());
ctx.report_operation_changes().await;
assert_eq!(recorder.updated_ids(), [["d"], ["d"]]);
}
/// A response that changes no status queues nothing, so no call is
/// made.
#[tokio::test]
async fn unchanged_response_queues_nothing() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
client.enqueue_checkpoint_response(TestResponse::Success(vec![step_op(
"s",
WireStatus::Started,
)]));
let recorder = Changes::default();
let log = Arc::new(CheckpointLog::from_records(vec![(
"s".to_owned(),
CheckpointRecord::with_status("s", CheckpointStatus::Started),
)]));
let ctx = ctx_on(client, log, None, recorder.plugins());
ctx.checkpoint_updates(vec![start("s")])
.await
.expect("the write succeeds");
assert!(recorder.calls().is_empty(), "{:?}", recorder.updated_ids());
}
/// An `EXECUTION` operation that changes in the response and again in
/// the state pages is listed once, with its last status.
#[tokio::test]
async fn execution_listed_once_per_change_set() {
let execution = |status: WireStatus| {
Operation::builder()
.id("exec-1")
.r#type(OperationType::Execution)
.status(status)
.start_timestamp(aws_smithy_types::DateTime::from_secs(0))
.build()
.expect("all fields set")
};
let client = Arc::new(InMemoryExecutionClient::new(vec![execution(
WireStatus::Succeeded,
)]));
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
vec![execution(WireStatus::Started)],
"page-2-token".to_owned(),
));
let recorder = Changes::default();
let ctx = ctx_on(
client,
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
ctx.checkpoint_updates(Vec::new())
.await
.expect("the write succeeds");
let calls = recorder.calls();
assert_eq!(calls.len(), 1, "{:?}", recorder.updated_ids());
let info = calls.first().expect("one call");
let statuses: Vec<_> = info
.updated_operations()
.iter()
.map(OperationInfo::status)
.collect();
assert_eq!(statuses, [Some(OperationStatus::Succeeded)]);
}
/// When reading the state pages fails, the failure is recorded, and
/// the change the response merged is still reported.
#[tokio::test]
async fn change_reported_when_pagination_hydration_fails() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
vec![step_op("op-hydration", WireStatus::Started)],
"page-2-token".to_owned(),
));
client.fail_get_state("injected get_state failure");
let recorder = Changes::default();
let ctx = ctx_on(
client,
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
let write = ctx.checkpoint_updates(vec![start("op-hydration")]);
assert!(
tokio::time::timeout(Duration::from_millis(100), write)
.await
.is_err(),
"the failed write never resolves"
);
assert!(ctx.coordinator().write_failed());
ctx.report_operation_changes().await;
assert_eq!(recorder.updated_ids(), [["op-hydration"]]);
}
/// The change that completes a waiting operation, merged from a
/// refresh, is reported before the operation's end hook. Without the
/// drain when the wait returns, the sibling step's write at 3 s would
/// deliver it, after the end hook.
#[tokio::test(start_paused = true)]
async fn refresh_reports_wait_change() {
let client = Arc::new(RefreshClient::new(|req| {
if req.empty_number == 1
&& let Some(start) = named(req.history, "w", &OperationAction::Start)
{
let record = operation_like(start, WireStatus::Succeeded)
.build()
.expect("all required fields set");
return Ok(vec![record]);
}
Ok(Vec::new())
}));
let recorder = Changes::default();
let ctx = ctx_on(
Arc::clone(&client) as Arc<dyn ExecutionClient>,
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
let outcome = drive_handler(ctx, None, |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(3)).await;
Ok(1_u32)
})
.name("s")
.spawn();
let (wait, _step) = tokio::join!(wait, step);
Ok(format!("{}", wait.is_ok()))
})
.await
.expect("no panic");
assert_eq!(
outcome,
crate::driver::InvocationOutcome::Complete("true".to_owned())
);
let succeeded = recorder.calls().iter().any(|info| {
info.updated_operations()
.iter()
.any(|op| op.name() == Some("w") && op.status() == Some(OperationStatus::Succeeded))
});
assert!(succeeded, "{:?}", recorder.timeline());
let timeline = recorder.timeline();
let change = timeline
.iter()
.position(|e| e == "change:w:SUCCEEDED")
.expect("the change is recorded");
let end = timeline
.iter()
.position(|e| e == "end:w")
.expect("the end hook ran");
assert!(change < end, "{timeline:?}");
}
/// The task that sends a refresh delivers the change the refresh
/// merged when the call returns, also for an operation nobody waits
/// on. Without that drain, the change waits for the next drain point:
/// the wait's completion at the second refresh, or the sibling step's
/// write at 3 s.
#[tokio::test(start_paused = true)]
async fn refresh_sender_reports_change() {
let client = Arc::new(RefreshClient::new(|req| {
let Some(start) = named(req.history, "w", &OperationAction::Start) else {
return Ok(Vec::new());
};
let record = match req.empty_number {
1 => step_op("x", WireStatus::Succeeded),
2 => operation_like(start, WireStatus::Succeeded)
.build()
.expect("all required fields set"),
_ => return Ok(Vec::new()),
};
Ok(vec![record])
}));
let at: Arc<Mutex<Vec<Duration>>> = Arc::default();
let mut recorder = Changes::default();
{
let at = Arc::clone(&at);
let started = tokio::time::Instant::now();
recorder.on_change = Some(Arc::new(move |info| {
if info.updated_operations().iter().any(|op| op.id() == "x") {
at.lock().unwrap().push(started.elapsed());
}
}));
}
let ctx = ctx_on(
Arc::clone(&client) as Arc<dyn ExecutionClient>,
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
drive_handler(ctx, None, |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(3)).await;
Ok(1_u32)
})
.name("s")
.spawn();
let (wait, _step) = tokio::join!(wait, step);
Ok(format!("{}", wait.is_ok()))
})
.await
.expect("no panic");
let at = at.lock().unwrap().clone();
assert_eq!(at.len(), 1, "{:?}", recorder.timeline());
assert!(
at.first()
.is_some_and(|t| *t < Duration::from_millis(1_500)),
"the change of x is reported at the first refresh: {at:?}, {:?}",
client.empty_answers()
);
}
/// Runs 50 new steps over a log of 2 000 succeeded steps with the
/// given number of recording plugins, and returns the projections the
/// run made and the number of change calls the first plugin received.
async fn projections_of_run(plugin_count: usize) -> (usize, usize) {
let records = (0..2_000)
.map(|i| {
let id = format!("old-{i}");
let mut record = CheckpointRecord::with_status(&id, CheckpointStatus::Succeeded);
record.op_type = Some("STEP".to_owned());
(id, record)
})
.collect();
let recorders: Vec<Changes> = (0..plugin_count).map(|_| Changes::default()).collect();
let plugins = crate::plugin::test_support::plugins_of_all(
recorders
.iter()
.map(|r| Arc::new(r.clone()) as Arc<dyn PluginFactory>)
.collect(),
);
let ctx = ctx_on(
echo_client(),
Arc::new(CheckpointLog::from_records(records)),
None,
plugins,
);
let before = crate::engine::projections();
drive_handler(ctx, None, |ctx| async move {
for i in 0..50_u32 {
ctx.step(move |_| async move { Ok(i) })
.name(format!("new-{i}"))
.await
.map_err(|e| {
crate::error::WireError::new(None::<String>, Some(e.to_string()))
})?;
}
Ok("done".to_owned())
})
.await
.expect("no panic");
let projected = crate::engine::projections() - before;
let calls = recorders.first().expect("a plugin").calls().len();
(projected, calls)
}
/// Each change event projects the log once, whatever the number of
/// plugins.
#[tokio::test]
async fn change_hooks_project_once_per_response() {
let (one_projected, one_calls) = projections_of_run(1).await;
let (three_projected, three_calls) = projections_of_run(3).await;
assert!(one_calls > 0);
assert_eq!(one_projected, one_calls);
assert_eq!(three_projected, three_calls);
assert_eq!(one_calls, three_calls);
}
/// An `EXECUTION` operation in a response replaces the plugins' slot,
/// is listed as a change, and does not enter the log.
#[tokio::test]
async fn execution_update_replaces_slot() {
let client = Arc::new(InMemoryExecutionClient::new(Vec::new()));
let execution = Operation::builder()
.id("exec-1")
.r#type(OperationType::Execution)
.status(WireStatus::Succeeded)
.start_timestamp(aws_smithy_types::DateTime::from_secs(0))
.build()
.expect("all fields set");
client.enqueue_checkpoint_response(TestResponse::Success(vec![
execution,
step_op("s", WireStatus::Started),
]));
let recorder = Changes::default();
let factories: Vec<(&'static str, Arc<dyn PluginFactory>)> =
vec![("test::Changes", Arc::new(recorder.clone()))];
let slot = OperationInfo::execution(
"exec-1",
"EXECUTION",
&CheckpointStatus::Started,
None,
None,
None,
);
let plugins =
crate::plugin::create_plugins(&factories, slot, crate::plugin::tests_support_info)
.expect("one factory");
let log = Arc::new(CheckpointLog::empty());
let ctx = ctx_on(client, Arc::clone(&log), None, plugins);
ctx.checkpoint_updates(vec![start("s")])
.await
.expect("the write succeeds");
let calls = recorder.calls();
let info = calls.first().expect("one call");
assert_eq!(
info.operations()
.get("exec-1")
.and_then(OperationInfo::status),
Some(OperationStatus::Succeeded)
);
assert!(
info.updated_operations()
.iter()
.any(|op| op.id() == "exec-1")
);
assert!(!log.contains("exec-1"));
}
/// A paginated response and its state pages give one change set, which
/// lists each changed ID once, with the status after both merges.
#[tokio::test]
async fn paginated_response_is_one_change_set() {
let client = Arc::new(InMemoryExecutionClient::new(vec![
step_op("step-1", WireStatus::Succeeded),
step_op("step-2", WireStatus::Succeeded),
]));
client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
vec![step_op("step-1", WireStatus::Started)],
"page-2-token".to_owned(),
));
let recorder = Changes::default();
let ctx = ctx_on(
client,
Arc::new(CheckpointLog::empty()),
None,
recorder.plugins(),
);
ctx.checkpoint_updates(Vec::new())
.await
.expect("the write succeeds");
assert_eq!(recorder.updated_ids(), [["step-1", "step-2"]]);
let calls = recorder.calls();
let step_1 = calls
.first()
.and_then(|info| info.updated_operations().first())
.expect("step-1 is listed");
assert_eq!(step_1.status(), Some(OperationStatus::Succeeded));
}
}
/// Tests of the write paths after a checkpoint response without a token,
/// and after a failed checkpoint write.
#[cfg(test)]
mod withdrawal_write_tests {
use super::{CheckpointCoalescer, DurableContext, WriteError};
use crate::client::{
CheckpointOutput, ExecutionClient, ExecutionClientError, ExecutionClientErrorScope,
GetStateOutput,
};
use crate::coordinator::PermitKind;
use crate::driver::{FatalError, FatalSeverity};
use crate::engine::CheckpointLog;
use aws_sdk_lambda::types::{OperationAction, OperationType, OperationUpdate};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
/// Answers every checkpoint request without a token, and counts them.
#[derive(Default)]
struct Tokenless(AtomicUsize);
impl ExecutionClient for Tokenless {
fn checkpoint(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
self.0.fetch_add(1, Ordering::SeqCst);
Box::pin(async { Ok(CheckpointOutput::new(None, Vec::new(), None)) })
}
fn get_state(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async { Ok(GetStateOutput::new(Vec::new(), None)) })
}
}
fn update(id: &str, action: OperationAction) -> OperationUpdate {
OperationUpdate::builder()
.id(id)
.r#type(OperationType::Step)
.action(action)
.build()
.unwrap()
}
/// An unbuffered root context over `client`.
fn ctx_with(client: Arc<dyn ExecutionClient>) -> DurableContext {
DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client,
"t0".to_owned(),
)
}
fn ctx_on(client: &Arc<Tokenless>, coalescer: Option<CheckpointCoalescer>) -> DurableContext {
let client = Arc::clone(client) as Arc<dyn ExecutionClient>;
let log = Arc::new(CheckpointLog::empty());
match coalescer {
Some(coalescer) => DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
client,
"t0".to_owned(),
coalescer,
),
None => DurableContext::new_root_with_client(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
log,
client,
"t0".to_owned(),
),
}
}
/// After the latch, a request sends nothing: a write after the drive
/// returns `Withdrawn` without calling the transport.
#[tokio::test]
async fn write_after_withdrawal_sends_nothing() {
let client = Arc::new(Tokenless::default());
let ctx = ctx_on(&client, None);
let first = ctx.checkpoint_updates_after_drive(vec![update("a", OperationAction::Start)]);
assert!(matches!(first.await, Err(WriteError::Stopped)));
assert!(ctx.coordinator().withdrawn());
assert_eq!(client.0.load(Ordering::SeqCst), 1);
let second = ctx.checkpoint_updates_after_drive(vec![update("b", OperationAction::Start)]);
assert!(matches!(second.await, Err(WriteError::Stopped)));
assert_eq!(
client.0.load(Ordering::SeqCst),
1,
"the second request is not sent"
);
}
/// Fails request 1 with an execution-scoped error, answers every later
/// request with a token, and counts the requests.
#[derive(Default)]
struct FailFirst(AtomicUsize);
impl ExecutionClient for FailFirst {
fn checkpoint(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_updates: Vec<OperationUpdate>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>,
> {
let call = self.0.fetch_add(1, Ordering::SeqCst);
Box::pin(async move {
if call == 0 {
Err(ExecutionClientError::new(
ExecutionClientErrorScope::Execution,
"down",
))
} else {
Ok(CheckpointOutput::new(
Some(format!("t{call}")),
Vec::new(),
None,
))
}
})
}
fn get_state(
&self,
_execution_arn: &str,
_checkpoint_token: &str,
_marker: Option<&str>,
) -> std::pin::Pin<
Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>,
> {
Box::pin(async { Ok(GetStateOutput::new(Vec::new(), None)) })
}
}
/// Yields until `done` holds, so the direct writer runs.
async fn until(done: impl Fn() -> bool) {
for _ in 0..1000 {
if done() {
return;
}
tokio::task::yield_now().await;
}
assert!(done(), "the condition never held");
}
/// An unbuffered context over [`FailFirst`] whose first write, `a`'s
/// START, failed. Returns the failed write's unresolved future.
async fn failed_first_write() -> (DurableContext, Arc<FailFirst>, super::SubmittedWrite) {
let client = Arc::new(FailFirst::default());
let ctx = ctx_with(Arc::clone(&client) as Arc<dyn ExecutionClient>);
let write = ctx.write_direct_detached(
vec![update("a", OperationAction::Start)],
Vec::new(),
None,
None,
);
until(|| ctx.coordinator().write_failed()).await;
(ctx, client, write)
}
/// A failed write sets the latch and records its classification for
/// its first update, and its caller never resolves.
#[tokio::test(start_paused = true)]
async fn failed_write_records_and_never_resolves() {
let (ctx, client, write) = failed_first_write().await;
let fatal = ctx.coordinator().fatal_error().expect("recorded");
assert_eq!(
fatal.error_type,
crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE
);
assert_eq!(
ctx.coordinator().write_failure().map(|f| f.error_message),
Some(fatal.error_message)
);
assert!(
tokio::time::timeout(Duration::from_secs(60), write)
.await
.is_err(),
"the failed write never resolves"
);
assert_eq!(client.0.load(Ordering::SeqCst), 1);
}
/// A reserved write released after a failed write sends nothing and
/// never resolves.
#[tokio::test(start_paused = true)]
async fn reserved_write_after_failure_sends_nothing() {
let (ctx, client, _failed) = failed_first_write().await;
let reserved = ctx.reserve_checkpoint_updates(vec![update("b", OperationAction::Start)]);
let write = reserved.release();
assert!(
tokio::time::timeout(Duration::from_secs(60), write)
.await
.is_err(),
"the reserved write never resolves"
);
assert_eq!(
client.0.load(Ordering::SeqCst),
1,
"the reserved write is not sent"
);
}
/// A write after the drive, after a write failed during the drive,
/// sends nothing and returns at once.
#[tokio::test(start_paused = true)]
async fn write_after_drive_after_failure_sends_nothing() {
let (ctx, client, _failed) = failed_first_write().await;
ctx.coordinator().finish();
let written = ctx
.checkpoint_updates_after_drive(vec![update("b", OperationAction::Start)])
.await;
assert!(matches!(written, Err(WriteError::Stopped)), "{written:?}");
assert_eq!(client.0.load(Ordering::SeqCst), 1, "nothing is sent");
}
/// A write without an execution client records the failure for its
/// first update, and never resolves.
#[tokio::test(start_paused = true)]
async fn write_without_client_records_the_failure() {
let ctx = DurableContext::test_context();
let write = ctx.write_direct_detached(
vec![update("a", OperationAction::Start)],
Vec::new(),
None,
None,
);
assert!(
tokio::time::timeout(Duration::from_secs(60), write)
.await
.is_err(),
"the write never resolves"
);
let fatal = ctx.coordinator().write_failure().expect("latched");
assert_eq!(
fatal.error_type,
crate::error::CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE
);
assert!(
fatal
.error_message
.contains("no execution client configured"),
"{fatal:?}"
);
}
/// A write without an execution client records its failure under the
/// checkpoint-token lock: while another write holds the lock, nothing
/// is recorded.
#[tokio::test(start_paused = true)]
async fn write_without_client_records_under_the_token_lock() {
let ctx = DurableContext::test_context();
let held = ctx.inner.checkpoint_token.lock().await;
let write = ctx.write_direct_detached(
vec![update("a", OperationAction::Start)],
Vec::new(),
None,
None,
);
tokio::time::sleep(Duration::from_secs(60)).await;
assert!(
!ctx.coordinator().write_failed(),
"nothing is recorded while the lock is held"
);
assert!(ctx.coordinator().fatal_error().is_none());
drop(held);
until(|| ctx.coordinator().write_failed()).await;
drop(write);
}
/// A write without an execution client that reaches the lock after
/// the checkpoint token was withdrawn records nothing: the latch is
/// checked before the client.
#[tokio::test(start_paused = true)]
async fn write_without_client_after_withdrawal_records_nothing() {
let ctx = DurableContext::test_context();
ctx.coordinator().withdraw("arn:test", "req", || {});
let written = ctx
.checkpoint_direct_with_events(
vec![update("a", OperationAction::Start)],
&[],
None,
None,
)
.await;
assert!(
matches!(written, Some(Err(WriteError::Stopped))),
"{written:?}"
);
assert!(!ctx.coordinator().write_failed());
assert!(ctx.coordinator().fatal_error().is_none());
}
/// A failed write drops the entries queued behind it, a held one
/// included, and none of them is sent or resolves.
#[tokio::test(start_paused = true)]
async fn failed_write_drops_the_queued_writes() {
let client = Arc::new(FailFirst::default());
let ctx = ctx_with(Arc::clone(&client) as Arc<dyn ExecutionClient>);
let first = ctx.write_direct_detached(
vec![update("a", OperationAction::Start)],
Vec::new(),
None,
None,
);
let held = ctx.reserve_checkpoint_updates(vec![update("b", OperationAction::Start)]);
until(|| ctx.coordinator().write_failed()).await;
assert!(ctx.queued_update_ids().is_empty(), "the queue is dropped");
let second = held.release();
let both = async { tokio::join!(first, second) };
assert!(
tokio::time::timeout(Duration::from_secs(60), both)
.await
.is_err(),
"neither write resolves"
);
assert_eq!(client.0.load(Ordering::SeqCst), 1, "`b` is not sent");
}
/// A failed direct write drops the coalescer's open batch, and a later
/// join is rejected: no contributor resolves, and the end-of-invocation
/// flush sends nothing.
#[tokio::test(start_paused = true)]
async fn failed_write_drops_the_open_batch_and_rejects_later_joins() {
let client = Arc::new(FailFirst::default());
let ctx = DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"t0".to_owned(),
CheckpointCoalescer::new(Duration::from_secs(60)),
);
let buffered = ctx.submit_checkpoint_updates(vec![update("b", OperationAction::Start)]);
let failed = ctx.write_direct_detached(
vec![update("a", OperationAction::Start)],
Vec::new(),
None,
None,
);
until(|| ctx.coordinator().write_failed()).await;
assert!(
ctx.queued_update_ids().is_empty(),
"the open batch is dropped"
);
let later = ctx.submit_checkpoint_updates(vec![update("c", OperationAction::Start)]);
assert!(
ctx.queued_update_ids().is_empty(),
"the later join is rejected"
);
ctx.flush_pending_checkpoints().await;
let all = async { tokio::join!(buffered, failed, later) };
assert!(
tokio::time::timeout(Duration::from_secs(120), all)
.await
.is_err(),
"no contributor resolves"
);
assert_eq!(client.0.load(Ordering::SeqCst), 1, "nothing more is sent");
}
/// A guard the race tests hold; any value is one.
trait Held {}
impl<T> Held for T {}
/// Submits `b`'s START on one thread while the test holds the queue
/// lock `lock_queue` takes. The submitting thread signals when it
/// reaches `point`, just before it takes that lock, so it has passed
/// every check made before the lock. A write failure then sets the
/// latch, and the lock is released. The submission must see the latch
/// under the lock: nothing waits to be sent, and nothing is sent. A
/// failed write drops a submission queued before the latch (see
/// `failed_write_drops_the_queued_writes`).
fn submission_racing_a_failed_write(
coalescer: Option<CheckpointCoalescer>,
point: crate::coordinator::race_points::RacePoint,
lock_queue: fn(&DurableContext) -> Box<dyn Held + '_>,
) {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let client = Arc::new(FailFirst::default());
let ctx = {
let _entered = runtime.enter();
let client = Arc::clone(&client) as Arc<dyn ExecutionClient>;
match coalescer {
Some(coalescer) => DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
client,
"t0".to_owned(),
coalescer,
),
None => ctx_with(client),
}
};
let held = lock_queue(&ctx);
let (reached_tx, reached_rx) = std::sync::mpsc::channel();
let submitter = {
let ctx = ctx.clone();
let handle = runtime.handle().clone();
std::thread::spawn(move || {
let _entered = handle.enter();
crate::coordinator::race_points::set(move |reached| {
if reached == point {
let _ = reached_tx.send(());
}
});
drop(ctx.submit_checkpoint_updates(vec![update("b", OperationAction::Start)]));
})
};
// The submitter is past every check made before the lock, and the
// latch is not set yet.
reached_rx.recv().unwrap();
ctx.coordinator().fail_write(
FatalError {
error_type: "Failed".to_owned(),
error_message: "failed".to_owned(),
severity: FatalSeverity::FailExecution,
},
|| {},
);
drop(held);
submitter.join().unwrap();
assert!(
ctx.queued_update_ids().is_empty(),
"nothing waits to be sent"
);
assert_eq!(client.0.load(Ordering::SeqCst), 0, "nothing is sent");
}
/// A direct submission that waits at the direct queue's lock while a
/// write fails is rejected: the latch is checked under that lock.
#[test]
fn direct_submission_waiting_at_the_queue_lock_sees_the_latch() {
submission_racing_a_failed_write(
None,
crate::coordinator::race_points::RacePoint::DirectQueueLock,
|ctx| Box::new(ctx.inner.direct.lock()),
);
}
/// A buffered submission that waits at the buffer lock while a write
/// fails is rejected: its checkpoint permit is refused under that lock.
#[test]
fn buffered_submission_waiting_at_the_buffer_lock_sees_the_latch() {
submission_racing_a_failed_write(
Some(CheckpointCoalescer::new(Duration::from_secs(60))),
crate::coordinator::race_points::RacePoint::BufferLock,
|ctx| {
Box::new(
ctx.inner
.coalescer
.as_ref()
.expect("buffered")
.hold_buffer_lock(),
)
},
);
}
/// After a failed write, a join is refused its checkpoint permit, so
/// nothing joins the buffer.
#[tokio::test(start_paused = true)]
async fn join_after_a_failed_write_is_refused_its_permit() {
let client = Arc::new(FailFirst::default());
let ctx = DurableContext::new_root_with_client_and_coalescer(
"arn:test".to_owned(),
lambda_runtime::Context::default(),
Arc::new(CheckpointLog::empty()),
Arc::clone(&client) as Arc<dyn ExecutionClient>,
"t0".to_owned(),
CheckpointCoalescer::new(Duration::from_secs(60)),
);
ctx.coordinator().fail_write(
FatalError {
error_type: "Failed".to_owned(),
error_message: "failed".to_owned(),
severity: FatalSeverity::FailExecution,
},
|| {},
);
assert!(
ctx.coordinator().acquire(PermitKind::Checkpoint).is_none(),
"no checkpoint permit"
);
assert!(
ctx.coordinator().acquire(PermitKind::Activity).is_some(),
"other permits are still taken"
);
drop(ctx.submit_checkpoint_updates(vec![update("b", OperationAction::Start)]));
assert_eq!(ctx.queued_update_ids(), Vec::<String>::new());
}
/// The end-of-invocation flush stops at a withdrawn batch: its
/// contributor never resolves, and the flush reports no failure.
#[tokio::test(start_paused = true)]
async fn end_flush_stops_at_withdrawal() {
let client = Arc::new(Tokenless::default());
let ctx = ctx_on(
&client,
Some(CheckpointCoalescer::new(Duration::from_secs(60))),
);
let write = ctx.submit_checkpoint_updates(vec![update("a", OperationAction::Start)]);
ctx.flush_pending_checkpoints().await;
assert!(ctx.coordinator().withdrawn());
assert_eq!(client.0.load(Ordering::SeqCst), 1);
assert!(
tokio::time::timeout(Duration::from_secs(120), write)
.await
.is_err(),
"the contributor never resolves"
);
assert_eq!(
client.0.load(Ordering::SeqCst),
1,
"the window flush sends nothing"
);
}
}