aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! The start step: the synchronous first phase of an operation.
//!
//! The JS SDK begins each non-combinator operation inside the call that
//! creates it. Its checkpoint manager queues an update synchronously, and
//! sends the queue only after the current synchronous code has returned.
//! [`start_step`] is the Rust form of that phase. It is a synchronous
//! function of the operation's execution state, so nothing is awaited
//! before it returns. In order, it:
//!
//! 1. returns [`StartStep::Refused`] when the context's admission refuses
//!    the operation, and queues nothing;
//! 2. runs the task-ownership check;
//! 3. runs the replay identity check and reads the operation's record;
//! 4. returns [`StartStep::Refused`] when [`rebuild_holds`] holds the
//!    operation in a rebuilt body, and queues nothing;
//! 5. when the cycle needs a `START` (no record, or a record that begins a
//!    new attempt), builds it and fixes its position in the write order;
//! 6. for an operation whose JS order is "queue `START`, then hook", fires
//!    `on_operation_start` and then releases the `START`;
//! 7. for a record that resumes work without a new `START`, fires its
//!    replay start hook.
//!
//! The order of the `START` write and `on_operation_start` follows JS for
//! each kind ([`StartOrder`]):
//!
//! - A step under `AtLeastOncePerRetry` and `wait_for_condition` queue
//!   `START`, fire `on_operation_start`, and do not wait for the response.
//!   The `START` is reserved (see
//!   [`ReservedWrite`](crate::context::ReservedWrite)) until the hook
//!   dispatch returns, so the hook returns before the request is sent on
//!   any runtime, as JS's `setImmediate` send runs after the hook.
//! - A step under `AtMostOncePerRetry`, a wait and a callback queue
//!   `START` here, and the rest of the operation awaits the response
//!   before it fires `on_operation_start`, as JS awaits the `START`
//!   promise before the hook. A callback's `START` is urgent: it flushes
//!   the coalescing buffer at once, because the response assigns the
//!   callback ID.
//!
//! `on_attempt_start` is not part of the start step. The rest of the
//! operation fires it before the body, as JS fires
//! `onOperationAttemptStart` after `onOperationStart`.

use aws_sdk_lambda::types::OperationUpdate;

use crate::context::{DurableContext, SubmittedWrite};
use crate::engine::{CheckpointStatus, CheckpointStatusView, OperationId};
use crate::error::OperationError;
use crate::plugin::InvocationPlugins;

/// When an operation fires `on_operation_start` relative to its `START`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StartOrder {
    /// Queue `START`, fire the hook, then release `START`. The rest of the
    /// operation does not wait for the response before its body.
    QueueThenHook,
    /// Queue `START`. The rest of the operation awaits the response, then
    /// fires the hook.
    AwaitResponse,
    /// As [`Self::AwaitResponse`], with an urgent `START` that flushes
    /// the coalescing buffer at once.
    AwaitUrgentResponse,
}

/// What the start step does for an operation that has a record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Cycle {
    /// The record begins a new attempt: queue its `START`. `is_replay` is
    /// the flag a [`StartOrder::QueueThenHook`] hook sees.
    Start { is_replay: bool },
    /// The record resumes work without a new `START`: fire the replay
    /// start hook.
    Resume,
    /// The record queues no `START` and fires no start hook: a terminal
    /// or waiting record, which the rest of the operation handles.
    Record,
}

/// The identity and start order of one operation.
pub(crate) struct StartSpec<'a> {
    pub(crate) op_id: &'a OperationId,
    /// The record type the replay identity check expects.
    pub(crate) operation_type: &'static str,
    pub(crate) sub_type: &'a str,
    pub(crate) name: Option<&'a str>,
    pub(crate) order: StartOrder,
}

/// The outcome of [`start_step`].
pub(crate) enum StartStep {
    /// Admission refused the operation, or [`rebuild_holds`] held it in a
    /// rebuilt body. Nothing was queued, and the operation's future never
    /// resolves.
    Refused,
    /// The operation has a record, and this cycle queues no `START`.
    Recorded(CheckpointStatusView),
    /// The `START` write of a first or later attempt, already in the write
    /// order. For [`StartOrder::QueueThenHook`] it was released after the
    /// hook dispatch returned.
    Queued(SubmittedWrite),
}

/// Whether an operation in a rebuilding context (see
/// [`DurableContext::new_child_rebuilding`]) never resolves. It does when
/// it has no record, and when replay cannot return its record without
/// running it again: a callback's `READY` record, an invoke's `STARTED`,
/// `PENDING` or `READY` record, and any other operation's record that is
/// neither `SUCCEEDED` nor `FAILED`. A callback with any other record
/// still returns its callback, so a rebuilt body that returns the
/// callback ID returns. An unrecognized status never gets here:
/// `checkpoint_view_validated` fails the execution first.
pub(crate) fn rebuild_holds(
    ctx: &DurableContext,
    operation_type: &str,
    status: Option<&CheckpointStatus>,
) -> bool {
    if !ctx.is_rebuilding() {
        return false;
    }
    let Some(status) = status else {
        return true;
    };
    match operation_type {
        "Callback" => *status == CheckpointStatus::Ready,
        "ChainedInvoke" => matches!(
            status,
            CheckpointStatus::Started | CheckpointStatus::Pending | CheckpointStatus::Ready
        ),
        _ => !matches!(
            status,
            CheckpointStatus::Succeeded | CheckpointStatus::Failed
        ),
    }
}

/// Runs the start step of the operation `spec` on `ctx` (see the module
/// documentation).
///
/// `classify` decides what a record means for this cycle; without a
/// record the cycle starts a first attempt. Neither applies when
/// [`rebuild_holds`] holds the operation. `start_update` builds the
/// `START`. `start_hook` fires `on_operation_start` with the given replay
/// flag. The start step calls it for a [`StartOrder::QueueThenHook`]
/// `START` and for a [`Cycle::Resume`] record, and only when plugins are
/// registered.
///
/// # Errors
///
/// A task-ownership error, or a replay identity error. Nothing is queued
/// in either case.
pub(crate) fn start_step(
    ctx: &DurableContext,
    spec: &StartSpec<'_>,
    classify: impl FnOnce(&CheckpointStatusView) -> Cycle,
    start_update: impl FnOnce() -> OperationUpdate,
    start_hook: impl FnOnce(&InvocationPlugins, bool),
) -> Result<StartStep, OperationError> {
    if !ctx.admission().admits(ctx.owners()) {
        return Ok(StartStep::Refused);
    }
    ctx.enforce_task_ownership()?;
    let view = ctx.checkpoint_view_validated(
        spec.op_id.positional(),
        spec.op_id.wire(),
        spec.operation_type,
        Some(spec.sub_type),
        spec.name,
    )?;
    if rebuild_holds(
        ctx,
        spec.operation_type,
        view.as_ref().map(|view| &view.status),
    ) {
        return Ok(StartStep::Refused);
    }
    let is_replay = match view {
        None => false,
        Some(view) => match classify(&view) {
            Cycle::Start { is_replay } => is_replay,
            Cycle::Resume => {
                if let Some(plugins) = ctx.plugins() {
                    start_hook(plugins, true);
                }
                return Ok(StartStep::Recorded(view));
            }
            Cycle::Record => return Ok(StartStep::Recorded(view)),
        },
    };
    let update = start_update();
    let write = match spec.order {
        StartOrder::QueueThenHook => {
            let reserved = ctx.reserve_checkpoint_updates(vec![update]);
            if let Some(plugins) = ctx.plugins() {
                start_hook(plugins, is_replay);
            }
            reserved.release()
        }
        StartOrder::AwaitResponse => ctx.submit_checkpoint_updates(vec![update]),
        StartOrder::AwaitUrgentResponse => ctx.submit_checkpoint_updates_urgent(vec![update]),
    };
    Ok(StartStep::Queued(write))
}

#[cfg(test)]
#[expect(clippy::panic, clippy::indexing_slicing)] // reason: test assertions
mod tests {
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::{Arc, Mutex};
    use std::time::Duration;

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

    use super::{Cycle, StartOrder, StartSpec, StartStep, start_step};
    use crate::client::{
        CheckpointOutput, ExecutionClient, ExecutionClientError, GetStateOutput,
        InMemoryExecutionClient,
    };
    use crate::context::DurableContext;
    use crate::engine::{CheckpointLog, CheckpointRecord, CheckpointStatus, OperationId};
    use crate::error::OperationError;
    use crate::plugin::test_support::OpHooks;
    use crate::step::{StepSemantics, step_cycle};

    /// The record of the first operation of the root, a step `a`.
    fn step_record(
        status: CheckpointStatus,
        attempt: u32,
        op_type: &str,
    ) -> (String, CheckpointRecord) {
        let id = crate::engine::compute_wire_id_public("1");
        let record = CheckpointRecord {
            id: id.clone(),
            status,
            result: None,
            error_type: None,
            error_message: None,
            error_data: None,
            stack_trace: None,
            attempt,
            invoke_result: None,
            invoke_error_type: None,
            invoke_error_message: None,
            invoke_error_data: None,
            invoke_stack_trace: None,
            replay_children: false,
            callback_id: None,
            op_type: Some(op_type.to_owned()),
            sub_type: Some("Step".to_owned()),
            due_at: None,
            op_name: Some("a".to_owned()),
            parent_id: None,
            start_timestamp: None,
            end_timestamp: None,
        };
        (id, record)
    }

    /// A root context over `records` and `client`, with the coalescer
    /// `window` and the plugin `hooks`.
    fn context(
        records: Vec<(String, CheckpointRecord)>,
        client: Arc<dyn ExecutionClient>,
        window: Duration,
        hooks: Option<&OpHooks>,
    ) -> DurableContext {
        DurableContext::new_root_with_client_and_defaults(
            "arn:test".to_owned(),
            lambda_runtime::Context::default(),
            Arc::new(CheckpointLog::from_records(records)),
            client,
            "token-0".to_owned(),
            window,
            0,
            hooks.map(OpHooks::plugins),
        )
    }

    fn in_memory() -> Arc<InMemoryExecutionClient> {
        Arc::new(InMemoryExecutionClient::new(Vec::new()))
    }

    /// In a rebuilding context, `rebuild_holds` holds every operation
    /// without a record, and every record except those that replay returns
    /// without running anything: `SUCCEEDED` and `FAILED` for every
    /// operation, also `TIMED_OUT`, `STOPPED` and `CANCELLED` for a chained
    /// invoke, and every status but `READY` for a callback. Outside a
    /// rebuilding context it holds nothing.
    #[test]
    fn rebuild_holds_matches_rebuilt_body_status_matrix() {
        use CheckpointStatus::{
            Cancelled, Failed, Pending, Ready, Started, Stopped, Succeeded, TimedOut,
        };
        let root = DurableContext::test_context();
        let rebuilding = root.new_child_rebuilding("1", None, true);
        let statuses = [
            Started, Pending, Ready, Succeeded, Failed, Cancelled, TimedOut, Stopped,
        ];
        let rows: [(&str, Vec<CheckpointStatus>); 5] = [
            ("Step", vec![Succeeded, Failed]),
            ("Wait", vec![Succeeded, Failed]),
            ("Context", vec![Succeeded, Failed]),
            (
                "ChainedInvoke",
                vec![Succeeded, Failed, Cancelled, TimedOut, Stopped],
            ),
            (
                "Callback",
                vec![
                    Started, Pending, Succeeded, Failed, Cancelled, TimedOut, Stopped,
                ],
            ),
        ];
        for (operation_type, returns) in &rows {
            assert!(
                super::rebuild_holds(&rebuilding, operation_type, None),
                "{operation_type} without a record"
            );
            assert!(!super::rebuild_holds(&root, operation_type, None));
            for status in &statuses {
                assert_eq!(
                    super::rebuild_holds(&rebuilding, operation_type, Some(status)),
                    !returns.contains(status),
                    "{operation_type} {status:?}"
                );
                assert!(!super::rebuild_holds(&root, operation_type, Some(status)));
            }
        }
    }

    fn start_update(op_id: &OperationId, r#type: OperationType, sub_type: &str) -> OperationUpdate {
        OperationUpdate::builder()
            .id(op_id.wire())
            .r#type(r#type)
            .sub_type(sub_type)
            .name("a")
            .action(OperationAction::Start)
            .build()
            .expect("all required OperationUpdate fields set")
    }

    /// Runs the start step of a step `a`, claimed on `ctx`, under
    /// `semantics`, as the step operation does.
    fn step_start(
        ctx: &DurableContext,
        semantics: StepSemantics,
    ) -> Result<StartStep, OperationError> {
        let op_id = ctx.mint_id();
        let order = match semantics {
            StepSemantics::AtLeastOncePerRetry => StartOrder::QueueThenHook,
            StepSemantics::AtMostOncePerRetry => StartOrder::AwaitResponse,
        };
        start_step(
            ctx,
            &StartSpec {
                op_id: &op_id,
                operation_type: "Step",
                sub_type: "Step",
                name: Some("a"),
                order,
            },
            |view| step_cycle(semantics, view),
            || start_update(&op_id, OperationType::Step, "Step"),
            |plugins, is_replay| {
                let info = crate::plugin::OperationInfo::for_operation(
                    ctx,
                    op_id.wire(),
                    crate::OperationKind::Step,
                    "Step",
                    Some("a"),
                )
                .with_status(crate::OperationStatus::Started)
                .with_replay(is_replay);
                crate::plugin::operation_started(plugins, &info);
            },
        )
    }

    /// Runs the start step of a wait or a callback `a` with no record.
    fn response_then_hook_start(
        ctx: &DurableContext,
        operation_type: &'static str,
        r#type: OperationType,
        order: StartOrder,
    ) -> StartStep {
        let op_id = ctx.mint_id();
        start_step(
            ctx,
            &StartSpec {
                op_id: &op_id,
                operation_type,
                sub_type: operation_type,
                name: Some("a"),
                order,
            },
            |_| Cycle::Record,
            || start_update(&op_id, r#type, operation_type),
            |_, _| unreachable!("no record resumes, and the hook follows the response"),
        )
        .expect("the start step succeeds")
    }

    /// The `(hook, replay)` of every start hook `hooks` recorded.
    fn starts(hooks: &OpHooks) -> Vec<bool> {
        hooks
            .records()
            .iter()
            .filter(|r| r.hook == "start")
            .map(|r| r.replay)
            .collect()
    }

    #[tokio::test]
    async fn start_step_queues_start_before_returning() {
        let client = in_memory();
        let ctx = context(Vec::new(), client.clone(), Duration::ZERO, None);
        let started = step_start(&ctx, StepSemantics::AtLeastOncePerRetry).expect("no error");
        assert!(matches!(started, StartStep::Queued(_)));
        assert_eq!(
            ctx.queued_update_ids(),
            [crate::engine::compute_wire_id_public("1")],
            "START is queued before anything is polled"
        );
        assert!(client.recorded_updates().is_empty(), "nothing is sent yet");
        let StartStep::Queued(write) = started else {
            unreachable!("checked above")
        };
        write.await.expect("START is written");
        assert_eq!(client.recorded_updates().len(), 1);
    }

    #[tokio::test]
    async fn start_step_returns_record_without_queuing() {
        let ctx = context(
            vec![step_record(CheckpointStatus::Started, 0, "Step")],
            in_memory(),
            Duration::ZERO,
            None,
        );
        let started = step_start(&ctx, StepSemantics::AtMostOncePerRetry).expect("no error");
        let StartStep::Recorded(view) = started else {
            panic!("a STARTED record queues no START");
        };
        assert_eq!(view.status, CheckpointStatus::Started);
        assert_eq!(ctx.queued_update_ids(), Vec::<String>::new());
    }

    #[tokio::test]
    async fn start_step_refused_by_admission_queues_nothing() {
        let client = in_memory();
        let root = context(Vec::new(), client.clone(), Duration::ZERO, None);
        let child = root.new_child("1", None);
        root.admission()
            .abandon([crate::engine::compute_wire_id_public("1").as_str()]);
        let started = step_start(&child, StepSemantics::AtLeastOncePerRetry).expect("no error");
        assert!(matches!(started, StartStep::Refused));
        assert_eq!(child.queued_update_ids(), Vec::<String>::new());

        // The operation's future never resolves, and writes nothing.
        let op_id = child.mint_id();
        let step = crate::step::StepExecution {
            ctx: child.clone(),
            op_id,
            name: Some("b".to_owned()),
            retry_strategy: None,
            serdes: crate::JsonSerdes,
            semantics: StepSemantics::AtLeastOncePerRetry,
            sub_type: crate::OperationSubType::STEP,
            plugin_name: None,
            closure: |_| async { Ok(1_u32) },
            _marker: std::marker::PhantomData,
        };
        assert!(
            tokio::time::timeout(Duration::from_millis(50), step.execute())
                .await
                .is_err(),
            "a refused operation never resolves"
        );
        assert_eq!(client.recorded_updates(), Vec::new());
    }

    #[tokio::test]
    async fn start_step_fires_live_hook_only_for_queue_then_hook() {
        let hooks = OpHooks::default();
        let ctx = context(Vec::new(), in_memory(), Duration::ZERO, Some(&hooks));
        let started = step_start(&ctx, StepSemantics::AtLeastOncePerRetry).expect("no error");
        assert!(matches!(started, StartStep::Queued(_)));
        assert_eq!(
            starts(&hooks),
            [false],
            "a default step fires the live hook"
        );

        let hooks = OpHooks::default();
        let ctx = context(Vec::new(), in_memory(), Duration::ZERO, Some(&hooks));
        let started =
            response_then_hook_start(&ctx, "Wait", OperationType::Wait, StartOrder::AwaitResponse);
        assert!(matches!(started, StartStep::Queued(_)));
        assert!(
            starts(&hooks).is_empty(),
            "a wait fires nothing in the start step"
        );
    }

    #[tokio::test]
    async fn start_step_fires_replay_hook_for_started_record() {
        let hooks = OpHooks::default();
        let ctx = context(
            vec![step_record(CheckpointStatus::Started, 0, "Step")],
            in_memory(),
            Duration::ZERO,
            Some(&hooks),
        );
        let started = step_start(&ctx, StepSemantics::AtLeastOncePerRetry).expect("no error");
        assert!(matches!(started, StartStep::Recorded(_)));
        assert_eq!(
            starts(&hooks),
            [true],
            "the replay hook fired before the return"
        );
        assert_eq!(ctx.queued_update_ids(), Vec::<String>::new());
    }

    #[tokio::test]
    async fn start_step_queues_callback_start_urgently_before_returning() {
        let client = in_memory();
        let ctx = context(Vec::new(), client.clone(), Duration::from_hours(1), None);
        let started = response_then_hook_start(
            &ctx,
            "Callback",
            OperationType::Callback,
            StartOrder::AwaitUrgentResponse,
        );
        let StartStep::Queued(write) = started else {
            panic!("a callback without a record queues START");
        };
        assert_eq!(
            ctx.queued_update_ids(),
            [crate::engine::compute_wire_id_public("1")],
            "START joined the coalescer"
        );
        tokio::task::yield_now().await;
        assert_eq!(
            client.recorded_updates().len(),
            1,
            "the urgent flush reached the client without the delay"
        );
        write.await.expect("START is written");
    }

    #[tokio::test]
    async fn start_step_returns_replay_identity_error_without_queuing() {
        let ctx = context(
            vec![step_record(CheckpointStatus::Started, 0, "Wait")],
            in_memory(),
            Duration::ZERO,
            None,
        );
        let Err(err) = step_start(&ctx, StepSemantics::AtLeastOncePerRetry) else {
            panic!("a record of another type fails the replay identity check");
        };
        assert!(err.to_string().contains("non_deterministic"), "{err}");
        assert_eq!(ctx.queued_update_ids(), Vec::<String>::new());
    }

    #[tokio::test]
    async fn start_step_queues_start_for_new_attempt_states() {
        for status in [
            CheckpointStatus::Ready,
            CheckpointStatus::Cancelled,
            CheckpointStatus::TimedOut,
            CheckpointStatus::Stopped,
        ] {
            let hooks = OpHooks::default();
            let client = in_memory();
            let ctx = context(
                vec![step_record(status.clone(), 1, "Step")],
                client.clone(),
                Duration::ZERO,
                Some(&hooks),
            );
            let started = step_start(&ctx, StepSemantics::AtLeastOncePerRetry).expect("no error");
            assert_eq!(
                starts(&hooks),
                [true],
                "{status:?}: the retry's hook is a replay, fired before the return"
            );
            assert_eq!(ctx.queued_update_ids().len(), 1, "{status:?}");
            let StartStep::Queued(write) = started else {
                panic!("{status:?} queues START");
            };
            write.await.expect("START is written");
            let updates = client.recorded_updates();
            assert_eq!(updates.len(), 1, "{status:?}");
            assert_eq!(updates[0].action(), &OperationAction::Start, "{status:?}");
        }
        let hooks = OpHooks::default();
        let ctx = context(
            vec![step_record(CheckpointStatus::Started, 1, "Step")],
            in_memory(),
            Duration::ZERO,
            Some(&hooks),
        );
        let started = step_start(&ctx, StepSemantics::AtLeastOncePerRetry).expect("no error");
        assert!(matches!(started, StartStep::Recorded(_)));
        assert_eq!(ctx.queued_update_ids(), Vec::<String>::new());
    }

    /// A client that logs `response <name>` for each `START` when its
    /// checkpoint future completes, after one yield.
    #[derive(Default)]
    struct LoggingClient(Arc<Mutex<Vec<String>>>);

    impl ExecutionClient for LoggingClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            let starts: Vec<String> = updates
                .iter()
                .filter(|u| u.action() == &OperationAction::Start)
                .map(|u| u.name().unwrap_or("-").to_owned())
                .collect();
            let log = Arc::clone(&self.0);
            Box::pin(async move {
                tokio::task::yield_now().await;
                for name in starts {
                    log.lock().unwrap().push(format!("response {name}"));
                }
                Ok(CheckpointOutput::new(
                    Some("t".to_owned()),
                    Vec::new(),
                    None,
                ))
            })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(GetStateOutput::new(Vec::new(), None)) })
        }
    }

    #[tokio::test]
    async fn at_most_once_retry_start_hook_fires_after_start_response() {
        let client = Arc::new(LoggingClient::default());
        let log = Arc::clone(&client.0);
        let hooks = OpHooks::probing(move || {
            log.lock()
                .unwrap()
                .iter()
                .any(|e| e == "response a")
                .to_string()
        });
        let ctx = context(
            vec![step_record(CheckpointStatus::Ready, 1, "Step")],
            client,
            Duration::ZERO,
            Some(&hooks),
        );
        let op_id = ctx.mint_id();
        let value = crate::step::StepExecution {
            ctx: ctx.clone(),
            op_id,
            name: Some("a".to_owned()),
            retry_strategy: None,
            serdes: crate::JsonSerdes,
            semantics: StepSemantics::AtMostOncePerRetry,
            sub_type: crate::OperationSubType::STEP,
            plugin_name: None,
            closure: |_| async { Ok(1_u32) },
            _marker: std::marker::PhantomData,
        }
        .execute()
        .await
        .expect("the step succeeds");
        assert_eq!(value, 1);
        let start = hooks
            .records()
            .into_iter()
            .find(|r| r.hook == "start")
            .expect("the start hook fired");
        assert!(start.replay, "the retry's start hook is a replay");
        assert_eq!(start.probe, "true", "response a came before the hook");
    }

    /// One submitted update the recorder saw: its name, wire ID, action
    /// and the first-poll flag of its write.
    type Submission = (
        String,
        String,
        OperationAction,
        Arc<std::sync::atomic::AtomicBool>,
    );

    /// A client that fails, with a non-retryable error, the request that
    /// carries the `START` of `target`, and accepts every other request.
    struct FailStartClient {
        target: &'static str,
    }

    /// The error [`FailStartClient`] returns.
    fn start_rejection() -> ExecutionClientError {
        ExecutionClientError::new(
            crate::client::ExecutionClientErrorScope::Execution,
            "START rejected",
        )
    }

    impl ExecutionClient for FailStartClient {
        fn checkpoint(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            updates: Vec<OperationUpdate>,
        ) -> Pin<Box<dyn Future<Output = Result<CheckpointOutput, ExecutionClientError>> + Send + '_>>
        {
            let fails = updates
                .iter()
                .any(|u| u.action() == &OperationAction::Start && u.name() == Some(self.target));
            Box::pin(async move {
                if fails {
                    Err(start_rejection())
                } else {
                    Ok(CheckpointOutput::new(
                        Some("t".to_owned()),
                        Vec::new(),
                        None,
                    ))
                }
            })
        }

        fn get_state(
            &self,
            _execution_arn: &str,
            _checkpoint_token: &str,
            _marker: Option<&str>,
        ) -> Pin<Box<dyn Future<Output = Result<GetStateOutput, ExecutionClientError>> + Send + '_>>
        {
            Box::pin(async { Ok(GetStateOutput::new(Vec::new(), None)) })
        }
    }

    /// The child-backed operations whose outcome waits for a failed
    /// `START` (test 26).
    #[derive(Debug, Clone, Copy)]
    enum Settler {
        ChildSuccess,
        ChildFailure,
        BatchParentEmpty,
        BatchParentAfterItems,
        BatchItemSuccess,
        BatchItemFailure,
        /// A child whose result fails to serialize: it writes `FAIL`.
        ChildSerializeFailure,
        /// A map item whose result fails to serialize: it writes `FAIL`.
        BatchItemSerializeFailure,
    }

    /// A serdes whose `serialize` always fails.
    struct FailSerialize;

    impl<T: Send + 'static> crate::Serdes<T> for FailSerialize {
        fn serialize(
            &self,
            _value: T,
            _context: crate::serdes::SerdesContext,
        ) -> impl Future<Output = Result<String, crate::BoxError>> + Send {
            std::future::ready(Err("cannot serialize".into()))
        }

        fn deserialize(
            &self,
            _wire: String,
            _context: crate::serdes::SerdesContext,
        ) -> impl Future<Output = Result<T, crate::BoxError>> + Send {
            std::future::ready(Err("cannot deserialize".into()))
        }
    }

    impl Settler {
        /// The name of the operation whose `START` is held and fails.
        fn target(self) -> &'static str {
            match self {
                Self::ChildSuccess | Self::ChildFailure | Self::ChildSerializeFailure => "c",
                Self::BatchParentEmpty | Self::BatchParentAfterItems => "m",
                Self::BatchItemSuccess
                | Self::BatchItemFailure
                | Self::BatchItemSerializeFailure => "map-item-0",
            }
        }

        /// The outcome action the settler is about to write.
        fn action(self) -> OperationAction {
            match self {
                Self::ChildFailure
                | Self::BatchItemFailure
                | Self::ChildSerializeFailure
                | Self::BatchItemSerializeFailure => OperationAction::Fail,
                _ => OperationAction::Succeed,
            }
        }

        /// Whether a body runs and logs `result ready` as its last
        /// statement.
        fn has_body(self) -> bool {
            !matches!(self, Self::BatchParentEmpty)
        }

        /// The operation's future on `ctx`. A body logs `result ready` to
        /// `log` as its last statement.
        fn future(
            self,
            ctx: &DurableContext,
            log: Arc<Mutex<Vec<String>>>,
        ) -> Pin<Box<dyn Future<Output = ()> + Send>> {
            let ready = move || log.lock().unwrap().push("result ready".to_owned());
            match self {
                Self::ChildSuccess | Self::ChildFailure => {
                    let fail = matches!(self, Self::ChildFailure);
                    let future = ctx
                        .run_in_child_context(move |_child| async move {
                            ready();
                            if fail {
                                Err::<u32, crate::BoxError>("boom".into())
                            } else {
                                Ok(1_u32)
                            }
                        })
                        .name("c")
                        .into_future();
                    Box::pin(async move {
                        let _ignored = future.await;
                    })
                }
                Self::ChildSerializeFailure => {
                    let future = ctx
                        .run_in_child_context(move |_child| async move {
                            ready();
                            Ok(1_u32)
                        })
                        .name("c")
                        .serdes(FailSerialize)
                        .into_future();
                    Box::pin(async move {
                        let _ignored = future.await;
                    })
                }
                Self::BatchItemSerializeFailure => {
                    let ready = Arc::new(ready);
                    let future = ctx
                        .map(vec![1_u32], move |_child, item, _| {
                            let ready = Arc::clone(&ready);
                            async move {
                                ready();
                                Ok(item)
                            }
                        })
                        .name("m")
                        .serdes(FailSerialize)
                        .completion(
                            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_percentage(100.0)
                                .expect("a valid percentage"),
                        )
                        .into_future();
                    Box::pin(async move {
                        let _ignored = future.await;
                    })
                }
                Self::BatchParentEmpty => {
                    let future = ctx
                        .map(Vec::<u32>::new(), |_child, item, _| async move { Ok(item) })
                        .name("m")
                        .into_future();
                    Box::pin(async move {
                        let _ignored = future.await;
                    })
                }
                Self::BatchParentAfterItems | Self::BatchItemSuccess | Self::BatchItemFailure => {
                    let fail = matches!(self, Self::BatchItemFailure);
                    let nesting = if matches!(self, Self::BatchParentAfterItems) {
                        crate::map_parallel::NestingMode::Flat
                    } else {
                        crate::map_parallel::NestingMode::Normal
                    };
                    let ready = Arc::new(ready);
                    let future = ctx
                        .map(vec![1_u32], move |_child, item, _| {
                            let ready = Arc::clone(&ready);
                            async move {
                                ready();
                                if fail {
                                    Err::<u32, crate::BoxError>("boom".into())
                                } else {
                                    Ok(item)
                                }
                            }
                        })
                        .name("m")
                        .nesting(nesting)
                        .completion(
                            crate::builders::map_parallel::CompletionConfig::with_tolerated_failure_percentage(100.0)
                                .expect("a valid percentage"),
                        )
                        .into_future();
                    Box::pin(async move {
                        let _ignored = future.await;
                    })
                }
            }
        }
    }

    /// Waits up to two seconds for `ready`, failing the test with `what`.
    async fn wait_until(what: &str, mut ready: impl FnMut() -> bool) {
        let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        while !ready() {
            assert!(tokio::time::Instant::now() < deadline, "timed out: {what}");
            tokio::time::sleep(Duration::from_millis(1)).await;
        }
    }

    /// Runs test 26 for `case` (see [`Settler`]).
    #[expect(clippy::too_many_lines)] // reason: the test's setup and its ordered checks read as one scenario
    async fn outcome_waits_for_failed_start(case: Settler) {
        let target = case.target();
        let ctx = context(
            Vec::new(),
            Arc::new(FailStartClient { target }),
            Duration::ZERO,
            None,
        );
        let gate = Arc::new(tokio::sync::Notify::new());
        let held = Arc::clone(&gate);
        ctx.set_pre_lock_gate(Arc::new(move |updates: &[OperationUpdate]| {
            updates
                .iter()
                .any(|u| u.action() == &OperationAction::Start && u.name() == Some(target))
                .then(|| Arc::clone(&held))
        }));
        let submissions: Arc<Mutex<Vec<Submission>>> = Arc::default();
        let recorded = Arc::clone(&submissions);
        ctx.set_submission_recorder(Arc::new(move |updates, flag| {
            let mut recorded = recorded.lock().unwrap();
            for u in updates {
                recorded.push((
                    u.name().unwrap_or("-").to_owned(),
                    u.id().to_owned(),
                    u.action().clone(),
                    Arc::clone(flag),
                ));
            }
        }));
        let entries: Arc<Mutex<Vec<(String, OperationAction)>>> = Arc::default();
        let entered = Arc::clone(&entries);
        ctx.set_settler_entry_recorder(Arc::new(move |wire_id, action| {
            entered.lock().unwrap().push((wire_id.to_owned(), action));
        }));
        let log: Arc<Mutex<Vec<String>>> = Arc::default();
        let operation = case.future(&ctx, Arc::clone(&log));

        let start_of = |submissions: &[Submission]| {
            submissions
                .iter()
                .find(|(name, _, action, _)| name == target && action == &OperationAction::Start)
                .map(|(_, id, _, flag)| (id.clone(), Arc::clone(flag)))
        };
        let outcomes_of = |submissions: &[Submission], id: &str| {
            submissions
                .iter()
                .filter(|(_, sid, action, _)| {
                    sid == id && matches!(action, OperationAction::Succeed | OperationAction::Fail)
                })
                .count()
        };
        let observe = async {
            wait_until("the target's START is submitted", || {
                start_of(&submissions.lock().unwrap()).is_some()
            })
            .await;
            let (id, flag) = start_of(&submissions.lock().unwrap()).expect("checked above");
            let action = case.action();
            wait_until("the settler-entry marker", || {
                entries
                    .lock()
                    .unwrap()
                    .contains(&(id.clone(), action.clone()))
            })
            .await;
            if case.has_body() {
                wait_until("the body's result", || {
                    log.lock().unwrap().iter().any(|e| e == "result ready")
                })
                .await;
            }
            assert!(
                flag.load(std::sync::atomic::Ordering::SeqCst),
                "{case:?}: the outcome path polls the retained START"
            );
            assert_eq!(
                outcomes_of(&submissions.lock().unwrap(), &id),
                0,
                "{case:?}: no outcome while START is held"
            );
            gate.notify_one();
            wait_until("the invocation's fatal error", || {
                ctx.coordinator().fatal_error().is_some()
            })
            .await;
            let fatal = ctx.coordinator().fatal_error().expect("checked above");
            let wire = crate::error::checkpoint_execution_failure_wire(&start_rejection());
            assert_eq!(
                fatal.error_type, "CheckpointUnrecoverableExecutionError",
                "{case:?}"
            );
            assert_eq!(
                Some(fatal.error_message.as_str()),
                wire.error_message(),
                "{case:?}"
            );
            for _ in 0..10 {
                tokio::task::yield_now().await;
            }
            assert_eq!(
                outcomes_of(&submissions.lock().unwrap(), &id),
                0,
                "{case:?}: no outcome after the failed START"
            );
        };
        tokio::select! {
            () = operation => panic!("{case:?}: the operation resolved after a failed START"),
            () = observe => {}
        }
    }

    #[tokio::test]
    async fn child_success_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::ChildSuccess).await;
    }

    #[tokio::test]
    async fn child_failure_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::ChildFailure).await;
    }

    #[tokio::test]
    async fn batch_parent_success_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::BatchParentEmpty).await;
    }

    #[tokio::test]
    async fn batch_parent_nonempty_success_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::BatchParentAfterItems).await;
    }

    #[tokio::test]
    async fn batch_item_success_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::BatchItemSuccess).await;
    }

    #[tokio::test]
    async fn batch_item_failure_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::BatchItemFailure).await;
    }

    #[tokio::test]
    async fn child_serialize_failure_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::ChildSerializeFailure).await;
    }

    #[tokio::test]
    async fn batch_item_serialize_failure_waits_for_failed_start() {
        outcome_waits_for_failed_start(Settler::BatchItemSerializeFailure).await;
    }
}