aws-durable-execution-sdk 0.2.0

Rust SDK for AWS Lambda Durable Functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
//! Internal replay engine: positional ID minting, wire ID hashing,
//! checkpoint-log pairing, and replay-mode detection.
//!
//! This module is a private engine concern: nothing here is part of the
//! public API surface.

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

use sha2::{Digest, Sha256};

/// A minted operation identity: the positional path and its SHA-256 wire
/// form, computed once at mint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct OperationId {
    /// The human-readable positional path (e.g. `"1"`, `"2-1"`, `"2-1-3"`).
    positional: String,
    /// SHA-256 hex digest (64 chars) of the positional string, computed once.
    wire: String,
}

impl OperationId {
    /// Builds the identity of the positional ID `positional`, with its
    /// wire ID.
    pub(crate) fn new(positional: String) -> Self {
        let wire = compute_wire_id(&positional);
        Self { positional, wire }
    }

    /// Returns the positional string.
    pub(crate) fn positional(&self) -> &str {
        &self.positional
    }

    /// Returns the 64-hex-char wire ID (SHA-256 of the positional string).
    pub(crate) fn wire(&self) -> &str {
        &self.wire
    }
}

/// Computes the SHA-256 hex digest of the given positional ID string.
///
/// The hash input is the raw UTF-8 bytes of the formatted positional string.
fn compute_wire_id(positional: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(positional.as_bytes());
    let digest = hasher.finalize();
    // Full 64-char hex digest: fits the 64-char OperationId wire cap exactly.
    hex::encode_sha256(digest.as_slice())
}

/// Computes the wire ID from a positional string (crate-internal accessor).
///
/// Used by context.rs to look up checkpoint records by positional ID when the
/// log is keyed by wire ID.
pub(crate) fn compute_wire_id_public(positional: &str) -> String {
    compute_wire_id(positional)
}

/// Minimal hex encoder for a SHA-256 digest (32 bytes → 64 hex chars).
/// Avoids pulling in the `hex` crate: the encoding is trivial.
mod hex {
    const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";

    pub(super) fn encode_sha256(bytes: &[u8]) -> String {
        let mut out = String::with_capacity(bytes.len() * 2);
        for &b in bytes {
            // SAFETY argument: (b >> 4) is in [0, 15] and (b & 0x0f) is in
            // [0, 15], both within HEX_CHARS' length of 16.
            #[expect(clippy::indexing_slicing)] // reason: index ≤ 15 for any u8 half-byte
            {
                out.push(HEX_CHARS[(b >> 4) as usize] as char);
                out.push(HEX_CHARS[(b & 0x0f) as usize] as char);
            }
        }
        out
    }
}

/// The per-context operation-ID counter.
///
/// Wrapped in `Arc` so that `DurableContext` clones (which share the same
/// operation namespace) share a single counter. The atomic provides interior
/// mutability without a lock: minting is a single `fetch_add(1, SeqCst)`.
///
/// `SeqCst` is deliberate: the spec's defining invariant is that ID
/// assignment follows program order. `SeqCst` is the only ordering that
/// prevents the compiler and CPU from reordering atomic operations with
/// respect to other memory accesses on the same thread, guaranteeing that
/// an ID is minted where the handler's control flow claims it: at the call
/// site for most operations, at a combinator's first poll or `.spawn()`,
/// when a `with_retry` builder with its own record becomes its future, and
/// at the start of each attempt of an unwrapped `with_retry` block.
#[derive(Debug)]
pub(crate) struct IdCounter {
    prefix: String,
    counter: AtomicU64,
}

impl IdCounter {
    /// Creates a new counter with the given prefix. Counter starts below 1
    /// so the first `mint()` yields position 1.
    pub(crate) fn new(prefix: String) -> Self {
        Self {
            prefix,
            counter: AtomicU64::new(0),
        }
    }

    /// Mints the next operation ID. Synchronous, lock-free.
    ///
    /// Every operation claims its ID through this. Most operations call it at
    /// their call site. A combinator calls it on its first poll or at
    /// `.spawn()`. A `with_retry` block with its own record calls it when the
    /// builder becomes its future (`.await`, `.future()` or `.spawn()`). A
    /// block without a child context never calls it for itself; each of its
    /// attempts and waits calls it when that attempt or wait starts. Every
    /// invocation advances the counter by
    /// exactly one position and returns the operation identity.
    pub(crate) fn mint(&self) -> OperationId {
        let n = self.counter.fetch_add(1, Ordering::SeqCst) + 1;
        OperationId::new(self.format(n))
    }

    /// Creates a child counter whose prefix is the given positional ID.
    /// Used when spawning child contexts.
    pub(crate) fn child(positional_id: &str) -> Self {
        Self::new(positional_id.to_owned())
    }

    fn format(&self, n: u64) -> String {
        if self.prefix.is_empty() {
            n.to_string()
        } else {
            format!("{}-{n}", self.prefix)
        }
    }

    /// Returns the prefix of this counter (empty string for root).
    pub(crate) fn prefix(&self) -> &str {
        &self.prefix
    }

    /// Peeks at the positional ID that the next `mint()` will produce,
    /// without advancing the counter.
    pub(crate) fn peek_next(&self) -> String {
        let next_n = self.counter.load(Ordering::SeqCst) + 1;
        self.format(next_n)
    }
}

/// The status of a checkpointed operation, as recorded by the backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CheckpointStatus {
    /// Operation started but not yet resolved.
    Started,
    /// Operation is awaiting an external event.
    Pending,
    /// Operation result is ready to be consumed.
    Ready,
    /// Operation completed successfully.
    Succeeded,
    /// Operation failed.
    Failed,
    /// Operation was cancelled.
    Cancelled,
    /// Operation timed out.
    TimedOut,
    /// Operation was stopped.
    Stopped,
    /// A status this SDK version does not recognize, carrying the raw
    /// value the service reported.
    ///
    /// A status the SDK cannot interpret must never be *acted on*: replay
    /// reaching an `Unknown` record fails the execution naming the raw
    /// status (see `DurableContext::checkpoint_view_validated`), because
    /// guessing, treating a possibly-terminal outcome as re-runnable, or
    /// fabricating a terminal outcome from an unreadable record, corrupts
    /// the execution either way.
    Unknown(String),
}

impl CheckpointStatus {
    /// Returns true if this status represents a terminal (settled) outcome
    /// that replay can return without re-executing.
    ///
    /// `Unknown` reports terminal: a status this SDK does not recognize may
    /// well be a terminal status the service added, so nothing may re-run
    /// or overwrite the record. Every replay path that would need to
    /// *interpret* the record fails the execution first (see
    /// `DurableContext::checkpoint_view_validated`), so this answer only
    /// steers bookkeeping that must not touch the record.
    pub(crate) fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Succeeded
                | Self::Failed
                | Self::Cancelled
                | Self::TimedOut
                | Self::Stopped
                | Self::Unknown(_)
        )
    }

    /// The wire (`UPPER_CASE`) spelling of this status, as the backend
    /// reports it. `Unknown` yields the raw value verbatim.
    pub(crate) fn wire_str(&self) -> &str {
        match self {
            Self::Started => "STARTED",
            Self::Pending => "PENDING",
            Self::Ready => "READY",
            Self::Succeeded => "SUCCEEDED",
            Self::Failed => "FAILED",
            Self::Cancelled => "CANCELLED",
            Self::TimedOut => "TIMED_OUT",
            Self::Stopped => "STOPPED",
            Self::Unknown(raw) => raw,
        }
    }
}

/// A stored operation record from the checkpoint log.
///
/// Models the checkpoint API response shape. Fields are added as the engine
/// consumes them in later slices.
#[derive(Debug, Clone)]
pub(crate) struct CheckpointRecord {
    /// The wire operation ID (SHA-256 hex) used as the map key.
    ///
    /// The log keys records by this same ID, so no code path needs to read
    /// it back off the record; it is kept on the record so `Debug` output
    /// of a record identifies the operation it belongs to.
    #[expect(dead_code)]
    // reason: never read back: the log keys records by this ID; retained for Debug diagnostics
    pub(crate) id: String,
    /// The operation's status.
    pub(crate) status: CheckpointStatus,
    /// The serialized result payload (for succeeded step operations).
    pub(crate) result: Option<String>,
    /// Error type identifier (for failed/timed-out operations).
    pub(crate) error_type: Option<String>,
    /// Error message (for failed/timed-out operations).
    pub(crate) error_message: Option<String>,
    /// Opaque error payload (for failed/timed-out operations). Written
    /// and passed through verbatim; never deserialized except for the
    /// SDK-authored `select_ok` `AllFailed` losers payload, which
    /// combinator replay decodes defensively.
    pub(crate) error_data: Option<String>,
    /// Recorded stack trace frames (for failed/timed-out operations).
    pub(crate) stack_trace: Option<Vec<String>>,
    /// The attempt number from the backend's step details (0 if unavailable).
    pub(crate) attempt: u32,
    /// The serialized result payload from a succeeded chained invoke.
    pub(crate) invoke_result: Option<String>,
    /// Error type from a failed chained invoke.
    pub(crate) invoke_error_type: Option<String>,
    /// Error message from a failed chained invoke.
    pub(crate) invoke_error_message: Option<String>,
    /// Opaque error payload from a failed chained invoke. Written and
    /// passed through verbatim, never deserialized.
    pub(crate) invoke_error_data: Option<String>,
    /// Recorded stack trace frames from a failed chained invoke.
    pub(crate) invoke_stack_trace: Option<Vec<String>>,
    /// Whether the child context result was too large and must be
    /// reconstructed by re-executing the child body (`ReplayChildren` mode).
    pub(crate) replay_children: bool,
    /// The callback ID assigned by the backend (for callback operations).
    pub(crate) callback_id: Option<String>,
    /// The operation type from the backend (e.g. `Step`, `Wait`, `Context`,
    /// `ChainedInvoke`, `Callback`). Used for non-determinism detection.
    pub(crate) op_type: Option<String>,
    /// The operation sub-type from the backend (e.g. `Step`, `Wait`, `Map`,
    /// `Parallel`). Used for non-determinism detection.
    pub(crate) sub_type: Option<String>,
    /// The operation name assigned by the user (if any). Used for
    /// non-determinism detection.
    pub(crate) op_name: Option<String>,
    /// When the operation is next due: a wait's scheduled end, or a
    /// step's next attempt. `None` when the service sent neither, or sent
    /// a value that does not convert. The refresh scheduler
    /// ([`crate::coordinator`]) arms a waiting operation's first refresh
    /// at this time.
    pub(crate) due_at: Option<std::time::SystemTime>,
    /// The wire `ParentId` of the operation, as the service reports it.
    /// No replay path reads it; plugins see it in their operation infos.
    pub(crate) parent_id: Option<String>,
    /// When the operation started, from the wire `StartTimestamp`. `None`
    /// when the service sent none, or sent a value that does not convert.
    /// No replay path reads it.
    pub(crate) start_timestamp: Option<std::time::SystemTime>,
    /// When the operation ended, from the wire `EndTimestamp`. `None` when
    /// the service sent none, or sent a value that does not convert. No
    /// replay path reads it.
    pub(crate) end_timestamp: Option<std::time::SystemTime>,
}

#[cfg(test)]
impl CheckpointRecord {
    /// A record of `id` with `status` and every other field empty.
    pub(crate) fn with_status(id: &str, status: CheckpointStatus) -> Self {
        Self {
            id: id.to_owned(),
            status,
            result: None,
            error_type: None,
            error_message: None,
            error_data: None,
            stack_trace: None,
            attempt: 0,
            invoke_result: None,
            invoke_error_type: None,
            invoke_error_message: None,
            invoke_error_data: None,
            invoke_stack_trace: None,
            replay_children: false,
            callback_id: None,
            op_type: None,
            sub_type: None,
            op_name: None,
            due_at: None,
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        }
    }
}

/// A compact, copyable view of a checkpoint record.
///
/// Carries the fields that nearly every operation reads at the start of its
/// replay check, the status, the attempt counter, and the
/// `replay_children` marker, without cloning any of the record's owned
/// strings. Use `CheckpointLog::status_view` (or the context-level
/// `checkpoint_status_view`) instead of `CheckpointLog::get` when the
/// caller consumes only these fields.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CheckpointStatusView {
    /// The operation's status.
    pub(crate) status: CheckpointStatus,
    /// The attempt number from the backend's step details (0 if unavailable).
    pub(crate) attempt: u32,
    /// Whether the child context result was too large and must be
    /// reconstructed by re-executing the child body (`ReplayChildren` mode).
    pub(crate) replay_children: bool,
}

/// The terminal-replay projection of a checkpoint record.
///
/// Carries exactly the fields the map/parallel replay helpers consume when
/// reconstructing a terminal batch or child item from the log, the status,
/// the `replay_children` marker, and the payload/error strings, so terminal
/// replay clones at most three optional strings instead of the whole record
/// (which also carries invoke, callback, ID, and identity fields those
/// helpers never read). Built via the context-level
/// `checkpoint_terminal_replay` accessor.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TerminalReplaySnapshot {
    /// The operation's status.
    pub(crate) status: CheckpointStatus,
    /// Whether the result was too large to store and must be reconstructed
    /// by re-executing the children (`ReplayChildren` mode).
    pub(crate) replay_children: bool,
    /// The serialized result payload (for succeeded operations).
    pub(crate) result: Option<String>,
    /// Error message (for failed operations).
    pub(crate) error_message: Option<String>,
    /// Error type identifier (for failed operations).
    pub(crate) error_type: Option<String>,
    /// Opaque error payload (for failed operations), passed through
    /// verbatim so a replayed batch item carries the same wire failure
    /// record its live counterpart did.
    pub(crate) error_data: Option<String>,
    /// Recorded stack trace frames (for failed operations).
    pub(crate) stack_trace: Option<Vec<String>>,
}

/// The checkpoint log: maps positional operation IDs to stored records.
///
/// The log is populated from the backend on invocation start, then updated
/// during execution as checkpoint responses merge backend-assigned fields
/// (e.g. `callback_id`) into the live log via [`Self::insert`]. Every merged
/// response also carries the operations the service changed since the last
/// one, so an operation that an external caller or a timer completed
/// becomes visible in this invocation when the next checkpoint response
/// arrives. While an operation waits beside other SDK work, the refresh
/// scheduler (see [`crate::coordinator`]) sends checkpoints with no updates
/// to get such a response. Without one, the result becomes visible when the
/// next invocation reloads the log from the backend.
#[derive(Debug)]
pub(crate) struct CheckpointLog {
    /// Records keyed by wire operation ID for fast lookup during replay.
    /// Uses interior mutability so that checkpoint responses can merge
    /// backend-assigned fields (e.g. `callback_id`) into the live log.
    records: RwLock<HashMap<String, CheckpointRecord>>,
}

impl CheckpointLog {
    /// Creates an empty checkpoint log (first-ever invocation).
    #[cfg(test)]
    pub(crate) fn empty() -> Self {
        Self {
            records: RwLock::new(HashMap::new()),
        }
    }

    /// Creates a checkpoint log from a list of records.
    ///
    /// Records are stored keyed by their wire ID. The caller must provide
    /// the wire-ID → record mapping (the inline parser uses the `Id` field
    /// from the backend directly as the key).
    pub(crate) fn from_records(records: Vec<(String, CheckpointRecord)>) -> Self {
        Self {
            records: RwLock::new(records.into_iter().collect()),
        }
    }

    /// Looks up a stored record by wire operation ID.
    ///
    /// Returns `Some` with the frozen result for replayed operations;
    /// `None` for live (not-yet-checkpointed) operations.
    ///
    /// This deep-clones the whole record (up to seven owned strings), so no
    /// production path uses it anymore: they read through
    /// [`Self::with_record`], [`Self::status_view`], or [`Self::contains`]
    /// instead. Retained for tests, which assert on whole stored records.
    #[cfg(test)]
    pub(crate) fn get(&self, wire_id: &str) -> Option<CheckpointRecord> {
        self.with_record(wire_id, Clone::clone)
    }

    /// Reads a stored record under the lock's read guard, applying `f` to
    /// it in place.
    ///
    /// Returns `None` when no record exists for `wire_id`. This is the
    /// zero-clone primitive behind the targeted accessors: `f` borrows the
    /// record and returns only what the caller consumes, so nothing is
    /// cloned that the caller does not take. `f` must not touch the
    /// checkpoint log (the read guard is held while it runs).
    pub(crate) fn with_record<R>(
        &self,
        wire_id: &str,
        f: impl FnOnce(&CheckpointRecord) -> R,
    ) -> Option<R> {
        let guard = self
            .records
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.get(wire_id).map(f)
    }

    /// Returns a compact view (status, attempt, `replay_children`) of the
    /// stored record, cloning only the status (a payload string on
    /// `Unknown`, nothing otherwise) and none of the record's owned
    /// payload strings.
    pub(crate) fn status_view(&self, wire_id: &str) -> Option<CheckpointStatusView> {
        self.with_record(wire_id, |record| CheckpointStatusView {
            status: record.status.clone(),
            attempt: record.attempt,
            replay_children: record.replay_children,
        })
    }

    /// Returns whether a record exists for the given wire ID, without
    /// cloning anything.
    pub(crate) fn contains(&self, wire_id: &str) -> bool {
        let guard = self
            .records
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.contains_key(wire_id)
    }

    /// Applies `f` to the stored record of `wire_id` under the write guard.
    /// Does nothing when no record exists. `f` must not touch the log.
    pub(crate) fn update(&self, wire_id: &str, f: impl FnOnce(&mut CheckpointRecord)) {
        let mut guard = self
            .records
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(record) = guard.get_mut(wire_id) {
            f(record);
        }
    }

    /// Inserts or replaces a record in the log.
    ///
    /// Used to merge backend-assigned fields (e.g. `callback_id`) from
    /// checkpoint responses into the live log so that subsequent reads
    /// in the same invocation observe the updated state.
    ///
    /// Returns the status of the record it replaced, or `None` when the log
    /// held no record of `wire_id`.
    pub(crate) fn insert(
        &self,
        wire_id: String,
        record: CheckpointRecord,
    ) -> Option<CheckpointStatus> {
        let mut guard = self
            .records
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard
            .insert(wire_id, record)
            .map(|previous| previous.status)
    }

    /// Applies `f` to every record under one read guard and returns the
    /// results, in no particular order.
    ///
    /// `f` borrows each record, so no record is cloned. Plugin hooks build
    /// their operations maps with this one call per hook event, which keeps
    /// full-record clones off every path that builds such a map. `f` must
    /// not touch the checkpoint log, because the read guard is held while
    /// it runs.
    pub(crate) fn project_records<R>(
        &self,
        mut f: impl FnMut(&str, &CheckpointRecord) -> R,
    ) -> Vec<R> {
        #[cfg(test)]
        PROJECTIONS.with(|count| count.set(count.get() + 1));
        let guard = self
            .records
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.iter().map(|(id, record)| f(id, record)).collect()
    }

    /// Returns true if the log has any records at all.
    pub(crate) fn has_records(&self) -> bool {
        let guard = self
            .records
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        !guard.is_empty()
    }
}

#[cfg(test)]
thread_local! {
    /// How many times [`CheckpointLog::project_records`] ran on this
    /// thread. A `#[tokio::test]` runs every SDK task on the test's own
    /// thread, so a test reads how many operations maps its invocations
    /// built, and tests on other threads do not change the count.
    static PROJECTIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The number of [`CheckpointLog::project_records`] calls on this thread.
#[cfg(test)]
pub(crate) fn projections() -> usize {
    PROJECTIONS.with(std::cell::Cell::get)
}

/// The shared engine state carried by every `DurableContext` clone.
///
/// The `Arc<EngineState>` is what makes `DurableContext` cheap to clone and
/// share across async boundaries. The `IdCounter` uses interior mutability
/// (atomic) so minting works through a shared reference.
#[derive(Debug)]
pub(crate) struct EngineState {
    /// The ID counter for this context's namespace.
    pub(crate) id_counter: IdCounter,
    /// The checkpoint log for replay pairing.
    pub(crate) checkpoint_log: Arc<CheckpointLog>,
}

impl EngineState {
    /// Creates engine state for a root context.
    pub(crate) fn new_root(checkpoint_log: Arc<CheckpointLog>) -> Self {
        Self {
            id_counter: IdCounter::new(String::new()),
            checkpoint_log,
        }
    }

    /// Creates engine state for a child context whose prefix is the parent
    /// operation's positional ID.
    pub(crate) fn new_child(
        parent_positional_id: &str,
        checkpoint_log: Arc<CheckpointLog>,
    ) -> Self {
        Self {
            id_counter: IdCounter::child(parent_positional_id),
            checkpoint_log,
        }
    }

    /// Mints the next operation ID for this context.
    pub(crate) fn mint_id(&self) -> OperationId {
        self.id_counter.mint()
    }

    /// Determines whether the context is in replay mode for the given
    /// positional operation ID.
    ///
    /// An operation is replaying if the checkpoint log contains a terminal
    /// record for it: meaning the result was frozen in a prior invocation.
    /// Production operation paths make this check through
    /// [`crate::context::DurableContext::checkpoint_view_validated`]; this
    /// direct form is retained for engine unit tests.
    #[cfg(test)]
    pub(crate) fn is_replaying_at(&self, positional_id: &str) -> bool {
        let wire_id = compute_wire_id(positional_id);
        self.checkpoint_log
            .status_view(&wire_id)
            .is_some_and(|view| view.status.is_terminal())
    }

    /// Returns whether the context is currently in replay mode (there are
    /// checkpointed records and we have not yet passed the high-water mark).
    ///
    /// The context is replaying as long as the NEXT operation to be claimed
    /// in this namespace has a checkpoint record of ANY status: a record,
    /// terminal or still `Started`, proves a prior invocation already
    /// executed the code path leading to that claim. A `Started` composite
    /// (child context, map, or parallel parent) counts: the resumed
    /// invocation re-enters it to replay its nested operations, so the code
    /// before it is a re-run. The context transitions to live mode when the
    /// next ID to be minted has no record at all.
    pub(crate) fn is_replaying(&self) -> bool {
        if !self.checkpoint_log.has_records() {
            return false;
        }
        let next_positional = self.id_counter.peek_next();
        let next_wire = compute_wire_id(&next_positional);
        self.checkpoint_log.contains(&next_wire)
    }
}

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

    // CheckpointStatus (issue #45)

    /// `Unknown` reports terminal: a status the SDK does not recognize may
    /// be a terminal status the service added, so bookkeeping must never
    /// treat the record as re-runnable or overwrite it. (Replay paths that
    /// would interpret the record fail the execution before this answer
    /// matters: see `checkpoint_view_validated`.)
    #[test]
    fn unknown_status_is_terminal_and_keeps_raw_wire_value() {
        let unknown = CheckpointStatus::Unknown("PAUSED".to_owned());
        assert!(unknown.is_terminal());
        assert_eq!(unknown.wire_str(), "PAUSED");
    }

    #[test]
    fn known_status_wire_spellings_are_upper_case() {
        assert_eq!(CheckpointStatus::TimedOut.wire_str(), "TIMED_OUT");
        assert_eq!(CheckpointStatus::Started.wire_str(), "STARTED");
        assert!(!CheckpointStatus::Started.is_terminal());
        assert!(CheckpointStatus::TimedOut.is_terminal());
    }

    /// `insert` returns `None` for a new record, and the replaced record's
    /// status for a replacement.
    #[test]
    fn insert_returns_previous_status() {
        let log = CheckpointLog::empty();
        assert_eq!(
            log.insert(
                "op".to_owned(),
                CheckpointRecord::with_status("op", CheckpointStatus::Started),
            ),
            None
        );
        assert_eq!(
            log.insert(
                "op".to_owned(),
                CheckpointRecord::with_status("op", CheckpointStatus::Succeeded),
            ),
            Some(CheckpointStatus::Started)
        );
    }

    // Counter basics

    #[test]
    fn counter_starts_at_one() {
        let counter = IdCounter::new(String::new());
        let id = counter.mint();
        assert_eq!(id.positional(), "1");
    }

    #[test]
    fn counter_increments_per_call() {
        let counter = IdCounter::new(String::new());
        let id1 = counter.mint();
        let id2 = counter.mint();
        let id3 = counter.mint();
        assert_eq!(id1.positional(), "1");
        assert_eq!(id2.positional(), "2");
        assert_eq!(id3.positional(), "3");
    }

    #[test]
    fn counter_with_prefix() {
        let counter = IdCounter::new("2".to_owned());
        let id1 = counter.mint();
        let id2 = counter.mint();
        assert_eq!(id1.positional(), "2-1");
        assert_eq!(id2.positional(), "2-2");
    }

    // Child prefix chaining produces full positional paths

    #[test]
    fn child_prefix_chaining() {
        // Root mints "1", "2"; child of "2" mints "2-1", "2-2";
        // grandchild of "2-1" mints "2-1-1", "2-1-2".
        let root = IdCounter::new(String::new());
        let _id1 = root.mint(); // "1"
        let id2 = root.mint(); // "2"
        assert_eq!(id2.positional(), "2");

        let child = IdCounter::child(id2.positional());
        let child_id1 = child.mint();
        let child_id2 = child.mint();
        assert_eq!(child_id1.positional(), "2-1");
        assert_eq!(child_id2.positional(), "2-2");

        let grandchild = IdCounter::child(child_id1.positional());
        let gc_id1 = grandchild.mint();
        let gc_id2 = grandchild.mint();
        assert_eq!(gc_id1.positional(), "2-1-1");
        assert_eq!(gc_id2.positional(), "2-1-2");
    }

    // SHA-256 wire ID: known-answer tests

    #[test]
    fn wire_id_known_answer_simple() {
        // SHA-256 of "1" (the string, UTF-8 bytes)
        // Independently computed: echo -n "1" | sha256sum
        // = 6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b
        let id = compute_wire_id("1");
        assert_eq!(
            id,
            "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b"
        );
    }

    #[test]
    fn wire_id_known_answer_prefixed() {
        // SHA-256 of "2-1" (positional string for first child of op 2)
        // echo -n "2-1" | sha256sum
        // = e2433ac3278279ac90b51abed3d4dd9057d9e1f66541ad9cdfd13762a30e5a43
        let id = compute_wire_id("2-1");
        assert_eq!(
            id,
            "e2433ac3278279ac90b51abed3d4dd9057d9e1f66541ad9cdfd13762a30e5a43"
        );
    }

    #[test]
    fn wire_id_known_answer_deep_path() {
        // SHA-256 of "2-1-3"
        // echo -n "2-1-3" | sha256sum
        // = c00876d4d917a061ad5a377270e059994251eea9818733e6abfef69c6080625b
        let id = compute_wire_id("2-1-3");
        assert_eq!(
            id,
            "c00876d4d917a061ad5a377270e059994251eea9818733e6abfef69c6080625b"
        );
    }

    #[test]
    fn wire_id_length_and_charset() {
        let counter = IdCounter::new(String::new());
        for _ in 0..20 {
            let id = counter.mint();
            let wire = id.wire();
            // Must be exactly 64 hex characters.
            assert_eq!(wire.len(), 64);
            assert!(
                wire.chars().all(|c| c.is_ascii_hexdigit()),
                "wire ID contains non-hex character: {wire}"
            );
            // All lowercase hex per SHA-256 convention.
            assert!(
                wire.chars().all(|c| !c.is_ascii_uppercase()),
                "wire ID should be lowercase: {wire}"
            );
        }
    }

    #[test]
    fn wire_id_at_mint_matches_standalone() {
        // Verify the wire ID carried in OperationId matches compute_wire_id.
        let counter = IdCounter::new("prefix".to_owned());
        let id = counter.mint();
        assert_eq!(id.wire(), compute_wire_id(id.positional()));
    }

    // IDs minted at call site (creation order, not await order)

    #[tokio::test]
    async fn ids_minted_at_creation_not_await() {
        // The defining test: creating two builders claims IDs in CREATION
        // order. Awaiting in reverse order does not change the IDs.
        let counter = Arc::new(IdCounter::new(String::new()));

        // Simulate two builder creations by minting synchronously.
        let id_first = counter.mint();
        let id_second = counter.mint();

        // Assert creation order is preserved regardless of "await" order.
        assert_eq!(id_first.positional(), "1");
        assert_eq!(id_second.positional(), "2");
    }

    #[tokio::test]
    async fn ids_stable_under_interleaved_join() {
        // join! over builder creations: IDs are trivially ordered because
        // mint is synchronous and executes within the owning task.
        let counter = Arc::new(IdCounter::new(String::new()));

        let c1 = Arc::clone(&counter);
        let c2 = Arc::clone(&counter);

        // tokio::join! polls futures but mint happens before any poll.
        let (id_a, id_b) = tokio::join!(async move { c1.mint() }, async move { c2.mint() },);

        // Both mints happened in the single task running this test (tokio
        // join! does not spawn). The first branch mints first.
        assert_eq!(id_a.positional(), "1");
        assert_eq!(id_b.positional(), "2");
    }

    // Checkpoint-log pairing

    #[test]
    fn checkpoint_log_returns_stored_result() {
        let log = CheckpointLog::from_records(vec![(
            "1".to_owned(),
            CheckpointRecord {
                id: "wire-1".to_owned(),
                status: CheckpointStatus::Succeeded,
                result: Some(r#""hello""#.to_owned()),
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )]);

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

    #[test]
    fn checkpoint_log_miss_for_unknown_id() {
        let log = CheckpointLog::from_records(vec![(
            "1".to_owned(),
            CheckpointRecord {
                id: "wire-1".to_owned(),
                status: CheckpointStatus::Succeeded,
                result: Some(r"42".to_owned()),
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )]);

        assert!(log.get("2").is_none());
        assert!(log.get("unknown").is_none());
    }

    #[test]
    fn checkpoint_log_empty_always_miss() {
        let log = CheckpointLog::empty();
        assert!(log.get("1").is_none());
        assert!(log.get("anything").is_none());
    }

    // Targeted accessors (clone-free lookups)

    /// Builds a record with every string field populated, so the tests can
    /// assert the targeted accessors surface the right values without
    /// needing the full-record clone that `get` performs.
    fn full_record() -> CheckpointRecord {
        CheckpointRecord {
            id: "wire-1".to_owned(),
            status: CheckpointStatus::Failed,
            result: Some(r#""payload""#.to_owned()),
            error_type: Some("SomeError".to_owned()),
            error_message: Some("it broke".to_owned()),
            error_data: None,
            stack_trace: None,
            attempt: 3,
            invoke_result: Some(r#""invoke-payload""#.to_owned()),
            invoke_error_type: Some("InvokeError".to_owned()),
            invoke_error_message: Some("invoke broke".to_owned()),
            invoke_error_data: None,
            invoke_stack_trace: None,
            replay_children: true,
            callback_id: Some("cb-123".to_owned()),
            op_type: Some("Step".to_owned()),
            sub_type: Some("Step".to_owned()),
            due_at: None,
            op_name: Some("my-step".to_owned()),
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        }
    }

    #[test]
    fn status_view_carries_status_attempt_and_replay_children() {
        let log = CheckpointLog::from_records(vec![("1".to_owned(), full_record())]);

        let view = log.status_view("1");
        assert!(view.is_some());
        let view = view.unwrap();
        assert_eq!(view.status, CheckpointStatus::Failed);
        assert_eq!(view.attempt, 3);
        assert!(view.replay_children);

        // The view clones cheaply: only an `Unknown` status carries an
        // owned string.
        let clone = view.clone();
        assert_eq!(clone, view);

        assert!(log.status_view("missing").is_none());
    }

    #[test]
    fn contains_reports_existence_without_cloning() {
        let log = CheckpointLog::from_records(vec![("1".to_owned(), full_record())]);
        assert!(log.contains("1"));
        assert!(!log.contains("2"));
        assert!(!CheckpointLog::empty().contains("1"));
    }

    #[test]
    fn with_record_projects_only_what_the_closure_takes() {
        let log = CheckpointLog::from_records(vec![("1".to_owned(), full_record())]);

        // Project a single owned field.
        let callback_id = log.with_record("1", |r| r.callback_id.clone()).flatten();
        assert_eq!(callback_id.as_deref(), Some("cb-123"));

        // Project a borrowed comparison: nothing cloned at all.
        let is_failed = log.with_record("1", |r| r.status == CheckpointStatus::Failed);
        assert_eq!(is_failed, Some(true));

        // Miss: the closure never runs.
        let ran = log.with_record("missing", |_| true);
        assert!(ran.is_none());
    }

    #[test]
    fn get_still_returns_the_full_record() {
        let log = CheckpointLog::from_records(vec![("1".to_owned(), full_record())]);
        let record = log.get("1");
        assert!(record.is_some());
        let record = record.unwrap();
        assert_eq!(record.result.as_deref(), Some(r#""payload""#));
        assert_eq!(record.invoke_error_message.as_deref(), Some("invoke broke"));
        assert_eq!(record.op_name.as_deref(), Some("my-step"));
    }

    // Replay-mode detection

    #[test]
    fn replay_mode_with_checkpointed_operations() {
        // Log has records keyed by wire IDs (hashes) for positions 1 and 2.
        let wire1 = compute_wire_id("1");
        let wire2 = compute_wire_id("2");
        let log = Arc::new(CheckpointLog::from_records(vec![
            (
                wire1.clone(),
                CheckpointRecord {
                    id: wire1,
                    status: CheckpointStatus::Succeeded,
                    result: Some("a".to_owned()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
            (
                wire2.clone(),
                CheckpointRecord {
                    id: wire2,
                    status: CheckpointStatus::Succeeded,
                    result: Some("b".to_owned()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
        ]));

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

        // Before any mint, next is "1" which has a record → replaying.
        assert!(engine.is_replaying());

        // Mint "1" → the record for "1" is terminal → replaying at "1".
        let id1 = engine.mint_id();
        assert_eq!(id1.positional(), "1");
        assert!(engine.is_replaying_at(id1.positional()));

        // Next would be "2" → still replaying.
        assert!(engine.is_replaying());

        // Mint "2" → replaying at "2".
        let id2 = engine.mint_id();
        assert_eq!(id2.positional(), "2");
        assert!(engine.is_replaying_at(id2.positional()));

        // Next would be "3" → no record → NOT replaying (live mode).
        assert!(!engine.is_replaying());
    }

    #[test]
    fn replay_mode_empty_log_never_replaying() {
        let log = Arc::new(CheckpointLog::empty());
        let engine = EngineState::new_root(log);

        assert!(!engine.is_replaying());
        let id = engine.mint_id();
        assert!(!engine.is_replaying_at(id.positional()));
    }

    #[test]
    fn replay_mode_non_terminal_record_still_replaying() {
        // A "Started" status is non-terminal: the operation re-executes.
        // But its record proves a prior invocation already claimed it, so
        // the code path leading to it is a re-run: the context reports
        // replaying until the claim (a started child context, map, or
        // parallel parent is re-entered to replay its nested operations).
        let wire1 = compute_wire_id("1");
        let log = Arc::new(CheckpointLog::from_records(vec![(
            wire1.clone(),
            CheckpointRecord {
                id: wire1,
                status: CheckpointStatus::Started,
                result: None,
                error_type: None,
                error_message: None,
                error_data: None,
                stack_trace: None,
                attempt: 0,
                invoke_result: None,
                invoke_error_type: None,
                invoke_error_message: None,
                invoke_error_data: None,
                invoke_stack_trace: None,
                replay_children: false,
                callback_id: None,
                op_type: None,
                sub_type: None,
                due_at: None,
                op_name: None,
                parent_id: None,
                start_timestamp: None,
                end_timestamp: None,
            },
        )]));

        let engine = EngineState::new_root(log);
        // Non-terminal record: STILL replaying: a prior invocation reached
        // this claim, so the code before it re-ran.
        assert!(engine.is_replaying());
        // The record is not terminal, so the operation itself re-executes.
        assert!(!engine.is_replaying_at("1"));
        // Past the started record: live.
        let _ = engine.mint_id();
        assert!(!engine.is_replaying());
    }

    #[test]
    fn replay_mode_child_context() {
        // Child context "2" has operations "2-1" and "2-2" checkpointed.
        let wire_2_1 = compute_wire_id("2-1");
        let wire_2_2 = compute_wire_id("2-2");
        let log = Arc::new(CheckpointLog::from_records(vec![
            (
                wire_2_1.clone(),
                CheckpointRecord {
                    id: wire_2_1,
                    status: CheckpointStatus::Succeeded,
                    result: Some("x".to_owned()),
                    error_type: None,
                    error_message: None,
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
            (
                wire_2_2.clone(),
                CheckpointRecord {
                    id: wire_2_2,
                    status: CheckpointStatus::Failed,
                    result: None,
                    error_type: Some("StepError".to_owned()),
                    error_message: Some("oops".to_owned()),
                    error_data: None,
                    stack_trace: None,
                    attempt: 0,
                    invoke_result: None,
                    invoke_error_type: None,
                    invoke_error_message: None,
                    invoke_error_data: None,
                    invoke_stack_trace: None,
                    replay_children: false,
                    callback_id: None,
                    op_type: None,
                    sub_type: None,
                    due_at: None,
                    op_name: None,
                    parent_id: None,
                    start_timestamp: None,
                    end_timestamp: None,
                },
            ),
        ]));

        let engine = EngineState::new_child("2", log);

        // "2-1" is next → replaying.
        assert!(engine.is_replaying());

        let id1 = engine.mint_id();
        assert_eq!(id1.positional(), "2-1");
        assert!(engine.is_replaying_at(id1.positional()));

        // "2-2" next → still replaying (Failed is terminal).
        assert!(engine.is_replaying());

        let id2 = engine.mint_id();
        assert_eq!(id2.positional(), "2-2");
        assert!(engine.is_replaying_at(id2.positional()));

        // "2-3" next → no record → live.
        assert!(!engine.is_replaying());
    }
}