durable-execution-sdk 0.1.0-alpha3

AWS Durable Execution SDK for Lambda Rust Runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
//! DurableContext and operation identifier types for the AWS Durable Execution SDK.
//!
//! This module provides the main `DurableContext` interface that user code interacts with,
//! as well as the `OperationIdentifier` type for deterministic operation ID generation.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};

use blake2::{Blake2b512, Digest};

use crate::error::DurableResult;
use crate::handlers::StepContext;
use crate::sealed::Sealed;
use crate::state::ExecutionState;
use crate::traits::DurableValue;
use crate::types::OperationId;

/// Identifies an operation within a durable execution.
///
/// Each operation has a unique ID that is deterministically generated
/// based on the parent context and step counter. This ensures that
/// the same operation gets the same ID across replays.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OperationIdentifier {
    /// The unique operation ID (deterministically generated)
    pub operation_id: String,
    /// The parent operation ID (None for root operations)
    pub parent_id: Option<String>,
    /// Optional human-readable name for the operation
    pub name: Option<String>,
}

impl OperationIdentifier {
    /// Creates a new OperationIdentifier with the given values.
    pub fn new(
        operation_id: impl Into<String>,
        parent_id: Option<String>,
        name: Option<String>,
    ) -> Self {
        Self {
            operation_id: operation_id.into(),
            parent_id,
            name,
        }
    }

    /// Creates a root operation identifier (no parent).
    pub fn root(operation_id: impl Into<String>) -> Self {
        Self {
            operation_id: operation_id.into(),
            parent_id: None,
            name: None,
        }
    }

    /// Creates an operation identifier with a parent.
    pub fn with_parent(operation_id: impl Into<String>, parent_id: impl Into<String>) -> Self {
        Self {
            operation_id: operation_id.into(),
            parent_id: Some(parent_id.into()),
            name: None,
        }
    }

    /// Sets the name for this operation identifier.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Returns the operation ID as an `OperationId` newtype.
    #[inline]
    pub fn operation_id_typed(&self) -> OperationId {
        OperationId::from(self.operation_id.clone())
    }

    /// Returns the parent ID as an `OperationId` newtype, if present.
    #[inline]
    pub fn parent_id_typed(&self) -> Option<OperationId> {
        self.parent_id
            .as_ref()
            .map(|id| OperationId::from(id.clone()))
    }

    /// Applies this identifier's parent_id and name to an `OperationUpdate`.
    ///
    /// This is a convenience method to avoid repeated boilerplate when building
    /// operation updates across handlers.
    pub fn apply_to(
        &self,
        mut update: crate::operation::OperationUpdate,
    ) -> crate::operation::OperationUpdate {
        if let Some(ref parent_id) = self.parent_id {
            update = update.with_parent_id(parent_id);
        }
        if let Some(ref name) = self.name {
            update = update.with_name(name);
        }
        update
    }
}

impl std::fmt::Display for OperationIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(ref name) = self.name {
            write!(f, "{}({})", name, self.operation_id)
        } else {
            write!(f, "{}", self.operation_id)
        }
    }
}

/// Generates deterministic operation IDs using blake2b hashing.
///
/// The ID is generated by hashing the parent ID (or execution ARN for root)
/// combined with the step counter value. This ensures:
/// - Same inputs always produce the same ID
/// - Different step counts produce different IDs
/// - IDs are unique within an execution
#[derive(Debug)]
pub struct OperationIdGenerator {
    /// The base identifier (execution ARN or parent operation ID)
    base_id: String,
    /// Thread-safe step counter
    step_counter: AtomicU64,
}

impl OperationIdGenerator {
    /// Creates a new OperationIdGenerator with the given base ID.
    ///
    /// # Arguments
    ///
    /// * `base_id` - The base identifier to use for hashing (typically execution ARN or parent ID)
    pub fn new(base_id: impl Into<String>) -> Self {
        Self {
            base_id: base_id.into(),
            step_counter: AtomicU64::new(0),
        }
    }

    /// Creates a new OperationIdGenerator with a specific starting counter value.
    ///
    /// # Arguments
    ///
    /// * `base_id` - The base identifier to use for hashing
    /// * `initial_counter` - The initial value for the step counter
    pub fn with_counter(base_id: impl Into<String>, initial_counter: u64) -> Self {
        Self {
            base_id: base_id.into(),
            step_counter: AtomicU64::new(initial_counter),
        }
    }

    /// Generates the next operation ID.
    ///
    /// This method atomically increments the step counter and generates
    /// a deterministic ID based on the base ID and counter value.
    ///
    /// # Returns
    ///
    /// A unique, deterministic operation ID string.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::Relaxed` because the step counter only needs to provide
    /// unique values - there's no synchronization requirement with other data.
    /// Each call gets a unique counter value, and the hash function ensures
    /// deterministic ID generation regardless of ordering between threads.
    ///
    /// Requirements: 4.1, 4.6
    pub fn next_id(&self) -> String {
        // Relaxed ordering is sufficient: we only need uniqueness, not synchronization.
        // The counter value is combined with base_id in a hash, so the only requirement
        // is that each call gets a different counter value, which fetch_add guarantees.
        let counter = self.step_counter.fetch_add(1, Ordering::Relaxed);
        generate_operation_id(&self.base_id, counter)
    }

    /// Generates an operation ID for a specific counter value without incrementing.
    ///
    /// This is useful for testing or when you need to generate an ID
    /// for a known counter value.
    ///
    /// # Arguments
    ///
    /// * `counter` - The counter value to use for ID generation
    ///
    /// # Returns
    ///
    /// A deterministic operation ID string.
    pub fn id_for_counter(&self, counter: u64) -> String {
        generate_operation_id(&self.base_id, counter)
    }

    /// Returns the current counter value without incrementing.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::Relaxed` because this is an informational read that doesn't
    /// need to synchronize with other operations. The value may be slightly stale
    /// in concurrent scenarios, but this is acceptable for debugging/monitoring use.
    ///
    /// Requirements: 4.1, 4.6
    pub fn current_counter(&self) -> u64 {
        // Relaxed ordering is sufficient: this is an informational read with no
        // synchronization requirements. Callers should not rely on this value
        // for correctness in concurrent scenarios.
        self.step_counter.load(Ordering::Relaxed)
    }

    /// Returns the base ID used for generation.
    pub fn base_id(&self) -> &str {
        &self.base_id
    }

    /// Creates a child generator with a new base ID.
    ///
    /// The child generator starts with counter 0 and uses the provided
    /// parent operation ID as its base.
    ///
    /// # Arguments
    ///
    /// * `parent_operation_id` - The operation ID to use as the base for the child
    pub fn create_child(&self, parent_operation_id: impl Into<String>) -> Self {
        Self::new(parent_operation_id)
    }
}

impl Clone for OperationIdGenerator {
    fn clone(&self) -> Self {
        Self {
            base_id: self.base_id.clone(),
            // Relaxed ordering is sufficient: we're creating a snapshot of the counter
            // for a new generator. The clone doesn't need to synchronize with the
            // original - it just needs a reasonable starting point.
            step_counter: AtomicU64::new(self.step_counter.load(Ordering::Relaxed)),
        }
    }
}

/// Generates a deterministic operation ID using blake2b hashing.
///
/// # Arguments
///
/// * `base_id` - The base identifier (execution ARN or parent operation ID)
/// * `counter` - The step counter value
///
/// # Returns
///
/// A hex-encoded operation ID string (first 32 characters of the hash).
pub fn generate_operation_id(base_id: &str, counter: u64) -> String {
    let mut hasher = Blake2b512::new();
    hasher.update(base_id.as_bytes());
    hasher.update(counter.to_le_bytes());
    let result = hasher.finalize();

    // Take first 16 bytes (32 hex chars) for a reasonably short but unique ID
    hex::encode(&result[..16])
}

/// Logger trait for structured logging in durable executions.
///
/// This trait is compatible with the `tracing` crate and allows
/// custom logging implementations.
///
/// # Sealed Trait
///
/// This trait is sealed and cannot be implemented outside of this crate.
/// This allows the SDK maintainers to evolve the logging interface without
/// breaking external code. If you need custom logging behavior, use the
/// provided factory functions or wrap one of the existing implementations.
#[allow(private_bounds)]
pub trait Logger: Sealed + Send + Sync {
    /// Logs a debug message.
    fn debug(&self, message: &str, info: &LogInfo);
    /// Logs an info message.
    fn info(&self, message: &str, info: &LogInfo);
    /// Logs a warning message.
    fn warn(&self, message: &str, info: &LogInfo);
    /// Logs an error message.
    fn error(&self, message: &str, info: &LogInfo);
}

/// Context information for log messages.
///
/// This struct provides context for log messages including execution ARN,
/// operation IDs, and replay status. The `is_replay` flag indicates whether
/// the current operation is being replayed from a checkpoint.
#[derive(Debug, Clone, Default)]
pub struct LogInfo {
    /// The durable execution ARN
    pub durable_execution_arn: Option<String>,
    /// The current operation ID
    pub operation_id: Option<String>,
    /// The parent operation ID
    pub parent_id: Option<String>,
    /// Whether the current operation is being replayed from a checkpoint
    ///
    /// When `true`, the operation is returning a previously checkpointed result
    /// without re-executing the operation's logic. Loggers can use this flag
    /// to suppress or annotate logs during replay.
    pub is_replay: bool,
    /// Additional key-value pairs
    pub extra: Vec<(String, String)>,
}

impl LogInfo {
    /// Creates a new LogInfo with the given execution ARN.
    pub fn new(durable_execution_arn: impl Into<String>) -> Self {
        Self {
            durable_execution_arn: Some(durable_execution_arn.into()),
            ..Default::default()
        }
    }

    /// Sets the operation ID.
    pub fn with_operation_id(mut self, operation_id: impl Into<String>) -> Self {
        self.operation_id = Some(operation_id.into());
        self
    }

    /// Sets the parent ID.
    pub fn with_parent_id(mut self, parent_id: impl Into<String>) -> Self {
        self.parent_id = Some(parent_id.into());
        self
    }

    /// Sets the replay flag.
    ///
    /// When set to `true`, indicates that the current operation is being
    /// replayed from a checkpoint rather than executing fresh.
    ///
    /// # Arguments
    ///
    /// * `is_replay` - Whether the operation is being replayed
    pub fn with_replay(mut self, is_replay: bool) -> Self {
        self.is_replay = is_replay;
        self
    }

    /// Adds an extra key-value pair.
    pub fn with_extra(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra.push((key.into(), value.into()));
        self
    }
}

/// Creates a tracing span for a durable operation.
///
/// This function creates a structured tracing span that includes all relevant
/// context for observability and debugging. The span can be used to trace
/// execution flow and correlate logs across operations.
///
/// # Arguments
///
/// * `operation_type` - The type of operation (e.g., "step", "wait", "callback", "invoke", "map", "parallel")
/// * `op_id` - The operation identifier containing operation_id, parent_id, and name
/// * `durable_execution_arn` - The ARN of the durable execution
///
/// # Returns
///
/// A `tracing::Span` that can be entered during operation execution.
///
/// # Example
///
/// ```rust,ignore
/// let span = create_operation_span("step", &op_id, state.durable_execution_arn());
/// let _guard = span.enter();
/// // ... operation execution ...
/// ```
pub fn create_operation_span(
    operation_type: &str,
    op_id: &OperationIdentifier,
    durable_execution_arn: &str,
) -> tracing::Span {
    tracing::info_span!(
        "durable_operation",
        operation_type = %operation_type,
        operation_id = %op_id.operation_id,
        parent_id = ?op_id.parent_id,
        name = ?op_id.name,
        durable_execution_arn = %durable_execution_arn,
        status = tracing::field::Empty,
    )
}

/// Default logger implementation using the `tracing` crate.
///
/// This logger includes the `is_replay` flag in all log messages to help
/// distinguish between fresh executions and replayed operations.
///
/// Extra fields from `LogInfo` are included in the tracing output as a formatted
/// string of key-value pairs, making them queryable in log aggregation systems.
#[derive(Debug, Clone, Default)]
pub struct TracingLogger;

// Implement Sealed for TracingLogger to allow it to implement Logger
impl Sealed for TracingLogger {}

impl TracingLogger {
    /// Formats extra fields as a string of key-value pairs.
    ///
    /// Returns an empty string if there are no extra fields, otherwise returns
    /// a comma-separated list of "key=value" pairs.
    fn format_extra_fields(extra: &[(String, String)]) -> String {
        if extra.is_empty() {
            String::new()
        } else {
            extra
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect::<Vec<_>>()
                .join(", ")
        }
    }
}

impl Logger for TracingLogger {
    fn debug(&self, message: &str, info: &LogInfo) {
        let extra_fields = Self::format_extra_fields(&info.extra);
        tracing::debug!(
            durable_execution_arn = ?info.durable_execution_arn,
            operation_id = ?info.operation_id,
            parent_id = ?info.parent_id,
            is_replay = info.is_replay,
            extra = %extra_fields,
            "{}",
            message
        );
    }

    fn info(&self, message: &str, info: &LogInfo) {
        let extra_fields = Self::format_extra_fields(&info.extra);
        tracing::info!(
            durable_execution_arn = ?info.durable_execution_arn,
            operation_id = ?info.operation_id,
            parent_id = ?info.parent_id,
            is_replay = info.is_replay,
            extra = %extra_fields,
            "{}",
            message
        );
    }

    fn warn(&self, message: &str, info: &LogInfo) {
        let extra_fields = Self::format_extra_fields(&info.extra);
        tracing::warn!(
            durable_execution_arn = ?info.durable_execution_arn,
            operation_id = ?info.operation_id,
            parent_id = ?info.parent_id,
            is_replay = info.is_replay,
            extra = %extra_fields,
            "{}",
            message
        );
    }

    fn error(&self, message: &str, info: &LogInfo) {
        let extra_fields = Self::format_extra_fields(&info.extra);
        tracing::error!(
            durable_execution_arn = ?info.durable_execution_arn,
            operation_id = ?info.operation_id,
            parent_id = ?info.parent_id,
            is_replay = info.is_replay,
            extra = %extra_fields,
            "{}",
            message
        );
    }
}

/// Configuration for replay-aware logging behavior.
///
/// This configuration controls how the `ReplayAwareLogger` handles log messages
/// during replay. Users can choose to suppress all logs during replay, allow
/// only certain log levels, or log all messages regardless of replay status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReplayLoggingConfig {
    /// Suppress all logs during replay (default).
    ///
    /// When in replay mode, no log messages will be emitted. This is useful
    /// to reduce noise in logs when replaying previously executed operations.
    #[default]
    SuppressAll,

    /// Allow all logs during replay.
    ///
    /// Log messages will be emitted regardless of replay status. The `is_replay`
    /// flag in `LogInfo` can still be used to distinguish replay logs.
    AllowAll,

    /// Allow only error logs during replay.
    ///
    /// Only error-level messages will be emitted during replay. This is useful
    /// when you want to see errors but suppress informational messages.
    ErrorsOnly,

    /// Allow error and warning logs during replay.
    ///
    /// Error and warning-level messages will be emitted during replay.
    /// Debug and info messages will be suppressed.
    WarningsAndErrors,
}

/// A logger wrapper that can suppress logs during replay based on configuration.
///
/// `ReplayAwareLogger` wraps any `Logger` implementation and adds replay-aware
/// behavior. When the `is_replay` flag in `LogInfo` is `true`, the logger will
/// suppress or allow logs based on the configured `ReplayLoggingConfig`.
///
/// # Example
///
/// ```rust
/// use durable_execution_sdk::{TracingLogger, ReplayAwareLogger, ReplayLoggingConfig};
/// use std::sync::Arc;
///
/// // Create a replay-aware logger that suppresses all logs during replay
/// let logger = ReplayAwareLogger::new(
///     Arc::new(TracingLogger),
///     ReplayLoggingConfig::SuppressAll,
/// );
///
/// // Create a replay-aware logger that allows errors during replay
/// let logger_with_errors = ReplayAwareLogger::new(
///     Arc::new(TracingLogger),
///     ReplayLoggingConfig::ErrorsOnly,
/// );
/// ```
pub struct ReplayAwareLogger {
    /// The underlying logger to delegate to
    inner: Arc<dyn Logger>,
    /// Configuration for replay logging behavior
    config: ReplayLoggingConfig,
}

// Implement Sealed for ReplayAwareLogger to allow it to implement Logger
impl Sealed for ReplayAwareLogger {}

impl ReplayAwareLogger {
    /// Creates a new `ReplayAwareLogger` with the specified configuration.
    ///
    /// # Arguments
    ///
    /// * `inner` - The underlying logger to delegate to
    /// * `config` - Configuration for replay logging behavior
    ///
    /// # Example
    ///
    /// ```rust
    /// use durable_execution_sdk::{TracingLogger, ReplayAwareLogger, ReplayLoggingConfig};
    /// use std::sync::Arc;
    ///
    /// let logger = ReplayAwareLogger::new(
    ///     Arc::new(TracingLogger),
    ///     ReplayLoggingConfig::SuppressAll,
    /// );
    /// ```
    pub fn new(inner: Arc<dyn Logger>, config: ReplayLoggingConfig) -> Self {
        Self { inner, config }
    }

    /// Creates a new `ReplayAwareLogger` that suppresses all logs during replay.
    ///
    /// This is a convenience constructor for the most common use case.
    ///
    /// # Arguments
    ///
    /// * `inner` - The underlying logger to delegate to
    pub fn suppress_replay(inner: Arc<dyn Logger>) -> Self {
        Self::new(inner, ReplayLoggingConfig::SuppressAll)
    }

    /// Creates a new `ReplayAwareLogger` that allows all logs during replay.
    ///
    /// # Arguments
    ///
    /// * `inner` - The underlying logger to delegate to
    pub fn allow_all(inner: Arc<dyn Logger>) -> Self {
        Self::new(inner, ReplayLoggingConfig::AllowAll)
    }

    /// Returns the current replay logging configuration.
    pub fn config(&self) -> ReplayLoggingConfig {
        self.config
    }

    /// Returns a reference to the underlying logger.
    pub fn inner(&self) -> &Arc<dyn Logger> {
        &self.inner
    }

    /// Checks if a log at the given level should be suppressed during replay.
    fn should_suppress(&self, info: &LogInfo, level: LogLevel) -> bool {
        if !info.is_replay {
            return false;
        }

        match self.config {
            ReplayLoggingConfig::SuppressAll => true,
            ReplayLoggingConfig::AllowAll => false,
            ReplayLoggingConfig::ErrorsOnly => level != LogLevel::Error,
            ReplayLoggingConfig::WarningsAndErrors => {
                level != LogLevel::Error && level != LogLevel::Warn
            }
        }
    }
}

/// Internal enum for log levels used by ReplayAwareLogger.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LogLevel {
    Debug,
    Info,
    Warn,
    Error,
}

impl std::fmt::Debug for ReplayAwareLogger {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReplayAwareLogger")
            .field("config", &self.config)
            .finish()
    }
}

impl Logger for ReplayAwareLogger {
    fn debug(&self, message: &str, info: &LogInfo) {
        if !self.should_suppress(info, LogLevel::Debug) {
            self.inner.debug(message, info);
        }
    }

    fn info(&self, message: &str, info: &LogInfo) {
        if !self.should_suppress(info, LogLevel::Info) {
            self.inner.info(message, info);
        }
    }

    fn warn(&self, message: &str, info: &LogInfo) {
        if !self.should_suppress(info, LogLevel::Warn) {
            self.inner.warn(message, info);
        }
    }

    fn error(&self, message: &str, info: &LogInfo) {
        if !self.should_suppress(info, LogLevel::Error) {
            self.inner.error(message, info);
        }
    }
}

/// A custom logger that delegates to user-provided closures.
///
/// This struct allows users to provide custom logging behavior without
/// implementing the sealed `Logger` trait directly. Each log level can
/// have its own closure for handling log messages.
///
/// # Example
///
/// ```rust
/// use durable_execution_sdk::context::{custom_logger, LogInfo};
/// use std::sync::Arc;
///
/// // Create a custom logger that prints to stdout
/// let logger = custom_logger(
///     |msg, info| println!("[DEBUG] {}: {:?}", msg, info),
///     |msg, info| println!("[INFO] {}: {:?}", msg, info),
///     |msg, info| println!("[WARN] {}: {:?}", msg, info),
///     |msg, info| println!("[ERROR] {}: {:?}", msg, info),
/// );
/// ```
pub struct CustomLogger<D, I, W, E>
where
    D: Fn(&str, &LogInfo) + Send + Sync,
    I: Fn(&str, &LogInfo) + Send + Sync,
    W: Fn(&str, &LogInfo) + Send + Sync,
    E: Fn(&str, &LogInfo) + Send + Sync,
{
    debug_fn: D,
    info_fn: I,
    warn_fn: W,
    error_fn: E,
}

// Implement Sealed for CustomLogger to allow it to implement Logger
impl<D, I, W, E> Sealed for CustomLogger<D, I, W, E>
where
    D: Fn(&str, &LogInfo) + Send + Sync,
    I: Fn(&str, &LogInfo) + Send + Sync,
    W: Fn(&str, &LogInfo) + Send + Sync,
    E: Fn(&str, &LogInfo) + Send + Sync,
{
}

impl<D, I, W, E> Logger for CustomLogger<D, I, W, E>
where
    D: Fn(&str, &LogInfo) + Send + Sync,
    I: Fn(&str, &LogInfo) + Send + Sync,
    W: Fn(&str, &LogInfo) + Send + Sync,
    E: Fn(&str, &LogInfo) + Send + Sync,
{
    fn debug(&self, message: &str, info: &LogInfo) {
        (self.debug_fn)(message, info);
    }

    fn info(&self, message: &str, info: &LogInfo) {
        (self.info_fn)(message, info);
    }

    fn warn(&self, message: &str, info: &LogInfo) {
        (self.warn_fn)(message, info);
    }

    fn error(&self, message: &str, info: &LogInfo) {
        (self.error_fn)(message, info);
    }
}

impl<D, I, W, E> std::fmt::Debug for CustomLogger<D, I, W, E>
where
    D: Fn(&str, &LogInfo) + Send + Sync,
    I: Fn(&str, &LogInfo) + Send + Sync,
    W: Fn(&str, &LogInfo) + Send + Sync,
    E: Fn(&str, &LogInfo) + Send + Sync,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomLogger").finish()
    }
}

/// Creates a custom logger with user-provided closures for each log level.
///
/// This factory function allows users to create custom logging behavior without
/// implementing the sealed `Logger` trait directly. Each log level has its own
/// closure that receives the log message and context information.
///
/// # Arguments
///
/// * `debug_fn` - Closure called for debug-level messages
/// * `info_fn` - Closure called for info-level messages
/// * `warn_fn` - Closure called for warning-level messages
/// * `error_fn` - Closure called for error-level messages
///
/// # Example
///
/// ```rust
/// use durable_execution_sdk::context::{custom_logger, LogInfo};
/// use std::sync::Arc;
///
/// // Create a custom logger that prints to stdout
/// let logger = custom_logger(
///     |msg, info| println!("[DEBUG] {}: {:?}", msg, info),
///     |msg, info| println!("[INFO] {}: {:?}", msg, info),
///     |msg, info| println!("[WARN] {}: {:?}", msg, info),
///     |msg, info| println!("[ERROR] {}: {:?}", msg, info),
/// );
///
/// // Use with Arc for sharing across contexts
/// let shared_logger = Arc::new(logger);
/// ```
pub fn custom_logger<D, I, W, E>(
    debug_fn: D,
    info_fn: I,
    warn_fn: W,
    error_fn: E,
) -> CustomLogger<D, I, W, E>
where
    D: Fn(&str, &LogInfo) + Send + Sync,
    I: Fn(&str, &LogInfo) + Send + Sync,
    W: Fn(&str, &LogInfo) + Send + Sync,
    E: Fn(&str, &LogInfo) + Send + Sync,
{
    CustomLogger {
        debug_fn,
        info_fn,
        warn_fn,
        error_fn,
    }
}

/// Creates a simple custom logger that uses a single closure for all log levels.
///
/// This is a convenience function for cases where you want the same handling
/// for all log levels. The closure receives the log level as a string, the
/// message, and the log info.
///
/// # Arguments
///
/// * `log_fn` - Closure called for all log messages. Receives (level, message, info).
///
/// # Example
///
/// ```rust
/// use durable_execution_sdk::context::{simple_custom_logger, LogInfo};
/// use std::sync::Arc;
///
/// // Create a simple logger that prints all messages with their level
/// let logger = simple_custom_logger(|level, msg, info| {
///     println!("[{}] {}: {:?}", level, msg, info);
/// });
///
/// // Use with Arc for sharing across contexts
/// let shared_logger = Arc::new(logger);
/// ```
pub fn simple_custom_logger<F>(log_fn: F) -> impl Logger
where
    F: Fn(&str, &str, &LogInfo) + Send + Sync + Clone + 'static,
{
    let debug_fn = log_fn.clone();
    let info_fn = log_fn.clone();
    let warn_fn = log_fn.clone();
    let error_fn = log_fn;

    custom_logger(
        move |msg, info| debug_fn("DEBUG", msg, info),
        move |msg, info| info_fn("INFO", msg, info),
        move |msg, info| warn_fn("WARN", msg, info),
        move |msg, info| error_fn("ERROR", msg, info),
    )
}

/// The main context for durable execution operations.
///
/// `DurableContext` provides all the durable operations that user code
/// can use to build reliable workflows. It handles checkpointing, replay,
/// and state management automatically.
///
/// # Thread Safety
///
/// `DurableContext` is `Send + Sync` and can be safely shared across
/// async tasks. The internal state uses appropriate synchronization
/// primitives for concurrent access.
///
/// # Example
///
/// ```rust,ignore
/// async fn my_workflow(ctx: DurableContext) -> Result<String, DurableError> {
///     // Execute a step (automatically checkpointed)
///     let result = ctx.step(|_| async move { Ok("hello".to_string()) }, None).await?;
///     
///     // Wait for 5 seconds (suspends Lambda, resumes later)
///     ctx.wait(Duration::from_seconds(5), None).await?;
///     
///     Ok(result)
/// }
/// ```
pub struct DurableContext {
    /// The execution state manager
    state: Arc<ExecutionState>,
    /// The Lambda context (if running in Lambda)
    lambda_context: Option<lambda_runtime::Context>,
    /// The parent operation ID (None for root context)
    parent_id: Option<String>,
    /// Operation ID generator for this context
    id_generator: Arc<OperationIdGenerator>,
    /// Logger for structured logging (wrapped in RwLock for runtime reconfiguration)
    logger: Arc<RwLock<Arc<dyn Logger>>>,
}

// Ensure DurableContext is Send + Sync
static_assertions::assert_impl_all!(DurableContext: Send, Sync);

impl DurableContext {
    /// Creates a new DurableContext with the given state.
    ///
    /// # Arguments
    ///
    /// * `state` - The execution state manager
    pub fn new(state: Arc<ExecutionState>) -> Self {
        let base_id = state.durable_execution_arn().to_string();
        Self {
            state,
            lambda_context: None,
            parent_id: None,
            id_generator: Arc::new(OperationIdGenerator::new(base_id)),
            logger: Arc::new(RwLock::new(Arc::new(TracingLogger))),
        }
    }

    /// Creates a DurableContext from a Lambda context.
    ///
    /// This is the primary factory method used when running in AWS Lambda.
    ///
    /// # Arguments
    ///
    /// * `state` - The execution state manager
    /// * `lambda_context` - The Lambda runtime context
    pub fn from_lambda_context(
        state: Arc<ExecutionState>,
        lambda_context: lambda_runtime::Context,
    ) -> Self {
        let base_id = state.durable_execution_arn().to_string();
        Self {
            state,
            lambda_context: Some(lambda_context),
            parent_id: None,
            id_generator: Arc::new(OperationIdGenerator::new(base_id)),
            logger: Arc::new(RwLock::new(Arc::new(TracingLogger))),
        }
    }

    /// Creates a child context for nested operations.
    ///
    /// Child contexts have their own step counter but share the same
    /// execution state. Operations in a child context are tracked
    /// with the parent's operation ID.
    ///
    /// # Arguments
    ///
    /// * `parent_operation_id` - The operation ID of the parent operation
    pub fn create_child_context(&self, parent_operation_id: impl Into<String>) -> Self {
        let parent_id = parent_operation_id.into();
        Self {
            state: self.state.clone(),
            lambda_context: self.lambda_context.clone(),
            parent_id: Some(parent_id.clone()),
            id_generator: Arc::new(OperationIdGenerator::new(parent_id)),
            logger: self.logger.clone(),
        }
    }

    /// Sets a custom logger for this context.
    ///
    /// # Arguments
    ///
    /// * `logger` - The logger implementation to use
    pub fn set_logger(&mut self, logger: Arc<dyn Logger>) {
        *self.logger.write().unwrap() = logger;
    }

    /// Returns a new context with the specified logger.
    ///
    /// # Arguments
    ///
    /// * `logger` - The logger implementation to use
    pub fn with_logger(self, logger: Arc<dyn Logger>) -> Self {
        *self.logger.write().unwrap() = logger;
        self
    }

    /// Reconfigures the logger for this context at runtime.
    ///
    /// All subsequent log calls on this context (and any clones sharing the
    /// same underlying `RwLock`) will use the new logger.
    ///
    /// # Arguments
    ///
    /// * `logger` - The new logger implementation to use
    pub fn configure_logger(&self, logger: Arc<dyn Logger>) {
        *self.logger.write().unwrap() = logger;
    }

    /// Returns a reference to the execution state.
    pub fn state(&self) -> &Arc<ExecutionState> {
        &self.state
    }

    /// Returns the durable execution ARN.
    pub fn durable_execution_arn(&self) -> &str {
        self.state.durable_execution_arn()
    }

    /// Returns the parent operation ID, if any.
    pub fn parent_id(&self) -> Option<&str> {
        self.parent_id.as_deref()
    }

    /// Returns a reference to the Lambda context, if available.
    pub fn lambda_context(&self) -> Option<&lambda_runtime::Context> {
        self.lambda_context.as_ref()
    }

    /// Returns a reference to the logger.
    pub fn logger(&self) -> Arc<dyn Logger> {
        self.logger.read().unwrap().clone()
    }

    /// Generates the next operation ID for this context.
    ///
    /// This method is thread-safe and will generate unique, deterministic
    /// IDs based on the context's base ID and step counter.
    pub fn next_operation_id(&self) -> String {
        self.id_generator.next_id()
    }

    /// Creates an OperationIdentifier for the next operation.
    ///
    /// # Arguments
    ///
    /// * `name` - Optional human-readable name for the operation
    pub fn next_operation_identifier(&self, name: Option<String>) -> OperationIdentifier {
        OperationIdentifier::new(self.next_operation_id(), self.parent_id.clone(), name)
    }

    /// Returns the current step counter value without incrementing.
    pub fn current_step_counter(&self) -> u64 {
        self.id_generator.current_counter()
    }

    /// Creates log info for the current context.
    ///
    /// The returned `LogInfo` includes the current replay status from the
    /// execution state, allowing loggers to distinguish between fresh
    /// executions and replayed operations.
    pub fn create_log_info(&self) -> LogInfo {
        let mut info = LogInfo::new(self.durable_execution_arn());
        if let Some(ref parent_id) = self.parent_id {
            info = info.with_parent_id(parent_id);
        }
        // Include replay status from execution state
        info = info.with_replay(self.state.is_replay());
        info
    }

    /// Creates log info with an operation ID.
    ///
    /// The returned `LogInfo` includes the current replay status from the
    /// execution state, allowing loggers to distinguish between fresh
    /// executions and replayed operations.
    pub fn create_log_info_with_operation(&self, operation_id: &str) -> LogInfo {
        self.create_log_info().with_operation_id(operation_id)
    }

    /// Creates log info with explicit replay status.
    ///
    /// This method allows callers to explicitly set the replay status,
    /// which is useful when the operation-specific replay status differs
    /// from the global execution state replay status.
    ///
    /// # Arguments
    ///
    /// * `operation_id` - The operation ID to include in the log info
    /// * `is_replay` - Whether this specific operation is being replayed
    pub fn create_log_info_with_replay(&self, operation_id: &str, is_replay: bool) -> LogInfo {
        let mut info = LogInfo::new(self.durable_execution_arn());
        if let Some(ref parent_id) = self.parent_id {
            info = info.with_parent_id(parent_id);
        }
        info.with_operation_id(operation_id).with_replay(is_replay)
    }

    // ========================================================================
    // Simplified Logging API
    // ========================================================================

    /// Logs a message at INFO level with automatic context.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output without requiring the caller to specify them.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_info("Processing order started");
    /// ```
    pub fn log_info(&self, message: &str) {
        self.log_with_level(LogLevel::Info, message, &[]);
    }

    /// Logs a message at INFO level with extra fields.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output, plus any additional fields specified.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    /// * `fields` - Additional key-value pairs to include in the log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_info_with("Processing order", &[("order_id", "123"), ("amount", "99.99")]);
    /// ```
    pub fn log_info_with(&self, message: &str, fields: &[(&str, &str)]) {
        self.log_with_level(LogLevel::Info, message, fields);
    }

    /// Logs a message at DEBUG level with automatic context.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output without requiring the caller to specify them.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_debug("Entering validation step");
    /// ```
    pub fn log_debug(&self, message: &str) {
        self.log_with_level(LogLevel::Debug, message, &[]);
    }

    /// Logs a message at DEBUG level with extra fields.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output, plus any additional fields specified.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    /// * `fields` - Additional key-value pairs to include in the log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_debug_with("Variable state", &[("x", "42"), ("y", "100")]);
    /// ```
    pub fn log_debug_with(&self, message: &str, fields: &[(&str, &str)]) {
        self.log_with_level(LogLevel::Debug, message, fields);
    }

    /// Logs a message at WARN level with automatic context.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output without requiring the caller to specify them.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_warn("Retry attempt 3 of 5");
    /// ```
    pub fn log_warn(&self, message: &str) {
        self.log_with_level(LogLevel::Warn, message, &[]);
    }

    /// Logs a message at WARN level with extra fields.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output, plus any additional fields specified.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    /// * `fields` - Additional key-value pairs to include in the log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_warn_with("Rate limit approaching", &[("current", "95"), ("limit", "100")]);
    /// ```
    pub fn log_warn_with(&self, message: &str, fields: &[(&str, &str)]) {
        self.log_with_level(LogLevel::Warn, message, fields);
    }

    /// Logs a message at ERROR level with automatic context.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output without requiring the caller to specify them.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_error("Failed to process payment");
    /// ```
    pub fn log_error(&self, message: &str) {
        self.log_with_level(LogLevel::Error, message, &[]);
    }

    /// Logs a message at ERROR level with extra fields.
    ///
    /// This method automatically includes the durable_execution_arn and parent_id
    /// in the log output, plus any additional fields specified.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to log
    /// * `fields` - Additional key-value pairs to include in the log
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// ctx.log_error_with("Payment failed", &[("error_code", "INSUFFICIENT_FUNDS"), ("amount", "150.00")]);
    /// ```
    pub fn log_error_with(&self, message: &str, fields: &[(&str, &str)]) {
        self.log_with_level(LogLevel::Error, message, fields);
    }

    /// Internal helper method to log at a specific level with optional extra fields.
    ///
    /// This method creates a LogInfo with automatic context (durable_execution_arn, parent_id)
    /// and any additional fields, then delegates to the configured logger.
    ///
    /// # Arguments
    ///
    /// * `level` - The log level
    /// * `message` - The message to log
    /// * `extra` - Additional key-value pairs to include
    fn log_with_level(&self, level: LogLevel, message: &str, extra: &[(&str, &str)]) {
        let mut log_info = self.create_log_info();

        for (key, value) in extra {
            log_info = log_info.with_extra(*key, *value);
        }

        let logger = self.logger.read().unwrap();
        match level {
            LogLevel::Debug => logger.debug(message, &log_info),
            LogLevel::Info => logger.info(message, &log_info),
            LogLevel::Warn => logger.warn(message, &log_info),
            LogLevel::Error => logger.error(message, &log_info),
        }
    }

    /// Returns the original user input from the EXECUTION operation.
    ///
    /// This method deserializes the input payload from the EXECUTION operation's
    /// ExecutionDetails.InputPayload field into the requested type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type to deserialize the input into. Must implement `DeserializeOwned`.
    ///
    /// # Returns
    ///
    /// `Ok(T)` if the input exists and can be deserialized, or a `DurableError` if:
    /// - No EXECUTION operation exists
    /// - No input payload is available
    /// - Deserialization fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// #[derive(Deserialize)]
    /// struct OrderEvent {
    ///     order_id: String,
    ///     amount: f64,
    /// }
    ///
    /// async fn my_workflow(ctx: DurableContext) -> Result<(), DurableError> {
    ///     // Get the original input that started this execution
    ///     let event: OrderEvent = ctx.get_original_input()?;
    ///     println!("Processing order: {}", event.order_id);
    ///     Ok(())
    /// }
    /// ```
    pub fn get_original_input<T>(&self) -> DurableResult<T>
    where
        T: serde::de::DeserializeOwned,
    {
        // Get the raw input payload from the execution state
        let input_payload = self.state.get_original_input_raw().ok_or_else(|| {
            crate::error::DurableError::Validation {
                message: "No original input available. The EXECUTION operation may not exist or has no input payload.".to_string(),
            }
        })?;

        // Deserialize the input payload to the requested type
        serde_json::from_str(input_payload).map_err(|e| crate::error::DurableError::SerDes {
            message: format!("Failed to deserialize original input: {}", e),
        })
    }

    /// Returns the raw original user input as a string, if available.
    ///
    /// This method returns the raw JSON string from the EXECUTION operation's
    /// ExecutionDetails.InputPayload field without deserializing it.
    ///
    /// # Returns
    ///
    /// `Some(&str)` if the input exists, `None` otherwise.
    pub fn get_original_input_raw(&self) -> Option<&str> {
        self.state.get_original_input_raw()
    }

    /// Completes the execution with a successful result via checkpointing.
    ///
    /// This method checkpoints a SUCCEED action on the EXECUTION operation,
    /// which is useful for large results that exceed the Lambda response size limit (6MB).
    /// After calling this method, the Lambda function should return an empty result.
    ///
    /// # Arguments
    ///
    /// * `result` - The result to checkpoint. Must implement `Serialize`.
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or a `DurableError` if:
    /// - No EXECUTION operation exists
    /// - Serialization fails
    /// - The checkpoint fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn my_workflow(ctx: DurableContext) -> Result<(), DurableError> {
    ///     let large_result = compute_large_result().await?;
    ///     
    ///     // Check if result would exceed Lambda response limit
    ///     if DurableExecutionInvocationOutput::would_exceed_max_size(&large_result) {
    ///         // Checkpoint the result instead of returning it
    ///         ctx.complete_execution_success(&large_result).await?;
    ///         // Return empty result - the actual result is checkpointed
    ///         return Ok(());
    ///     }
    ///     
    ///     Ok(())
    /// }
    /// ```
    pub async fn complete_execution_success<T>(&self, result: &T) -> DurableResult<()>
    where
        T: serde::Serialize,
    {
        let serialized =
            serde_json::to_string(result).map_err(|e| crate::error::DurableError::SerDes {
                message: format!("Failed to serialize execution result: {}", e),
            })?;

        self.state
            .complete_execution_success(Some(serialized))
            .await
    }

    /// Completes the execution with a failure via checkpointing.
    ///
    /// This method checkpoints a FAIL action on the EXECUTION operation.
    /// After calling this method, the Lambda function should return a FAILED status.
    ///
    /// # Arguments
    ///
    /// * `error` - The error details to checkpoint
    ///
    /// # Returns
    ///
    /// `Ok(())` on success, or a `DurableError` if:
    /// - No EXECUTION operation exists
    /// - The checkpoint fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn my_workflow(ctx: DurableContext) -> Result<(), DurableError> {
    ///     if let Err(e) = process_order().await {
    ///         // Checkpoint the failure
    ///         ctx.complete_execution_failure(ErrorObject::new("ProcessingError", &e.to_string())).await?;
    ///         return Err(DurableError::execution(&e.to_string()));
    ///     }
    ///     Ok(())
    /// }
    /// ```
    pub async fn complete_execution_failure(
        &self,
        error: crate::error::ErrorObject,
    ) -> DurableResult<()> {
        self.state.complete_execution_failure(error).await
    }

    /// Completes the execution with a successful result, automatically handling large results.
    ///
    /// This method checks if the result would exceed the Lambda response size limit (6MB).
    /// If so, it checkpoints the result via the EXECUTION operation and returns `true`.
    /// If the result fits within the limit, it returns `false` and the caller should
    /// return the result normally.
    ///
    /// # Arguments
    ///
    /// * `result` - The result to potentially checkpoint. Must implement `Serialize`.
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the result was checkpointed (caller should return empty result),
    /// `Ok(false)` if the result fits within limits (caller should return it normally),
    /// or a `DurableError` if checkpointing fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// async fn my_workflow(ctx: DurableContext) -> Result<LargeResult, DurableError> {
    ///     let result = compute_result().await?;
    ///     
    ///     // Automatically handle large results
    ///     if ctx.complete_execution_if_large(&result).await? {
    ///         // Result was checkpointed, return a placeholder
    ///         // The actual result is stored in the EXECUTION operation
    ///         return Ok(LargeResult::default());
    ///     }
    ///     
    ///     // Result fits within limits, return normally
    ///     Ok(result)
    /// }
    /// ```
    pub async fn complete_execution_if_large<T>(&self, result: &T) -> DurableResult<bool>
    where
        T: serde::Serialize,
    {
        if crate::lambda::DurableExecutionInvocationOutput::would_exceed_max_size(result) {
            self.complete_execution_success(result).await?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    // ========================================================================
    // Durable Operations
    // ========================================================================

    /// Executes a step operation with automatic checkpointing.
    ///
    /// Steps are the fundamental unit of work in durable executions. Each step
    /// is checkpointed, allowing the workflow to resume from the last completed
    /// step after interruptions.
    ///
    /// # Arguments
    ///
    /// * `func` - The function to execute
    /// * `config` - Optional step configuration (retry strategy, semantics, serdes)
    ///
    /// # Returns
    ///
    /// The result of the step function, or an error if execution fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result: i32 = ctx.step(|_step_ctx| async move {
    ///     Ok(42)
    /// }, None).await?;
    /// ```
    pub async fn step<T, F, Fut>(
        &self,
        func: F,
        config: Option<crate::config::StepConfig>,
    ) -> DurableResult<T>
    where
        T: DurableValue,
        F: FnOnce(StepContext) -> Fut + Send,
        Fut: std::future::Future<Output = Result<T, Box<dyn std::error::Error + Send + Sync>>>
            + Send,
    {
        let op_id = self.next_operation_identifier(None);
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::step_handler(func, &self.state, &op_id, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Executes a named step operation with automatic checkpointing.
    ///
    /// Same as `step`, but allows specifying a human-readable name for the operation.
    ///
    /// # Arguments
    ///
    /// * `name` - Human-readable name for the step
    /// * `func` - The function to execute
    /// * `config` - Optional step configuration
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result: i32 = ctx.step_named("validate_input", |_step_ctx| async move {
    ///     Ok(42)
    /// }, None).await?;
    /// ```
    pub async fn step_named<T, F, Fut>(
        &self,
        name: &str,
        func: F,
        config: Option<crate::config::StepConfig>,
    ) -> DurableResult<T>
    where
        T: DurableValue,
        F: FnOnce(StepContext) -> Fut + Send,
        Fut: std::future::Future<Output = Result<T, Box<dyn std::error::Error + Send + Sync>>>
            + Send,
    {
        let op_id = self.next_operation_identifier(Some(name.to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::step_handler(func, &self.state, &op_id, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Pauses execution for a specified duration.
    ///
    /// Wait operations suspend the Lambda execution and resume after the
    /// specified duration has elapsed. This is efficient because it doesn't
    /// block Lambda resources during the wait.
    ///
    /// # Arguments
    ///
    /// * `duration` - The duration to wait (must be at least 1 second)
    /// * `name` - Optional human-readable name for the operation
    ///
    /// # Returns
    ///
    /// Ok(()) when the wait has elapsed, or an error if validation fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Wait for 5 seconds
    /// ctx.wait(Duration::from_seconds(5), None).await?;
    ///
    /// // Wait with a name
    /// ctx.wait(Duration::from_minutes(1), Some("wait_for_processing")).await?;
    /// ```
    pub async fn wait(
        &self,
        duration: crate::duration::Duration,
        name: Option<&str>,
    ) -> DurableResult<()> {
        let op_id = self.next_operation_identifier(name.map(|s| s.to_string()));

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::wait_handler(duration, &self.state, &op_id, &logger).await;

        // Track replay after completion (only if not suspended)
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Cancels an active wait operation.
    ///
    /// This method allows cancelling a wait operation that was previously started.
    /// If the wait has already completed (succeeded, failed, or timed out), this
    /// method will return Ok(()) without making any changes.
    ///
    /// # Arguments
    ///
    /// * `operation_id` - The operation ID of the wait to cancel
    ///
    /// # Returns
    ///
    /// Ok(()) if the wait was cancelled or was already completed, or an error if:
    /// - The operation doesn't exist
    /// - The operation is not a WAIT operation
    /// - The checkpoint fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Start a wait in a parallel branch
    /// let wait_op_id = ctx.next_operation_id();
    ///
    /// // Later, cancel the wait from another branch
    /// ctx.cancel_wait(&wait_op_id).await?;
    /// ```
    pub async fn cancel_wait(&self, operation_id: &str) -> DurableResult<()> {
        let logger = self.logger.read().unwrap().clone();
        crate::handlers::wait_cancel_handler(&self.state, operation_id, &logger).await
    }

    /// Creates a callback and returns a handle to wait for the result.
    ///
    /// Callbacks allow external systems to signal completion of asynchronous
    /// operations. The callback ID can be shared with external systems, which
    /// can then call the Lambda durable execution callback API.
    ///
    /// # Arguments
    ///
    /// * `config` - Optional callback configuration (timeout, heartbeat)
    ///
    /// # Returns
    ///
    /// A `Callback<T>` handle that can be used to wait for the result.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let callback = ctx.create_callback::<ApprovalResponse>(None).await?;
    ///
    /// // Share callback.callback_id with external system
    /// notify_approver(&callback.callback_id).await?;
    ///
    /// // Wait for the callback result
    /// let approval = callback.result().await?;
    /// ```
    pub async fn create_callback<T>(
        &self,
        config: Option<crate::config::CallbackConfig>,
    ) -> DurableResult<crate::handlers::Callback<T>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned,
    {
        let op_id = self.next_operation_identifier(None);
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::callback_handler(&self.state, &op_id, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Creates a named callback and returns a handle to wait for the result.
    ///
    /// Same as `create_callback`, but allows specifying a human-readable name.
    pub async fn create_callback_named<T>(
        &self,
        name: &str,
        config: Option<crate::config::CallbackConfig>,
    ) -> DurableResult<crate::handlers::Callback<T>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned,
    {
        let op_id = self.next_operation_identifier(Some(name.to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::callback_handler(&self.state, &op_id, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Invokes another durable Lambda function.
    ///
    /// This method calls another Lambda function and waits for its result.
    /// The invocation is checkpointed, so if the workflow is interrupted,
    /// it will resume with the result of the invocation.
    ///
    /// # Arguments
    ///
    /// * `function_name` - The name or ARN of the Lambda function to invoke
    /// * `payload` - The payload to send to the function
    /// * `config` - Optional invoke configuration (timeout, serdes)
    ///
    /// # Returns
    ///
    /// The result from the invoked function, or an error if invocation fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result: ProcessingResult = ctx.invoke(
    ///     "process-order-function",
    ///     OrderPayload { order_id: "123".to_string() },
    ///     None,
    /// ).await?;
    /// ```
    pub async fn invoke<P, R>(
        &self,
        function_name: &str,
        payload: P,
        config: Option<crate::config::InvokeConfig<P, R>>,
    ) -> DurableResult<R>
    where
        P: serde::Serialize + serde::de::DeserializeOwned + Send,
        R: serde::Serialize + serde::de::DeserializeOwned + Send,
    {
        let op_id = self.next_operation_identifier(Some(format!("invoke:{}", function_name)));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::invoke_handler(
            function_name,
            payload,
            &self.state,
            &op_id,
            &config,
            &logger,
        )
        .await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Processes a collection in parallel with configurable concurrency.
    ///
    /// Map operations execute a function for each item in the collection,
    /// with configurable concurrency limits and failure tolerance.
    ///
    /// # Arguments
    ///
    /// * `items` - The collection of items to process
    /// * `func` - The function to apply to each item
    /// * `config` - Optional map configuration (concurrency, completion criteria)
    ///
    /// # Returns
    ///
    /// A `BatchResult<U>` containing results for all items.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = ctx.map(
    ///     vec![1, 2, 3, 4, 5],
    ///     |child_ctx, item, index| async move {
    ///         Ok(item * 2)
    ///     },
    ///     Some(MapConfig {
    ///         max_concurrency: Some(3),
    ///         ..Default::default()
    ///     }),
    /// ).await?;
    /// ```
    pub async fn map<T, U, F, Fut>(
        &self,
        items: Vec<T>,
        func: F,
        config: Option<crate::config::MapConfig>,
    ) -> DurableResult<crate::concurrency::BatchResult<U>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + Clone + 'static,
        U: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
        F: Fn(DurableContext, T, usize) -> Fut + Send + Sync + Clone + 'static,
        Fut: std::future::Future<Output = DurableResult<U>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("map".to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::map_handler(items, func, &self.state, &op_id, self, &config, &logger)
                .await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Executes multiple operations in parallel.
    ///
    /// Parallel operations execute multiple independent functions concurrently,
    /// with configurable concurrency limits and completion criteria.
    ///
    /// # Arguments
    ///
    /// * `branches` - The list of functions to execute in parallel
    /// * `config` - Optional parallel configuration (concurrency, completion criteria)
    ///
    /// # Returns
    ///
    /// A `BatchResult<T>` containing results for all branches.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = ctx.parallel(
    ///     vec![
    ///         |ctx| async move { Ok(fetch_data_a(&ctx).await?) },
    ///         |ctx| async move { Ok(fetch_data_b(&ctx).await?) },
    ///         |ctx| async move { Ok(fetch_data_c(&ctx).await?) },
    ///     ],
    ///     None,
    /// ).await?;
    /// ```
    pub async fn parallel<T, F, Fut>(
        &self,
        branches: Vec<F>,
        config: Option<crate::config::ParallelConfig>,
    ) -> DurableResult<crate::concurrency::BatchResult<T>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
        F: FnOnce(DurableContext) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = DurableResult<T>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("parallel".to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::parallel_handler(
            branches,
            &self.state,
            &op_id,
            self,
            &config,
            &logger,
        )
        .await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Executes a function in a child context.
    ///
    /// Child contexts provide isolation for nested workflows. Operations in
    /// a child context are tracked separately and can be checkpointed as a unit.
    ///
    /// # Arguments
    ///
    /// * `func` - The function to execute in the child context
    /// * `config` - Optional child context configuration
    ///
    /// # Returns
    ///
    /// The result of the child function, or an error if execution fails.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = ctx.run_in_child_context(|child_ctx| async move {
    ///     let step1 = child_ctx.step(|_| Ok(1), None).await?;
    ///     let step2 = child_ctx.step(|_| Ok(2), None).await?;
    ///     Ok(step1 + step2)
    /// }, None).await?;
    /// ```
    pub async fn run_in_child_context<T, F, Fut>(
        &self,
        func: F,
        config: Option<crate::config::ChildConfig>,
    ) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send,
        F: FnOnce(DurableContext) -> Fut + Send,
        Fut: std::future::Future<Output = DurableResult<T>> + Send,
    {
        let op_id = self.next_operation_identifier(Some("child_context".to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::child_handler(func, &self.state, &op_id, self, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Executes a named function in a child context.
    ///
    /// Same as `run_in_child_context`, but allows specifying a human-readable name.
    pub async fn run_in_child_context_named<T, F, Fut>(
        &self,
        name: &str,
        func: F,
        config: Option<crate::config::ChildConfig>,
    ) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send,
        F: FnOnce(DurableContext) -> Fut + Send,
        Fut: std::future::Future<Output = DurableResult<T>> + Send,
    {
        let op_id = self.next_operation_identifier(Some(name.to_string()));
        let config = config.unwrap_or_default();

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::child_handler(func, &self.state, &op_id, self, &config, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Polls until a condition is met.
    ///
    /// This method repeatedly checks a condition until it returns a successful
    /// result. Between checks, it waits for a configurable duration using the
    /// RETRY mechanism with NextAttemptDelaySeconds.
    ///
    /// # Implementation
    ///
    /// This method is implemented as a single STEP operation with RETRY mechanism,
    /// which is more efficient than using multiple steps and waits. The state is
    /// passed as Payload on retry (not Error), and the attempt number is tracked
    /// in StepDetails.Attempt.
    ///
    /// # Arguments
    ///
    /// * `check` - The function to check the condition
    /// * `config` - Configuration for the wait (interval, max attempts, timeout)
    ///
    /// # Returns
    ///
    /// The result when the condition is met, or an error if timeout/max attempts exceeded.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = ctx.wait_for_condition(
    ///     |state, ctx| {
    ///         let order_id = state.order_id.clone();
    ///         async move {
    ///             // Check if order is ready
    ///             let status = check_order_status(&order_id).await?;
    ///             if status == "ready" {
    ///                 Ok(OrderReady { order_id })
    ///             } else {
    ///                 Err("Order not ready yet".into())
    ///             }
    ///         }
    ///     },
    ///     WaitForConditionConfig::from_interval(
    ///         OrderState { order_id: "123".to_string() },
    ///         Duration::from_seconds(5),
    ///         Some(10),
    ///     ),
    /// ).await?;
    /// ```
    pub async fn wait_for_condition<T, S, F, Fut>(
        &self,
        check: F,
        config: WaitForConditionConfig<S>,
    ) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send,
        S: serde::Serialize + serde::de::DeserializeOwned + Clone + Send + Sync,
        F: Fn(&S, &WaitForConditionContext) -> Fut + Send + Sync,
        Fut: std::future::Future<Output = Result<T, Box<dyn std::error::Error + Send + Sync>>>
            + Send,
    {
        let op_id = self.next_operation_identifier(Some("wait_for_condition".to_string()));

        let logger = self.logger.read().unwrap().clone();
        // Use the new wait_for_condition_handler which implements the single STEP with RETRY pattern
        // This is more efficient than the previous child context + multiple steps approach
        let result = crate::handlers::wait_for_condition_handler(
            check,
            config,
            &self.state,
            &op_id,
            &logger,
        )
        .await;

        // Track replay after completion (only if not suspended)
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Creates a callback and waits for the result with a submitter function.
    ///
    /// This is a convenience method that combines callback creation with
    /// a submitter function that sends the callback ID to an external system.
    /// The submitter execution is checkpointed within a child context to ensure
    /// replay safety - the submitter will not be re-executed during replay.
    ///
    /// # Arguments
    ///
    /// * `submitter` - Function that receives the callback ID and submits it to external system
    /// * `config` - Optional callback configuration (timeout, heartbeat)
    ///
    /// # Returns
    ///
    /// The callback result from the external system.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let approval = ctx.wait_for_callback(
    ///     |callback_id| async move {
    ///         // Send callback ID to approval system
    ///         send_approval_request(&callback_id, &request).await
    ///     },
    ///     Some(CallbackConfig {
    ///         timeout: Duration::from_hours(24),
    ///         ..Default::default()
    ///     }),
    /// ).await?;
    /// ```
    pub async fn wait_for_callback<T, F, Fut>(
        &self,
        submitter: F,
        config: Option<crate::config::CallbackConfig>,
    ) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Sync,
        F: FnOnce(String) -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<(), Box<dyn std::error::Error + Send + Sync>>>
            + Send
            + 'static,
    {
        // Create the callback first with the provided configuration (Requirement 1.4)
        let callback: crate::handlers::Callback<T> = self.create_callback(config).await?;
        let callback_id = callback.callback_id.clone();

        // Generate operation ID for the child context that will execute the submitter
        let op_id = self.next_operation_identifier(Some("wait_for_callback_submitter".to_string()));

        // Execute the submitter within a child context for proper checkpointing (Requirements 1.1, 1.2)
        // The child context ensures the submitter execution is tracked and not re-executed during replay
        let child_config = crate::config::ChildConfig::default();

        let logger = self.logger.read().unwrap().clone();
        crate::handlers::child_handler(
            |child_ctx| {
                let callback_id = callback_id.clone();
                async move {
                    // Use a step to checkpoint that we're about to execute the submitter
                    // This step returns () on success, indicating submission completed
                    child_ctx
                        .step_named(
                            "execute_submitter",
                            move |_| async move {
                                // The step just marks that we're executing the submitter
                                // The actual async submitter call happens after this checkpoint
                                Ok(())
                            },
                            None,
                        )
                        .await?;

                    // Now execute the actual submitter
                    // If we're replaying and the step above succeeded, we won't reach here
                    // because the child context will return the checkpointed result
                    submitter(callback_id).await.map_err(|e| {
                        crate::error::DurableError::UserCode {
                            message: e.to_string(),
                            error_type: "SubmitterError".to_string(),
                            stack_trace: None,
                        }
                    })?;

                    Ok(())
                }
            },
            &self.state,
            &op_id,
            self,
            &child_config,
            &logger,
        )
        .await?;

        // Track replay after child context completion
        self.state.track_replay(&op_id.operation_id).await;

        // Wait for the callback result
        callback.result().await
    }

    // ========================================================================
    // Promise Combinators
    // ========================================================================

    /// Waits for all futures to complete successfully.
    ///
    /// Returns all results if all futures succeed, or returns the first error encountered.
    /// This is implemented within a STEP operation for durability.
    ///
    /// # Arguments
    ///
    /// * `futures` - Vector of futures to execute
    ///
    /// # Returns
    ///
    /// `Ok(Vec<T>)` if all futures succeed, or `Err` with the first error.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = ctx.all(vec![
    ///     ctx.step(|_| Ok(1), None),
    ///     ctx.step(|_| Ok(2), None),
    ///     ctx.step(|_| Ok(3), None),
    /// ]).await?;
    /// assert_eq!(results, vec![1, 2, 3]);
    /// ```
    pub async fn all<T, Fut>(&self, futures: Vec<Fut>) -> DurableResult<Vec<T>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Clone + 'static,
        Fut: std::future::Future<Output = DurableResult<T>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("all".to_string()));

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::all_handler(futures, &self.state, &op_id, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Waits for all futures to settle (success or failure).
    ///
    /// Returns a BatchResult containing outcomes for all futures, regardless of success or failure.
    /// This is implemented within a STEP operation for durability.
    ///
    /// # Arguments
    ///
    /// * `futures` - Vector of futures to execute
    ///
    /// # Returns
    ///
    /// `BatchResult<T>` containing results for all futures.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let results = ctx.all_settled(vec![
    ///     ctx.step(|_| Ok(1), None),
    ///     ctx.step(|_| Err("error".into()), None),
    ///     ctx.step(|_| Ok(3), None),
    /// ]).await?;
    /// assert_eq!(results.success_count(), 2);
    /// assert_eq!(results.failure_count(), 1);
    /// ```
    pub async fn all_settled<T, Fut>(
        &self,
        futures: Vec<Fut>,
    ) -> DurableResult<crate::concurrency::BatchResult<T>>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Clone + 'static,
        Fut: std::future::Future<Output = DurableResult<T>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("all_settled".to_string()));

        let logger = self.logger.read().unwrap().clone();
        let result =
            crate::handlers::all_settled_handler(futures, &self.state, &op_id, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Returns the result of the first future to settle.
    ///
    /// Returns the result (success or failure) of whichever future completes first.
    /// This is implemented within a STEP operation for durability.
    ///
    /// # Arguments
    ///
    /// * `futures` - Vector of futures to execute
    ///
    /// # Returns
    ///
    /// The result of the first future to settle.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = ctx.race(vec![
    ///     ctx.step(|_| Ok(1), None),
    ///     ctx.step(|_| Ok(2), None),
    /// ]).await?;
    /// // result is either 1 or 2, whichever completed first
    /// ```
    pub async fn race<T, Fut>(&self, futures: Vec<Fut>) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Clone + 'static,
        Fut: std::future::Future<Output = DurableResult<T>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("race".to_string()));

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::race_handler(futures, &self.state, &op_id, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }

    /// Returns the result of the first future to succeed.
    ///
    /// Returns the result of the first future to succeed. If all futures fail,
    /// returns an error containing all the failures.
    /// This is implemented within a STEP operation for durability.
    ///
    /// # Arguments
    ///
    /// * `futures` - Vector of futures to execute
    ///
    /// # Returns
    ///
    /// The result of the first future to succeed, or an error if all fail.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let result = ctx.any(vec![
    ///     ctx.step(|_| Err("error".into()), None),
    ///     ctx.step(|_| Ok(2), None),
    ///     ctx.step(|_| Ok(3), None),
    /// ]).await?;
    /// // result is either 2 or 3, whichever succeeded first
    /// ```
    pub async fn any<T, Fut>(&self, futures: Vec<Fut>) -> DurableResult<T>
    where
        T: serde::Serialize + serde::de::DeserializeOwned + Send + Clone + 'static,
        Fut: std::future::Future<Output = DurableResult<T>> + Send + 'static,
    {
        let op_id = self.next_operation_identifier(Some("any".to_string()));

        let logger = self.logger.read().unwrap().clone();
        let result = crate::handlers::any_handler(futures, &self.state, &op_id, &logger).await;

        // Track replay after completion
        if result.is_ok() {
            self.state.track_replay(&op_id.operation_id).await;
        }

        result
    }
}

/// Configuration for wait_for_condition operations.
#[allow(clippy::type_complexity)]
pub struct WaitForConditionConfig<S> {
    /// Initial state to pass to the check function.
    pub initial_state: S,
    /// Wait strategy function that determines polling behavior.
    ///
    /// Takes a reference to the current state and the attempt number (1-indexed),
    /// and returns a [`WaitDecision`](crate::config::WaitDecision).
    pub wait_strategy: Box<dyn Fn(&S, usize) -> crate::config::WaitDecision + Send + Sync>,
    /// Overall timeout for the operation.
    pub timeout: Option<crate::duration::Duration>,
    /// Optional custom serializer/deserializer.
    pub serdes: Option<std::sync::Arc<dyn crate::config::SerDesAny>>,
}

impl<S> std::fmt::Debug for WaitForConditionConfig<S>
where
    S: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaitForConditionConfig")
            .field("initial_state", &self.initial_state)
            .field("wait_strategy", &"<fn>")
            .field("timeout", &self.timeout)
            .field("serdes", &self.serdes.is_some())
            .finish()
    }
}

impl<S> WaitForConditionConfig<S> {
    /// Creates a backward-compatible `WaitForConditionConfig` from interval and max_attempts.
    ///
    /// This constructor converts the old-style `interval` + `max_attempts` parameters
    /// into a wait strategy that uses a fixed delay (no backoff, no jitter).
    ///
    /// # Arguments
    ///
    /// * `initial_state` - Initial state to pass to the check function.
    /// * `interval` - Fixed interval between condition checks.
    /// * `max_attempts` - Maximum number of attempts (`None` for unlimited).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use durable_execution_sdk::{WaitForConditionConfig, Duration};
    ///
    /// let config = WaitForConditionConfig::from_interval(
    ///     my_initial_state,
    ///     Duration::from_seconds(5),
    ///     Some(10),
    /// );
    /// ```
    pub fn from_interval(
        initial_state: S,
        interval: crate::duration::Duration,
        max_attempts: Option<usize>,
    ) -> Self
    where
        S: Send + Sync + 'static,
    {
        let interval_secs = interval.to_seconds();
        let max = max_attempts.unwrap_or(usize::MAX);

        Self {
            initial_state,
            wait_strategy: Box::new(move |_state: &S, attempts_made: usize| {
                // In the backward-compatible mode, the check function's Ok/Err
                // determines whether polling is done. The strategy only provides
                // the delay and enforces max_attempts.
                // Return Done when max_attempts exceeded (handler will checkpoint failure
                // if check returned Err, or success if check returned Ok).
                if attempts_made >= max {
                    return crate::config::WaitDecision::Done;
                }
                crate::config::WaitDecision::Continue {
                    delay: crate::duration::Duration::from_seconds(interval_secs),
                }
            }),
            timeout: None,
            serdes: None,
        }
    }
}

impl<S: Default + Send + Sync + 'static> Default for WaitForConditionConfig<S> {
    fn default() -> Self {
        Self::from_interval(
            S::default(),
            crate::duration::Duration::from_seconds(5),
            None,
        )
    }
}

/// Context provided to wait_for_condition check functions.
#[derive(Debug, Clone)]
pub struct WaitForConditionContext {
    /// Current attempt number (1-indexed).
    pub attempt: usize,
    /// Maximum number of attempts (None for unlimited).
    pub max_attempts: Option<usize>,
}

impl Clone for DurableContext {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            lambda_context: self.lambda_context.clone(),
            parent_id: self.parent_id.clone(),
            id_generator: self.id_generator.clone(),
            logger: self.logger.clone(),
        }
    }
}

impl std::fmt::Debug for DurableContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DurableContext")
            .field("durable_execution_arn", &self.durable_execution_arn())
            .field("parent_id", &self.parent_id)
            .field("step_counter", &self.current_step_counter())
            .finish_non_exhaustive()
    }
}

// Add hex encoding dependency
mod hex {
    const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";

    pub fn encode(bytes: &[u8]) -> String {
        let mut result = String::with_capacity(bytes.len() * 2);
        for &byte in bytes {
            result.push(HEX_CHARS[(byte >> 4) as usize] as char);
            result.push(HEX_CHARS[(byte & 0x0f) as usize] as char);
        }
        result
    }
}

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

    #[test]
    fn test_operation_identifier_new() {
        let id = OperationIdentifier::new(
            "op-123",
            Some("parent-456".to_string()),
            Some("my-step".to_string()),
        );
        assert_eq!(id.operation_id, "op-123");
        assert_eq!(id.parent_id, Some("parent-456".to_string()));
        assert_eq!(id.name, Some("my-step".to_string()));
    }

    #[test]
    fn test_operation_identifier_root() {
        let id = OperationIdentifier::root("op-123");
        assert_eq!(id.operation_id, "op-123");
        assert!(id.parent_id.is_none());
        assert!(id.name.is_none());
    }

    #[test]
    fn test_operation_identifier_with_parent() {
        let id = OperationIdentifier::with_parent("op-123", "parent-456");
        assert_eq!(id.operation_id, "op-123");
        assert_eq!(id.parent_id, Some("parent-456".to_string()));
        assert!(id.name.is_none());
    }

    #[test]
    fn test_operation_identifier_with_name() {
        let id = OperationIdentifier::root("op-123").with_name("my-step");
        assert_eq!(id.name, Some("my-step".to_string()));
    }

    #[test]
    fn test_operation_identifier_display() {
        let id = OperationIdentifier::root("op-123");
        assert_eq!(format!("{}", id), "op-123");

        let id_with_name = OperationIdentifier::root("op-123").with_name("my-step");
        assert_eq!(format!("{}", id_with_name), "my-step(op-123)");
    }

    #[test]
    fn test_generate_operation_id_deterministic() {
        let id1 = generate_operation_id("base-123", 0);
        let id2 = generate_operation_id("base-123", 0);
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_generate_operation_id_different_counters() {
        let id1 = generate_operation_id("base-123", 0);
        let id2 = generate_operation_id("base-123", 1);
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_generate_operation_id_different_bases() {
        let id1 = generate_operation_id("base-123", 0);
        let id2 = generate_operation_id("base-456", 0);
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_generate_operation_id_length() {
        let id = generate_operation_id("base-123", 0);
        assert_eq!(id.len(), 32); // 16 bytes = 32 hex chars
    }

    #[test]
    fn test_operation_id_generator_new() {
        let gen = OperationIdGenerator::new("base-123");
        assert_eq!(gen.base_id(), "base-123");
        assert_eq!(gen.current_counter(), 0);
    }

    #[test]
    fn test_operation_id_generator_with_counter() {
        let gen = OperationIdGenerator::with_counter("base-123", 10);
        assert_eq!(gen.current_counter(), 10);
    }

    #[test]
    fn test_operation_id_generator_next_id() {
        let gen = OperationIdGenerator::new("base-123");

        let id1 = gen.next_id();
        assert_eq!(gen.current_counter(), 1);

        let id2 = gen.next_id();
        assert_eq!(gen.current_counter(), 2);

        assert_ne!(id1, id2);
    }

    #[test]
    fn test_operation_id_generator_id_for_counter() {
        let gen = OperationIdGenerator::new("base-123");

        let id_0 = gen.id_for_counter(0);
        let id_1 = gen.id_for_counter(1);

        // id_for_counter should not increment the counter
        assert_eq!(gen.current_counter(), 0);

        // Should match what next_id would produce
        let next = gen.next_id();
        assert_eq!(next, id_0);

        let next = gen.next_id();
        assert_eq!(next, id_1);
    }

    #[test]
    fn test_operation_id_generator_create_child() {
        let gen = OperationIdGenerator::new("base-123");
        gen.next_id(); // Increment parent counter

        let child = gen.create_child("child-op-id");
        assert_eq!(child.base_id(), "child-op-id");
        assert_eq!(child.current_counter(), 0);
    }

    #[test]
    fn test_operation_id_generator_clone() {
        let gen = OperationIdGenerator::new("base-123");
        gen.next_id();
        gen.next_id();

        let cloned = gen.clone();
        assert_eq!(cloned.base_id(), gen.base_id());
        assert_eq!(cloned.current_counter(), gen.current_counter());
    }

    #[test]
    fn test_operation_id_generator_thread_safety() {
        use std::thread;

        let gen = Arc::new(OperationIdGenerator::new("base-123"));
        let mut handles = vec![];

        for _ in 0..10 {
            let gen_clone = gen.clone();
            handles.push(thread::spawn(move || {
                let mut ids = vec![];
                for _ in 0..100 {
                    ids.push(gen_clone.next_id());
                }
                ids
            }));
        }

        let mut all_ids = vec![];
        for handle in handles {
            all_ids.extend(handle.join().unwrap());
        }

        // All IDs should be unique
        let unique_count = {
            let mut set = std::collections::HashSet::new();
            for id in &all_ids {
                set.insert(id.clone());
            }
            set.len()
        };

        assert_eq!(unique_count, 1000);
        assert_eq!(gen.current_counter(), 1000);
    }

    #[test]
    fn test_log_info_new() {
        let info = LogInfo::new("arn:test");
        assert_eq!(info.durable_execution_arn, Some("arn:test".to_string()));
        assert!(info.operation_id.is_none());
        assert!(info.parent_id.is_none());
    }

    #[test]
    fn test_log_info_with_operation_id() {
        let info = LogInfo::new("arn:test").with_operation_id("op-123");
        assert_eq!(info.operation_id, Some("op-123".to_string()));
    }

    #[test]
    fn test_log_info_with_parent_id() {
        let info = LogInfo::new("arn:test").with_parent_id("parent-456");
        assert_eq!(info.parent_id, Some("parent-456".to_string()));
    }

    #[test]
    fn test_log_info_with_extra() {
        let info = LogInfo::new("arn:test")
            .with_extra("key1", "value1")
            .with_extra("key2", "value2");
        assert_eq!(info.extra.len(), 2);
        assert_eq!(info.extra[0], ("key1".to_string(), "value1".to_string()));
    }

    #[test]
    fn test_hex_encode() {
        assert_eq!(hex::encode(&[0x00]), "00");
        assert_eq!(hex::encode(&[0xff]), "ff");
        assert_eq!(hex::encode(&[0x12, 0x34, 0xab, 0xcd]), "1234abcd");
    }
}

#[cfg(test)]
mod durable_context_tests {
    use super::*;
    use crate::client::SharedDurableServiceClient;
    use crate::lambda::InitialExecutionState;
    use std::sync::Arc;

    #[cfg(test)]
    fn create_mock_client() -> SharedDurableServiceClient {
        use crate::client::MockDurableServiceClient;
        Arc::new(MockDurableServiceClient::new())
    }

    fn create_test_state() -> Arc<ExecutionState> {
        let client = create_mock_client();
        Arc::new(ExecutionState::new(
            "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
            "token-123",
            InitialExecutionState::new(),
            client,
        ))
    }

    #[test]
    fn test_durable_context_new() {
        let state = create_test_state();
        let ctx = DurableContext::new(state.clone());

        assert_eq!(
            ctx.durable_execution_arn(),
            "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123"
        );
        assert!(ctx.parent_id().is_none());
        assert!(ctx.lambda_context().is_none());
        assert_eq!(ctx.current_step_counter(), 0);
    }

    #[test]
    fn test_durable_context_next_operation_id() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let id1 = ctx.next_operation_id();
        let id2 = ctx.next_operation_id();

        assert_ne!(id1, id2);
        assert_eq!(ctx.current_step_counter(), 2);
    }

    #[test]
    fn test_durable_context_next_operation_identifier() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let op_id = ctx.next_operation_identifier(Some("my-step".to_string()));

        assert!(op_id.parent_id.is_none());
        assert_eq!(op_id.name, Some("my-step".to_string()));
        assert!(!op_id.operation_id.is_empty());
    }

    #[test]
    fn test_durable_context_create_child_context() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        // Generate a parent operation ID
        let parent_op_id = ctx.next_operation_id();

        // Create child context
        let child_ctx = ctx.create_child_context(&parent_op_id);

        assert_eq!(child_ctx.parent_id(), Some(parent_op_id.as_str()));
        assert_eq!(child_ctx.current_step_counter(), 0);
        assert_eq!(
            child_ctx.durable_execution_arn(),
            ctx.durable_execution_arn()
        );
    }

    #[test]
    fn test_durable_context_child_generates_different_ids() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let parent_op_id = ctx.next_operation_id();
        let child_ctx = ctx.create_child_context(&parent_op_id);

        // Child should generate different IDs than parent
        let child_id = child_ctx.next_operation_id();
        let parent_id = ctx.next_operation_id();

        assert_ne!(child_id, parent_id);
    }

    #[test]
    fn test_durable_context_child_operation_identifier_has_parent() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let parent_op_id = ctx.next_operation_id();
        let child_ctx = ctx.create_child_context(&parent_op_id);

        let child_op_id = child_ctx.next_operation_identifier(None);

        assert_eq!(child_op_id.parent_id, Some(parent_op_id));
    }

    #[test]
    fn test_durable_context_set_logger() {
        let state = create_test_state();
        let mut ctx = DurableContext::new(state);

        // Create a custom logger
        let custom_logger: Arc<dyn Logger> = Arc::new(TracingLogger);
        ctx.set_logger(custom_logger);

        // Just verify it doesn't panic - the logger is set
        let _ = ctx.logger();
    }

    #[test]
    fn test_durable_context_with_logger() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let custom_logger: Arc<dyn Logger> = Arc::new(TracingLogger);
        let ctx_with_logger = ctx.with_logger(custom_logger);

        // Just verify it doesn't panic - the logger is set
        let _ = ctx_with_logger.logger();
    }

    #[test]
    fn test_durable_context_create_log_info() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let info = ctx.create_log_info();

        assert_eq!(
            info.durable_execution_arn,
            Some("arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123".to_string())
        );
        assert!(info.parent_id.is_none());
    }

    #[test]
    fn test_durable_context_create_log_info_with_parent() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let parent_op_id = ctx.next_operation_id();
        let child_ctx = ctx.create_child_context(&parent_op_id);

        let info = child_ctx.create_log_info();

        assert_eq!(info.parent_id, Some(parent_op_id));
    }

    #[test]
    fn test_durable_context_create_log_info_with_operation() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let info = ctx.create_log_info_with_operation("op-123");

        assert_eq!(info.operation_id, Some("op-123".to_string()));
    }

    #[test]
    fn test_log_info_with_replay() {
        let info = LogInfo::new("arn:test")
            .with_operation_id("op-123")
            .with_replay(true);

        assert!(info.is_replay);
        assert_eq!(info.operation_id, Some("op-123".to_string()));
    }

    #[test]
    fn test_log_info_default_not_replay() {
        let info = LogInfo::default();
        assert!(!info.is_replay);
    }

    #[test]
    fn test_replay_logging_config_default() {
        let config = ReplayLoggingConfig::default();
        assert_eq!(config, ReplayLoggingConfig::SuppressAll);
    }

    #[test]
    fn test_replay_aware_logger_suppress_all() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        // Create counters for each log level
        let debug_count = Arc::new(AtomicUsize::new(0));
        let info_count = Arc::new(AtomicUsize::new(0));
        let warn_count = Arc::new(AtomicUsize::new(0));
        let error_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            {
                let count = debug_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = info_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = warn_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = error_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
        ));

        let logger = ReplayAwareLogger::new(inner, ReplayLoggingConfig::SuppressAll);

        // Non-replay logs should pass through
        let non_replay_info = LogInfo::new("arn:test").with_replay(false);
        logger.debug("test", &non_replay_info);
        logger.info("test", &non_replay_info);
        logger.warn("test", &non_replay_info);
        logger.error("test", &non_replay_info);

        assert_eq!(debug_count.load(Ordering::SeqCst), 1);
        assert_eq!(info_count.load(Ordering::SeqCst), 1);
        assert_eq!(warn_count.load(Ordering::SeqCst), 1);
        assert_eq!(error_count.load(Ordering::SeqCst), 1);

        // Replay logs should be suppressed
        let replay_info = LogInfo::new("arn:test").with_replay(true);
        logger.debug("test", &replay_info);
        logger.info("test", &replay_info);
        logger.warn("test", &replay_info);
        logger.error("test", &replay_info);

        // Counts should not have increased
        assert_eq!(debug_count.load(Ordering::SeqCst), 1);
        assert_eq!(info_count.load(Ordering::SeqCst), 1);
        assert_eq!(warn_count.load(Ordering::SeqCst), 1);
        assert_eq!(error_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_replay_aware_logger_allow_all() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let call_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            {
                let count = call_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = call_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = call_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = call_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
        ));

        let logger = ReplayAwareLogger::allow_all(inner);

        // All logs should pass through even during replay
        let replay_info = LogInfo::new("arn:test").with_replay(true);
        logger.debug("test", &replay_info);
        logger.info("test", &replay_info);
        logger.warn("test", &replay_info);
        logger.error("test", &replay_info);

        assert_eq!(call_count.load(Ordering::SeqCst), 4);
    }

    #[test]
    fn test_replay_aware_logger_errors_only() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let debug_count = Arc::new(AtomicUsize::new(0));
        let info_count = Arc::new(AtomicUsize::new(0));
        let warn_count = Arc::new(AtomicUsize::new(0));
        let error_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            {
                let count = debug_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = info_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = warn_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = error_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
        ));

        let logger = ReplayAwareLogger::new(inner, ReplayLoggingConfig::ErrorsOnly);

        // During replay, only errors should pass through
        let replay_info = LogInfo::new("arn:test").with_replay(true);
        logger.debug("test", &replay_info);
        logger.info("test", &replay_info);
        logger.warn("test", &replay_info);
        logger.error("test", &replay_info);

        assert_eq!(debug_count.load(Ordering::SeqCst), 0);
        assert_eq!(info_count.load(Ordering::SeqCst), 0);
        assert_eq!(warn_count.load(Ordering::SeqCst), 0);
        assert_eq!(error_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_replay_aware_logger_warnings_and_errors() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let debug_count = Arc::new(AtomicUsize::new(0));
        let info_count = Arc::new(AtomicUsize::new(0));
        let warn_count = Arc::new(AtomicUsize::new(0));
        let error_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            {
                let count = debug_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = info_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = warn_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            {
                let count = error_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
        ));

        let logger = ReplayAwareLogger::new(inner, ReplayLoggingConfig::WarningsAndErrors);

        // During replay, only warnings and errors should pass through
        let replay_info = LogInfo::new("arn:test").with_replay(true);
        logger.debug("test", &replay_info);
        logger.info("test", &replay_info);
        logger.warn("test", &replay_info);
        logger.error("test", &replay_info);

        assert_eq!(debug_count.load(Ordering::SeqCst), 0);
        assert_eq!(info_count.load(Ordering::SeqCst), 0);
        assert_eq!(warn_count.load(Ordering::SeqCst), 1);
        assert_eq!(error_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_replay_aware_logger_suppress_replay_constructor() {
        let inner: Arc<dyn Logger> = Arc::new(TracingLogger);
        let logger = ReplayAwareLogger::suppress_replay(inner);

        assert_eq!(logger.config(), ReplayLoggingConfig::SuppressAll);
    }

    #[test]
    fn test_replay_aware_logger_debug() {
        let inner: Arc<dyn Logger> = Arc::new(TracingLogger);
        let logger = ReplayAwareLogger::new(inner, ReplayLoggingConfig::SuppressAll);

        let debug_str = format!("{:?}", logger);
        assert!(debug_str.contains("ReplayAwareLogger"));
        assert!(debug_str.contains("SuppressAll"));
    }

    #[test]
    fn test_durable_context_create_log_info_with_replay_method() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let info = ctx.create_log_info_with_replay("op-123", true);

        assert_eq!(info.operation_id, Some("op-123".to_string()));
        assert!(info.is_replay);
    }

    #[test]
    fn test_durable_context_clone() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        ctx.next_operation_id();
        ctx.next_operation_id();

        let cloned = ctx.clone();

        assert_eq!(cloned.durable_execution_arn(), ctx.durable_execution_arn());
        assert_eq!(cloned.current_step_counter(), ctx.current_step_counter());
    }

    #[test]
    fn test_durable_context_debug() {
        let state = create_test_state();
        let ctx = DurableContext::new(state);

        let debug_str = format!("{:?}", ctx);

        assert!(debug_str.contains("DurableContext"));
        assert!(debug_str.contains("durable_execution_arn"));
    }

    #[test]
    fn test_durable_context_state_access() {
        let state = create_test_state();
        let ctx = DurableContext::new(state.clone());

        // Verify we can access the state
        assert!(Arc::ptr_eq(ctx.state(), &state));
    }

    #[test]
    fn test_durable_context_send_sync() {
        // This test verifies at compile time that DurableContext is Send + Sync
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<DurableContext>();
    }

    // ========================================================================
    // Simplified Logging API Tests
    // ========================================================================

    #[test]
    fn test_log_info_method() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Mutex;

        let info_count = Arc::new(AtomicUsize::new(0));
        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = info_count.clone();
                move |_, info: &LogInfo| {
                    count.fetch_add(1, Ordering::SeqCst);
                    *captured_info_clone.lock().unwrap() = Some(info.clone());
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_info("Test message");

        assert_eq!(info_count.load(Ordering::SeqCst), 1);

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();
        assert_eq!(
            info.durable_execution_arn,
            Some("arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123".to_string())
        );
    }

    #[test]
    fn test_log_debug_method() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let debug_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            {
                let count = debug_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_debug("Debug message");

        assert_eq!(debug_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_log_warn_method() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let warn_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(
            |_, _| {},
            |_, _| {},
            {
                let count = warn_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_warn("Warning message");

        assert_eq!(warn_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_log_error_method() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        let error_count = Arc::new(AtomicUsize::new(0));

        let inner = Arc::new(custom_logger(|_, _| {}, |_, _| {}, |_, _| {}, {
            let count = error_count.clone();
            move |_, _| {
                count.fetch_add(1, Ordering::SeqCst);
            }
        }));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_error("Error message");

        assert_eq!(error_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_log_info_with_extra_fields() {
        use std::sync::Mutex;

        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner = Arc::new(custom_logger(
            |_, _| {},
            move |_, info: &LogInfo| {
                *captured_info_clone.lock().unwrap() = Some(info.clone());
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_info_with("Test message", &[("order_id", "123"), ("amount", "99.99")]);

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();

        // Verify extra fields are present
        assert_eq!(info.extra.len(), 2);
        assert!(info
            .extra
            .contains(&("order_id".to_string(), "123".to_string())));
        assert!(info
            .extra
            .contains(&("amount".to_string(), "99.99".to_string())));
    }

    #[test]
    fn test_log_debug_with_extra_fields() {
        use std::sync::Mutex;

        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner = Arc::new(custom_logger(
            move |_, info: &LogInfo| {
                *captured_info_clone.lock().unwrap() = Some(info.clone());
            },
            |_, _| {},
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_debug_with("Debug message", &[("key", "value")]);

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();

        assert_eq!(info.extra.len(), 1);
        assert!(info
            .extra
            .contains(&("key".to_string(), "value".to_string())));
    }

    #[test]
    fn test_log_warn_with_extra_fields() {
        use std::sync::Mutex;

        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner = Arc::new(custom_logger(
            |_, _| {},
            |_, _| {},
            move |_, info: &LogInfo| {
                *captured_info_clone.lock().unwrap() = Some(info.clone());
            },
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_warn_with("Warning message", &[("retry", "3")]);

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();

        assert_eq!(info.extra.len(), 1);
        assert!(info.extra.contains(&("retry".to_string(), "3".to_string())));
    }

    #[test]
    fn test_log_error_with_extra_fields() {
        use std::sync::Mutex;

        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner = Arc::new(custom_logger(
            |_, _| {},
            |_, _| {},
            |_, _| {},
            move |_, info: &LogInfo| {
                *captured_info_clone.lock().unwrap() = Some(info.clone());
            },
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner);

        ctx.log_error_with(
            "Error message",
            &[("error_code", "E001"), ("details", "Something went wrong")],
        );

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();

        assert_eq!(info.extra.len(), 2);
        assert!(info
            .extra
            .contains(&("error_code".to_string(), "E001".to_string())));
        assert!(info
            .extra
            .contains(&("details".to_string(), "Something went wrong".to_string())));
    }

    #[test]
    fn test_log_methods_include_parent_id_in_child_context() {
        use std::sync::Mutex;

        let captured_info = Arc::new(Mutex::new(None::<LogInfo>));

        let captured_info_clone = captured_info.clone();
        let inner: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            move |_, info: &LogInfo| {
                *captured_info_clone.lock().unwrap() = Some(info.clone());
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(inner.clone());

        let parent_op_id = ctx.next_operation_id();
        let child_ctx = ctx.create_child_context(&parent_op_id).with_logger(inner);

        child_ctx.log_info("Child context message");

        let captured = captured_info.lock().unwrap();
        let info = captured.as_ref().unwrap();

        // Verify parent_id is included
        assert_eq!(info.parent_id, Some(parent_op_id));
    }

    // ========================================================================
    // Runtime Logger Reconfiguration Tests (Req 13.1, 13.2)
    // ========================================================================

    #[test]
    fn test_configure_logger_swaps_logger() {
        // Req 13.1: configure_logger swaps the logger, subsequent calls use new logger
        use std::sync::atomic::{AtomicUsize, Ordering};

        let original_count = Arc::new(AtomicUsize::new(0));
        let new_count = Arc::new(AtomicUsize::new(0));

        let original_logger: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = original_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let new_logger: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = new_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(original_logger);

        // Log with original logger
        ctx.log_info("before swap");
        assert_eq!(original_count.load(Ordering::SeqCst), 1);
        assert_eq!(new_count.load(Ordering::SeqCst), 0);

        // Swap logger at runtime (note: &self, not &mut self)
        ctx.configure_logger(new_logger);

        // Subsequent calls use the new logger
        ctx.log_info("after swap");
        assert_eq!(original_count.load(Ordering::SeqCst), 1); // unchanged
        assert_eq!(new_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_original_logger_used_when_configure_logger_not_called() {
        // Req 13.2: Original logger used when configure_logger not called
        use std::sync::atomic::{AtomicUsize, Ordering};

        let original_count = Arc::new(AtomicUsize::new(0));

        let original_logger: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = original_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(original_logger);

        // Log multiple times without calling configure_logger
        ctx.log_info("message 1");
        ctx.log_info("message 2");
        ctx.log_info("message 3");

        assert_eq!(original_count.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_configure_logger_affects_child_contexts() {
        // Verify that child contexts sharing the same RwLock see the swapped logger
        use std::sync::atomic::{AtomicUsize, Ordering};

        let original_count = Arc::new(AtomicUsize::new(0));
        let new_count = Arc::new(AtomicUsize::new(0));

        let original_logger: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = original_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let new_logger: Arc<dyn Logger> = Arc::new(custom_logger(
            |_, _| {},
            {
                let count = new_count.clone();
                move |_, _| {
                    count.fetch_add(1, Ordering::SeqCst);
                }
            },
            |_, _| {},
            |_, _| {},
        ));

        let state = create_test_state();
        let ctx = DurableContext::new(state).with_logger(original_logger);
        let parent_op_id = ctx.next_operation_id();
        let child_ctx = ctx.create_child_context(&parent_op_id);

        // Child uses original logger
        child_ctx.log_info("child before swap");
        assert_eq!(original_count.load(Ordering::SeqCst), 1);

        // Swap on parent
        ctx.configure_logger(new_logger);

        // Child now uses the new logger (shared RwLock)
        child_ctx.log_info("child after swap");
        assert_eq!(new_count.load(Ordering::SeqCst), 1);
        assert_eq!(original_count.load(Ordering::SeqCst), 1); // unchanged
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    // Property 3: Operation ID Determinism
    // *For any* DurableContext with a given parent_id and step counter state,
    // calling create_operation_id() SHALL produce the same ID when called
    // in the same sequence position across multiple executions.
    // **Validates: Requirements 1.10**
    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Feature: durable-execution-rust-sdk, Property 3: Operation ID Determinism
        /// Validates: Requirements 1.10
        #[test]
        fn prop_operation_id_determinism(
            base_id in "[a-zA-Z0-9:/-]{1,100}",
            counter in 0u64..10000u64,
        ) {
            // Generate the same ID twice with the same inputs
            let id1 = generate_operation_id(&base_id, counter);
            let id2 = generate_operation_id(&base_id, counter);

            // IDs must be identical for the same inputs
            prop_assert_eq!(&id1, &id2, "Same base_id and counter must produce identical IDs");

            // ID must be a valid hex string of expected length
            prop_assert_eq!(id1.len(), 32, "ID must be 32 hex characters");
            prop_assert!(id1.chars().all(|c| c.is_ascii_hexdigit()), "ID must be valid hex");
        }

        /// Feature: durable-execution-rust-sdk, Property 3: Operation ID Determinism (Generator)
        /// Validates: Requirements 1.10
        #[test]
        fn prop_operation_id_generator_determinism(
            base_id in "[a-zA-Z0-9:/-]{1,100}",
            num_ids in 1usize..50usize,
        ) {
            // Create two generators with the same base ID
            let gen1 = OperationIdGenerator::new(&base_id);
            let gen2 = OperationIdGenerator::new(&base_id);

            // Generate the same sequence of IDs from both
            let ids1: Vec<String> = (0..num_ids).map(|_| gen1.next_id()).collect();
            let ids2: Vec<String> = (0..num_ids).map(|_| gen2.next_id()).collect();

            // Sequences must be identical
            prop_assert_eq!(&ids1, &ids2, "Same generator sequence must produce identical IDs");

            // All IDs in a sequence must be unique
            let unique_count = {
                let mut set = std::collections::HashSet::new();
                for id in &ids1 {
                    set.insert(id.clone());
                }
                set.len()
            };
            prop_assert_eq!(unique_count, num_ids, "All IDs in sequence must be unique");
        }

        /// Feature: durable-execution-rust-sdk, Property 3: Operation ID Determinism (Replay Simulation)
        /// Validates: Requirements 1.10
        #[test]
        fn prop_operation_id_replay_determinism(
            base_id in "[a-zA-Z0-9:/-]{1,100}",
            operations in prop::collection::vec(0u32..3u32, 1..20),
        ) {
            // Simulate two executions with the same sequence of operations
            // Each operation type increments the counter

            let gen1 = OperationIdGenerator::new(&base_id);
            let gen2 = OperationIdGenerator::new(&base_id);

            let mut ids1 = Vec::new();
            let mut ids2 = Vec::new();

            // First "execution"
            for op_type in &operations {
                // Each operation generates an ID
                ids1.push(gen1.next_id());

                // Some operations might generate additional child IDs
                if *op_type == 2 {
                    let parent_id = ids1.last().unwrap().clone();
                    let child_gen = gen1.create_child(parent_id);
                    ids1.push(child_gen.next_id());
                }
            }

            // Second "execution" (replay) - must produce same IDs
            for op_type in &operations {
                ids2.push(gen2.next_id());

                if *op_type == 2 {
                    let parent_id = ids2.last().unwrap().clone();
                    let child_gen = gen2.create_child(parent_id);
                    ids2.push(child_gen.next_id());
                }
            }

            // Both executions must produce identical ID sequences
            prop_assert_eq!(&ids1, &ids2, "Replay must produce identical operation IDs");
        }
    }

    // Property 5: Concurrent ID Generation Uniqueness
    // *For any* number of concurrent tasks generating operation IDs from the same
    // DurableContext, all generated IDs SHALL be unique.
    // **Validates: Requirements 17.3**
    mod concurrent_id_tests {
        use super::*;
        use std::sync::Arc;
        use std::thread;

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(100))]

            /// Feature: durable-execution-rust-sdk, Property 5: Concurrent ID Generation Uniqueness
            /// Validates: Requirements 17.3
            #[test]
            fn prop_concurrent_id_uniqueness(
                base_id in "[a-zA-Z0-9:/-]{1,100}",
                num_threads in 2usize..10usize,
                ids_per_thread in 10usize..100usize,
            ) {
                let gen = Arc::new(OperationIdGenerator::new(&base_id));
                let mut handles = vec![];

                // Spawn multiple threads that concurrently generate IDs
                for _ in 0..num_threads {
                    let gen_clone = gen.clone();
                    let count = ids_per_thread;
                    handles.push(thread::spawn(move || {
                        let mut ids = Vec::with_capacity(count);
                        for _ in 0..count {
                            ids.push(gen_clone.next_id());
                        }
                        ids
                    }));
                }

                // Collect all IDs from all threads
                let mut all_ids = Vec::new();
                for handle in handles {
                    all_ids.extend(handle.join().unwrap());
                }

                let total_expected = num_threads * ids_per_thread;

                // Verify we got the expected number of IDs
                prop_assert_eq!(all_ids.len(), total_expected, "Should have generated {} IDs", total_expected);

                // Verify all IDs are unique
                let unique_count = {
                    let mut set = std::collections::HashSet::new();
                    for id in &all_ids {
                        set.insert(id.clone());
                    }
                    set.len()
                };

                prop_assert_eq!(
                    unique_count,
                    total_expected,
                    "All {} IDs must be unique, but only {} were unique",
                    total_expected,
                    unique_count
                );

                // Verify the counter was incremented correctly
                prop_assert_eq!(
                    gen.current_counter() as usize,
                    total_expected,
                    "Counter should equal total IDs generated"
                );
            }

            /// Feature: durable-execution-rust-sdk, Property 5: Concurrent ID Generation Uniqueness (Stress)
            /// Validates: Requirements 17.3
            #[test]
            fn prop_concurrent_id_uniqueness_stress(
                base_id in "[a-zA-Z0-9:/-]{1,50}",
            ) {
                // Fixed high-concurrency stress test
                let num_threads = 20;
                let ids_per_thread = 500;

                let gen = Arc::new(OperationIdGenerator::new(&base_id));
                let mut handles = vec![];

                for _ in 0..num_threads {
                    let gen_clone = gen.clone();
                    handles.push(thread::spawn(move || {
                        let mut ids = Vec::with_capacity(ids_per_thread);
                        for _ in 0..ids_per_thread {
                            ids.push(gen_clone.next_id());
                        }
                        ids
                    }));
                }

                let mut all_ids = Vec::new();
                for handle in handles {
                    all_ids.extend(handle.join().unwrap());
                }

                let total_expected = num_threads * ids_per_thread;

                // Verify all IDs are unique
                let unique_count = {
                    let mut set = std::collections::HashSet::new();
                    for id in &all_ids {
                        set.insert(id.clone());
                    }
                    set.len()
                };

                prop_assert_eq!(
                    unique_count,
                    total_expected,
                    "All {} IDs must be unique under high concurrency",
                    total_expected
                );
            }
        }
    }

    // Property 9: Logging Methods Automatic Context
    // *For any* call to log_info, log_debug, log_warn, or log_error on DurableContext,
    // the resulting log message SHALL include durable_execution_arn and parent_id
    // (when available) without the caller needing to specify them.
    // **Validates: Requirements 4.5**
    mod logging_automatic_context_tests {
        use super::*;
        use std::sync::{Arc, Mutex};

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(100))]

            /// Feature: sdk-ergonomics-improvements, Property 9: Logging Methods Automatic Context
            /// Validates: Requirements 4.5
            #[test]
            fn prop_logging_automatic_context(
                message in "[a-zA-Z0-9 ]{1,100}",
                log_level in 0u8..4u8,
            ) {
                use crate::client::MockDurableServiceClient;
                use crate::lambda::InitialExecutionState;

                let captured_info = Arc::new(Mutex::new(None::<LogInfo>));
                let captured_info_clone = captured_info.clone();

                // Create a logger that captures the LogInfo
                let inner = Arc::new(custom_logger(
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                ));

                let client: crate::client::SharedDurableServiceClient = Arc::new(MockDurableServiceClient::new());
                let state = Arc::new(ExecutionState::new(
                    "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
                    "token-123",
                    InitialExecutionState::new(),
                    client,
                ));
                let ctx = DurableContext::new(state).with_logger(inner);

                // Call the appropriate log method based on log_level
                match log_level {
                    0 => ctx.log_debug(&message),
                    1 => ctx.log_info(&message),
                    2 => ctx.log_warn(&message),
                    _ => ctx.log_error(&message),
                }

                // Verify the captured LogInfo has the automatic context
                let captured = captured_info.lock().unwrap();
                let info = captured.as_ref().expect("LogInfo should be captured");

                // durable_execution_arn must always be present
                prop_assert!(
                    info.durable_execution_arn.is_some(),
                    "durable_execution_arn must be automatically included"
                );
                prop_assert_eq!(
                    info.durable_execution_arn.as_ref().unwrap(),
                    "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
                    "durable_execution_arn must match the context's ARN"
                );
            }

            /// Feature: sdk-ergonomics-improvements, Property 9: Logging Methods Automatic Context (Child Context)
            /// Validates: Requirements 4.5
            #[test]
            fn prop_logging_automatic_context_child(
                message in "[a-zA-Z0-9 ]{1,100}",
                log_level in 0u8..4u8,
            ) {
                use crate::client::MockDurableServiceClient;
                use crate::lambda::InitialExecutionState;

                let captured_info = Arc::new(Mutex::new(None::<LogInfo>));
                let captured_info_clone = captured_info.clone();

                // Create a logger that captures the LogInfo
                let inner: Arc<dyn Logger> = Arc::new(custom_logger(
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                ));

                let client: crate::client::SharedDurableServiceClient = Arc::new(MockDurableServiceClient::new());
                let state = Arc::new(ExecutionState::new(
                    "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
                    "token-123",
                    InitialExecutionState::new(),
                    client,
                ));
                let ctx = DurableContext::new(state).with_logger(inner.clone());

                // Create a child context
                let parent_op_id = ctx.next_operation_id();
                let child_ctx = ctx.create_child_context(&parent_op_id).with_logger(inner);

                // Call the appropriate log method based on log_level
                match log_level {
                    0 => child_ctx.log_debug(&message),
                    1 => child_ctx.log_info(&message),
                    2 => child_ctx.log_warn(&message),
                    _ => child_ctx.log_error(&message),
                }

                // Verify the captured LogInfo has the automatic context including parent_id
                let captured = captured_info.lock().unwrap();
                let info = captured.as_ref().expect("LogInfo should be captured");

                // durable_execution_arn must always be present
                prop_assert!(
                    info.durable_execution_arn.is_some(),
                    "durable_execution_arn must be automatically included in child context"
                );

                // parent_id must be present in child context
                prop_assert!(
                    info.parent_id.is_some(),
                    "parent_id must be automatically included in child context"
                );
                prop_assert_eq!(
                    info.parent_id.as_ref().unwrap(),
                    &parent_op_id,
                    "parent_id must match the parent operation ID"
                );
            }
        }
    }

    // Property 10: Logging Methods Extra Fields
    // *For any* call to log_info_with, log_debug_with, log_warn_with, or log_error_with
    // with extra fields, those fields SHALL appear in the resulting log output.
    // **Validates: Requirements 4.6**
    mod logging_extra_fields_tests {
        use super::*;
        use std::sync::{Arc, Mutex};

        proptest! {
            #![proptest_config(ProptestConfig::with_cases(100))]

            /// Feature: sdk-ergonomics-improvements, Property 10: Logging Methods Extra Fields
            /// Validates: Requirements 4.6
            #[test]
            fn prop_logging_extra_fields(
                message in "[a-zA-Z0-9 ]{1,100}",
                log_level in 0u8..4u8,
                key1 in "[a-zA-Z_][a-zA-Z0-9_]{0,20}",
                value1 in "[a-zA-Z0-9]{1,50}",
                key2 in "[a-zA-Z_][a-zA-Z0-9_]{0,20}",
                value2 in "[a-zA-Z0-9]{1,50}",
            ) {
                use crate::client::MockDurableServiceClient;
                use crate::lambda::InitialExecutionState;

                let captured_info = Arc::new(Mutex::new(None::<LogInfo>));
                let captured_info_clone = captured_info.clone();

                // Create a logger that captures the LogInfo
                let inner = Arc::new(custom_logger(
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                ));

                let client: crate::client::SharedDurableServiceClient = Arc::new(MockDurableServiceClient::new());
                let state = Arc::new(ExecutionState::new(
                    "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
                    "token-123",
                    InitialExecutionState::new(),
                    client,
                ));
                let ctx = DurableContext::new(state).with_logger(inner);

                // Create extra fields
                let fields: Vec<(&str, &str)> = vec![(&key1, &value1), (&key2, &value2)];

                // Call the appropriate log method based on log_level
                match log_level {
                    0 => ctx.log_debug_with(&message, &fields),
                    1 => ctx.log_info_with(&message, &fields),
                    2 => ctx.log_warn_with(&message, &fields),
                    _ => ctx.log_error_with(&message, &fields),
                }

                // Verify the captured LogInfo has the extra fields
                let captured = captured_info.lock().unwrap();
                let info = captured.as_ref().expect("LogInfo should be captured");

                // Extra fields must be present
                prop_assert_eq!(
                    info.extra.len(),
                    2,
                    "Extra fields must be included in the log output"
                );

                // Verify each field is present
                prop_assert!(
                    info.extra.contains(&(key1.clone(), value1.clone())),
                    "First extra field must be present: {}={}", key1, value1
                );
                prop_assert!(
                    info.extra.contains(&(key2.clone(), value2.clone())),
                    "Second extra field must be present: {}={}", key2, value2
                );
            }

            /// Feature: sdk-ergonomics-improvements, Property 10: Logging Methods Extra Fields (Empty)
            /// Validates: Requirements 4.6
            #[test]
            fn prop_logging_extra_fields_empty(
                message in "[a-zA-Z0-9 ]{1,100}",
                log_level in 0u8..4u8,
            ) {
                use crate::client::MockDurableServiceClient;
                use crate::lambda::InitialExecutionState;

                let captured_info = Arc::new(Mutex::new(None::<LogInfo>));
                let captured_info_clone = captured_info.clone();

                // Create a logger that captures the LogInfo
                let inner = Arc::new(custom_logger(
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                    {
                        let captured = captured_info_clone.clone();
                        move |_, info: &LogInfo| {
                            *captured.lock().unwrap() = Some(info.clone());
                        }
                    },
                ));

                let client: crate::client::SharedDurableServiceClient = Arc::new(MockDurableServiceClient::new());
                let state = Arc::new(ExecutionState::new(
                    "arn:aws:lambda:us-east-1:123456789012:function:test:durable:abc123",
                    "token-123",
                    InitialExecutionState::new(),
                    client,
                ));
                let ctx = DurableContext::new(state).with_logger(inner);

                // Call the appropriate log method with empty fields
                let empty_fields: &[(&str, &str)] = &[];
                match log_level {
                    0 => ctx.log_debug_with(&message, empty_fields),
                    1 => ctx.log_info_with(&message, empty_fields),
                    2 => ctx.log_warn_with(&message, empty_fields),
                    _ => ctx.log_error_with(&message, empty_fields),
                }

                // Verify the captured LogInfo has no extra fields
                let captured = captured_info.lock().unwrap();
                let info = captured.as_ref().expect("LogInfo should be captured");

                prop_assert!(
                    info.extra.is_empty(),
                    "Extra fields should be empty when none are provided"
                );

                // But automatic context should still be present
                prop_assert!(
                    info.durable_execution_arn.is_some(),
                    "durable_execution_arn must still be present even with empty extra fields"
                );
            }
        }
    }
}

#[cfg(test)]
mod sealed_trait_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// Tests for sealed Logger trait implementations.
    ///
    /// The Logger trait is sealed, meaning it cannot be implemented outside this crate.
    /// This is enforced at compile time by requiring the private `Sealed` supertrait.
    /// External crates attempting to implement Logger will get a compile error:
    /// "the trait bound `MyType: Sealed` is not satisfied"
    ///
    /// These tests verify that the internal implementations work correctly.
    mod logger_tests {
        use super::*;

        #[test]
        fn test_tracing_logger_implements_logger() {
            // TracingLogger should implement Logger (compile-time check)
            let logger: &dyn Logger = &TracingLogger;
            let info = LogInfo::default();

            // These calls should not panic
            logger.debug("test debug", &info);
            logger.info("test info", &info);
            logger.warn("test warn", &info);
            logger.error("test error", &info);
        }

        #[test]
        fn test_replay_aware_logger_implements_logger() {
            // ReplayAwareLogger should implement Logger (compile-time check)
            let inner = Arc::new(TracingLogger);
            let logger = ReplayAwareLogger::new(inner, ReplayLoggingConfig::AllowAll);
            let logger_ref: &dyn Logger = &logger;
            let info = LogInfo::default();

            // These calls should not panic
            logger_ref.debug("test debug", &info);
            logger_ref.info("test info", &info);
            logger_ref.warn("test warn", &info);
            logger_ref.error("test error", &info);
        }

        #[test]
        fn test_custom_logger_implements_logger() {
            // CustomLogger should implement Logger (compile-time check)
            let call_count = Arc::new(AtomicUsize::new(0));
            let count_clone = call_count.clone();

            let logger = custom_logger(
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
            );

            let logger_ref: &dyn Logger = &logger;
            let info = LogInfo::default();

            logger_ref.debug("test", &info);
            logger_ref.info("test", &info);
            logger_ref.warn("test", &info);
            logger_ref.error("test", &info);

            assert_eq!(call_count.load(Ordering::SeqCst), 4);
        }

        #[test]
        fn test_simple_custom_logger() {
            let call_count = Arc::new(AtomicUsize::new(0));
            let count_clone = call_count.clone();

            let logger = simple_custom_logger(move |_level, _msg, _info| {
                count_clone.fetch_add(1, Ordering::SeqCst);
            });

            let info = LogInfo::default();

            logger.debug("test", &info);
            logger.info("test", &info);
            logger.warn("test", &info);
            logger.error("test", &info);

            assert_eq!(call_count.load(Ordering::SeqCst), 4);
        }

        #[test]
        fn test_custom_logger_receives_correct_messages() {
            let messages = Arc::new(std::sync::Mutex::new(Vec::new()));
            let messages_clone = messages.clone();

            let logger = simple_custom_logger(move |level, msg, _info| {
                messages_clone
                    .lock()
                    .unwrap()
                    .push(format!("[{}] {}", level, msg));
            });

            let info = LogInfo::default();

            logger.debug("debug message", &info);
            logger.info("info message", &info);
            logger.warn("warn message", &info);
            logger.error("error message", &info);

            let logged = messages.lock().unwrap();
            assert_eq!(logged.len(), 4);
            assert_eq!(logged[0], "[DEBUG] debug message");
            assert_eq!(logged[1], "[INFO] info message");
            assert_eq!(logged[2], "[WARN] warn message");
            assert_eq!(logged[3], "[ERROR] error message");
        }

        #[test]
        fn test_custom_logger_receives_log_info() {
            let received_info = Arc::new(std::sync::Mutex::new(None));
            let info_clone = received_info.clone();

            let logger = simple_custom_logger(move |_level, _msg, info| {
                *info_clone.lock().unwrap() = Some(info.clone());
            });

            let info = LogInfo::new("arn:aws:test")
                .with_operation_id("op-123")
                .with_parent_id("parent-456")
                .with_replay(true);

            logger.info("test", &info);

            let received = received_info.lock().unwrap().clone().unwrap();
            assert_eq!(
                received.durable_execution_arn,
                Some("arn:aws:test".to_string())
            );
            assert_eq!(received.operation_id, Some("op-123".to_string()));
            assert_eq!(received.parent_id, Some("parent-456".to_string()));
            assert!(received.is_replay);
        }

        #[test]
        fn test_replay_aware_logger_suppresses_during_replay() {
            let call_count = Arc::new(AtomicUsize::new(0));
            let count_clone = call_count.clone();

            let inner_logger = Arc::new(custom_logger(
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
            ));

            let logger = ReplayAwareLogger::new(inner_logger, ReplayLoggingConfig::SuppressAll);

            // Non-replay logs should pass through
            let non_replay_info = LogInfo::default().with_replay(false);
            logger.debug("test", &non_replay_info);
            logger.info("test", &non_replay_info);
            logger.warn("test", &non_replay_info);
            logger.error("test", &non_replay_info);
            assert_eq!(call_count.load(Ordering::SeqCst), 4);

            // Replay logs should be suppressed
            let replay_info = LogInfo::default().with_replay(true);
            logger.debug("test", &replay_info);
            logger.info("test", &replay_info);
            logger.warn("test", &replay_info);
            logger.error("test", &replay_info);
            assert_eq!(call_count.load(Ordering::SeqCst), 4); // Still 4, no new calls
        }

        #[test]
        fn test_replay_aware_logger_errors_only_during_replay() {
            let call_count = Arc::new(AtomicUsize::new(0));
            let count_clone = call_count.clone();

            let inner_logger = Arc::new(custom_logger(
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
                {
                    let count = count_clone.clone();
                    move |_msg, _info| {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                },
            ));

            let logger = ReplayAwareLogger::new(inner_logger, ReplayLoggingConfig::ErrorsOnly);

            let replay_info = LogInfo::default().with_replay(true);
            logger.debug("test", &replay_info);
            logger.info("test", &replay_info);
            logger.warn("test", &replay_info);
            logger.error("test", &replay_info);

            // Only error should pass through during replay
            assert_eq!(call_count.load(Ordering::SeqCst), 1);
        }
    }
}