aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
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
//! The checkpoint transport: the trait the SDK calls to checkpoint
//! operation updates and read execution state, its error type, and the
//! default transport backed by `aws-sdk-lambda`.

use std::pin::Pin;
use std::sync::Arc;
#[cfg(test)]
use std::sync::Mutex;

use aws_sdk_lambda::types::{Operation, OperationType, OperationUpdate};

use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus};

/// The recovery scope of an [`ExecutionClientError`].
///
/// The scope decides what the SDK does with a transport failure. See the
/// [`ExecutionClient`] contract for each case.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExecutionClientErrorScope {
    /// The invocation fails; the service re-invokes and replay resumes.
    Invocation,
    /// The execution fails.
    Execution,
}

/// The terminal outcome a transport returns: a scope, a message and,
/// when the transport has one, the error that caused it.
///
/// [`source()`](std::error::Error::source) returns the error passed to
/// [`with_source`](Self::with_source).
///
/// A transport puts the detail a log needs into the message. The built-in
/// [`LambdaExecutionClient`] keeps the full `DisplayErrorContext` text of
/// the AWS SDK error in the message, and passes the final `SdkError` as the
/// source.
///
/// The name of this type is not a wire `ErrorType`, and its `Display` text
/// is not a wire `ErrorMessage`. An [`Execution`](ExecutionClientErrorScope::Execution)-scoped
/// error that ends the bootstrap state read records the AWS error code when
/// the Lambda transport supplied it, and `DurableExecutionClientError`
/// otherwise. A recorded message is the AWS error's message when the Lambda
/// transport supplied one, and the message passed to [`new`](Self::new) or
/// [`with_source`](Self::with_source) otherwise.
///
/// `Clone` because a coalesced checkpoint batch publishes one result to
/// every operation that contributed updates to it. The source is held in an
/// `Arc` for that reason.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExecutionClientError {
    scope: ExecutionClientErrorScope,
    message: String,
    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
}

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

impl std::error::Error for ExecutionClientError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source
            .as_deref()
            .map(|s| s as &(dyn std::error::Error + 'static))
    }
}

impl ExecutionClientError {
    /// Creates an error with the given scope and message, and no source.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::{ExecutionClientError, ExecutionClientErrorScope};
    ///
    /// let err = ExecutionClientError::new(ExecutionClientErrorScope::Execution, "rejected");
    /// assert_eq!(err.scope(), ExecutionClientErrorScope::Execution);
    /// assert_eq!(err.to_string(), "durable: client: rejected");
    /// ```
    #[must_use]
    pub fn new(scope: ExecutionClientErrorScope, message: impl Into<String>) -> Self {
        Self {
            scope,
            message: message.into(),
            source: None,
        }
    }

    /// Creates an error with the given scope and message, keeping `source`
    /// as the error that caused it.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::error::Error as _;
    /// use aws_durable_execution_sdk::{ExecutionClientError, ExecutionClientErrorScope};
    ///
    /// let cause = std::io::Error::other("connection reset");
    /// let err = ExecutionClientError::with_source(
    ///     ExecutionClientErrorScope::Invocation,
    ///     "checkpoint failed",
    ///     cause,
    /// );
    /// assert!(err.source().is_some());
    /// ```
    #[must_use]
    pub fn with_source(
        scope: ExecutionClientErrorScope,
        message: impl Into<String>,
        source: impl Into<crate::BoxError>,
    ) -> Self {
        Self {
            scope,
            message: message.into(),
            source: Some(Arc::from(source.into())),
        }
    }

    /// The recovery scope of this error.
    pub fn scope(&self) -> ExecutionClientErrorScope {
        self.scope
    }

    /// Whether this error fails only the invocation: `true` exactly for
    /// [`ExecutionClientErrorScope::Invocation`]. `false` means a permanent
    /// rejection, which fails the execution.
    pub(crate) fn is_retryable(&self) -> bool {
        self.scope == ExecutionClientErrorScope::Invocation
    }

    /// The error's message, without the `durable: client: ` prefix that
    /// `Display` adds.
    pub(crate) fn message(&self) -> &str {
        &self.message
    }

    /// Creates a non-retryable error from an owned message. Only test
    /// doubles call it: the Lambda transport builds every error with a
    /// source.
    #[cfg(test)]
    pub(crate) fn non_retryable(message: String) -> Self {
        Self::new(ExecutionClientErrorScope::Execution, message)
    }

    /// Creates a non-retryable error from a string slice (convenience).
    pub(crate) fn new_non_retryable(message: &str) -> Self {
        Self::new(ExecutionClientErrorScope::Execution, message)
    }

    /// Creates an `Invocation`-scoped error from an owned message. Only
    /// test doubles call it: the Lambda transport builds every error with a
    /// source.
    #[cfg(any(test, feature = "test-util"))]
    pub(crate) fn from_retryable(message: String) -> Self {
        Self::new(ExecutionClientErrorScope::Invocation, message)
    }
}

/// The message the SDK records for a transport error: the service's
/// message when the Lambda transport supplied an AWS error, and the
/// transport's own message otherwise.
///
/// It reads, in this order:
///
/// 1. The `message()` of the AWS error, when the source is the final
///    `SdkError` of `CheckpointDurableExecution` or
///    `GetDurableExecutionState` and that error has a message. JS reads
///    `awsError.message` the same way.
/// 2. Otherwise [`ExecutionClientError::message`], without the
///    `durable: client: ` prefix of `Display`, as JS reads the `message` of
///    the error the transport threw.
pub(crate) fn client_error_record_message(err: &ExecutionClientError) -> String {
    use aws_sdk_lambda::error::ProvideErrorMetadata;
    use std::error::Error as _;

    if let Some(source) = err.source() {
        if let Some(sdk) = source.downcast_ref::<CheckpointSdkError>()
            && let Some(m) = sdk.message()
        {
            return m.to_owned();
        }
        if let Some(sdk) = source.downcast_ref::<GetStateSdkError>()
            && let Some(m) = sdk.message()
        {
            return m.to_owned();
        }
    }
    err.message().to_owned()
}

/// The wire `ErrorType` of the bootstrap `FAILED` record for `err`.
///
/// When the source is the final `SdkError` of `GetDurableExecutionState`
/// and it carries an AWS error code, the type is that code, as JS records
/// the AWS error's `name`. Otherwise the type is
/// [`EXECUTION_CLIENT_ERROR_TYPE`](crate::error::EXECUTION_CLIENT_ERROR_TYPE),
/// as JS records for its `DurableExecutionClientError`.
pub(crate) fn bootstrap_error_type(err: &ExecutionClientError) -> String {
    use aws_sdk_lambda::error::ProvideErrorMetadata;
    use std::error::Error as _;

    err.source()
        .and_then(|s| s.downcast_ref::<GetStateSdkError>())
        .and_then(ProvideErrorMetadata::code)
        .unwrap_or(crate::error::EXECUTION_CLIENT_ERROR_TYPE)
        .to_owned()
}

/// The final error of a `CheckpointDurableExecution` call.
type CheckpointSdkError = aws_sdk_lambda::error::SdkError<
    aws_sdk_lambda::operation::checkpoint_durable_execution::CheckpointDurableExecutionError,
    aws_sdk_lambda::config::http::HttpResponse,
>;

/// The final error of a `GetDurableExecutionState` call.
type GetStateSdkError = aws_sdk_lambda::error::SdkError<
    aws_sdk_lambda::operation::get_durable_execution_state::GetDurableExecutionStateError,
    aws_sdk_lambda::config::http::HttpResponse,
>;

/// The output of a successful [`ExecutionClient::checkpoint`] call.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CheckpointOutput {
    /// The new checkpoint token for subsequent calls. `None` when the
    /// service returned no token.
    pub(crate) checkpoint_token: Option<String>,
    /// Updated operations from the backend (may be empty).
    pub(crate) updated_operations: Vec<Operation>,
    /// Pagination marker: if present, more operations are available via
    /// `get_state` and the caller must paginate.
    pub(crate) next_marker: Option<String>,
}

impl CheckpointOutput {
    /// Creates a checkpoint output.
    ///
    /// `checkpoint_token` is the token for the next request, or `None` when
    /// the service returned none. `next_marker` is the pagination marker of
    /// the returned state, or `None` when `updated_operations` is complete.
    #[must_use]
    pub fn new(
        checkpoint_token: Option<String>,
        updated_operations: Vec<Operation>,
        next_marker: Option<String>,
    ) -> Self {
        Self {
            checkpoint_token,
            updated_operations,
            next_marker,
        }
    }

    /// The token for the next request. An empty token reads as `None`.
    pub fn checkpoint_token(&self) -> Option<&str> {
        self.checkpoint_token.as_deref().filter(|t| !t.is_empty())
    }
}

/// One page of execution state, returned by [`ExecutionClient::get_state`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct GetStateOutput {
    /// The operations of this page.
    pub(crate) operations: Vec<Operation>,
    /// The marker of the next page, `None` on the last page.
    pub(crate) next_marker: Option<String>,
}

impl GetStateOutput {
    /// Creates one page of execution state. `next_marker` is the marker of
    /// the next page, or `None` on the last page.
    #[must_use]
    pub fn new(operations: Vec<Operation>, next_marker: Option<String>) -> Self {
        Self {
            operations,
            next_marker,
        }
    }

    /// The marker of the next page. An empty marker reads as `None`.
    pub fn next_marker(&self) -> Option<&str> {
        self.next_marker.as_deref().filter(|m| !m.is_empty())
    }
}

/// The transport for the two durable execution service calls.
///
/// The SDK uses [`LambdaExecutionClient`] unless
/// [`OptionsBuilder::execution_client`](crate::OptionsBuilder::execution_client)
/// supplies another implementation. The trait is object-safe, so a
/// transport is passed as `Arc<dyn ExecutionClient>`.
///
/// # Contract
///
/// 1. [`checkpoint`](Self::checkpoint) sends `updates` in order in one
///    request. It returns the new token, the operations the backend
///    returned, and the pagination marker of the returned state.
/// 2. The returned token is `None` when the service accepted the request
///    and returned no token for the next one. An empty token is reported
///    as `None`.
/// 3. [`get_state`](Self::get_state) returns one page of the execution's
///    operations and the marker of the next page, or `None` on the last
///    page. The SDK follows the marker.
/// 4. Transient retry is the transport's job. An error the method returns
///    is final for the invocation.
/// 5. An error's [`scope`](ExecutionClientError::scope) decides the
///    outcome:
///    - [`Invocation`](ExecutionClientErrorScope::Invocation) fails the
///      invocation; the service re-invokes and replay resumes.
///    - [`Execution`](ExecutionClientErrorScope::Execution) from
///      `checkpoint` fails the execution. The SDK sends no further
///      checkpoint in the invocation and writes no further update for the
///      operation, so its record stays at the last update the service
///      accepted. The execution's `FAILED` record has `ErrorType`
///      `CheckpointUnrecoverableExecutionError` and `ErrorMessage`
///      `[Unrecoverable Execution] Checkpoint failed: {m}`.
///      `{m}` is the AWS error's message when the Lambda transport supplied
///      one, and the error's own message otherwise.
///    - `Execution` from the bootstrap `get_state` returns a `FAILED`
///      response. Its `ErrorType` is the AWS error code when the Lambda
///      transport supplied one, and `DurableExecutionClientError`
///      otherwise. Its `ErrorMessage` is `{m}` as above.
pub trait ExecutionClient: Send + Sync {
    /// Checkpoints operation updates and returns the next token.
    fn checkpoint(
        &self,
        execution_arn: &str,
        checkpoint_token: &str,
        updates: Vec<OperationUpdate>,
    ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>;

    /// Reads one page of the execution state. `None` reads the first page,
    /// and `Some(m)` reads the page after marker `m`.
    fn get_state(
        &self,
        execution_arn: &str,
        checkpoint_token: &str,
        marker: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>;
}

/// The page size of a `GetDurableExecutionState` request, as in JS.
const GET_STATE_MAX_ITEMS: i32 = 1000;

/// The token the SDK adds to the `User-Agent` header of its own requests.
///
/// The name is a literal because the crate is named
/// `aws-durable-execution-sdk`, and the durable execution SDKs for the other
/// languages send `aws-durable-execution-sdk-<language>/<version>`. The
/// version is the crate version, so the token always matches it.
const USER_AGENT_TOKEN: &str =
    concat!("aws-durable-execution-sdk-rust/", env!("CARGO_PKG_VERSION"));

/// Appends [`USER_AGENT_TOKEN`] to the `User-Agent` header of one request.
///
/// The AWS SDK writes `User-Agent` in `modify_before_signing`. This
/// interceptor runs later, in `modify_before_transmit`. `SigV4` leaves
/// `user-agent` out of the signature, so the change keeps the signature
/// valid. The runtime rewinds the request before each retry attempt, so
/// each attempt appends the token once to a freshly written header.
///
/// `framework_metadata` on the client config is not used, because it
/// writes the token with a `lib/` prefix.
#[derive(Debug)]
struct UserAgentTokenInterceptor;

impl aws_sdk_lambda::config::Intercept for UserAgentTokenInterceptor {
    fn name(&self) -> &'static str {
        "UserAgentTokenInterceptor"
    }

    fn modify_before_transmit(
        &self,
        context: &mut aws_sdk_lambda::config::interceptors::BeforeTransmitInterceptorContextMut<'_>,
        _runtime_components: &aws_sdk_lambda::config::RuntimeComponents,
        _cfg: &mut aws_sdk_lambda::config::ConfigBag,
    ) -> Result<(), aws_sdk_lambda::error::BoxError> {
        let headers = context.request_mut().headers_mut();
        let value = user_agent_with_token(headers.get("user-agent"));
        // `insert` replaces the value. `append` would add a second
        // `User-Agent` header. The value is the current valid header value,
        // a space and an ASCII token, so it is a valid header value.
        headers.insert("user-agent", value);
        Ok(())
    }
}

/// Returns `current` followed by a space and [`USER_AGENT_TOKEN`], or the
/// token alone when the request has no `User-Agent` header. The AWS SDK
/// always writes the header, but an interceptor on a caller's client can
/// remove it.
fn user_agent_with_token(current: Option<&str>) -> String {
    match current {
        Some(current) => format!("{current} {USER_AGENT_TOKEN}"),
        None => USER_AGENT_TOKEN.to_owned(),
    }
}

/// The transport the SDK uses when `execution_client` is not set. Wrap it
/// to decorate the default.
///
/// Retry is delegated entirely to the wrapped SDK client's own retry
/// strategy (standard retry by default: jittered exponential backoff, 3
/// attempts). This matches the sibling JS and Python SDKs, which rely on
/// their AWS SDKs' built-in retry. A call that exhausts the SDK's retries
/// fails the invocation; the durable execution service re-invokes the
/// handler, which is the recovery path: longer in-process retry would
/// only delay it. Callers who need a different retry policy supply a
/// preconfigured client.
///
/// Every request it sends carries the token
/// `aws-durable-execution-sdk-rust/<version>` as one more space-separated
/// part of its `User-Agent` header, where `<version>` is the crate version.
/// The token is added to each request, so the wrapped client is not changed.
///
/// Every final error carries the final `SdkError` as its
/// [`source`](std::error::Error::source).
///
/// # Examples
///
/// ```no_run
/// use std::sync::Arc;
/// use aws_durable_execution_sdk::{
///     ExecutionClient, LambdaClient, LambdaExecutionClient, Options, SdkConfig,
/// };
///
/// let client = LambdaClient::new(&SdkConfig::builder().build());
/// let transport: Arc<dyn ExecutionClient> = Arc::new(LambdaExecutionClient::new(client));
/// let options = Options::builder()
///     .execution_client(transport)
///     .build()
///     .expect("valid config");
/// # drop(options);
/// ```
#[derive(Clone)]
#[non_exhaustive]
pub struct LambdaExecutionClient {
    client: aws_sdk_lambda::Client,
}

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

impl LambdaExecutionClient {
    /// Creates a transport that calls the service through `client`.
    #[must_use]
    pub fn new(client: crate::LambdaClient) -> Self {
        Self { client }
    }
}

impl ExecutionClient for LambdaExecutionClient {
    fn checkpoint(
        &self,
        execution_arn: &str,
        checkpoint_token: &str,
        updates: Vec<OperationUpdate>,
    ) -> 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 result = self
                .client
                .checkpoint_durable_execution()
                .durable_execution_arn(&arn)
                .checkpoint_token(&token)
                .set_updates(Some(updates))
                .customize()
                .interceptor(UserAgentTokenInterceptor)
                .send()
                .await;

            match result {
                Ok(output) => {
                    let new_token = output.checkpoint_token.filter(|t| !t.is_empty());
                    let (updated_ops, next_marker) = match output.new_execution_state {
                        Some(state) => (
                            state.operations.unwrap_or_default(),
                            state.next_marker.filter(|m| !m.is_empty()),
                        ),
                        None => (Vec::new(), None),
                    };
                    Ok(CheckpointOutput::new(new_token, updated_ops, next_marker))
                }
                // The SDK's standard retry has already retried everything
                // transient; the final error is classified into a recovery
                // scope (invocation vs execution): see
                // `classify_checkpoint_error`.
                Err(err) => Err(classify_checkpoint_error(err)),
            }
        })
    }

    /// Sends one `GetDurableExecutionState` request with `MaxItems` 1000.
    /// The four KMS errors are `Execution`-scoped, and every other final
    /// error, a plain 4xx included, is `Invocation`-scoped, as in JS.
    fn get_state(
        &self,
        execution_arn: &str,
        checkpoint_token: &str,
        marker: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
    {
        let arn = execution_arn.to_owned();
        let token = checkpoint_token.to_owned();
        let marker = marker.map(str::to_owned);
        Box::pin(async move {
            // As with `checkpoint`, the SDK's standard retry owns the
            // transient-failure retry; the final error is classified by
            // `classify_get_state_error`.
            let output = self
                .client
                .get_durable_execution_state()
                .durable_execution_arn(&arn)
                .checkpoint_token(&token)
                .set_marker(marker)
                .max_items(GET_STATE_MAX_ITEMS)
                .customize()
                .interceptor(UserAgentTokenInterceptor)
                .send()
                .await
                .map_err(classify_get_state_error)?;

            Ok(GetStateOutput::new(
                output.operations,
                output.next_marker.filter(|m| !m.is_empty()),
            ))
        })
    }
}

/// Reads the whole execution state: calls [`ExecutionClient::get_state`]
/// with no marker, then with each returned marker until
/// [`GetStateOutput::next_marker`] is `None`, and concatenates the pages.
pub(crate) async fn get_full_state(
    client: &dyn ExecutionClient,
    execution_arn: &str,
    checkpoint_token: &str,
) -> Result<Vec<Operation>, ExecutionClientError> {
    let mut operations = Vec::new();
    let mut marker: Option<String> = None;
    loop {
        let page = client
            .get_state(execution_arn, checkpoint_token, marker.as_deref())
            .await?;
        let next = page.next_marker().map(str::to_owned);
        operations.extend(page.operations);
        match next {
            Some(m) => marker = Some(m),
            None => return Ok(operations),
        }
    }
}

/// The message prefix the service puts on an `InvalidParameterValueException`
/// that rejects a stale checkpoint token.
///
/// A stale token resolves on re-invocation (the service issues a fresh one),
/// so this specific rejection is classified retryable: the carve-out the
/// Java SDK's `DurableApiErrorClassifier` applies.
const STALE_TOKEN_MESSAGE_PREFIX: &str = "Invalid checkpoint token";

/// Classifies a final `CheckpointDurableExecution` error into a recovery
/// scope, carried as [`ExecutionClientError::scope`]. The final error is
/// kept as the source.
///
/// By the time this runs, the aws-sdk's standard retry has exhausted its
/// transport-level attempts, so the question is no longer "try again now"
/// but *which recovery converges*:
///
/// - **Retryable**: fail the invocation; the durable service re-invokes
///   and replay resumes from the recorded state. This is the same recovery
///   as an interruption. Applied to transport-level failures (dispatch,
///   timeout, a malformed response without a 4xx status), throttling (any
///   429), 5xx, and the stale-token carve-out
///   ([`STALE_TOKEN_MESSAGE_PREFIX`]).
/// - **Non-retryable**: the service permanently rejected this write (for
///   example an oversized payload, a KMS misconfiguration, or any other
///   4xx except 429). Re-invoking re-runs the body and hits
///   the same rejection, so the SDK fails the execution instead.
///
/// After the modeled variants, the classifier reads the HTTP status of the
/// raw response, as JS reads `$metadata.httpStatusCode`. A status from 400
/// to 499 other than 429 is non-retryable: the service rejected the
/// request, so the same write fails the same way on every invocation. This
/// covers an unmodeled service error, such as a 403
/// `AccessDeniedException` when the role lacks
/// `lambda:CheckpointDurableExecution`, and a response the SDK could not
/// parse. Every other status, and an error without a raw response
/// (dispatch failure, timeout, construction failure), is retryable.
///
/// **An unmodeled error is retryable unless its status is a 4xx other
/// than 429.** The original classification
/// (pre-#43) defaulted unknown to non-retryable, with the rationale, from
/// the r3726032098 review thread, that the surfaced error only failed the
/// invocation and the service re-invoked anyway, so the default was
/// harmless. That rationale belongs to the old model: under this model a
/// non-retryable classification fails the *execution*, so a novel
/// transient error variant defaulting to non-retryable would kill
/// executions. A novel transient error arrives as 429, 5xx or a transport
/// failure, and those stay retryable; a 4xx other than 429 is a permanent
/// rejection, which JS also fails the execution on. Java and Python
/// default unknown to retryable for the same reason. The
/// `checkpoint_error_variant_canary` test pins the variant set this
/// function classifies explicitly, so a new upstream variant fails CI for
/// reclassification instead of falling silently into the status rule.
fn classify_checkpoint_error(err: CheckpointSdkError) -> ExecutionClientError {
    let message = format!("{}", aws_sdk_lambda::error::DisplayErrorContext(&err));
    let scope = checkpoint_error_scope(&err);
    ExecutionClientError::with_source(scope, message, err)
}

/// The recovery scope of a final `CheckpointDurableExecution` error: see
/// [`classify_checkpoint_error`].
fn checkpoint_error_scope(err: &CheckpointSdkError) -> ExecutionClientErrorScope {
    use ExecutionClientErrorScope::{Execution, Invocation};
    use aws_sdk_lambda::error::SdkError;
    use aws_sdk_lambda::operation::checkpoint_durable_execution::CheckpointDurableExecutionError as E;

    if let SdkError::ServiceError(service_err) = err {
        match service_err.err() {
            // Throttling and service-side 5xx: transient by definition.
            E::TooManyRequestsException(_) | E::ServiceException(_) => return Invocation,
            // A parameter rejection is deterministic, the same write fails
            // the same way on every lap, EXCEPT the stale-token rejection,
            // which a re-invocation resolves with a fresh token.
            E::InvalidParameterValueException(inner) => {
                return if inner
                    .message()
                    .is_some_and(|m| m.starts_with(STALE_TOKEN_MESSAGE_PREFIX))
                {
                    Invocation
                } else {
                    Execution
                };
            }
            // KMS misconfiguration on the function: deterministic until an
            // operator fixes the key, so re-invoking loops without progress.
            E::KmsAccessDeniedException(_)
            | E::KmsDisabledException(_)
            | E::KmsInvalidStateException(_)
            | E::KmsNotFoundException(_) => return Execution,
            // Unmodeled errors fall through to the status rule. The variant
            // canary test keeps this arm from silently absorbing new modeled
            // variants.
            _ => {}
        }
    }

    // The status rule: see the function docs. Errors without a raw response
    // (dispatch failure, timeout, construction failure) are channel-level:
    // nothing was rejected.
    match err.raw_response().map(|r| r.status().as_u16()) {
        Some(status) if (400..500).contains(&status) && status != 429 => Execution,
        _ => Invocation,
    }
}

/// Classifies a final `GetDurableExecutionState` error into a recovery
/// scope, carried as [`ExecutionClientError::scope`]. The final error is
/// kept as the source.
///
/// The four KMS errors are non-retryable: the function's key is
/// misconfigured, so every re-invocation fails the same way. Every other
/// error is retryable, a plain 4xx included, because JS rethrows every
/// other error of its bootstrap state read and so fails only the
/// invocation. The message is the `DisplayErrorContext` text, so it names
/// the exception.
fn classify_get_state_error(err: GetStateSdkError) -> ExecutionClientError {
    use aws_sdk_lambda::operation::get_durable_execution_state::GetDurableExecutionStateError as E;

    let message = format!("{}", aws_sdk_lambda::error::DisplayErrorContext(&err));
    let scope = match err.as_service_error() {
        Some(
            E::KmsAccessDeniedException(_)
            | E::KmsDisabledException(_)
            | E::KmsInvalidStateException(_)
            | E::KmsNotFoundException(_),
        ) => ExecutionClientErrorScope::Execution,
        _ => ExecutionClientErrorScope::Invocation,
    };
    ExecutionClientError::with_source(scope, message, err)
}

/// An HTTP error response as the service sends it: the AWS error code in
/// the `x-amzn-errortype` header and the message in the JSON body. The
/// generated deserializer reads both into the error's metadata, which a
/// modeled error built in a test does not carry.
#[cfg(test)]
pub(crate) fn mock_aws_error_response(
    status: u16,
    code: &str,
    message: &str,
) -> aws_sdk_lambda::config::http::HttpResponse {
    let body = serde_json::json!({ "Type": "User", "message": message }).to_string();
    let mut response = aws_sdk_lambda::config::http::HttpResponse::new(
        aws_smithy_runtime_api::http::StatusCode::try_from(status).expect("valid HTTP status"),
        aws_smithy_types::body::SdkBody::from(body),
    );
    response
        .headers_mut()
        .insert("x-amzn-errortype", code.to_owned());
    response
        .headers_mut()
        .insert("content-type", "application/json");
    response
}

/// Injection point for controlling test double behavior per call.
#[cfg(test)]
#[derive(Debug, Clone)]
pub(crate) enum TestResponse {
    /// Return success with the given operations.
    Success(Vec<Operation>),
    /// Return success with given operations and a pagination marker,
    /// indicating more operations are available via `get_state`.
    SuccessPaginated(Vec<Operation>, String),
    /// Return a retryable failure.
    RetryableError(String),
    /// Return a non-retryable failure.
    NonRetryableError(String),
    /// Accept the request's updates, then return a retryable failure, as
    /// when the service recorded a write whose response was lost.
    AcceptThenRetryableError(String),
}

/// In-memory test double for `ExecutionClient`.
///
/// Supports injecting failures and recording calls for assertions.
/// Sufficient for unit tests, not the full `test-util` `LocalRunner`.
#[cfg(test)]
#[derive(Debug)]
pub(crate) struct InMemoryExecutionClient {
    /// Pre-loaded state returned by `get_state`.
    state_operations: Mutex<Vec<Operation>>,
    /// Queue of responses for checkpoint calls; if empty, returns success.
    checkpoint_responses: Mutex<Vec<TestResponse>>,
    /// Counter for checkpoint calls made (including retries).
    pub(crate) checkpoint_call_count: Mutex<u32>,
    /// Counter for `get_state` calls made.
    pub(crate) get_state_call_count: Mutex<u32>,
    /// When set, `get_state` fails with a non-retryable error carrying this
    /// message (used to test that a persisted checkpoint's lifecycle events
    /// survive a failed pagination fetch).
    get_state_failure: Mutex<Option<String>>,
    /// Token counter for generating unique tokens.
    token_counter: Mutex<u32>,
    /// Counter for backend-style callback ID assignment on Callback START.
    callback_counter: Mutex<u32>,
    /// All operation updates received across checkpoint calls.
    recorded_updates: Mutex<Vec<OperationUpdate>>,
}

#[cfg(test)]
impl InMemoryExecutionClient {
    /// Creates a new test double with the given pre-loaded state.
    pub(crate) fn new(state_operations: Vec<Operation>) -> Self {
        Self {
            state_operations: Mutex::new(state_operations),
            checkpoint_responses: Mutex::new(Vec::new()),
            checkpoint_call_count: Mutex::new(0),
            get_state_call_count: Mutex::new(0),
            get_state_failure: Mutex::new(None),
            token_counter: Mutex::new(0),
            callback_counter: Mutex::new(0),
            recorded_updates: Mutex::new(Vec::new()),
        }
    }

    /// Enqueues a response for the next checkpoint call.
    pub(crate) fn enqueue_checkpoint_response(&self, response: TestResponse) {
        let mut responses = self
            .checkpoint_responses
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        responses.push(response);
    }

    /// Makes every subsequent `get_state` call fail non-retryably with the
    /// given message.
    pub(crate) fn fail_get_state(&self, message: &str) {
        let mut failure = self
            .get_state_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *failure = Some(message.to_owned());
    }

    /// Returns all operation updates recorded across checkpoint calls.
    pub(crate) fn recorded_updates(&self) -> Vec<OperationUpdate> {
        self.recorded_updates
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }
}

#[cfg(test)]
impl ExecutionClient for InMemoryExecutionClient {
    fn checkpoint(
        &self,
        _execution_arn: &str,
        _checkpoint_token: &str,
        updates: Vec<OperationUpdate>,
    ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
    {
        {
            let mut count = self
                .checkpoint_call_count
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *count += 1;
        }

        // Mirror the backend contract: the Callback START response carries
        // the backend-assigned callback ID (issue #47). Assign one per
        // Callback START update so the default success path behaves like
        // the real service; explicitly enqueued responses stay
        // authoritative and receive no auto-assigned operations.
        let auto_ops: Vec<Operation> = updates
            .iter()
            .filter(|u| {
                u.r#type() == &OperationType::Callback
                    && u.action() == &aws_sdk_lambda::types::OperationAction::Start
            })
            .map(|u| {
                let mut counter = self
                    .callback_counter
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                *counter += 1;
                Operation::builder()
                    .id(u.id())
                    .r#type(OperationType::Callback)
                    .status(aws_sdk_lambda::types::OperationStatus::Pending)
                    .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                    .callback_details(
                        aws_sdk_lambda::types::CallbackDetails::builder()
                            .callback_id(format!("in-mem-cb-{counter}"))
                            .build(),
                    )
                    .build()
                    .expect("all required Operation fields set")
            })
            .collect();

        // Record the updates for test assertions.
        {
            let mut recorded = self
                .recorded_updates
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            recorded.extend(updates);
        }

        let response = {
            let mut responses = self
                .checkpoint_responses
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if responses.is_empty() {
                None
            } else {
                Some(responses.remove(0))
            }
        };

        Box::pin(async move {
            match response {
                // The updates are recorded above in both cases.
                Some(
                    TestResponse::RetryableError(msg) | TestResponse::AcceptThenRetryableError(msg),
                ) => Err(ExecutionClientError::from_retryable(msg)),
                Some(TestResponse::NonRetryableError(msg)) => {
                    Err(ExecutionClientError::non_retryable(msg))
                }
                Some(TestResponse::Success(ops)) => {
                    let mut counter = self
                        .token_counter
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    *counter += 1;
                    Ok(CheckpointOutput {
                        checkpoint_token: Some(format!("token-{counter}")),
                        updated_operations: ops,
                        next_marker: None,
                    })
                }
                Some(TestResponse::SuccessPaginated(ops, marker)) => {
                    let mut counter = self
                        .token_counter
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    *counter += 1;
                    Ok(CheckpointOutput {
                        checkpoint_token: Some(format!("token-{counter}")),
                        updated_operations: ops,
                        next_marker: Some(marker),
                    })
                }
                None => {
                    let mut counter = self
                        .token_counter
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    *counter += 1;
                    Ok(CheckpointOutput {
                        checkpoint_token: Some(format!("token-{counter}")),
                        updated_operations: auto_ops,
                        next_marker: None,
                    })
                }
            }
        })
    }

    fn get_state(
        &self,
        _execution_arn: &str,
        _checkpoint_token: &str,
        _marker: Option<&str>,
    ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
    {
        {
            let mut count = self
                .get_state_call_count
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *count += 1;
        }

        let failure = self
            .get_state_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        if let Some(message) = failure {
            return Box::pin(async move { Err(ExecutionClientError::non_retryable(message)) });
        }

        let ops = self
            .state_operations
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();

        Box::pin(async move { Ok(GetStateOutput::new(ops, None)) })
    }
}

/// Converts a single SDK `Operation` into a `(wire_id, CheckpointRecord)` pair.
fn operation_to_record(op: &Operation) -> (String, CheckpointRecord) {
    let attempt = op.step_details.as_ref().map_or(0, |s| {
        #[expect(clippy::cast_sign_loss)] // reason: attempt is non-negative from backend
        {
            s.attempt.max(0) as u32
        }
    });
    let record = CheckpointRecord {
        id: op.id().to_owned(),
        status: sdk_status_to_checkpoint_status(op.status()),
        result: extract_result(op),
        error_type: extract_error_type(op),
        error_message: extract_error_message(op),
        error_data: extract_wire_error_field(op, |e| e.error_data.clone()),
        stack_trace: extract_wire_error_field(op, |e| {
            (!e.stack_trace().is_empty()).then(|| e.stack_trace().to_vec())
        }),
        attempt,
        // ChainedInvoke payloads live in their own record fields: mirroring
        // parse_single_operation in lib.rs, which is the JSON-path reference
        // for this mapping. invoke.rs replays exclusively from these.
        invoke_result: op
            .chained_invoke_details
            .as_ref()
            .and_then(|i| i.result.clone()),
        invoke_error_type: op
            .chained_invoke_details
            .as_ref()
            .and_then(|i| i.error.as_ref())
            .and_then(|e| e.error_type.clone()),
        invoke_error_message: op
            .chained_invoke_details
            .as_ref()
            .and_then(|i| i.error.as_ref())
            .and_then(|e| e.error_message.clone()),
        invoke_error_data: op
            .chained_invoke_details
            .as_ref()
            .and_then(|i| i.error.as_ref())
            .and_then(|e| e.error_data.clone()),
        invoke_stack_trace: op
            .chained_invoke_details
            .as_ref()
            .and_then(|i| i.error.as_ref())
            .and_then(|e| (!e.stack_trace().is_empty()).then(|| e.stack_trace().to_vec())),
        // Large child contexts require ContextDetails.ReplayChildren to
        // signal re-execution of children; mirror the JSON path.
        replay_children: op
            .context_details
            .as_ref()
            .and_then(|c| c.replay_children)
            .unwrap_or(false),
        callback_id: op
            .callback_details
            .as_ref()
            .and_then(|cb| cb.callback_id.clone()),
        op_type: Some(operation_type_to_string(&op.r#type)),
        sub_type: op.sub_type.clone(),
        op_name: op.name.clone(),
        due_at: operation_due_at(op),
        parent_id: op.parent_id().map(str::to_owned),
        start_timestamp: crate::to_system_time(*op.start_timestamp()),
        end_timestamp: op.end_timestamp().and_then(|t| crate::to_system_time(*t)),
    };
    (op.id().to_owned(), record)
}

/// When `op` is next due: a WAIT's scheduled end, or a STEP's next attempt.
/// `None` for any other type, a missing value, or a value outside the range
/// of `SystemTime`.
fn operation_due_at(op: &Operation) -> Option<std::time::SystemTime> {
    let timestamp = match op.r#type() {
        OperationType::Wait => op
            .wait_details
            .as_ref()
            .and_then(|d| d.scheduled_end_timestamp),
        OperationType::Step => op
            .step_details
            .as_ref()
            .and_then(|d| d.next_attempt_timestamp),
        _ => None,
    }?;
    crate::to_system_time(timestamp)
}

/// Returns the wire token of an `OperationType`, such as `CONTEXT`, for
/// every variant, including one this SDK version does not know.
fn operation_type_to_string(op_type: &OperationType) -> String {
    op_type.as_str().to_owned()
}

/// Builds the plugin info of a fetched `EXECUTION` operation, or returns
/// `None` for an operation of any other type.
pub(crate) fn execution_info_from_operation(
    op: &Operation,
) -> Option<crate::plugin::OperationInfo> {
    crate::plugin::OperationInfo::execution(
        op.id(),
        op.r#type().as_str(),
        &sdk_status_to_checkpoint_status(op.status()),
        op.parent_id().map(str::to_owned),
        crate::to_system_time(*op.start_timestamp()),
        op.end_timestamp().and_then(|t| crate::to_system_time(*t)),
    )
}

/// Converts SDK `Operation` records into a `CheckpointLog`.
///
/// Keyed by wire ID (the operation's `id` field from the service). Only
/// tests build a log this way: bootstrap merges the fetched pages into the
/// inline log in [`resolve_bootstrap_log`].
#[cfg(test)]
pub(crate) fn operations_to_checkpoint_log(operations: &[Operation]) -> CheckpointLog {
    let records: Vec<(String, CheckpointRecord)> = operations
        .iter()
        // Skip Execution-type operations for consistency with
        // parse_inline_operations, which filters them in the JSON path.
        .filter(|op| op.r#type != OperationType::Execution)
        .map(operation_to_record)
        .collect();
    CheckpointLog::from_records(records)
}

/// Merges updated operations from a checkpoint response into an existing log.
///
/// After a checkpoint call, the backend may return operations with
/// backend-assigned fields (e.g. `callback_id`). These must be visible to
/// subsequent reads in the same invocation.
///
/// Skips every `EXECUTION` operation: the log holds none, and the plugins
/// keep the `EXECUTION` operation in their own slot. Returns the wire ID of
/// each merged operation whose status changed, in input order: the log
/// held no record of it, or held one with another status. Other fields do
/// not count.
pub(crate) fn merge_operations_into_log(
    log: &CheckpointLog,
    operations: &[Operation],
) -> Vec<String> {
    let mut changed = Vec::new();
    for op in operations {
        if op.r#type == OperationType::Execution {
            continue;
        }
        let (wire_id, record) = operation_to_record(op);
        let status = record.status.clone();
        if log.insert(wire_id.clone(), record).as_ref() != Some(&status) {
            changed.push(wire_id);
        }
    }
    changed
}

/// The execution state the bootstrap reads: the checkpoint log, the
/// execution input and the `EXECUTION` operation.
#[derive(Debug)]
pub(crate) struct BootstrapState {
    /// The checkpoint log, without the `EXECUTION` operation.
    pub(crate) log: CheckpointLog,
    /// The `InputPayload` of the `EXECUTION` operation, or `None` when it
    /// is absent or no page holds the operation.
    pub(crate) input_payload: Option<String>,
    /// The plugin info of the `EXECUTION` operation, or `None` when no page
    /// read so far holds it.
    pub(crate) execution: Option<crate::plugin::OperationInfo>,
}

/// Resolves the bootstrap state, following the pagination marker.
///
/// This is the single production decision point for bootstrap pagination.
/// `first_page` is the state parsed from the inline
/// `InitialExecutionState`, and `next_marker` is its `NextMarker`.
/// `first_page.execution.is_some()` says that the inline page holds the
/// `EXECUTION` operation, so its input is `first_page.input_payload`.
///
/// - Without a marker the inline page is the whole state. The function
///   returns `first_page` unchanged, and calls nothing.
/// - With a marker the function keeps `first_page`. It calls
///   [`ExecutionClient::get_state`] with the inline marker, merges each
///   returned page into the log, and calls again with each returned marker
///   until a page has none. It never reads the first page again.
///
/// When the inline page lacks the `EXECUTION` operation, the function takes
/// the operation and its `InputPayload` from the first `EXECUTION`
/// operation of the fetched pages, in page order. The caller parses the
/// input after this function returns, so an input on a later page reaches
/// the handler.
pub(crate) async fn resolve_bootstrap_log(
    client: &dyn ExecutionClient,
    execution_arn: &str,
    checkpoint_token: &str,
    first_page: BootstrapState,
    next_marker: Option<&str>,
) -> Result<BootstrapState, ExecutionClientError> {
    let mut state = first_page;
    let mut marker = next_marker.map(str::to_owned);
    while let Some(current) = marker {
        let page = client
            .get_state(execution_arn, checkpoint_token, Some(&current))
            .await?;
        marker = page.next_marker().map(str::to_owned);
        // The checkpoint log skips EXECUTION operations, so the input and
        // the operation are read from the raw page before it is merged.
        if state.execution.is_none()
            && let Some(op) = page
                .operations
                .iter()
                .find(|op| op.r#type == OperationType::Execution)
        {
            state.input_payload = op
                .execution_details
                .as_ref()
                .and_then(|d| d.input_payload.clone());
            state.execution = execution_info_from_operation(op);
        }
        for op in page
            .operations
            .iter()
            .filter(|op| op.r#type != OperationType::Execution)
        {
            let (wire_id, record) = operation_to_record(op);
            state.log.insert(wire_id, record);
        }
    }
    Ok(state)
}

/// What one page of the execution state holds of the execution input.
///
/// The input is the `InputPayload` of the EXECUTION operation. That
/// operation may sit on a later page, so a page that lacks it differs from
/// a page whose EXECUTION operation has no payload. Only the first case
/// makes [`resolve_bootstrap_log`] keep searching the fetched pages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PageInput {
    /// The page holds no EXECUTION operation.
    NoExecutionOperation,
    /// The page holds the EXECUTION operation. The value is its
    /// `InputPayload`, or `None` when the payload is absent or JSON `null`.
    Execution(Option<String>),
}

impl PageInput {
    /// Returns the `InputPayload`, or `None` when the page holds no
    /// EXECUTION operation or the operation has no payload.
    pub(crate) fn into_payload(self) -> Option<String> {
        match self {
            Self::NoExecutionOperation => None,
            Self::Execution(payload) => payload,
        }
    }
}

/// Maps SDK `OperationStatus` to internal `CheckpointStatus`.
///
/// Every modeled variant maps explicitly; anything else, the generated
/// enum's unknown-variant carrier, or a variant added by an
/// aws-sdk-lambda upgrade before this list is revisited, maps to
/// [`CheckpointStatus::Unknown`] carrying the raw wire value, which replay
/// refuses to interpret (issue #45). The `operation_status_variant_canary`
/// test pins the modeled variant set, so a new upstream variant fails CI
/// for explicit classification instead of shipping through `Unknown`.
fn sdk_status_to_checkpoint_status(
    status: &aws_sdk_lambda::types::OperationStatus,
) -> CheckpointStatus {
    match status {
        aws_sdk_lambda::types::OperationStatus::Started => CheckpointStatus::Started,
        aws_sdk_lambda::types::OperationStatus::Pending => CheckpointStatus::Pending,
        aws_sdk_lambda::types::OperationStatus::Ready => CheckpointStatus::Ready,
        aws_sdk_lambda::types::OperationStatus::Succeeded => CheckpointStatus::Succeeded,
        aws_sdk_lambda::types::OperationStatus::Failed => CheckpointStatus::Failed,
        aws_sdk_lambda::types::OperationStatus::Cancelled => CheckpointStatus::Cancelled,
        aws_sdk_lambda::types::OperationStatus::TimedOut => CheckpointStatus::TimedOut,
        aws_sdk_lambda::types::OperationStatus::Stopped => CheckpointStatus::Stopped,
        other => CheckpointStatus::Unknown(other.as_str().to_owned()),
    }
}

/// Extracts the result payload from an `Operation`.
///
/// `ChainedInvoke` results are deliberately excluded: they map to
/// `invoke_result` (see `operation_to_record`), matching the JSON path in
/// `parse_single_operation`.
fn extract_result(op: &Operation) -> Option<String> {
    op.step_details
        .as_ref()
        .and_then(|s| s.result.clone())
        .or_else(|| op.context_details.as_ref().and_then(|c| c.result.clone()))
        .or_else(|| {
            op.callback_details
                .as_ref()
                .and_then(|cb| cb.result.clone())
        })
}

/// Extracts the error type from an `Operation`.
///
/// `ChainedInvoke` errors are deliberately excluded: they map to
/// `invoke_error_type` (see `operation_to_record`), matching the JSON path
/// in `parse_single_operation`.
fn extract_error_type(op: &Operation) -> Option<String> {
    op.step_details
        .as_ref()
        .and_then(|s| s.error.as_ref())
        .and_then(|e| e.error_type.clone())
        .or_else(|| {
            op.context_details
                .as_ref()
                .and_then(|c| c.error.as_ref())
                .and_then(|e| e.error_type.clone())
        })
        .or_else(|| {
            op.callback_details
                .as_ref()
                .and_then(|cb| cb.error.as_ref())
                .and_then(|e| e.error_type.clone())
        })
}

/// Extracts the error message from an `Operation`.
///
/// `ChainedInvoke` errors are deliberately excluded: they map to
/// `invoke_error_message` (see `operation_to_record`), matching the JSON
/// path in `parse_single_operation`.
fn extract_error_message(op: &Operation) -> Option<String> {
    op.step_details
        .as_ref()
        .and_then(|s| s.error.as_ref())
        .and_then(|e| e.error_message.clone())
        .or_else(|| {
            op.context_details
                .as_ref()
                .and_then(|c| c.error.as_ref())
                .and_then(|e| e.error_message.clone())
        })
        .or_else(|| {
            op.callback_details
                .as_ref()
                .and_then(|cb| cb.error.as_ref())
                .and_then(|e| e.error_message.clone())
        })
}

/// Extracts one field of the first error object present on the operation,
/// checking step, context, and callback details in that order (mirroring
/// [`extract_error_type`]).
fn extract_wire_error_field<T>(
    op: &Operation,
    read: impl Fn(&aws_sdk_lambda::types::ErrorObject) -> Option<T>,
) -> Option<T> {
    op.step_details
        .as_ref()
        .and_then(|s| s.error.as_ref())
        .and_then(&read)
        .or_else(|| {
            op.context_details
                .as_ref()
                .and_then(|c| c.error.as_ref())
                .and_then(&read)
        })
        .or_else(|| {
            op.callback_details
                .as_ref()
                .and_then(|cb| cb.error.as_ref())
                .and_then(&read)
        })
}

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

    /// The `get_state` path reads `ParentId` and both timestamps.
    #[test]
    fn sdk_operation_parent_and_timestamps() {
        use std::time::{Duration, UNIX_EPOCH};
        let with_all = Operation::builder()
            .id("s")
            .r#type(OperationType::Step)
            .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
            .parent_id("p")
            .start_timestamp(aws_smithy_types::DateTime::from_secs(10))
            .end_timestamp(aws_smithy_types::DateTime::from_secs(12))
            .build()
            .expect("all required fields set");
        let (_, record) = operation_to_record(&with_all);
        assert_eq!(record.parent_id.as_deref(), Some("p"));
        assert_eq!(
            record.start_timestamp,
            Some(UNIX_EPOCH + Duration::from_secs(10))
        );
        assert_eq!(
            record.end_timestamp,
            Some(UNIX_EPOCH + Duration::from_secs(12))
        );

        let bare = Operation::builder()
            .id("s")
            .r#type(OperationType::Step)
            .status(aws_sdk_lambda::types::OperationStatus::Started)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(10))
            .build()
            .expect("all required fields set");
        let (_, record) = operation_to_record(&bare);
        assert_eq!(record.parent_id, None);
        assert_eq!(record.end_timestamp, None);
    }

    /// The `get_state` path keeps the wire tokens of a type and a status
    /// this SDK version does not know.
    #[test]
    fn unknown_type_and_status_keep_wire_tokens_on_get_state_path() {
        let op = Operation::builder()
            .id("f")
            .r#type(OperationType::from("FUTURE_OP"))
            .status(aws_sdk_lambda::types::OperationStatus::from(
                "FUTURE_STATUS",
            ))
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
            .build()
            .expect("all required fields set");
        let (id, record) = operation_to_record(&op);
        let info = crate::plugin::OperationInfo::from_record(&id, &record);
        assert_eq!(info.kind(), None);
        assert_eq!(info.status(), None);
        assert_eq!(info.type_str(), Some("FUTURE_OP"));
        assert_eq!(info.status_str(), Some("FUTURE_STATUS"));
    }

    /// Every known operation type is stored as its wire token.
    #[test]
    fn operation_type_to_string_returns_wire_tokens() {
        for (op_type, token) in [
            (OperationType::Callback, "CALLBACK"),
            (OperationType::ChainedInvoke, "CHAINED_INVOKE"),
            (OperationType::Context, "CONTEXT"),
            (OperationType::Execution, "EXECUTION"),
            (OperationType::Step, "STEP"),
            (OperationType::Wait, "WAIT"),
        ] {
            assert_eq!(operation_type_to_string(&op_type), token);
        }
    }

    /// A fetched `EXECUTION` operation converts with its wire fields; any
    /// other type gives `None`.
    #[test]
    fn execution_info_from_operation_reads_execution_only() {
        use std::time::{Duration, UNIX_EPOCH};
        let execution = Operation::builder()
            .id("exec")
            .r#type(OperationType::Execution)
            .status(aws_sdk_lambda::types::OperationStatus::Started)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(3))
            .end_timestamp(aws_smithy_types::DateTime::from_secs(4))
            .build()
            .expect("all required fields set");
        let info = execution_info_from_operation(&execution).expect("an EXECUTION operation");
        assert_eq!(info.id(), "exec");
        assert_eq!(info.type_str(), Some("EXECUTION"));
        assert_eq!(info.status_str(), Some("STARTED"));
        assert_eq!(info.parent_id(), None);
        assert_eq!(
            info.start_timestamp(),
            Some(UNIX_EPOCH + Duration::from_secs(3))
        );
        assert_eq!(
            info.end_timestamp(),
            Some(UNIX_EPOCH + Duration::from_secs(4))
        );
        let step = Operation::builder()
            .id("s")
            .r#type(OperationType::Step)
            .status(aws_sdk_lambda::types::OperationStatus::Started)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(3))
            .build()
            .expect("all required fields set");
        assert!(execution_info_from_operation(&step).is_none());
    }

    #[test]
    fn due_at_from_wait_and_step_details() {
        let op = |r#type: OperationType| {
            Operation::builder()
                .id("op")
                .r#type(r#type)
                .status(aws_sdk_lambda::types::OperationStatus::Started)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
        };
        let wait = op(OperationType::Wait)
            .wait_details(
                aws_sdk_lambda::types::WaitDetails::builder()
                    .scheduled_end_timestamp(aws_smithy_types::DateTime::from_secs(100))
                    .build(),
            )
            .build()
            .expect("all required fields set");
        let step = op(OperationType::Step)
            .step_details(
                aws_sdk_lambda::types::StepDetails::builder()
                    .next_attempt_timestamp(aws_smithy_types::DateTime::from_secs(200))
                    .build(),
            )
            .build()
            .expect("all required fields set");
        let neither = op(OperationType::Wait)
            .build()
            .expect("all required fields set");
        // Only a WAIT and a STEP carry an end time.
        let callback = op(OperationType::Callback)
            .wait_details(
                aws_sdk_lambda::types::WaitDetails::builder()
                    .scheduled_end_timestamp(aws_smithy_types::DateTime::from_secs(300))
                    .build(),
            )
            .build()
            .expect("all required fields set");
        let epoch = std::time::UNIX_EPOCH;
        assert_eq!(
            operation_to_record(&wait).1.due_at,
            Some(epoch + std::time::Duration::from_secs(100))
        );
        assert_eq!(
            operation_to_record(&step).1.due_at,
            Some(epoch + std::time::Duration::from_secs(200))
        );
        assert_eq!(operation_to_record(&neither).1.due_at, None);
        assert_eq!(operation_to_record(&callback).1.due_at, None);
    }

    // Request mapping (aws-smithy-mocks)
    //
    // These tests mock the Lambda SDK client at the HTTP layer and pin the
    // per-operation request mapping of `LambdaExecutionClient`: what the
    // client puts on the wire, how it maps responses back, and how the
    // final error (after the SDK's own retry) maps into `ExecutionClientError`.

    use aws_sdk_lambda::operation::checkpoint_durable_execution::{
        CheckpointDurableExecutionError, CheckpointDurableExecutionOutput,
    };
    use aws_sdk_lambda::operation::get_durable_execution_state::{
        GetDurableExecutionStateError, GetDurableExecutionStateOutput,
    };
    use aws_sdk_lambda::types::{CheckpointUpdatedExecutionState, OperationAction};
    use aws_smithy_mocks::{RuleMode, mock, mock_client};

    /// Builds a minimal `OperationUpdate` for request-mapping assertions.
    fn make_update(id: &str, action: OperationAction) -> OperationUpdate {
        OperationUpdate::builder()
            .id(id)
            .r#type(OperationType::Step)
            .action(action)
            .build()
            .expect("valid OperationUpdate")
    }

    /// `checkpoint` maps its arguments onto the `CheckpointDurableExecution`
    /// request, ARN, token, and every update, and maps the response's
    /// token, updated operations, and pagination marker back out.
    #[tokio::test]
    async fn checkpoint_maps_request_and_response() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .match_requests(|req| {
                req.durable_execution_arn() == Some("arn:aws:lambda:us-east-1:1:function:f")
                    && req.checkpoint_token() == Some("tok-in")
                    && req.updates().len() == 2
                    && req.updates().first().map(OperationUpdate::id) == Some("op-1")
                    && req.updates().get(1).map(OperationUpdate::id) == Some("op-2")
            })
            .then_output(|| {
                CheckpointDurableExecutionOutput::builder()
                    .checkpoint_token("tok-out")
                    .new_execution_state(
                        CheckpointUpdatedExecutionState::builder()
                            .operations(make_step_op("op-1", r#""r1""#))
                            .next_marker("more-pages")
                            .build(),
                    )
                    .build()
            });
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let updates = vec![
            make_update("op-1", OperationAction::Start),
            make_update("op-2", OperationAction::Succeed),
        ];
        let output = client
            .checkpoint("arn:aws:lambda:us-east-1:1:function:f", "tok-in", updates)
            .await
            .expect("mocked checkpoint succeeds");

        assert_eq!(output.checkpoint_token(), Some("tok-out"));
        assert_eq!(output.updated_operations.len(), 1);
        assert_eq!(
            output.updated_operations.first().map(Operation::id),
            Some("op-1")
        );
        assert_eq!(output.next_marker.as_deref(), Some("more-pages"));
        assert_eq!(rule.num_calls(), 1);
    }

    /// The wire ID of the first root operation: the SHA-256 of `"1"`.
    const FIRST_ROOT_WIRE_ID: &str =
        "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b";

    /// Drives `wrap` over `sdk_client` with a one-step handler on a fresh
    /// execution, so the step's first request is its START. Returns the
    /// response.
    ///
    /// The step awaits each checkpoint before it sends the next, so each
    /// checkpoint is its own request and a test can count the requests.
    async fn invoke_one_step(sdk_client: aws_sdk_lambda::Client) -> serde_json::Value {
        let service = crate::wrap(
            |_event: serde_json::Value, ctx: crate::DurableContext| async move {
                let value: u32 = ctx.step(|_| async { Ok(7_u32) }).name("one").await?;
                Ok::<u32, crate::BoxError>(value)
            },
            crate::Options::builder()
                .execution_client(Arc::new(LambdaExecutionClient::new(sdk_client)))
                .build()
                .expect("options build"),
        );
        let event = lambda_runtime::LambdaEvent::new(
            crate::InvocationPayload(serde_json::json!({
                "DurableExecutionArn": "arn:aws:lambda:us-east-1:1:function:test",
                "CheckpointToken": "token-abc",
                "InitialExecutionState": {
                    "Operations": [
                        {
                            "Id": "root",
                            "Type": "Execution",
                            "Status": "STARTED",
                            "ExecutionDetails": { "InputPayload": "{}" }
                        }
                    ]
                }
            })),
            lambda_runtime::Context::default(),
        );
        service(event)
            .await
            .map(|response| response.0)
            .expect("a tokenless response answers PENDING, not an invocation error")
    }

    /// Every mocked checkpoint response has no `CheckpointToken`.
    ///
    /// (a) The transport reports the response as `Ok` with no token.
    /// (b) A request without an `EXECUTION` update withdraws the token: the
    /// handler answers exactly `{"Status":"PENDING"}` after one request,
    /// the step's START, and sends no terminal `FAIL`.
    /// (c) A request with an `EXECUTION` update is exempt: the call returns
    /// `Ok`, no latch is set, the phase stays `Running`, and no WARN is
    /// logged.
    #[tokio::test]
    async fn checkpoint_output_without_token_answers_pending_unless_execution_update() {
        use std::sync::{Arc, Mutex as StdMutex};

        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .then_output(|| CheckpointDurableExecutionOutput::builder().build());
        let client = LambdaExecutionClient::new(mock_client!(aws_sdk_lambda, [&rule]));
        let output = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect("a tokenless response is Ok");
        assert_eq!(output.checkpoint_token(), None);

        // Capture each request's updates.
        let requests: Arc<StdMutex<Vec<Vec<OperationUpdate>>>> = Arc::default();
        let seen = Arc::clone(&requests);
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .match_requests(move |req| {
                seen.lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(req.updates().to_vec());
                true
            })
            .then_output(|| CheckpointDurableExecutionOutput::builder().build());
        let response =
            invoke_one_step(mock_client!(aws_sdk_lambda, RuleMode::MatchAny, [&rule])).await;
        assert_eq!(response, serde_json::json!({ "Status": "PENDING" }));
        let requests = requests
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        assert_eq!(requests.len(), 1, "{requests:?}");
        let first = requests.first().expect("one request");
        assert_eq!(first.len(), 1, "{first:?}");
        let start = first.first().expect("the step's START");
        assert_eq!(start.id(), FIRST_ROOT_WIRE_ID);
        assert_eq!(start.action(), &OperationAction::Start);
        assert!(
            requests
                .iter()
                .flatten()
                .all(|u| u.action() != &OperationAction::Fail),
            "no terminal FAIL is sent: {requests:?}"
        );

        let (messages, _guard) = crate::driver::test_support::EventMessages::install();
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .then_output(|| CheckpointDurableExecutionOutput::builder().build());
        let ctx = crate::DurableContext::new_root_with_client(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::empty()),
            Arc::new(LambdaExecutionClient::new(mock_client!(
                aws_sdk_lambda,
                [&rule]
            ))),
            "tok".to_owned(),
        );
        let succeed = OperationUpdate::builder()
            .id("root")
            .r#type(OperationType::Execution)
            .action(OperationAction::Succeed)
            .payload("1")
            .build()
            .expect("valid update");
        ctx.checkpoint_updates_direct(vec![succeed])
            .await
            .expect("an EXECUTION update is exempt from withdrawal");
        assert!(!ctx.coordinator().withdrawn());
        assert_eq!(
            ctx.coordinator().phase(),
            crate::coordinator::Phase::Running
        );
        assert!(
            messages.at(tracing::Level::WARN).is_empty(),
            "{:?}",
            messages.at(tracing::Level::WARN)
        );
    }

    /// `ExecutionClientError::new` keeps the scope and the message, has no
    /// source, and `is_retryable` derives from the scope.
    #[test]
    fn execution_client_error_new_keeps_scope_and_message() {
        use std::error::Error as _;

        let err = ExecutionClientError::new(ExecutionClientErrorScope::Execution, "x");
        assert_eq!(err.scope(), ExecutionClientErrorScope::Execution);
        assert!(!err.is_retryable());
        assert!(err.source().is_none());
        assert_eq!(err.to_string(), "durable: client: x");

        let err = ExecutionClientError::new(ExecutionClientErrorScope::Invocation, "x");
        assert_eq!(err.scope(), ExecutionClientErrorScope::Invocation);
        assert!(err.is_retryable());
    }

    /// The Lambda transport keeps the final `SdkError` as the source, and
    /// keeps today's `DisplayErrorContext` text as the message.
    #[tokio::test]
    async fn lambda_transport_error_source_downcasts_to_sdk_error() {
        use std::error::Error as _;

        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .sequence()
            .http_status(403, None)
            .build();
        let client = LambdaExecutionClient::new(mock_client!(aws_sdk_lambda, [&rule]));
        let err = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect_err("a 403 fails the call");

        let source = err.source().expect("the transport keeps the SdkError");
        let sdk = source
            .downcast_ref::<CheckpointSdkError>()
            .expect("the source is the final SdkError");
        let text = format!("{}", aws_sdk_lambda::error::DisplayErrorContext(sdk));
        assert_eq!(err.message(), text);
        assert_eq!(format!("{err:#}"), format!("durable: client: {text}"));
        assert_eq!(err.scope(), ExecutionClientErrorScope::Execution);
    }

    /// A checkpoint call whose final outcome is a modeled parameter
    /// rejection, a deterministic client fault the SDK does not retry,
    /// classifies NON-retryable: re-invoking replays into the same
    /// rejection, so the recovery is failing the execution, not another
    /// lap.
    #[tokio::test]
    async fn checkpoint_final_error_maps_to_non_retryable_client_error() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution).then_error(|| {
            CheckpointDurableExecutionError::InvalidParameterValueException(
                aws_sdk_lambda::types::error::InvalidParameterValueException::builder().build(),
            )
        });
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect_err("modeled error must fail the call");
        assert!(!err.is_retryable());
        assert_eq!(rule.num_calls(), 1, "a client fault is not retried");
    }

    /// The backend reports stale checkpoint tokens as an
    /// `InvalidParameterValueException` whose message starts with
    /// `Invalid checkpoint token`; the production client must classify
    /// that modeled 4xx as retryable so the invocation fails and durable
    /// execution can resume with a fresh token.
    #[tokio::test]
    async fn checkpoint_stale_token_error_maps_to_retryable_client_error() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution).then_error(|| {
            CheckpointDurableExecutionError::InvalidParameterValueException(
                aws_sdk_lambda::types::error::InvalidParameterValueException::builder()
                    .message("Invalid checkpoint token: token has been superseded")
                    .build(),
            )
        });
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect_err("stale checkpoint token must fail the call");
        assert!(err.is_retryable());
        assert_eq!(rule.num_calls(), 1, "a client fault is not retried");
    }

    /// Transient-failure retry belongs to the aws-sdk's standard retry and
    /// nothing else: a persistent 503 is attempted exactly the SDK's
    /// default 3 times, not 9, which the deleted hand-rolled outer loop
    /// used to multiply it to, and the exhausted call maps to a retryable
    /// `ExecutionClientError`.
    #[tokio::test]
    async fn checkpoint_retry_is_the_sdk_standard_retry_alone() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .sequence()
            .http_status(503, None)
            .repeatedly()
            .build();
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect_err("persistent 503 must exhaust retries");
        assert!(err.is_retryable());
        assert_eq!(
            rule.num_calls(),
            3,
            "attempts must equal the SDK standard-retry budget — no outer loop multiplying them"
        );
    }

    /// `get_state` sends one request with the given marker and `MaxItems`
    /// 1000, and returns that page and its `NextMarker`.
    #[tokio::test]
    async fn get_state_returns_one_page_with_marker() {
        let rule = mock!(aws_sdk_lambda::Client::get_durable_execution_state)
            .match_requests(|req| {
                req.durable_execution_arn() == Some("arn:test")
                    && req.checkpoint_token() == Some("tok")
                    && req.marker() == Some("m-1")
                    && req.max_items() == Some(1000)
            })
            .then_output(|| {
                GetDurableExecutionStateOutput::builder()
                    .operations(make_step_op("op-1", r#""p1""#))
                    .operations(make_step_op("op-2", r#""p2""#))
                    .next_marker("m-2")
                    .build()
                    .expect("operations is set")
            });
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let page = client
            .get_state("arn:test", "tok", Some("m-1"))
            .await
            .expect("get_state succeeds");

        assert_eq!(rule.num_calls(), 1);
        assert_eq!(page.operations.len(), 2);
        assert_eq!(page.operations.first().map(Operation::id), Some("op-1"));
        assert_eq!(page.operations.get(1).map(Operation::id), Some("op-2"));
        assert_eq!(page.next_marker(), Some("m-2"));
    }

    /// A transport that returns three pages, the last without a marker,
    /// and records the marker of every call.
    struct ThreePageClient {
        markers: Mutex<Vec<Option<String>>>,
    }

    impl ExecutionClient for ThreePageClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(CheckpointOutput::new(Some("t".to_owned()), vec![], None)) })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            self.markers
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(marker.map(str::to_owned));
            let page = match marker {
                None => GetStateOutput::new(vec![make_step_op("a", "1")], Some("p-2".to_owned())),
                Some("p-2") => {
                    GetStateOutput::new(vec![make_step_op("b", "2")], Some("p-3".to_owned()))
                }
                Some(_) => GetStateOutput::new(vec![make_step_op("c", "3")], None),
            };
            Box::pin(async move { Ok(page) })
        }
    }

    /// The whole-state helper follows each marker until the last page and
    /// concatenates the pages in order.
    #[tokio::test]
    async fn sdk_loops_get_state_until_marker_empty() {
        let client = ThreePageClient {
            markers: Mutex::new(Vec::new()),
        };
        let operations = get_full_state(&client, "arn:test", "tok")
            .await
            .expect("whole state");

        let ids: Vec<&str> = operations.iter().map(Operation::id).collect();
        assert_eq!(ids, ["a", "b", "c"]);
        let markers = client
            .markers
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        assert_eq!(
            markers,
            [None, Some("p-2".to_owned()), Some("p-3".to_owned())]
        );
    }

    /// A transport that serves page 2 for marker `m-1` and page 3 for
    /// marker `m-2`, and records the marker of every call. A call without
    /// a marker, a re-read of the first page, gets a step `s0` that the
    /// test then finds in the log.
    struct InlineContinuationClient {
        markers: Mutex<Vec<Option<String>>>,
    }

    impl ExecutionClient for InlineContinuationClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(CheckpointOutput::new(Some("t".to_owned()), vec![], None)) })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            self.markers
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(marker.map(str::to_owned));
            let page = match marker {
                Some("m-1") => {
                    GetStateOutput::new(vec![make_step_op("s2", "2")], Some("m-2".to_owned()))
                }
                Some("m-2") => GetStateOutput::new(vec![make_step_op("s3", "3")], None),
                _ => GetStateOutput::new(vec![make_step_op("s0", "0")], None),
            };
            Box::pin(async move { Ok(page) })
        }
    }

    /// Bootstrap keeps the inline page and continues from its marker: it
    /// never re-reads the first page, and the merged log holds the inline
    /// step and the steps of both fetched pages.
    #[tokio::test]
    async fn bootstrap_keeps_inline_page_and_continues_from_marker() {
        let client = InlineContinuationClient {
            markers: Mutex::new(Vec::new()),
        };
        let execution = Operation::builder()
            .id("execution")
            .r#type(OperationType::Execution)
            .status(aws_sdk_lambda::types::OperationStatus::Started)
            .start_timestamp(aws_sdk_lambda::primitives::DateTime::from_secs(0))
            .execution_details(
                aws_sdk_lambda::types::ExecutionDetails::builder()
                    .input_payload("{}")
                    .build(),
            )
            .build()
            .expect("id, type, status and start timestamp are set");
        let execution_info = execution_info_from_operation(&execution);
        let first_page = BootstrapState {
            log: operations_to_checkpoint_log(&[execution, make_step_op("s1", "1")]),
            input_payload: Some("{}".to_owned()),
            execution: execution_info,
        };

        let BootstrapState {
            log,
            input_payload: input,
            ..
        } = resolve_bootstrap_log(&client, "arn:test", "tok", first_page, Some("m-1"))
            .await
            .expect("bootstrap succeeds");

        let markers = client
            .markers
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        assert_eq!(markers, [Some("m-1".to_owned()), Some("m-2".to_owned())]);
        for id in ["s1", "s2", "s3"] {
            assert!(log.get(id).is_some(), "{id} must be in the merged log");
        }
        assert!(
            log.get("s0").is_none(),
            "the first page must not be re-read"
        );
        assert_eq!(input.as_deref(), Some("{}"));
    }

    /// Builds an EXECUTION operation with the given `InputPayload`, or with
    /// none when `input` is `None`.
    fn make_execution_op(id: &str, input: Option<&str>) -> Operation {
        let mut details = aws_sdk_lambda::types::ExecutionDetails::builder();
        if let Some(input) = input {
            details = details.input_payload(input);
        }
        Operation::builder()
            .id(id)
            .r#type(OperationType::Execution)
            .status(aws_sdk_lambda::types::OperationStatus::Started)
            .start_timestamp(aws_sdk_lambda::primitives::DateTime::from_secs(0))
            .execution_details(details.build())
            .build()
            .expect("id, type, status and start timestamp are set")
    }

    /// A transport that serves a fixed page for each marker and records the
    /// marker of every call. A marker it does not know gets an empty last
    /// page.
    struct MarkerPagesClient {
        pages: Vec<(&'static str, Vec<Operation>, Option<&'static str>)>,
        markers: Mutex<Vec<Option<String>>>,
    }

    impl ExecutionClient for MarkerPagesClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(CheckpointOutput::new(Some("t".to_owned()), vec![], None)) })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            self.markers
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(marker.map(str::to_owned));
            let page = self
                .pages
                .iter()
                .find(|(key, _, _)| Some(*key) == marker)
                .map_or_else(
                    || GetStateOutput::new(vec![], None),
                    |(_, ops, next)| GetStateOutput::new(ops.clone(), next.map(str::to_owned)),
                );
            Box::pin(async move { Ok(page) })
        }
    }

    /// Resolves a bootstrap whose inline page holds no operation and has
    /// marker `m-1`, against the given fetched pages. Returns the input and
    /// the recorded markers.
    async fn resolve_input_from_pages(
        pages: Vec<(&'static str, Vec<Operation>, Option<&'static str>)>,
    ) -> (Option<String>, Vec<Option<String>>) {
        let client = MarkerPagesClient {
            pages,
            markers: Mutex::new(Vec::new()),
        };
        let BootstrapState {
            input_payload: input,
            ..
        } = resolve_bootstrap_log(
            &client,
            "arn:test",
            "tok",
            BootstrapState {
                log: operations_to_checkpoint_log(&[]),
                input_payload: None,
                execution: None,
            },
            Some("m-1"),
        )
        .await
        .expect("bootstrap succeeds");
        let markers = client
            .markers
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        (input, markers)
    }

    /// When the inline page holds no EXECUTION operation, the input comes
    /// from the first EXECUTION operation of the fetched pages, in page
    /// order. The search continues past a fetched page that holds none.
    /// The first EXECUTION operation decides the input even when its
    /// `InputPayload` is absent, so a later page's payload does not replace
    /// it.
    #[tokio::test]
    async fn bootstrap_input_comes_from_first_fetched_execution_operation() {
        let (input, markers) = resolve_input_from_pages(vec![
            ("m-1", vec![make_step_op("s1", "1")], Some("m-2")),
            (
                "m-2",
                vec![make_execution_op("execution", Some(r#"{"count":1}"#))],
                Some("m-3"),
            ),
            (
                "m-3",
                vec![make_execution_op("late", Some(r#"{"late":1}"#))],
                None,
            ),
        ])
        .await;
        assert_eq!(input.as_deref(), Some(r#"{"count":1}"#));
        assert_eq!(
            markers,
            [
                Some("m-1".to_owned()),
                Some("m-2".to_owned()),
                Some("m-3".to_owned())
            ]
        );

        let (input, markers) = resolve_input_from_pages(vec![
            ("m-1", vec![make_step_op("s1", "1")], Some("m-2")),
            (
                "m-2",
                vec![make_execution_op("execution", None)],
                Some("m-3"),
            ),
            (
                "m-3",
                vec![make_execution_op("late", Some(r#"{"late":1}"#))],
                None,
            ),
        ])
        .await;
        assert_eq!(input, None, "an absent first payload must not be replaced");
        assert_eq!(markers.len(), 3, "pagination still reaches the last page");
    }

    /// The accessors of a transport's output read an empty token or an
    /// empty marker as `None`, so a custom transport that passes the
    /// service's empty string through behaves like an absent value.
    #[test]
    fn output_accessors_read_empty_values_as_none() {
        let output = CheckpointOutput::new(Some(String::new()), vec![], None);
        assert_eq!(output.checkpoint_token(), None);
        let page = GetStateOutput::new(vec![], Some(String::new()));
        assert_eq!(page.next_marker(), None);
    }

    /// A transport whose first page carries an empty marker.
    struct EmptyMarkerClient {
        calls: Mutex<u32>,
    }

    impl ExecutionClient for EmptyMarkerClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(CheckpointOutput::new(Some("t".to_owned()), vec![], None)) })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            *self
                .calls
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) += 1;
            let page = GetStateOutput::new(vec![make_step_op("a", "1")], Some(String::new()));
            Box::pin(async move { Ok(page) })
        }
    }

    /// The whole-state helper treats an empty marker as the last page: it
    /// makes one call and returns that page.
    #[tokio::test]
    async fn sdk_stops_paginating_on_empty_marker() {
        let client = EmptyMarkerClient {
            calls: Mutex::new(0),
        };
        let operations = get_full_state(&client, "arn:test", "tok")
            .await
            .expect("whole state");

        let ids: Vec<&str> = operations.iter().map(Operation::id).collect();
        assert_eq!(ids, ["a"]);
        assert_eq!(
            *client
                .calls
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            1
        );
    }

    /// `checkpoint` stores an empty `CheckpointToken` and an empty
    /// `NextMarker` as `None`. `DurableContext` reads the marker field
    /// directly to decide whether to paginate, so the transport itself must
    /// normalize it.
    #[tokio::test]
    async fn checkpoint_maps_empty_token_and_marker_to_none() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution).then_output(|| {
            CheckpointDurableExecutionOutput::builder()
                .checkpoint_token("")
                .new_execution_state(
                    CheckpointUpdatedExecutionState::builder()
                        .operations(make_step_op("op-1", r#""r1""#))
                        .next_marker("")
                        .build(),
                )
                .build()
        });
        let client = LambdaExecutionClient::new(mock_client!(aws_sdk_lambda, [&rule]));

        let output = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect("mocked checkpoint succeeds");

        assert_eq!(output.checkpoint_token, None);
        assert_eq!(output.next_marker, None);
        assert_eq!(output.updated_operations.len(), 1);
    }

    /// `get_state` stores an empty `NextMarker` as `None`.
    #[tokio::test]
    async fn get_state_maps_empty_marker_to_none() {
        let rule = mock!(aws_sdk_lambda::Client::get_durable_execution_state).then_output(|| {
            GetDurableExecutionStateOutput::builder()
                .operations(make_step_op("op-1", r#""p1""#))
                .next_marker("")
                .build()
                .expect("operations is set")
        });
        let client = LambdaExecutionClient::new(mock_client!(aws_sdk_lambda, [&rule]));

        let page = client
            .get_state("arn:test", "tok", None)
            .await
            .expect("get_state succeeds");

        assert_eq!(page.next_marker, None);
        assert_eq!(page.operations.len(), 1);
    }

    /// A `get_state` failure maps into a retryable `ExecutionClientError` exactly
    /// like a checkpoint failure.
    #[tokio::test]
    async fn get_state_final_error_maps_to_retryable_client_error() {
        let rule = mock!(aws_sdk_lambda::Client::get_durable_execution_state).then_error(|| {
            GetDurableExecutionStateError::InvalidParameterValueException(
                aws_sdk_lambda::types::error::InvalidParameterValueException::builder().build(),
            )
        });
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .get_state("arn:test", "tok", None)
            .await
            .expect_err("modeled error must fail the call");
        assert!(err.is_retryable());
    }

    /// An unmodeled 403 on a checkpoint, such as an `AccessDeniedException`
    /// when the role lacks `lambda:CheckpointDurableExecution`, fails the
    /// execution. Standard retry does not retry it.
    #[tokio::test]
    async fn checkpoint_unmodeled_403_fails_the_execution() {
        let rule = mock!(aws_sdk_lambda::Client::checkpoint_durable_execution)
            .sequence()
            .http_status(403, None)
            .repeatedly()
            .build();
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect_err("a 403 must fail the call");
        assert!(!err.is_retryable());
        assert_eq!(rule.num_calls(), 1, "a 403 is not retried");
    }

    /// The four KMS errors of `GetDurableExecutionState` are a function
    /// misconfiguration that a re-invocation cannot fix, so each one is
    /// non-retryable, and the message names the exception.
    #[tokio::test]
    async fn get_state_kms_errors_classify_non_retryable() {
        use aws_sdk_lambda::types::error::{
            KmsAccessDeniedException, KmsDisabledException, KmsInvalidStateException,
            KmsNotFoundException,
        };
        type Make = fn() -> GetDurableExecutionStateError;
        let cases: [(Make, &str); 4] = [
            (
                || {
                    GetDurableExecutionStateError::KmsAccessDeniedException(
                        KmsAccessDeniedException::builder().build(),
                    )
                },
                "KMSAccessDeniedException",
            ),
            (
                || {
                    GetDurableExecutionStateError::KmsDisabledException(
                        KmsDisabledException::builder().build(),
                    )
                },
                "KMSDisabledException",
            ),
            (
                || {
                    GetDurableExecutionStateError::KmsInvalidStateException(
                        KmsInvalidStateException::builder().build(),
                    )
                },
                "KMSInvalidStateException",
            ),
            (
                || {
                    GetDurableExecutionStateError::KmsNotFoundException(
                        KmsNotFoundException::builder().build(),
                    )
                },
                "KMSNotFoundException",
            ),
        ];
        for (make, wire_name) in cases {
            let rule = mock!(aws_sdk_lambda::Client::get_durable_execution_state).then_error(make);
            let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
            let client = LambdaExecutionClient::new(sdk_client);

            let err = client
                .get_state("arn:test", "tok", None)
                .await
                .expect_err("a KMS error must fail the call");
            assert!(!err.is_retryable(), "{wire_name} must be non-retryable");
            assert!(
                err.to_string().contains(wire_name),
                "message must name {wire_name}, got: {err}"
            );
        }
    }

    /// A plain 4xx on the state read stays retryable, as in JS, which
    /// rethrows it and so fails only the invocation.
    #[tokio::test]
    async fn get_state_plain_4xx_stays_retryable() {
        let rule = mock!(aws_sdk_lambda::Client::get_durable_execution_state)
            .sequence()
            .http_status(403, None)
            .repeatedly()
            .build();
        let sdk_client = mock_client!(aws_sdk_lambda, [&rule]);
        let client = LambdaExecutionClient::new(sdk_client);

        let err = client
            .get_state("arn:test", "tok", None)
            .await
            .expect_err("a 403 must fail the call");
        assert!(err.is_retryable());
    }

    // Test double behavior

    /// A queued `AcceptThenRetryableError` records the request's updates,
    /// then answers with a retryable error carrying its message.
    #[tokio::test]
    async fn accept_then_retryable_error_records_then_fails() {
        let client = InMemoryExecutionClient::new(Vec::new());
        client.enqueue_checkpoint_response(TestResponse::AcceptThenRetryableError(
            "lost response".to_owned(),
        ));
        let update = OperationUpdate::builder()
            .id("e")
            .r#type(OperationType::Execution)
            .action(OperationAction::Succeed)
            .build()
            .expect("valid update");
        let err = client
            .checkpoint("arn", "token", vec![update])
            .await
            .expect_err("a retryable error");
        assert!(err.is_retryable());
        assert_eq!(err.message(), "lost response");
        assert_eq!(client.recorded_updates().len(), 1);
    }

    #[tokio::test]
    async fn in_memory_client_returns_queued_responses_in_order() {
        let client = InMemoryExecutionClient::new(Vec::new());
        client.enqueue_checkpoint_response(TestResponse::RetryableError("throttled".to_owned()));
        client.enqueue_checkpoint_response(TestResponse::NonRetryableError("invalid".to_owned()));
        client.enqueue_checkpoint_response(TestResponse::Success(Vec::new()));

        let first = client.checkpoint("arn:test", "token-0", Vec::new()).await;
        let first_err = first.unwrap_err();
        assert!(first_err.is_retryable());

        let second = client.checkpoint("arn:test", "token-0", Vec::new()).await;
        let second_err = second.unwrap_err();
        assert!(!second_err.is_retryable());

        let third = client.checkpoint("arn:test", "token-0", Vec::new()).await;
        assert!(third.is_ok());

        let count = *client
            .checkpoint_call_count
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(count, 3);
    }

    #[tokio::test]
    async fn success_returns_checkpoint_output() {
        let client = InMemoryExecutionClient::new(Vec::new());
        let result = client.checkpoint("arn:test", "token-0", Vec::new()).await;

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(
            output
                .checkpoint_token()
                .is_some_and(|t| t.starts_with("token-"))
        );
    }

    // Checkpoint log population

    #[test]
    fn checkpoint_log_from_operations_maps_statuses() {
        let ops = vec![
            Operation::builder()
                .id("op-1")
                .r#type(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()
                        .attempt(1)
                        .result(r#""hello""#)
                        .build(),
                )
                .build()
                .unwrap(),
            Operation::builder()
                .id("op-2")
                .r#type(OperationType::Step)
                .status(aws_sdk_lambda::types::OperationStatus::Failed)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(1))
                .step_details(
                    aws_sdk_lambda::types::StepDetails::builder()
                        .attempt(2)
                        .error(
                            aws_sdk_lambda::types::ErrorObject::builder()
                                .error_type("StepError")
                                .error_message("oops")
                                .build(),
                        )
                        .build(),
                )
                .build()
                .unwrap(),
        ];

        let log = operations_to_checkpoint_log(&ops);

        let r1 = log.get("op-1");
        assert!(r1.is_some());
        let r1 = r1.unwrap();
        assert_eq!(r1.status, CheckpointStatus::Succeeded);
        assert_eq!(r1.result.as_deref(), Some(r#""hello""#));
        assert_eq!(r1.attempt, 1);

        let r2 = log.get("op-2");
        assert!(r2.is_some());
        let r2 = r2.unwrap();
        assert_eq!(r2.status, CheckpointStatus::Failed);
        assert_eq!(r2.error_type.as_deref(), Some("StepError"));
        assert_eq!(r2.error_message.as_deref(), Some("oops"));
        assert_eq!(r2.attempt, 2);
    }

    /// A paginated `ChainedInvoke` operation converts into the
    /// invoke-specific record fields (`invoke_result` /
    /// `invoke_error_*`) that invoke replay reads, matching the inline
    /// JSON conversion in `parse_single_operation`, and never leaks into
    /// the generic `result` / `error_*` fields.
    #[test]
    fn chained_invoke_maps_to_invoke_specific_fields() {
        let ops = vec![
            Operation::builder()
                .id("invoke-ok")
                .r#type(OperationType::ChainedInvoke)
                .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .chained_invoke_details(
                    aws_sdk_lambda::types::ChainedInvokeDetails::builder()
                        .result(r#""invoke-payload""#)
                        .build(),
                )
                .build()
                .unwrap(),
            Operation::builder()
                .id("invoke-err")
                .r#type(OperationType::ChainedInvoke)
                .status(aws_sdk_lambda::types::OperationStatus::Failed)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(1))
                .chained_invoke_details(
                    aws_sdk_lambda::types::ChainedInvokeDetails::builder()
                        .error(
                            aws_sdk_lambda::types::ErrorObject::builder()
                                .error_type("InvokeError")
                                .error_message("downstream failed")
                                .build(),
                        )
                        .build(),
                )
                .build()
                .unwrap(),
        ];

        let log = operations_to_checkpoint_log(&ops);

        let ok = log.get("invoke-ok");
        assert!(ok.is_some());
        let ok = ok.unwrap();
        assert_eq!(ok.invoke_result.as_deref(), Some(r#""invoke-payload""#));
        assert_eq!(
            ok.result, None,
            "invoke results must not leak into the generic result field"
        );

        let err = log.get("invoke-err");
        assert!(err.is_some());
        let err = err.unwrap();
        assert_eq!(err.invoke_error_type.as_deref(), Some("InvokeError"));
        assert_eq!(
            err.invoke_error_message.as_deref(),
            Some("downstream failed")
        );
        assert_eq!(
            err.error_type, None,
            "invoke errors must not leak into the generic error fields"
        );
        assert_eq!(err.error_message, None);
    }

    /// A paginated child-context operation preserves
    /// `ContextDetails.ReplayChildren`, which large child contexts require
    /// for correct replay: matching the inline JSON conversion.
    #[test]
    fn context_replay_children_is_preserved() {
        let ops = vec![
            Operation::builder()
                .id("child-replay")
                .r#type(OperationType::Context)
                .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .context_details(
                    aws_sdk_lambda::types::ContextDetails::builder()
                        .replay_children(true)
                        .build(),
                )
                .build()
                .unwrap(),
            Operation::builder()
                .id("child-inline")
                .r#type(OperationType::Context)
                .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(1))
                .context_details(
                    aws_sdk_lambda::types::ContextDetails::builder()
                        .result(r#""child-result""#)
                        .build(),
                )
                .build()
                .unwrap(),
        ];

        let log = operations_to_checkpoint_log(&ops);

        let replayed = log.get("child-replay");
        assert!(replayed.is_some());
        let replayed = replayed.unwrap();
        assert!(
            replayed.replay_children,
            "ReplayChildren must survive the typed-state conversion"
        );

        let inline = log.get("child-inline");
        assert!(inline.is_some());
        let inline = inline.unwrap();
        assert!(!inline.replay_children);
        assert_eq!(inline.result.as_deref(), Some(r#""child-result""#));
    }

    /// Execution-type operations are filtered from the typed-state
    /// conversion, matching `parse_inline_operations` in the JSON path.
    #[test]
    fn execution_operations_are_filtered_from_log() {
        let ops = vec![
            Operation::builder()
                .id("exec-0")
                .r#type(OperationType::Execution)
                .status(aws_sdk_lambda::types::OperationStatus::Started)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .build()
                .unwrap(),
            Operation::builder()
                .id("step-1")
                .r#type(OperationType::Step)
                .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(1))
                .build()
                .unwrap(),
        ];

        let log = operations_to_checkpoint_log(&ops);

        assert!(
            log.get("exec-0").is_none(),
            "Execution operations must be filtered like the JSON path does"
        );
        assert!(log.get("step-1").is_some());
    }

    // Get state

    #[tokio::test]
    async fn get_state_returns_preloaded_operations() {
        let ops = vec![
            Operation::builder()
                .id("op-1")
                .r#type(OperationType::Step)
                .status(aws_sdk_lambda::types::OperationStatus::Succeeded)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .build()
                .unwrap(),
        ];

        let client = InMemoryExecutionClient::new(ops);
        let result = client.get_state("arn:test", "token-0", None).await;

        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output.operations.len(), 1);
        assert_eq!(output.operations.first().map(Operation::id), Some("op-1"));
    }

    // Merge updated operations into log

    #[test]
    fn merge_operations_inserts_callback_id_into_existing_log() {
        // Simulate: log starts with a STARTED callback (no callback_id yet).
        let log = CheckpointLog::from_records(vec![(
            "op-cb".to_owned(),
            CheckpointRecord {
                id: "op-cb".to_owned(),
                status: CheckpointStatus::Started,
                result: None,
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )]);

        // Backend returns the operation with callback_id assigned.
        let updated_ops = vec![
            Operation::builder()
                .id("op-cb")
                .r#type(OperationType::Callback)
                .status(aws_sdk_lambda::types::OperationStatus::Pending)
                .start_timestamp(aws_smithy_types::DateTime::from_secs(0))
                .callback_details(
                    aws_sdk_lambda::types::CallbackDetails::builder()
                        .callback_id("assigned-cb-id-42")
                        .build(),
                )
                .build()
                .unwrap(),
        ];

        merge_operations_into_log(&log, &updated_ops);

        let record = log.get("op-cb");
        assert!(record.is_some());
        let record = record.unwrap();
        assert_eq!(record.callback_id.as_deref(), Some("assigned-cb-id-42"));
        assert_eq!(record.status, CheckpointStatus::Pending);
    }

    #[test]
    fn merge_operations_adds_new_record_to_log() {
        let log = CheckpointLog::empty();

        // Backend returns a new operation not previously in the log.
        let updated_ops = vec![
            Operation::builder()
                .id("new-op")
                .r#type(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(r#""merged result""#)
                        .build(),
                )
                .build()
                .unwrap(),
        ];

        merge_operations_into_log(&log, &updated_ops);

        let record = log.get("new-op");
        assert!(record.is_some());
        let record = record.unwrap();
        assert_eq!(record.status, CheckpointStatus::Succeeded);
        assert_eq!(record.result.as_deref(), Some(r#""merged result""#));
    }

    /// An operation of type `ty` and status `status`, with a callback ID
    /// when `callback_id` is set.
    fn status_op(
        id: &str,
        ty: OperationType,
        status: aws_sdk_lambda::types::OperationStatus,
        callback_id: Option<&str>,
    ) -> Operation {
        let mut builder = Operation::builder()
            .id(id)
            .r#type(ty)
            .status(status)
            .start_timestamp(aws_smithy_types::DateTime::from_secs(0));
        if let Some(callback_id) = callback_id {
            builder = builder.callback_details(
                aws_sdk_lambda::types::CallbackDetails::builder()
                    .callback_id(callback_id)
                    .build(),
            );
        }
        builder.build().unwrap()
    }

    /// The four merge cases in one call: a new record and a status change
    /// count, a field-only change does not, and the `EXECUTION` operation
    /// is skipped and never enters the log.
    #[test]
    fn merge_reports_status_changes() {
        use aws_sdk_lambda::types::OperationStatus as S;
        let log = CheckpointLog::from_records(vec![
            (
                "b".to_owned(),
                CheckpointRecord::with_status("b", CheckpointStatus::Started),
            ),
            (
                "c".to_owned(),
                CheckpointRecord::with_status("c", CheckpointStatus::Started),
            ),
        ]);
        let changed = merge_operations_into_log(
            &log,
            &[
                status_op("a", OperationType::Step, S::Started, None),
                status_op("b", OperationType::Callback, S::Started, Some("cb-1")),
                status_op("c", OperationType::Step, S::Succeeded, None),
                status_op("exec", OperationType::Execution, S::Started, None),
            ],
        );
        assert_eq!(changed, ["a", "c"]);
        assert_eq!(
            log.get("b").unwrap().callback_id.as_deref(),
            Some("cb-1"),
            "the field-only change is still merged"
        );
        assert!(!log.contains("exec"));
    }

    /// Two statuses this SDK does not know differ when their tokens
    /// differ, and are equal when the tokens are equal.
    #[test]
    fn merge_compares_unknown_statuses_by_token() {
        use aws_sdk_lambda::types::OperationStatus as S;
        let log = CheckpointLog::from_records(vec![(
            "u".to_owned(),
            CheckpointRecord::with_status("u", CheckpointStatus::Unknown("A".to_owned())),
        )]);
        let op = |token: &str| status_op("u", OperationType::Step, S::from(token), None);
        assert_eq!(
            merge_operations_into_log(&log, &[op("A")]),
            Vec::<String>::new()
        );
        assert_eq!(merge_operations_into_log(&log, &[op("B")]), ["u"]);
    }

    // Pagination tests

    /// Helper: builds a Step operation with a result for pagination tests.
    fn make_step_op(id: &str, result: &str) -> Operation {
        Operation::builder()
            .id(id)
            .r#type(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 `get_state` in `InMemoryExecutionClient` returns all
    /// pre-loaded operations (simulating a paginated full fetch).
    #[tokio::test]
    async fn in_memory_get_state_returns_all_operations() {
        let ops = vec![
            make_step_op("step-1", "\"page1\""),
            make_step_op("step-2", "\"page2\""),
            make_step_op("step-3", "\"page3\""),
        ];
        let client = InMemoryExecutionClient::new(ops);

        let state = client.get_state("arn:test", "token-0", None).await;
        assert!(state.is_ok());
        let state = state.unwrap();
        assert_eq!(state.operations.len(), 3);
    }

    /// Tests that a paginated checkpoint response (with `next_marker`)
    /// triggers the caller to call `get_state`. This test verifies the
    /// `SuccessPaginated` variant works correctly.
    #[tokio::test]
    async fn checkpoint_with_marker_returns_paginated_response() {
        let all_ops = vec![
            make_step_op("step-1", "\"r1\""),
            make_step_op("step-2", "\"r2\""),
            make_step_op("step-3", "\"r3\""),
        ];
        let client = InMemoryExecutionClient::new(all_ops);

        // Enqueue a checkpoint response that indicates pagination.
        let page1_ops = vec![make_step_op("step-1", "\"r1\"")];
        client.enqueue_checkpoint_response(TestResponse::SuccessPaginated(
            page1_ops,
            "marker-page-2".to_owned(),
        ));

        let result = client.checkpoint("arn:test", "token-0", vec![]).await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output.updated_operations.len(), 1);
        assert_eq!(output.next_marker, Some("marker-page-2".to_owned()));

        // Caller should then call get_state to get all operations.
        let full_state = client
            .get_state(
                "arn:test",
                output.checkpoint_token().unwrap_or_default(),
                None,
            )
            .await;
        assert!(full_state.is_ok());
        let full_state = full_state.unwrap();
        assert_eq!(full_state.operations.len(), 3);
    }

    /// Tests that `operations_to_checkpoint_log` correctly converts a
    /// multi-page set of operations into a complete checkpoint log.
    #[test]
    fn operations_to_checkpoint_log_handles_multi_page_operations() {
        let ops = vec![
            make_step_op("step-1", "\"result-1\""),
            make_step_op("step-2", "\"result-2\""),
            make_step_op("step-3", "\"result-3\""),
        ];

        let log = operations_to_checkpoint_log(&ops);

        // All three operations should be in the log.
        assert!(log.get("step-1").is_some());
        assert!(log.get("step-2").is_some());
        assert!(log.get("step-3").is_some());

        let r1 = log.get("step-1").unwrap();
        assert_eq!(r1.result.as_deref(), Some("\"result-1\""));
        assert_eq!(r1.status, CheckpointStatus::Succeeded);

        let r3 = log.get("step-3").unwrap();
        assert_eq!(r3.result.as_deref(), Some("\"result-3\""));
    }

    // Checkpoint error classification

    use aws_sdk_lambda::config::http::HttpResponse;
    use aws_sdk_lambda::error::SdkError;
    use aws_sdk_lambda::operation::checkpoint_durable_execution::CheckpointDurableExecutionError as CkptErr;
    use aws_smithy_runtime_api::http::StatusCode;
    use aws_smithy_types::body::SdkBody;

    /// A raw HTTP response with the given status and an empty body.
    fn raw_response(status: u16) -> HttpResponse {
        HttpResponse::new(
            StatusCode::try_from(status).expect("valid HTTP status"),
            SdkBody::empty(),
        )
    }

    /// Classifies `err` as a service error whose raw response has `status`.
    fn classify<E: Into<CkptErr>>(err: E, status: u16) -> ExecutionClientError {
        classify_checkpoint_error(SdkError::service_error(err.into(), raw_response(status)))
    }

    fn invalid_parameter(message: Option<&str>) -> CkptErr {
        let mut builder = aws_sdk_lambda::types::error::InvalidParameterValueException::builder();
        if let Some(m) = message {
            builder = builder.message(m);
        }
        CkptErr::InvalidParameterValueException(builder.build())
    }

    #[test]
    fn throttling_and_5xx_classify_retryable() {
        let throttled = classify(
            CkptErr::TooManyRequestsException(
                aws_sdk_lambda::types::error::TooManyRequestsException::builder().build(),
            ),
            429,
        );
        assert!(throttled.is_retryable());

        let server = classify(
            CkptErr::ServiceException(
                aws_sdk_lambda::types::error::ServiceException::builder().build(),
            ),
            500,
        );
        assert!(server.is_retryable());
    }

    #[test]
    fn invalid_parameter_classifies_non_retryable() {
        assert!(!classify(invalid_parameter(Some("payload too large")), 400).is_retryable());
        // No message at all: no stale-token evidence, permanent rejection.
        assert!(!classify(invalid_parameter(None), 400).is_retryable());
    }

    /// The stale-token carve-out: `InvalidParameterValueException` whose
    /// message starts with `Invalid checkpoint token` resolves on
    /// re-invocation (the service issues a fresh token), so it is
    /// retryable. Prefix match only: a stale-token mention elsewhere in
    /// the message does not qualify. The carve-out precedes the status
    /// rule, so the 400 status does not make it non-retryable.
    #[test]
    fn stale_token_rejection_classifies_retryable() {
        let stale = classify(
            invalid_parameter(Some("Invalid checkpoint token: token has been superseded")),
            400,
        );
        assert!(stale.is_retryable());

        let not_prefix = classify(
            invalid_parameter(Some(
                "field X rejected (not an Invalid checkpoint token case)",
            )),
            400,
        );
        assert!(!not_prefix.is_retryable());

        let wrong_case = classify(
            invalid_parameter(Some("Invalid Checkpoint Token: old non-service spelling")),
            400,
        );
        assert!(!wrong_case.is_retryable());
    }

    #[test]
    fn kms_misconfiguration_classifies_non_retryable() {
        let kms = classify(
            CkptErr::KmsAccessDeniedException(
                aws_sdk_lambda::types::error::KmsAccessDeniedException::builder().build(),
            ),
            502,
        );
        assert!(!kms.is_retryable());
    }

    /// An unmodeled 4xx other than 429 is the service rejecting the
    /// request, so the same write fails the same way on every invocation:
    /// it fails the execution, as in JS.
    #[test]
    fn unhandled_4xx_classifies_non_retryable() {
        for status in [400, 403, 404, 409, 413] {
            let err = classify(CkptErr::unhandled("unmodeled rejection"), status);
            assert!(!err.is_retryable(), "status {status} must be non-retryable");
        }
    }

    /// An unmodeled 429 is throttling, so it stays retryable.
    #[test]
    fn unhandled_429_classifies_retryable() {
        assert!(classify(CkptErr::unhandled("throttled"), 429).is_retryable());
    }

    /// Unmodeled 5xx errors stay RETRYABLE. Under the #43 model a
    /// non-retryable classification fails the execution, so a novel
    /// transient error must not kill executions by default (the pre-#43
    /// non-retryable default relied on the old model, where the surfaced
    /// error only failed the invocation: r3726032098).
    #[test]
    fn unhandled_5xx_classifies_retryable() {
        for status in [500, 502, 503] {
            let err = classify(CkptErr::unhandled("some new service error"), status);
            assert!(err.is_retryable(), "status {status} must be retryable");
        }
    }

    /// A 4xx response whose body the SDK could not parse is a service
    /// rejection too, so it fails the execution.
    #[test]
    fn response_error_4xx_classifies_non_retryable() {
        let err: SdkError<CkptErr, HttpResponse> =
            SdkError::response_error("unparseable body", raw_response(403));
        assert!(!classify_checkpoint_error(err).is_retryable());
    }

    /// An unparseable 200 response is a channel fault, not a rejection.
    #[test]
    fn response_error_200_classifies_retryable() {
        let err: SdkError<CkptErr, HttpResponse> =
            SdkError::response_error("unparseable body", raw_response(200));
        assert!(classify_checkpoint_error(err).is_retryable());
    }

    #[test]
    fn transport_failures_classify_retryable() {
        let timeout: SdkError<CkptErr, HttpResponse> = SdkError::timeout_error("connect timed out");
        assert!(classify_checkpoint_error(timeout).is_retryable());
    }

    /// Canary: pins the variant set of `CheckpointDurableExecutionError`,
    /// the upstream enum [`classify_checkpoint_error`] matches with a
    /// wildcard arm.
    ///
    /// The enum is `#[non_exhaustive]`, so the classifier's `match` cannot
    /// reject new variants at compile time: a variant added by an
    /// aws-sdk-lambda upgrade would silently take the unknown→retryable
    /// default. This test parses the enum out of the dependency's own
    /// source (the exact version Cargo.lock pins, in the local cargo
    /// registry) and fails when the variant set changes, forcing the
    /// classification to be revisited instead of defaulted. The sibling
    /// audit for the `types` enums lives in
    /// `upstream_type_enum_variant_canary` (issue #45).
    #[test]
    fn checkpoint_error_variant_canary() {
        const CLASSIFIED_VARIANTS: &[&str] = &[
            "InvalidParameterValueException",
            "KmsAccessDeniedException",
            "KmsDisabledException",
            "KmsInvalidStateException",
            "KmsNotFoundException",
            "ServiceException",
            "TooManyRequestsException",
            "Unhandled",
        ];

        let source = read_sdk_source("src/operation/checkpoint_durable_execution.rs");
        let mut actual = extract_enum_variants(&source, "CheckpointDurableExecutionError");
        actual.sort_unstable();

        let mut expected: Vec<String> = CLASSIFIED_VARIANTS
            .iter()
            .map(|s| (*s).to_owned())
            .collect();
        expected.sort_unstable();

        assert_eq!(
            actual, expected,
            "aws-sdk-lambda's CheckpointDurableExecutionError variant set changed. \
             Reclassify the new/removed variants in classify_checkpoint_error \
             (src/client.rs), then update this canary's pinned list."
        );
    }

    /// Canary: pins the variant set of every upstream `types` enum the SDK
    /// matches with a wildcard arm: `OperationStatus`, `OperationType`,
    /// `OperationAction`, `ExecutionStatus`, and `EventType` (issue #45,
    /// extending the #43 pattern above).
    ///
    /// All five enums are `#[non_exhaustive]`, so a variant added by an
    /// aws-sdk-lambda upgrade would silently take each match's wildcard
    /// default: for `OperationStatus` that now means
    /// `CheckpointStatus::Unknown`, which fails replay rather than
    /// misclassifying, but the canary still forces the variant to be mapped
    /// explicitly instead of shipping through the fallback. The pinned
    /// lists include the generated enums' own `Unknown` carrier variant.
    #[test]
    #[expect(clippy::too_many_lines)] // reason: table-driven canary pins five enums' variant lists
    fn upstream_type_enum_variant_canary() {
        struct Pin {
            file: &'static str,
            enum_name: &'static str,
            variants: &'static [&'static str],
            wildcard_sites: &'static str,
        }
        let pins = [
            Pin {
                file: "src/types/_operation_status.rs",
                enum_name: "OperationStatus",
                variants: &[
                    "Cancelled",
                    "Failed",
                    "Pending",
                    "Ready",
                    "Started",
                    "Stopped",
                    "Succeeded",
                    "TimedOut",
                    "Unknown",
                ],
                wildcard_sites: "sdk_status_to_checkpoint_status (src/client.rs); \
                                 operation_status_str and operation_status_wire_str \
                                 (src/test_util.rs)",
            },
            Pin {
                file: "src/types/_operation_type.rs",
                enum_name: "OperationType",
                variants: &[
                    "Callback",
                    "ChainedInvoke",
                    "Context",
                    "Execution",
                    "Step",
                    "Unknown",
                    "Wait",
                ],
                wildcard_sites: "operation_type_str (src/tracing_layer.rs); \
                                 operation_type_str (src/test_util.rs)",
            },
            Pin {
                file: "src/types/_operation_action.rs",
                enum_name: "OperationAction",
                variants: &["Cancel", "Fail", "Retry", "Start", "Succeed", "Unknown"],
                wildcard_sites: "PendingTransitionEvent::emit (src/tracing_layer.rs); \
                                 BackendState::apply_update (src/test_util.rs); \
                                 child_starts_before_first_terminal \
                                 (src/map_parallel.rs tests)",
            },
            Pin {
                file: "src/types/_execution_status.rs",
                enum_name: "ExecutionStatus",
                variants: &[
                    "Failed",
                    "Running",
                    "Stopped",
                    "Succeeded",
                    "TimedOut",
                    "Unknown",
                ],
                wildcard_sites: "execution_status_str (src/test_util.rs)",
            },
            Pin {
                file: "src/types/_event_type.rs",
                enum_name: "EventType",
                variants: &[
                    "CallbackFailed",
                    "CallbackStarted",
                    "CallbackSucceeded",
                    "CallbackTimedOut",
                    "ChainedInvokeFailed",
                    "ChainedInvokeStarted",
                    "ChainedInvokeStopped",
                    "ChainedInvokeSucceeded",
                    "ChainedInvokeTimedOut",
                    "ContextFailed",
                    "ContextStarted",
                    "ContextSucceeded",
                    "ExecutionFailed",
                    "ExecutionStarted",
                    "ExecutionStopped",
                    "ExecutionSucceeded",
                    "ExecutionTimedOut",
                    "InvocationCompleted",
                    "StepFailed",
                    "StepStarted",
                    "StepSucceeded",
                    "Unknown",
                    "WaitCancelled",
                    "WaitStarted",
                    "WaitSucceeded",
                ],
                wildcard_sites: "apply_event_to_op and event_op_type (src/test_util.rs)",
            },
        ];

        for pin in pins {
            let source = read_sdk_source(pin.file);
            let mut actual = extract_enum_variants(&source, pin.enum_name);
            actual.sort_unstable();

            let mut expected: Vec<String> = pin.variants.iter().map(|s| (*s).to_owned()).collect();
            expected.sort_unstable();

            assert_eq!(
                actual, expected,
                "aws-sdk-lambda's {} variant set changed. Classify the new/removed \
                 variants explicitly at every wildcard match site — {} — then update \
                 this canary's pinned list.",
                pin.enum_name, pin.wildcard_sites
            );
        }
    }

    /// A modeled `OperationStatus` maps to its explicit `CheckpointStatus`;
    /// anything the SDK build does not model maps to
    /// `CheckpointStatus::Unknown` carrying the raw wire value, never to a
    /// guessed known status (the pre-#45 wildcard mapped it to `Started`,
    /// silently treating a possibly-terminal operation as re-runnable).
    #[test]
    fn unknown_operation_status_maps_to_unknown_carrying_raw() {
        use aws_sdk_lambda::types::OperationStatus;

        let novel = OperationStatus::from("PAUSED");
        assert_eq!(
            sdk_status_to_checkpoint_status(&novel),
            CheckpointStatus::Unknown("PAUSED".to_owned())
        );

        let modeled = [
            (OperationStatus::Started, CheckpointStatus::Started),
            (OperationStatus::Pending, CheckpointStatus::Pending),
            (OperationStatus::Ready, CheckpointStatus::Ready),
            (OperationStatus::Succeeded, CheckpointStatus::Succeeded),
            (OperationStatus::Failed, CheckpointStatus::Failed),
            (OperationStatus::Cancelled, CheckpointStatus::Cancelled),
            (OperationStatus::TimedOut, CheckpointStatus::TimedOut),
            (OperationStatus::Stopped, CheckpointStatus::Stopped),
        ];
        for (sdk, expected) in modeled {
            assert_eq!(
                sdk_status_to_checkpoint_status(&sdk),
                expected,
                "modeled variant {sdk:?} must map explicitly"
            );
        }
    }

    /// Reads a source file out of the aws-sdk-lambda version Cargo.lock
    /// pins, from the local cargo registry (already extracted: the test
    /// binary that runs this compiled against it).
    fn read_sdk_source(relative: &str) -> String {
        let manifest_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        let lockfile = std::fs::read_to_string(manifest_dir.join("Cargo.lock"))
            .expect("Cargo.lock readable at the workspace root");
        let version = lockfile
            .split("[[package]]")
            .find(|block| block.contains("name = \"aws-sdk-lambda\""))
            .and_then(|block| {
                block
                    .lines()
                    .find_map(|line| line.trim().strip_prefix("version = \""))
                    .map(|rest| rest.trim_end_matches('"').to_owned())
            })
            .expect("aws-sdk-lambda pinned in Cargo.lock");

        let cargo_home = std::env::var_os("CARGO_HOME").map_or_else(
            || {
                let home = std::env::var_os("HOME").expect("HOME set");
                std::path::PathBuf::from(home).join(".cargo")
            },
            std::path::PathBuf::from,
        );
        let registry_src = cargo_home.join("registry").join("src");
        let crate_dir_name = format!("aws-sdk-lambda-{version}");
        let crate_dir = std::fs::read_dir(&registry_src)
            .expect("cargo registry src directory readable")
            .filter_map(Result::ok)
            .map(|entry| entry.path().join(&crate_dir_name))
            .find(|candidate| candidate.is_dir())
            .expect("pinned aws-sdk-lambda version extracted in the cargo registry");

        std::fs::read_to_string(crate_dir.join(relative)).expect("SDK source file readable")
    }

    /// Extracts the variant identifiers of a top-level `pub enum` from
    /// generated SDK source. The generated layout is stable: variants sit
    /// at one indentation level, as `Identifier(...)` or bare
    /// `Identifier,`.
    #[expect(clippy::panic, clippy::map_unwrap_or)]
    // reason: test helper assertions over generated-source text
    fn extract_enum_variants(source: &str, enum_name: &str) -> Vec<String> {
        let header = format!("pub enum {enum_name} {{");
        let start = source
            .find(&header)
            .unwrap_or_else(|| panic!("enum {enum_name} present in SDK source"));
        let body_start = start + header.len();
        let body_end = source[body_start..]
            .find("\n}")
            .map(|offset| body_start + offset)
            .unwrap_or_else(|| panic!("enum {enum_name} body terminated"));
        let body = &source[body_start..body_end];

        body.lines()
            .filter_map(|line| {
                let trimmed = line.trim();
                // Variant lines start with an uppercase identifier followed
                // directly by `(` (tuple payload) or `,` (unit variant).
                // Doc comments, attributes (including multi-line
                // deprecation notes), and continuation lines do not.
                let first = trimmed.chars().next()?;
                if !first.is_ascii_uppercase() {
                    return None;
                }
                let ident: String = trimmed
                    .chars()
                    .take_while(char::is_ascii_alphanumeric)
                    .collect();
                let rest = trimmed.get(ident.len()..)?;
                if ident.is_empty() || !(rest.starts_with('(') || rest.starts_with(',')) {
                    return None;
                }
                Some(ident)
            })
            .collect()
    }

    // User-Agent token
    //
    // These tests send requests through `LambdaExecutionClient` over a
    // `StaticReplayClient`, which records the headers of every attempt.
    // They build the expected token from the literal and the crate version,
    // not from `USER_AGENT_TOKEN`, so a wrong constant fails them.

    use aws_sdk_lambda::config::{AppName, BehaviorVersion, Credentials, Region};
    use aws_smithy_http_client::test_util::{ReplayEvent, StaticReplayClient};
    use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
    use aws_smithy_types::retry::RetryConfig;

    fn expected_token() -> String {
        format!(
            "aws-durable-execution-sdk-rust/{}",
            env!("CARGO_PKG_VERSION")
        )
    }

    fn replay_event(status: u16, body: &'static str) -> ReplayEvent {
        let response = HttpResponse::new(
            StatusCode::try_from(status).expect("valid status"),
            SdkBody::from(body),
        );
        ReplayEvent::new(HttpRequest::new(SdkBody::empty()), response)
    }

    /// Builds a `LambdaExecutionClient` over `http`, with a near-zero retry
    /// backoff so the retry test does not sleep.
    fn replay_lambda_client(
        http: &StaticReplayClient,
        app_name: Option<AppName>,
    ) -> LambdaExecutionClient {
        let mut config = aws_sdk_lambda::config::Builder::new()
            .behavior_version(BehaviorVersion::latest())
            .region(Region::new("us-east-1"))
            .credentials_provider(Credentials::new("akid", "secret", None, None, "test"))
            .retry_config(
                RetryConfig::standard().with_initial_backoff(std::time::Duration::from_millis(1)),
            )
            .http_client(http.clone());
        config.set_app_name(app_name);
        LambdaExecutionClient::new(aws_sdk_lambda::Client::from_conf(config.build()))
    }

    /// The `User-Agent` values of every recorded attempt, one entry per
    /// header, so a request with two `User-Agent` headers is visible.
    fn user_agent_headers(http: &StaticReplayClient) -> Vec<Vec<String>> {
        http.actual_requests()
            .map(|req| {
                req.headers()
                    .get_all("user-agent")
                    .map(str::to_owned)
                    .collect()
            })
            .collect()
    }

    /// Asserts criterion 1 on one attempt: exactly one `User-Agent` header,
    /// and exactly one of its space-separated parts equals the token.
    fn assert_one_token(headers: &[String]) {
        assert_eq!(
            headers.len(),
            1,
            "exactly one User-Agent header: {headers:?}"
        );
        let value = headers.first().expect("one header");
        let token = expected_token();
        let count = value.split(' ').filter(|part| *part == token).count();
        assert_eq!(count, 1, "exactly one {token} part in {value:?}");
    }

    #[tokio::test]
    async fn user_agent_token_on_checkpoint() {
        let http = StaticReplayClient::new(vec![replay_event(200, r#"{"CheckpointToken":"t-1"}"#)]);
        let client = replay_lambda_client(&http, None);

        let output = client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect("replayed checkpoint succeeds");
        assert_eq!(output.checkpoint_token(), Some("t-1"));

        let attempts = user_agent_headers(&http);
        assert_eq!(attempts.len(), 1);
        for headers in &attempts {
            assert_one_token(headers);
        }
    }

    #[tokio::test]
    async fn user_agent_token_on_get_state() {
        let http = StaticReplayClient::new(vec![replay_event(200, r#"{"Operations":[]}"#)]);
        let client = replay_lambda_client(&http, None);

        let output = client
            .get_state("arn:test", "tok", None)
            .await
            .expect("replayed state read succeeds");
        assert_eq!(output.next_marker(), None);

        let attempts = user_agent_headers(&http);
        assert_eq!(attempts.len(), 1, "one get_state call sends one request");
        for headers in &attempts {
            assert_one_token(headers);
        }
    }

    #[tokio::test]
    async fn user_agent_token_once_per_retry_attempt() {
        let http = StaticReplayClient::new(vec![
            replay_event(503, "{}"),
            replay_event(200, r#"{"CheckpointToken":"t-1"}"#),
        ]);
        let client = replay_lambda_client(&http, None);

        client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect("the retry succeeds");

        let attempts = user_agent_headers(&http);
        assert_eq!(attempts.len(), 2, "the 503 is retried once");
        for headers in &attempts {
            assert_one_token(headers);
        }
    }

    #[tokio::test]
    async fn user_agent_keeps_app_name() {
        let http = StaticReplayClient::new(vec![replay_event(200, r#"{"CheckpointToken":"t-1"}"#)]);
        let app_name = AppName::new("my-app").expect("valid app name");
        let client = replay_lambda_client(&http, Some(app_name));

        client
            .checkpoint("arn:test", "tok", Vec::new())
            .await
            .expect("replayed checkpoint succeeds");

        let token = expected_token();
        let requests: Vec<_> = http.actual_requests().collect();
        assert_eq!(requests.len(), 1);
        for req in requests {
            let user_agent = req.headers().get("user-agent").expect("User-Agent header");
            assert!(
                user_agent.split(' ').any(|part| part == "app/my-app"),
                "the app name stays in {user_agent:?}"
            );
            let amz_user_agent = req
                .headers()
                .get("x-amz-user-agent")
                .expect("x-amz-user-agent header");
            assert!(
                !amz_user_agent.contains(&token),
                "x-amz-user-agent stays unchanged: {amz_user_agent:?}"
            );
        }
    }

    #[test]
    fn user_agent_with_token_appends_or_starts() {
        let token = expected_token();
        assert_eq!(
            user_agent_with_token(Some("aws-sdk-rust/1.3.0 os/linux")),
            format!("aws-sdk-rust/1.3.0 os/linux {token}")
        );
        assert_eq!(user_agent_with_token(None), token);
    }

    /// A number with no leading zero.
    fn is_version_number(s: &str) -> bool {
        !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && (s == "0" || !s.starts_with('0'))
    }

    /// `X.Y.Z`, optionally followed by `-alpha`, `-beta` or `-rc` and an
    /// optional `.N`, with no leading zero in any number.
    fn has_supported_version_form(version: &str) -> bool {
        let (core, pre_release) = match version.split_once('-') {
            Some((core, pre_release)) => (core, Some(pre_release)),
            None => (version, None),
        };
        let numbers: Vec<&str> = core.split('.').collect();
        if numbers.len() != 3 || !numbers.iter().all(|n| is_version_number(n)) {
            return false;
        }
        let Some(pre_release) = pre_release else {
            return true;
        };
        let (label, number) = match pre_release.split_once('.') {
            Some((label, number)) => (label, Some(number)),
            None => (pre_release, None),
        };
        matches!(label, "alpha" | "beta" | "rc") && number.is_none_or(is_version_number)
    }

    #[test]
    fn crate_version_has_the_supported_form() {
        for version in [
            "0.1.0",
            "1.0.0",
            "1.1.0-alpha",
            "1.1.0-beta.2",
            "1.1.0-rc.1",
        ] {
            assert!(has_supported_version_form(version), "{version} must fit");
        }
        for version in [
            "1.0.0-rc1",
            "1.0.0-preview",
            "1.0.0-RC.1",
            "1.0.0+build.1",
            "v1.0.0",
            "1.0",
            "01.0.0",
            "1.0.0-rc.01",
        ] {
            assert!(
                !has_supported_version_form(version),
                "{version} must not fit"
            );
        }
        assert!(
            has_supported_version_form(env!("CARGO_PKG_VERSION")),
            "the crate version {} has an unsupported form",
            env!("CARGO_PKG_VERSION")
        );
    }
}