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
//! Main execution state management.
//!
//! This module provides the [`ExecutionState`] struct which manages the execution
//! state for a durable execution, including checkpoint tracking, replay logic,
//! and operation state management.

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
use std::time::Duration as StdDuration;

use tokio::sync::{Mutex, RwLock};

use crate::client::SharedDurableServiceClient;
use crate::error::{DurableError, ErrorObject};
use crate::operation::{Operation, OperationStatus, OperationType, OperationUpdate};
use crate::types::ExecutionArn;

use super::batcher::{
    create_checkpoint_queue, CheckpointBatcher, CheckpointBatcherConfig, CheckpointSender,
};
use super::checkpoint_result::CheckpointedResult;
use super::replay_status::ReplayStatus;

/// Manages the execution state for a durable execution.
///
/// This struct tracks all checkpointed operations, handles replay logic,
/// and manages communication with the Lambda durable execution service.
pub struct ExecutionState {
    /// The ARN of the durable execution
    durable_execution_arn: String,

    /// The current checkpoint token (updated after each checkpoint batch)
    checkpoint_token: Arc<RwLock<String>>,

    /// Map of operation_id to Operation for quick lookup during replay
    operations: RwLock<HashMap<String, Operation>>,

    /// The service client for communicating with Lambda
    service_client: SharedDurableServiceClient,

    /// Current replay status (Replay or New)
    replay_status: AtomicU8,

    /// Set of operation IDs that have been replayed (for tracking replay progress)
    replayed_operations: RwLock<HashSet<String>>,

    /// Marker for pagination when loading additional operations
    next_marker: RwLock<Option<String>>,

    /// Set of parent operation IDs that have completed (for orphan prevention)
    parent_done_lock: Mutex<HashSet<String>>,

    /// Optional checkpoint sender for batched checkpointing
    checkpoint_sender: Option<CheckpointSender>,

    /// The EXECUTION operation (first operation in state) - provides access to original input
    /// Requirements: 19.1, 19.2
    execution_operation: Option<Operation>,

    /// The checkpointing mode that controls the trade-off between durability and performance.
    checkpointing_mode: crate::config::CheckpointingMode,
}

impl ExecutionState {
    /// Creates a new ExecutionState from the Lambda invocation input.
    ///
    /// # Arguments
    ///
    /// * `durable_execution_arn` - The ARN of the durable execution
    /// * `checkpoint_token` - The initial checkpoint token
    /// * `initial_state` - The initial execution state with operations
    /// * `service_client` - The service client for Lambda communication
    pub fn new(
        durable_execution_arn: impl Into<String>,
        checkpoint_token: impl Into<String>,
        initial_state: crate::lambda::InitialExecutionState,
        service_client: SharedDurableServiceClient,
    ) -> Self {
        Self::with_checkpointing_mode(
            durable_execution_arn,
            checkpoint_token,
            initial_state,
            service_client,
            crate::config::CheckpointingMode::default(),
        )
    }

    /// Creates a new ExecutionState with a specific checkpointing mode.
    pub fn with_checkpointing_mode(
        durable_execution_arn: impl Into<String>,
        checkpoint_token: impl Into<String>,
        initial_state: crate::lambda::InitialExecutionState,
        service_client: SharedDurableServiceClient,
        checkpointing_mode: crate::config::CheckpointingMode,
    ) -> Self {
        // Find and extract the EXECUTION operation (first operation of type EXECUTION)
        let execution_operation = initial_state
            .operations
            .iter()
            .find(|op| op.operation_type == OperationType::Execution)
            .cloned();

        // Build the operations map from the initial state
        let operations: HashMap<String, Operation> = initial_state
            .operations
            .into_iter()
            .map(|op| (op.operation_id.clone(), op))
            .collect();

        // Determine initial replay status based on whether we have operations
        let replay_status = if operations.is_empty() {
            ReplayStatus::New
        } else {
            ReplayStatus::Replay
        };

        Self {
            durable_execution_arn: durable_execution_arn.into(),
            checkpoint_token: Arc::new(RwLock::new(checkpoint_token.into())),
            operations: RwLock::new(operations),
            service_client,
            replay_status: AtomicU8::new(replay_status as u8),
            replayed_operations: RwLock::new(HashSet::new()),
            next_marker: RwLock::new(initial_state.next_marker),
            parent_done_lock: Mutex::new(HashSet::new()),
            checkpoint_sender: None,
            execution_operation,
            checkpointing_mode,
        }
    }

    /// Creates a new ExecutionState with a checkpoint batcher.
    ///
    /// This method sets up the checkpoint queue and batcher for efficient
    /// batched checkpointing. Returns the ExecutionState and a handle to
    /// the batcher that should be run in a background task.
    pub fn with_batcher(
        durable_execution_arn: impl Into<String>,
        checkpoint_token: impl Into<String>,
        initial_state: crate::lambda::InitialExecutionState,
        service_client: SharedDurableServiceClient,
        batcher_config: CheckpointBatcherConfig,
        queue_buffer_size: usize,
    ) -> (Self, CheckpointBatcher) {
        Self::with_batcher_and_mode(
            durable_execution_arn,
            checkpoint_token,
            initial_state,
            service_client,
            batcher_config,
            queue_buffer_size,
            crate::config::CheckpointingMode::default(),
        )
    }

    /// Creates a new ExecutionState with a checkpoint batcher and specific checkpointing mode.
    pub fn with_batcher_and_mode(
        durable_execution_arn: impl Into<String>,
        checkpoint_token: impl Into<String>,
        initial_state: crate::lambda::InitialExecutionState,
        service_client: SharedDurableServiceClient,
        batcher_config: CheckpointBatcherConfig,
        queue_buffer_size: usize,
        checkpointing_mode: crate::config::CheckpointingMode,
    ) -> (Self, CheckpointBatcher) {
        let arn: String = durable_execution_arn.into();
        let token: String = checkpoint_token.into();

        // Find and extract the EXECUTION operation
        let execution_operation = initial_state
            .operations
            .iter()
            .find(|op| op.operation_type == OperationType::Execution)
            .cloned();

        // Build the operations map from the initial state
        let operations: HashMap<String, Operation> = initial_state
            .operations
            .into_iter()
            .map(|op| (op.operation_id.clone(), op))
            .collect();

        // Determine initial replay status based on whether we have operations
        let replay_status = if operations.is_empty() {
            ReplayStatus::New
        } else {
            ReplayStatus::Replay
        };

        // Create the checkpoint queue
        let (sender, rx) = create_checkpoint_queue(queue_buffer_size);
        let checkpoint_token = Arc::new(RwLock::new(token));

        // Create the batcher
        let batcher = CheckpointBatcher::new(
            batcher_config,
            rx,
            service_client.clone(),
            arn.clone(),
            checkpoint_token.clone(),
        );

        let state = Self {
            durable_execution_arn: arn,
            checkpoint_token,
            operations: RwLock::new(operations),
            service_client,
            replay_status: AtomicU8::new(replay_status as u8),
            replayed_operations: RwLock::new(HashSet::new()),
            next_marker: RwLock::new(initial_state.next_marker),
            parent_done_lock: Mutex::new(HashSet::new()),
            checkpoint_sender: Some(sender),
            execution_operation,
            checkpointing_mode,
        };

        (state, batcher)
    }

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

    /// Returns the durable execution ARN as an `ExecutionArn` newtype.
    #[inline]
    pub fn durable_execution_arn_typed(&self) -> ExecutionArn {
        ExecutionArn::from(self.durable_execution_arn.clone())
    }

    /// Returns the current checkpoint token.
    pub async fn checkpoint_token(&self) -> String {
        self.checkpoint_token.read().await.clone()
    }

    /// Updates the checkpoint token after a successful checkpoint.
    pub async fn set_checkpoint_token(&self, token: impl Into<String>) {
        let mut guard = self.checkpoint_token.write().await;
        *guard = token.into();
    }

    /// Returns the current replay status.
    ///
    /// # Memory Ordering
    ///
    /// Uses `Ordering::Acquire` to ensure that when we read the replay status,
    /// we also see all the operations that were replayed before the status was
    /// set to `New`. This creates a happens-before relationship with the
    /// `Release` store in `track_replay`.
    ///
    /// Requirements: 4.2, 4.3, 4.6
    pub fn replay_status(&self) -> ReplayStatus {
        // Acquire ordering ensures we see all writes that happened before
        // the corresponding Release store that set this value.
        ReplayStatus::from(self.replay_status.load(Ordering::Acquire))
    }

    /// Returns true if currently in replay mode.
    pub fn is_replay(&self) -> bool {
        self.replay_status().is_replay()
    }

    /// Returns true if executing new operations.
    pub fn is_new(&self) -> bool {
        self.replay_status().is_new()
    }

    /// Returns the current checkpointing mode.
    pub fn checkpointing_mode(&self) -> crate::config::CheckpointingMode {
        self.checkpointing_mode
    }

    /// Returns true if eager checkpointing mode is enabled.
    pub fn is_eager_checkpointing(&self) -> bool {
        self.checkpointing_mode.is_eager()
    }

    /// Returns true if batched checkpointing mode is enabled.
    pub fn is_batched_checkpointing(&self) -> bool {
        self.checkpointing_mode.is_batched()
    }

    /// Returns true if optimistic checkpointing mode is enabled.
    pub fn is_optimistic_checkpointing(&self) -> bool {
        self.checkpointing_mode.is_optimistic()
    }

    /// Returns a reference to the EXECUTION operation if it exists.
    pub fn execution_operation(&self) -> Option<&Operation> {
        self.execution_operation.as_ref()
    }

    /// Returns the original user input from the EXECUTION operation.
    pub fn get_original_input_raw(&self) -> Option<&str> {
        self.execution_operation
            .as_ref()
            .and_then(|op| op.execution_details.as_ref())
            .and_then(|details| details.input_payload.as_deref())
    }

    /// Returns the EXECUTION operation's ID if it exists.
    pub fn execution_operation_id(&self) -> Option<&str> {
        self.execution_operation
            .as_ref()
            .map(|op| op.operation_id.as_str())
    }

    /// Completes the execution with a successful result via checkpointing.
    pub async fn complete_execution_success(
        &self,
        result: Option<String>,
    ) -> Result<(), DurableError> {
        let execution_id =
            self.execution_operation_id()
                .ok_or_else(|| DurableError::Validation {
                    message: "Cannot complete execution: no EXECUTION operation exists".to_string(),
                })?;

        let update = OperationUpdate::succeed(execution_id, OperationType::Execution, result);

        self.create_checkpoint(update, true).await
    }

    /// Completes the execution with a failure via checkpointing.
    pub async fn complete_execution_failure(&self, error: ErrorObject) -> Result<(), DurableError> {
        let execution_id =
            self.execution_operation_id()
                .ok_or_else(|| DurableError::Validation {
                    message: "Cannot complete execution: no EXECUTION operation exists".to_string(),
                })?;

        let update = OperationUpdate::fail(execution_id, OperationType::Execution, error);

        self.create_checkpoint(update, true).await
    }

    /// Gets the checkpoint result for an operation.
    pub async fn get_checkpoint_result(&self, operation_id: &str) -> CheckpointedResult {
        let operations = self.operations.read().await;
        CheckpointedResult::new(operations.get(operation_id).cloned())
    }

    /// Tracks that an operation has been replayed.
    pub async fn track_replay(&self, operation_id: &str) {
        {
            let mut replayed = self.replayed_operations.write().await;
            replayed.insert(operation_id.to_string());
        }

        let (replayed_count, total_count) = {
            let replayed = self.replayed_operations.read().await;
            let operations = self.operations.read().await;
            (replayed.len(), operations.len())
        };

        if replayed_count >= total_count {
            let has_more = self.next_marker.read().await.is_some();
            if !has_more {
                // Release ordering ensures that all the replay tracking writes
                // (replayed_operations updates) are visible to any thread that
                // subsequently reads the replay_status with Acquire ordering.
                // This establishes a happens-before relationship.
                //
                // Requirements: 4.2, 4.3, 4.6
                self.replay_status
                    .store(ReplayStatus::New as u8, Ordering::Release);
            }
        }
    }

    /// Loads additional operations from the service for pagination.
    pub async fn load_more_operations(&self) -> Result<bool, DurableError> {
        let marker = {
            let guard = self.next_marker.read().await;
            match guard.as_ref() {
                Some(m) => m.clone(),
                None => return Ok(false),
            }
        };

        let response = self.get_operations_with_retry(&marker).await?;

        {
            let mut operations = self.operations.write().await;
            for op in response.operations {
                operations.insert(op.operation_id.clone(), op);
            }
        }

        {
            let mut next_marker = self.next_marker.write().await;
            *next_marker = response.next_marker;
        }

        Ok(true)
    }

    /// Fetches operations from the service with retry for throttling errors.
    async fn get_operations_with_retry(
        &self,
        marker: &str,
    ) -> Result<crate::client::GetOperationsResponse, DurableError> {
        const MAX_RETRIES: u32 = 5;
        const INITIAL_DELAY_MS: u64 = 100;
        const MAX_DELAY_MS: u64 = 10_000;
        const BACKOFF_MULTIPLIER: u64 = 2;

        let mut attempt = 0;
        let mut delay_ms = INITIAL_DELAY_MS;

        loop {
            let result = self
                .service_client
                .get_operations(&self.durable_execution_arn, marker)
                .await;

            match result {
                Ok(response) => return Ok(response),
                Err(error) if error.is_throttling() => {
                    attempt += 1;
                    if attempt > MAX_RETRIES {
                        tracing::warn!(
                            attempt = attempt,
                            "GetOperations throttling: max retries exceeded"
                        );
                        return Err(error);
                    }

                    let actual_delay = error.get_retry_after_ms().unwrap_or(delay_ms);
                    tracing::debug!(
                        attempt = attempt,
                        delay_ms = actual_delay,
                        "GetOperations throttled, retrying"
                    );
                    tokio::time::sleep(StdDuration::from_millis(actual_delay)).await;
                    delay_ms = (delay_ms * BACKOFF_MULTIPLIER).min(MAX_DELAY_MS);
                }
                Err(error) => return Err(error),
            }
        }
    }

    /// Loads all remaining operations from the service.
    pub async fn load_all_operations(&self) -> Result<(), DurableError> {
        while self.load_more_operations().await? {}
        Ok(())
    }

    /// Returns true if there are more operations to load.
    pub async fn has_more_operations(&self) -> bool {
        self.next_marker.read().await.is_some()
    }

    /// Returns the number of loaded operations.
    pub async fn operation_count(&self) -> usize {
        self.operations.read().await.len()
    }

    /// Returns a reference to the service client.
    pub fn service_client(&self) -> &SharedDurableServiceClient {
        &self.service_client
    }

    /// Adds an operation to the local cache.
    pub async fn add_operation(&self, operation: Operation) {
        let mut operations = self.operations.write().await;
        operations.insert(operation.operation_id.clone(), operation);
    }

    /// Updates an existing operation in the local cache.
    pub async fn update_operation(
        &self,
        operation_id: &str,
        update_fn: impl FnOnce(&mut Operation),
    ) {
        let mut operations = self.operations.write().await;
        if let Some(op) = operations.get_mut(operation_id) {
            update_fn(op);
        }
    }

    /// Checks if an operation exists in the local cache.
    pub async fn has_operation(&self, operation_id: &str) -> bool {
        self.operations.read().await.contains_key(operation_id)
    }

    /// Gets a clone of an operation from the local cache.
    pub async fn get_operation(&self, operation_id: &str) -> Option<Operation> {
        self.operations.read().await.get(operation_id).cloned()
    }

    /// Marks a parent operation as done.
    pub async fn mark_parent_done(&self, parent_id: &str) {
        let mut done_parents = self.parent_done_lock.lock().await;
        done_parents.insert(parent_id.to_string());
    }

    /// Checks if a parent operation has been marked as done.
    pub async fn is_parent_done(&self, parent_id: &str) -> bool {
        let done_parents = self.parent_done_lock.lock().await;
        done_parents.contains(parent_id)
    }

    /// Checks if an operation would be orphaned.
    pub async fn is_orphaned(&self, parent_id: Option<&str>) -> bool {
        match parent_id {
            Some(pid) => self.is_parent_done(pid).await,
            None => false,
        }
    }

    /// Creates a checkpoint for an operation.
    pub async fn create_checkpoint(
        &self,
        operation: OperationUpdate,
        is_sync: bool,
    ) -> Result<(), DurableError> {
        // Check for orphaned child
        if let Some(ref parent_id) = operation.parent_id {
            if self.is_parent_done(parent_id).await {
                return Err(DurableError::OrphanedChild {
                    message: format!(
                        "Cannot checkpoint operation {} - parent {} has completed",
                        operation.operation_id, parent_id
                    ),
                    operation_id: operation.operation_id.clone(),
                });
            }
        }

        // Determine effective sync behavior based on checkpointing mode
        let effective_is_sync = match self.checkpointing_mode {
            crate::config::CheckpointingMode::Eager => true,
            crate::config::CheckpointingMode::Batched => is_sync,
            crate::config::CheckpointingMode::Optimistic => is_sync,
        };

        // In Eager mode, bypass the batcher and send directly
        if self.checkpointing_mode.is_eager() {
            return self.checkpoint_direct(operation, effective_is_sync).await;
        }

        // Use the checkpoint sender if available (batched mode)
        if let Some(ref sender) = self.checkpoint_sender {
            let result = sender
                .checkpoint(operation.clone(), effective_is_sync)
                .await;
            if result.is_ok() {
                self.update_local_cache_from_update(&operation).await;
            }
            return result;
        }

        // Direct checkpoint (non-batched mode)
        self.checkpoint_direct(operation, effective_is_sync).await
    }

    /// Sends a checkpoint directly to the service, bypassing the batcher.
    async fn checkpoint_direct(
        &self,
        operation: OperationUpdate,
        _is_sync: bool,
    ) -> Result<(), DurableError> {
        let token = self.checkpoint_token.read().await.clone();
        let response = self
            .service_client
            .checkpoint(&self.durable_execution_arn, &token, vec![operation.clone()])
            .await?;

        {
            let mut token_guard = self.checkpoint_token.write().await;
            *token_guard = response.checkpoint_token;
        }

        // Update local cache from the response's NewExecutionState if available
        if let Some(ref new_state) = response.new_execution_state {
            self.update_local_cache_from_response(new_state).await;
        } else {
            self.update_local_cache_from_update(&operation).await;
        }
        Ok(())
    }

    /// Creates a checkpoint and returns the full response including NewExecutionState.
    /// This is useful for operations like CALLBACK that need service-generated values.
    pub async fn create_checkpoint_with_response(
        &self,
        operation: OperationUpdate,
    ) -> Result<crate::client::CheckpointResponse, DurableError> {
        // Check for orphaned child
        if let Some(ref parent_id) = operation.parent_id {
            if self.is_parent_done(parent_id).await {
                return Err(DurableError::OrphanedChild {
                    message: format!(
                        "Cannot checkpoint operation {} - parent {} has completed",
                        operation.operation_id, parent_id
                    ),
                    operation_id: operation.operation_id.clone(),
                });
            }
        }

        let token = self.checkpoint_token.read().await.clone();
        let response = self
            .service_client
            .checkpoint(&self.durable_execution_arn, &token, vec![operation.clone()])
            .await?;

        tracing::debug!(
            has_new_state = response.new_execution_state.is_some(),
            num_operations = response
                .new_execution_state
                .as_ref()
                .map(|s| s.operations.len())
                .unwrap_or(0),
            "Checkpoint response received"
        );

        {
            let mut token_guard = self.checkpoint_token.write().await;
            *token_guard = response.checkpoint_token.clone();
        }

        // Update local cache from the response's NewExecutionState if available
        if let Some(ref new_state) = response.new_execution_state {
            self.update_local_cache_from_response(new_state).await;
        } else {
            self.update_local_cache_from_update(&operation).await;
        }

        Ok(response)
    }

    /// Updates the local operation cache from a checkpoint response's NewExecutionState.
    async fn update_local_cache_from_response(&self, new_state: &crate::client::NewExecutionState) {
        let mut operations = self.operations.write().await;
        for op in &new_state.operations {
            operations.insert(op.operation_id.clone(), op.clone());
        }
    }

    /// Creates a synchronous checkpoint (waits for confirmation).
    pub async fn checkpoint_sync(&self, operation: OperationUpdate) -> Result<(), DurableError> {
        self.create_checkpoint(operation, true).await
    }

    /// Creates an asynchronous checkpoint (fire-and-forget).
    pub async fn checkpoint_async(&self, operation: OperationUpdate) -> Result<(), DurableError> {
        self.create_checkpoint(operation, false).await
    }

    /// Creates a checkpoint using the optimal sync behavior for the current mode.
    pub async fn checkpoint_optimal(
        &self,
        operation: OperationUpdate,
        prefer_sync: bool,
    ) -> Result<(), DurableError> {
        let is_sync = match self.checkpointing_mode {
            crate::config::CheckpointingMode::Eager => true,
            crate::config::CheckpointingMode::Batched => prefer_sync,
            crate::config::CheckpointingMode::Optimistic => prefer_sync,
        };
        self.create_checkpoint(operation, is_sync).await
    }

    /// Returns whether async checkpointing is recommended for the current mode.
    pub fn should_use_async_checkpoint(&self) -> bool {
        match self.checkpointing_mode {
            crate::config::CheckpointingMode::Eager => false,
            crate::config::CheckpointingMode::Batched => true,
            crate::config::CheckpointingMode::Optimistic => true,
        }
    }

    /// Returns whether the current mode prioritizes performance over durability.
    pub fn prioritizes_performance(&self) -> bool {
        self.checkpointing_mode.is_optimistic()
    }

    /// Returns whether the current mode prioritizes durability over performance.
    pub fn prioritizes_durability(&self) -> bool {
        self.checkpointing_mode.is_eager()
    }

    /// Updates the local operation cache based on an operation update.
    async fn update_local_cache_from_update(&self, update: &OperationUpdate) {
        let mut operations = self.operations.write().await;

        match update.action {
            crate::operation::OperationAction::Start => {
                let mut op = Operation::new(&update.operation_id, update.operation_type);
                op.parent_id = update.parent_id.clone();
                op.name = update.name.clone();
                operations.insert(update.operation_id.clone(), op);
            }
            crate::operation::OperationAction::Succeed => {
                if let Some(op) = operations.get_mut(&update.operation_id) {
                    op.status = OperationStatus::Succeeded;
                    op.result = update.result.clone();
                } else {
                    let mut op = Operation::new(&update.operation_id, update.operation_type);
                    op.status = OperationStatus::Succeeded;
                    op.result = update.result.clone();
                    op.parent_id = update.parent_id.clone();
                    op.name = update.name.clone();
                    operations.insert(update.operation_id.clone(), op);
                }
            }
            crate::operation::OperationAction::Fail => {
                if let Some(op) = operations.get_mut(&update.operation_id) {
                    op.status = OperationStatus::Failed;
                    op.error = update.error.clone();
                } else {
                    let mut op = Operation::new(&update.operation_id, update.operation_type);
                    op.status = OperationStatus::Failed;
                    op.error = update.error.clone();
                    op.parent_id = update.parent_id.clone();
                    op.name = update.name.clone();
                    operations.insert(update.operation_id.clone(), op);
                }
            }
            crate::operation::OperationAction::Cancel => {
                if let Some(op) = operations.get_mut(&update.operation_id) {
                    op.status = OperationStatus::Cancelled;
                } else {
                    let mut op = Operation::new(&update.operation_id, update.operation_type);
                    op.status = OperationStatus::Cancelled;
                    op.parent_id = update.parent_id.clone();
                    op.name = update.name.clone();
                    operations.insert(update.operation_id.clone(), op);
                }
            }
            crate::operation::OperationAction::Retry => {
                if let Some(op) = operations.get_mut(&update.operation_id) {
                    op.status = OperationStatus::Pending;
                    if update.result.is_some() || update.step_options.is_some() {
                        let step_details =
                            op.step_details
                                .get_or_insert(crate::operation::StepDetails {
                                    result: None,
                                    attempt: None,
                                    next_attempt_timestamp: None,
                                    error: None,
                                    payload: None,
                                });
                        if update.result.is_some() {
                            step_details.payload = update.result.clone();
                        }
                        step_details.attempt = Some(step_details.attempt.unwrap_or(0) + 1);
                    }
                    if update.error.is_some() {
                        op.error = update.error.clone();
                    }
                } else {
                    let mut op = Operation::new(&update.operation_id, update.operation_type);
                    op.status = OperationStatus::Pending;
                    op.parent_id = update.parent_id.clone();
                    op.name = update.name.clone();
                    op.error = update.error.clone();
                    if update.result.is_some() || update.step_options.is_some() {
                        op.step_details = Some(crate::operation::StepDetails {
                            result: None,
                            attempt: Some(1),
                            next_attempt_timestamp: None,
                            error: None,
                            payload: update.result.clone(),
                        });
                    }
                    operations.insert(update.operation_id.clone(), op);
                }
            }
        }
    }

    /// Returns a reference to the shared checkpoint token.
    pub fn shared_checkpoint_token(&self) -> Arc<RwLock<String>> {
        self.checkpoint_token.clone()
    }

    /// Returns true if this ExecutionState has a checkpoint sender configured.
    pub fn has_checkpoint_sender(&self) -> bool {
        self.checkpoint_sender.is_some()
    }

    /// Loads child operations for a specific parent operation.
    pub async fn load_child_operations(
        &self,
        parent_id: &str,
    ) -> Result<Vec<Operation>, DurableError> {
        let operations = self.operations.read().await;
        let children: Vec<Operation> = operations
            .values()
            .filter(|op| op.parent_id.as_deref() == Some(parent_id))
            .cloned()
            .collect();

        Ok(children)
    }

    /// Gets all child operations for a specific parent from the local cache.
    pub async fn get_child_operations(&self, parent_id: &str) -> Vec<Operation> {
        let operations = self.operations.read().await;
        operations
            .values()
            .filter(|op| op.parent_id.as_deref() == Some(parent_id))
            .cloned()
            .collect()
    }

    /// Checks if a CONTEXT operation has ReplayChildren enabled.
    pub async fn has_replay_children(&self, operation_id: &str) -> bool {
        let operations = self.operations.read().await;
        operations
            .get(operation_id)
            .filter(|op| op.operation_type == OperationType::Context)
            .and_then(|op| op.context_details.as_ref())
            .and_then(|details| details.replay_children)
            .unwrap_or(false)
    }
}

// Implement Debug manually since we can't derive it with async locks
impl std::fmt::Debug for ExecutionState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExecutionState")
            .field("durable_execution_arn", &self.durable_execution_arn)
            .field("replay_status", &self.replay_status())
            .finish_non_exhaustive()
    }
}

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

    use crate::client::{
        CheckpointResponse, GetOperationsResponse, MockDurableServiceClient,
        SharedDurableServiceClient,
    };
    use crate::error::ErrorObject;
    use crate::lambda::InitialExecutionState;
    use crate::operation::{
        ContextDetails, ExecutionDetails, Operation, OperationStatus, OperationType,
        OperationUpdate,
    };

    fn create_mock_client() -> SharedDurableServiceClient {
        Arc::new(MockDurableServiceClient::new())
    }

    fn create_test_operation(id: &str, status: OperationStatus) -> Operation {
        let mut op = Operation::new(id, OperationType::Step);
        op.status = status;
        op
    }

    fn create_execution_operation(input_payload: Option<&str>) -> Operation {
        let mut op = Operation::new("exec-123", OperationType::Execution);
        op.status = OperationStatus::Started;
        op.execution_details = Some(ExecutionDetails {
            input_payload: input_payload.map(|s| s.to_string()),
        });
        op
    }

    // Basic ExecutionState tests

    #[tokio::test]
    async fn test_execution_state_new_empty() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert_eq!(state.durable_execution_arn(), "arn:test");
        assert_eq!(state.checkpoint_token().await, "token-123");
        assert!(state.is_new());
        assert!(!state.is_replay());
        assert_eq!(state.operation_count().await, 0);
        assert!(!state.has_more_operations().await);
    }

    #[tokio::test]
    async fn test_execution_state_new_with_operations() {
        let client = create_mock_client();
        let ops = vec![
            create_test_operation("op-1", OperationStatus::Succeeded),
            create_test_operation("op-2", OperationStatus::Succeeded),
        ];
        let initial_state = InitialExecutionState::with_operations(ops);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(state.is_replay());
        assert!(!state.is_new());
        assert_eq!(state.operation_count().await, 2);
    }

    #[tokio::test]
    async fn test_get_checkpoint_result_exists() {
        let client = create_mock_client();
        let mut op = create_test_operation("op-1", OperationStatus::Succeeded);
        op.result = Some(r#"{"value": 42}"#.to_string());
        let initial_state = InitialExecutionState::with_operations(vec![op]);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let result = state.get_checkpoint_result("op-1").await;
        assert!(result.is_existent());
        assert!(result.is_succeeded());
        assert_eq!(result.result(), Some(r#"{"value": 42}"#));
    }

    #[tokio::test]
    async fn test_get_checkpoint_result_not_exists() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let result = state.get_checkpoint_result("non-existent").await;
        assert!(!result.is_existent());
    }

    #[tokio::test]
    async fn test_track_replay_transitions_to_new() {
        let client = create_mock_client();
        let ops = vec![
            create_test_operation("op-1", OperationStatus::Succeeded),
            create_test_operation("op-2", OperationStatus::Succeeded),
        ];
        let initial_state = InitialExecutionState::with_operations(ops);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(state.is_replay());
        state.track_replay("op-1").await;
        assert!(state.is_replay());
        state.track_replay("op-2").await;
        assert!(state.is_new());
    }

    #[tokio::test]
    async fn test_track_replay_with_pagination() {
        let client = Arc::new(
            MockDurableServiceClient::new().with_get_operations_response(Ok(
                GetOperationsResponse {
                    operations: vec![create_test_operation("op-3", OperationStatus::Succeeded)],
                    next_marker: None,
                },
            )),
        );

        let ops = vec![create_test_operation("op-1", OperationStatus::Succeeded)];
        let mut initial_state = InitialExecutionState::with_operations(ops);
        initial_state.next_marker = Some("marker-1".to_string());

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        state.track_replay("op-1").await;
        assert!(state.is_replay());
    }

    #[tokio::test]
    async fn test_set_checkpoint_token() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert_eq!(state.checkpoint_token().await, "token-123");
        state.set_checkpoint_token("token-456").await;
        assert_eq!(state.checkpoint_token().await, "token-456");
    }

    #[tokio::test]
    async fn test_add_operation() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert!(!state.has_operation("op-1").await);

        let op = create_test_operation("op-1", OperationStatus::Succeeded);
        state.add_operation(op).await;

        assert!(state.has_operation("op-1").await);
        assert_eq!(state.operation_count().await, 1);
    }

    #[tokio::test]
    async fn test_update_operation() {
        let client = create_mock_client();
        let ops = vec![create_test_operation("op-1", OperationStatus::Started)];
        let initial_state = InitialExecutionState::with_operations(ops);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let op = state.get_operation("op-1").await.unwrap();
        assert_eq!(op.status, OperationStatus::Started);

        state
            .update_operation("op-1", |op| {
                op.status = OperationStatus::Succeeded;
                op.result = Some("done".to_string());
            })
            .await;

        let op = state.get_operation("op-1").await.unwrap();
        assert_eq!(op.status, OperationStatus::Succeeded);
        assert_eq!(op.result, Some("done".to_string()));
    }

    #[tokio::test]
    async fn test_load_more_operations() {
        let client = Arc::new(
            MockDurableServiceClient::new().with_get_operations_response(Ok(
                GetOperationsResponse {
                    operations: vec![
                        create_test_operation("op-2", OperationStatus::Succeeded),
                        create_test_operation("op-3", OperationStatus::Succeeded),
                    ],
                    next_marker: None,
                },
            )),
        );

        let ops = vec![create_test_operation("op-1", OperationStatus::Succeeded)];
        let mut initial_state = InitialExecutionState::with_operations(ops);
        initial_state.next_marker = Some("marker-1".to_string());

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert_eq!(state.operation_count().await, 1);
        assert!(state.has_more_operations().await);

        let loaded = state.load_more_operations().await.unwrap();
        assert!(loaded);

        assert_eq!(state.operation_count().await, 3);
        assert!(!state.has_more_operations().await);
    }

    #[tokio::test]
    async fn test_load_more_operations_no_more() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let loaded = state.load_more_operations().await.unwrap();
        assert!(!loaded);
    }

    #[tokio::test]
    async fn test_load_all_operations() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_get_operations_response(Ok(GetOperationsResponse {
                    operations: vec![create_test_operation("op-2", OperationStatus::Succeeded)],
                    next_marker: Some("marker-2".to_string()),
                }))
                .with_get_operations_response(Ok(GetOperationsResponse {
                    operations: vec![create_test_operation("op-3", OperationStatus::Succeeded)],
                    next_marker: None,
                })),
        );

        let ops = vec![create_test_operation("op-1", OperationStatus::Succeeded)];
        let mut initial_state = InitialExecutionState::with_operations(ops);
        initial_state.next_marker = Some("marker-1".to_string());

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert_eq!(state.operation_count().await, 1);
        state.load_all_operations().await.unwrap();

        assert_eq!(state.operation_count().await, 3);
        assert!(!state.has_more_operations().await);
    }

    #[tokio::test]
    async fn test_mark_parent_done() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert!(!state.is_parent_done("parent-1").await);
        state.mark_parent_done("parent-1").await;
        assert!(state.is_parent_done("parent-1").await);
        assert!(!state.is_parent_done("parent-2").await);
    }

    #[tokio::test]
    async fn test_is_orphaned() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert!(!state.is_orphaned(None).await);
        assert!(!state.is_orphaned(Some("parent-1")).await);

        state.mark_parent_done("parent-1").await;

        assert!(state.is_orphaned(Some("parent-1")).await);
        assert!(!state.is_orphaned(Some("parent-2")).await);
    }

    #[tokio::test]
    async fn test_debug_impl() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let debug_str = format!("{:?}", state);
        assert!(debug_str.contains("ExecutionState"));
        assert!(debug_str.contains("arn:test"));
    }

    #[tokio::test]
    async fn test_create_checkpoint_direct() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.create_checkpoint(update, true).await;

        assert!(result.is_ok());
        assert_eq!(state.checkpoint_token().await, "new-token");
        assert!(state.has_operation("op-1").await);
    }

    #[tokio::test]
    async fn test_create_checkpoint_updates_local_cache_on_succeed() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("token-1")))
                .with_checkpoint_response(Ok(CheckpointResponse::new("token-2"))),
        );

        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let update = OperationUpdate::start("op-1", OperationType::Step);
        state.create_checkpoint(update, true).await.unwrap();

        let op = state.get_operation("op-1").await.unwrap();
        assert_eq!(op.status, OperationStatus::Started);

        let update = OperationUpdate::succeed(
            "op-1",
            OperationType::Step,
            Some(r#"{"result": "ok"}"#.to_string()),
        );
        state.create_checkpoint(update, true).await.unwrap();

        let op = state.get_operation("op-1").await.unwrap();
        assert_eq!(op.status, OperationStatus::Succeeded);
        assert_eq!(op.result, Some(r#"{"result": "ok"}"#.to_string()));
    }

    #[tokio::test]
    async fn test_create_checkpoint_rejects_orphaned_child() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        state.mark_parent_done("parent-1").await;

        let update =
            OperationUpdate::start("child-1", OperationType::Step).with_parent_id("parent-1");
        let result = state.create_checkpoint(update, true).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DurableError::OrphanedChild { operation_id, .. } => {
                assert_eq!(operation_id, "child-1");
            }
            _ => panic!("Expected OrphanedChild error"),
        }
    }

    #[tokio::test]
    async fn test_with_batcher_creates_state_and_batcher() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let (state, mut batcher) = ExecutionState::with_batcher(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            CheckpointBatcherConfig {
                max_batch_time_ms: 10,
                ..Default::default()
            },
            100,
        );

        assert!(state.has_checkpoint_sender());
        assert_eq!(state.durable_execution_arn(), "arn:test");

        let batcher_handle = tokio::spawn(async move {
            batcher.run().await;
        });

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.create_checkpoint(update, true).await;

        drop(state);
        batcher_handle.await.unwrap();

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_checkpoint_sync_convenience_method() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.checkpoint_sync(update).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_checkpoint_async_convenience_method() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.checkpoint_async(update).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_shared_checkpoint_token() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let shared_token = state.shared_checkpoint_token();
        assert_eq!(*shared_token.read().await, "token-123");

        {
            let mut guard = shared_token.write().await;
            *guard = "modified-token".to_string();
        }

        assert_eq!(state.checkpoint_token().await, "modified-token");
    }

    // Tests for ReplayChildren support (Requirements 10.5, 10.6)

    #[tokio::test]
    async fn test_load_child_operations_returns_children() {
        let client = create_mock_client();

        let mut parent_op = Operation::new("parent-ctx", OperationType::Context);
        parent_op.status = OperationStatus::Succeeded;

        let mut child1 = create_test_operation("child-1", OperationStatus::Succeeded);
        child1.parent_id = Some("parent-ctx".to_string());

        let mut child2 = create_test_operation("child-2", OperationStatus::Succeeded);
        child2.parent_id = Some("parent-ctx".to_string());

        let mut other_child = create_test_operation("other-child", OperationStatus::Succeeded);
        other_child.parent_id = Some("other-parent".to_string());

        let initial_state =
            InitialExecutionState::with_operations(vec![parent_op, child1, child2, other_child]);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let children = state.load_child_operations("parent-ctx").await.unwrap();

        assert_eq!(children.len(), 2);
        let child_ids: Vec<&str> = children.iter().map(|c| c.operation_id.as_str()).collect();
        assert!(child_ids.contains(&"child-1"));
        assert!(child_ids.contains(&"child-2"));
    }

    #[tokio::test]
    async fn test_load_child_operations_no_children() {
        let client = create_mock_client();

        let parent_op = Operation::new("parent-ctx", OperationType::Context);
        let initial_state = InitialExecutionState::with_operations(vec![parent_op]);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let children = state.load_child_operations("parent-ctx").await.unwrap();

        assert!(children.is_empty());
    }

    #[tokio::test]
    async fn test_get_child_operations_returns_cached_children() {
        let client = create_mock_client();

        let mut parent_op = Operation::new("parent-ctx", OperationType::Context);
        parent_op.status = OperationStatus::Succeeded;

        let mut child1 = create_test_operation("child-1", OperationStatus::Succeeded);
        child1.parent_id = Some("parent-ctx".to_string());

        let mut child2 = create_test_operation("child-2", OperationStatus::Succeeded);
        child2.parent_id = Some("parent-ctx".to_string());

        let initial_state = InitialExecutionState::with_operations(vec![parent_op, child1, child2]);

        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let children = state.get_child_operations("parent-ctx").await;

        assert_eq!(children.len(), 2);
    }

    #[tokio::test]
    async fn test_get_child_operations_empty_for_nonexistent_parent() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        let children = state.get_child_operations("nonexistent-parent").await;
        assert!(children.is_empty());
    }

    #[tokio::test]
    async fn test_has_replay_children_true() {
        let client = create_mock_client();

        let mut ctx_op = Operation::new("ctx-with-replay", OperationType::Context);
        ctx_op.status = OperationStatus::Succeeded;
        ctx_op.context_details = Some(ContextDetails {
            result: None,
            replay_children: Some(true),
            error: None,
        });

        let initial_state = InitialExecutionState::with_operations(vec![ctx_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(state.has_replay_children("ctx-with-replay").await);
    }

    #[tokio::test]
    async fn test_has_replay_children_false_when_not_set() {
        let client = create_mock_client();

        let mut ctx_op = Operation::new("ctx-no-replay", OperationType::Context);
        ctx_op.status = OperationStatus::Succeeded;
        ctx_op.context_details = Some(ContextDetails {
            result: None,
            replay_children: None,
            error: None,
        });

        let initial_state = InitialExecutionState::with_operations(vec![ctx_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(!state.has_replay_children("ctx-no-replay").await);
    }

    // Tests for CheckpointingMode (Requirements 24.1, 24.2, 24.3, 24.4)

    #[tokio::test]
    async fn test_checkpointing_mode_default_is_batched() {
        let client = create_mock_client();
        let state = ExecutionState::new(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
        );

        assert_eq!(
            state.checkpointing_mode(),
            crate::config::CheckpointingMode::Batched
        );
        assert!(state.is_batched_checkpointing());
        assert!(!state.is_eager_checkpointing());
        assert!(!state.is_optimistic_checkpointing());
    }

    #[tokio::test]
    async fn test_checkpointing_mode_eager() {
        let client = create_mock_client();
        let state = ExecutionState::with_checkpointing_mode(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            crate::config::CheckpointingMode::Eager,
        );

        assert_eq!(
            state.checkpointing_mode(),
            crate::config::CheckpointingMode::Eager
        );
        assert!(state.is_eager_checkpointing());
        assert!(!state.is_batched_checkpointing());
        assert!(!state.is_optimistic_checkpointing());
        assert!(state.prioritizes_durability());
        assert!(!state.prioritizes_performance());
        assert!(!state.should_use_async_checkpoint());
    }

    #[tokio::test]
    async fn test_checkpointing_mode_optimistic() {
        let client = create_mock_client();
        let state = ExecutionState::with_checkpointing_mode(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            crate::config::CheckpointingMode::Optimistic,
        );

        assert_eq!(
            state.checkpointing_mode(),
            crate::config::CheckpointingMode::Optimistic
        );
        assert!(state.is_optimistic_checkpointing());
        assert!(!state.is_eager_checkpointing());
        assert!(!state.is_batched_checkpointing());
        assert!(state.prioritizes_performance());
        assert!(!state.prioritizes_durability());
        assert!(state.should_use_async_checkpoint());
    }

    #[tokio::test]
    async fn test_checkpointing_mode_batched_helpers() {
        let client = create_mock_client();
        let state = ExecutionState::with_checkpointing_mode(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            crate::config::CheckpointingMode::Batched,
        );

        assert!(!state.prioritizes_durability());
        assert!(!state.prioritizes_performance());
        assert!(state.should_use_async_checkpoint());
    }

    #[tokio::test]
    async fn test_checkpoint_optimal_eager_mode() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let state = ExecutionState::with_checkpointing_mode(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            crate::config::CheckpointingMode::Eager,
        );

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.checkpoint_optimal(update, false).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_eager_mode_bypasses_batcher() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let (state, mut batcher) = ExecutionState::with_batcher_and_mode(
            "arn:test",
            "token-123",
            InitialExecutionState::new(),
            client,
            CheckpointBatcherConfig {
                max_batch_time_ms: 10,
                ..Default::default()
            },
            100,
            crate::config::CheckpointingMode::Eager,
        );

        let batcher_handle = tokio::spawn(async move {
            batcher.run().await;
        });

        let update = OperationUpdate::start("op-1", OperationType::Step);
        let result = state.create_checkpoint(update, false).await;

        drop(state);
        batcher_handle.await.unwrap();

        assert!(result.is_ok());
    }

    // Tests for EXECUTION operation handling (Requirements 19.1-19.5)

    #[tokio::test]
    async fn test_execution_operation_recognized() {
        let client = create_mock_client();
        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));
        let step_op = Operation::new("step-1", OperationType::Step);

        let initial_state = InitialExecutionState::with_operations(vec![exec_op, step_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(state.execution_operation().is_some());
        let exec = state.execution_operation().unwrap();
        assert_eq!(exec.operation_type, OperationType::Execution);
        assert_eq!(exec.operation_id, "exec-123");
    }

    #[tokio::test]
    async fn test_execution_operation_not_present() {
        let client = create_mock_client();
        let step_op = Operation::new("step-1", OperationType::Step);

        let initial_state = InitialExecutionState::with_operations(vec![step_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        assert!(state.execution_operation().is_none());
    }

    #[tokio::test]
    async fn test_get_original_input_raw() {
        let client = create_mock_client();
        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));

        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let input = state.get_original_input_raw();
        assert!(input.is_some());
        assert_eq!(input.unwrap(), r#"{"order_id": "123"}"#);
    }

    #[tokio::test]
    async fn test_get_original_input_raw_no_payload() {
        let client = create_mock_client();
        let exec_op = create_execution_operation(None);

        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let input = state.get_original_input_raw();
        assert!(input.is_none());
    }

    #[tokio::test]
    async fn test_get_original_input_raw_no_execution_operation() {
        let client = create_mock_client();
        let step_op = Operation::new("step-1", OperationType::Step);

        let initial_state = InitialExecutionState::with_operations(vec![step_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let input = state.get_original_input_raw();
        assert!(input.is_none());
    }

    #[tokio::test]
    async fn test_execution_operation_id() {
        let client = create_mock_client();
        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));

        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let id = state.execution_operation_id();
        assert!(id.is_some());
        assert_eq!(id.unwrap(), "exec-123");
    }

    #[tokio::test]
    async fn test_complete_execution_success() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));
        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let result = state
            .complete_execution_success(Some(r#"{"status": "completed"}"#.to_string()))
            .await;
        assert!(result.is_ok());

        let op = state.get_operation("exec-123").await.unwrap();
        assert_eq!(op.status, OperationStatus::Succeeded);
        assert_eq!(op.result, Some(r#"{"status": "completed"}"#.to_string()));
    }

    #[tokio::test]
    async fn test_complete_execution_success_no_execution_operation() {
        let client = create_mock_client();
        let step_op = Operation::new("step-1", OperationType::Step);

        let initial_state = InitialExecutionState::with_operations(vec![step_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let result = state
            .complete_execution_success(Some("result".to_string()))
            .await;
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DurableError::Validation { message } => {
                assert!(message.contains("no EXECUTION operation"));
            }
            _ => panic!("Expected Validation error"),
        }
    }

    #[tokio::test]
    async fn test_complete_execution_failure() {
        let client = Arc::new(
            MockDurableServiceClient::new()
                .with_checkpoint_response(Ok(CheckpointResponse::new("new-token"))),
        );

        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));
        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let error = ErrorObject::new("ProcessingError", "Order processing failed");
        let result = state.complete_execution_failure(error).await;
        assert!(result.is_ok());

        let op = state.get_operation("exec-123").await.unwrap();
        assert_eq!(op.status, OperationStatus::Failed);
        assert!(op.error.is_some());
        assert_eq!(op.error.as_ref().unwrap().error_type, "ProcessingError");
    }

    #[tokio::test]
    async fn test_complete_execution_failure_no_execution_operation() {
        let client = create_mock_client();
        let step_op = Operation::new("step-1", OperationType::Step);

        let initial_state = InitialExecutionState::with_operations(vec![step_op]);
        let state = ExecutionState::new("arn:test", "token-123", initial_state, client);

        let error = ErrorObject::new("TestError", "Test message");
        let result = state.complete_execution_failure(error).await;
        assert!(result.is_err());
        match result.unwrap_err() {
            crate::error::DurableError::Validation { message } => {
                assert!(message.contains("no EXECUTION operation"));
            }
            _ => panic!("Expected Validation error"),
        }
    }

    #[tokio::test]
    async fn test_with_batcher_recognizes_execution_operation() {
        let client = Arc::new(MockDurableServiceClient::new());
        let exec_op = create_execution_operation(Some(r#"{"order_id": "123"}"#));

        let initial_state = InitialExecutionState::with_operations(vec![exec_op]);
        let (state, _batcher) = ExecutionState::with_batcher(
            "arn:test",
            "token-123",
            initial_state,
            client,
            CheckpointBatcherConfig::default(),
            100,
        );

        assert!(state.execution_operation().is_some());
        let exec = state.execution_operation().unwrap();
        assert_eq!(exec.operation_type, OperationType::Execution);
        assert_eq!(
            state.get_original_input_raw(),
            Some(r#"{"order_id": "123"}"#)
        );
    }

    // Property-based tests for orphan prevention

    mod property_tests {
        use super::*;
        use proptest::prelude::*;

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

            #[test]
            fn prop_orphaned_child_checkpoint_fails(
                parent_id in "[a-z]{5,10}",
                child_id in "[a-z]{5,10}",
            ) {
                let rt = tokio::runtime::Runtime::new().unwrap();
                let result: Result<(), TestCaseError> = rt.block_on(async {
                    let client = Arc::new(
                        MockDurableServiceClient::new()
                            .with_checkpoint_response(Ok(CheckpointResponse::new("new-token")))
                    );

                    let state = ExecutionState::new(
                        "arn:test",
                        "token-123",
                        InitialExecutionState::new(),
                        client,
                    );

                    state.mark_parent_done(&parent_id).await;

                    let update = OperationUpdate::start(&child_id, OperationType::Step)
                        .with_parent_id(&parent_id);
                    let checkpoint_result = state.create_checkpoint(update, true).await;

                    match checkpoint_result {
                        Err(DurableError::OrphanedChild { operation_id, .. }) => {
                            if operation_id != child_id {
                                return Err(TestCaseError::fail(format!(
                                    "Expected operation_id '{}' in OrphanedChild error, got '{}'",
                                    child_id, operation_id
                                )));
                            }
                        }
                        Ok(_) => {
                            return Err(TestCaseError::fail(
                                "Expected OrphanedChild error, but checkpoint succeeded"
                            ));
                        }
                        Err(other) => {
                            return Err(TestCaseError::fail(format!(
                                "Expected OrphanedChild error, got {:?}",
                                other
                            )));
                        }
                    }

                    Ok(())
                });
                result?;
            }

            #[test]
            fn prop_non_orphaned_child_checkpoint_succeeds(
                parent_id in "[a-z]{5,10}",
                child_id in "[a-z]{5,10}",
            ) {
                let rt = tokio::runtime::Runtime::new().unwrap();
                let result: Result<(), TestCaseError> = rt.block_on(async {
                    let client = Arc::new(
                        MockDurableServiceClient::new()
                            .with_checkpoint_response(Ok(CheckpointResponse::new("new-token")))
                    );

                    let state = ExecutionState::new(
                        "arn:test",
                        "token-123",
                        InitialExecutionState::new(),
                        client,
                    );

                    let update = OperationUpdate::start(&child_id, OperationType::Step)
                        .with_parent_id(&parent_id);
                    let checkpoint_result = state.create_checkpoint(update, true).await;

                    if let Err(e) = checkpoint_result {
                        return Err(TestCaseError::fail(format!(
                            "Expected checkpoint to succeed for non-orphaned child, got error: {:?}",
                            e
                        )));
                    }

                    Ok(())
                });
                result?;
            }

            #[test]
            fn prop_root_operation_never_orphaned(
                operation_id in "[a-z]{5,10}",
            ) {
                let rt = tokio::runtime::Runtime::new().unwrap();
                let result: Result<(), TestCaseError> = rt.block_on(async {
                    let client = Arc::new(
                        MockDurableServiceClient::new()
                            .with_checkpoint_response(Ok(CheckpointResponse::new("new-token")))
                    );

                    let state = ExecutionState::new(
                        "arn:test",
                        "token-123",
                        InitialExecutionState::new(),
                        client,
                    );

                    let update = OperationUpdate::start(&operation_id, OperationType::Step);
                    let checkpoint_result = state.create_checkpoint(update, true).await;

                    if let Err(e) = checkpoint_result {
                        return Err(TestCaseError::fail(format!(
                            "Expected checkpoint to succeed for root operation, got error: {:?}",
                            e
                        )));
                    }

                    Ok(())
                });
                result?;
            }

            #[test]
            fn prop_marking_parent_done_affects_future_checkpoints(
                parent_id in "[a-z]{5,10}",
                child_id_before in "[a-z]{5,10}",
                child_id_after in "[a-z]{5,10}",
            ) {
                let rt = tokio::runtime::Runtime::new().unwrap();
                let result: Result<(), TestCaseError> = rt.block_on(async {
                    let client = Arc::new(
                        MockDurableServiceClient::new()
                            .with_checkpoint_response(Ok(CheckpointResponse::new("token-1")))
                            .with_checkpoint_response(Ok(CheckpointResponse::new("token-2")))
                    );

                    let state = ExecutionState::new(
                        "arn:test",
                        "token-123",
                        InitialExecutionState::new(),
                        client,
                    );

                    let update_before = OperationUpdate::start(&child_id_before, OperationType::Step)
                        .with_parent_id(&parent_id);
                    let result_before = state.create_checkpoint(update_before, true).await;

                    if let Err(e) = result_before {
                        return Err(TestCaseError::fail(format!(
                            "Expected first checkpoint to succeed, got error: {:?}",
                            e
                        )));
                    }

                    state.mark_parent_done(&parent_id).await;

                    let update_after = OperationUpdate::start(&child_id_after, OperationType::Step)
                        .with_parent_id(&parent_id);
                    let result_after = state.create_checkpoint(update_after, true).await;

                    match result_after {
                        Err(DurableError::OrphanedChild { .. }) => {
                            // Expected
                        }
                        Ok(_) => {
                            return Err(TestCaseError::fail(
                                "Expected OrphanedChild error after marking parent done"
                            ));
                        }
                        Err(other) => {
                            return Err(TestCaseError::fail(format!(
                                "Expected OrphanedChild error, got {:?}",
                                other
                            )));
                        }
                    }

                    Ok(())
                });
                result?;
            }
        }
    }
}