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
//! Integration tests for the combinator error surface (issue #28).
//!
//! Verifies that `race` surfaces a losing branch's failure as
//! `CombinatorErrorKind::FirstSettledFailed`, with the same variant and
//! message live and on replay, and that `race` and `select_ok` agree on
//! `CombinatorErrorKind::EmptyInput` for empty input.

#![cfg(feature = "test-util")]
#![expect(clippy::expect_used, clippy::indexing_slicing)] // reason: test assertions

use std::sync::{Arc, Mutex};
use std::time::Duration;

use aws_durable_execution_sdk as durable;
use durable::test_util::LocalRunner;
use durable::{CombinatorErrorKind, DurableFuture, OperationErrorKind, RetryDecision};

/// Renders the combinator error kind a handler observed, so the test can
/// compare the live observation against the replayed one.
fn describe_combinator_error(err: &durable::OperationError) -> String {
    match err.kind() {
        OperationErrorKind::Combinator(ce) => match ce.kind() {
            CombinatorErrorKind::FirstSettledFailed { .. } => {
                // The race's record carries the loser's recorded message.
                let message = err
                    .wire()
                    .and_then(durable::WireError::error_message)
                    .unwrap_or_default();
                format!("FirstSettledFailed:{message}")
            }
            CombinatorErrorKind::EmptyInput { .. } => "EmptyInput".to_owned(),
            other => format!("other:{other:?}"),
        },
        other => format!("non-combinator:{other:?}"),
    }
}

/// The race loser's error identity survives replay: the live invocation
/// and the replayed invocation both observe `FirstSettledFailed` carrying
/// the losing step's message.
#[tokio::test]
async fn race_loser_error_identity_survives_replay() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    // The loser fails immediately; the slow branch never wins.
                    let loser = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-loser".into()) })
                        .name("loser")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();
                    let slow = ctx
                        .step(|_| async {
                            tokio::time::sleep(Duration::from_secs(30)).await;
                            Ok("slow".to_owned())
                        })
                        .name("slow")
                        .future();

                    let race_err = match ctx.race([loser, slow]).name("race").await {
                        Ok(winner) => {
                            return Err(format!("race unexpectedly won: {winner}").into());
                        }
                        Err(err) => err,
                    };
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(describe_combinator_error(&race_err));
                    }

                    // Suspend so the next invocation REPLAYS the failed race
                    // from its checkpoint record.
                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;

                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    assert!(
        result.invocation_count() >= 2,
        "the wait must force at least one replay, got {} invocation(s)",
        result.invocation_count()
    );

    let seen = observed.lock().expect("observation lock").clone();
    assert!(
        seen.len() >= 2,
        "the race error must be observed live and on replay: {seen:?}"
    );
    for (i, entry) in seen.iter().enumerate() {
        assert!(
            entry.starts_with("FirstSettledFailed:"),
            "invocation {i} must observe FirstSettledFailed: {entry}"
        );
        assert!(
            entry.contains("boom-loser"),
            "invocation {i} must preserve the loser's message: {entry}"
        );
    }
    // Live and replayed observations are identical (same variant, same message).
    assert!(
        seen.windows(2).all(|w| w[0] == w[1]),
        "live and replayed errors must be indistinguishable: {seen:?}"
    );
}

/// `race([])` and `select_ok([])` both fail with `EmptyInput`.
#[tokio::test]
async fn race_and_select_ok_agree_on_empty_input() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let Err(race_err) = ctx
                        .race(Vec::<DurableFuture<String>>::new())
                        .name("empty-race")
                        .await
                    else {
                        return Err("race([]) unexpectedly succeeded".into());
                    };
                    let Err(select_err) = ctx
                        .select_ok(Vec::<DurableFuture<String>>::new())
                        .name("empty-select")
                        .await
                    else {
                        return Err("select_ok([]) unexpectedly succeeded".into());
                    };
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(describe_combinator_error(&race_err));
                        seen.push(describe_combinator_error(&select_err));
                    }
                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert_eq!(
        seen,
        vec!["EmptyInput".to_owned(), "EmptyInput".to_owned()],
        "race([]) and select_ok([]) must both yield EmptyInput"
    );
}

/// Renders a `try_join_all` failure as its variant plus the failed index,
/// so live and replayed observations compare structurally.
fn describe_join_failure(err: &durable::OperationError) -> String {
    match err.kind() {
        OperationErrorKind::Combinator(ce) => match ce.kind() {
            CombinatorErrorKind::JoinFailed(details) => {
                format!("JoinFailed@{}", details.failed_index())
            }
            other => format!("other:{other:?}"),
        },
        other => format!("non-combinator:{other:?}"),
    }
}

/// A `try_join_all` failure classifies as `JoinFailed` carrying the failed
/// input's index on the live path, and replay must reconstruct the SAME
/// variant and index from the recorded discriminator: a handler that
/// branches on either takes the same path live and replayed.
#[tokio::test]
async fn try_join_all_failure_kind_and_index_survive_replay() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let ok = ctx
                        .step(|_| async { Ok("fine".to_owned()) })
                        .name("ok")
                        .future();
                    let bad = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-join".into()) })
                        .name("bad")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let join_err = match ctx.try_join_all([ok, bad]).name("gather").await {
                        Ok(values) => {
                            return Err(format!("unexpectedly succeeded: {values:?}").into());
                        }
                        Err(err) => err,
                    };
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(describe_join_failure(&join_err));
                    }

                    // Suspend so the next invocation replays the failure.
                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;
                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert!(
        seen.len() >= 2,
        "the failure must be observed live and on replay: {seen:?}"
    );
    assert_eq!(
        seen[0], "JoinFailed@1",
        "the live failure names the failing input's index: {seen:?}"
    );
    assert!(
        seen.windows(2).all(|w| w[0] == w[1]),
        "live and replayed kinds (including the index) must match: {seen:?}"
    );
}

/// A `select_ok` whose inputs all fail classifies as `AllFailed` with one
/// loser per input on the live path, and replay must reconstruct the SAME
/// variant with the SAME loser count from the recorded discriminator.
#[tokio::test]
async fn select_ok_all_failed_kind_and_loser_count_survive_replay() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let first = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-a".into()) })
                        .name("first")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();
                    let second = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-b".into()) })
                        .name("second")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let select_err = match ctx.select_ok([first, second]).name("pick").await {
                        Ok(value) => {
                            return Err(format!("unexpectedly succeeded: {value}").into());
                        }
                        Err(err) => err,
                    };
                    let label = match select_err.kind() {
                        OperationErrorKind::Combinator(ce) => match ce.kind() {
                            CombinatorErrorKind::AllFailed { .. } => {
                                format!("AllFailed:{}", ce.failures().len())
                            }
                            other => format!("other:{other:?}"),
                        },
                        other => format!("non-combinator:{other:?}"),
                    };
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(label);
                    }

                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;
                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert!(
        seen.len() >= 2,
        "the failure must be observed live and on replay: {seen:?}"
    );
    assert_eq!(
        seen[0], "AllFailed:2",
        "the live failure carries one loser per input: {seen:?}"
    );
    assert!(
        seen.windows(2).all(|w| w[0] == w[1]),
        "live and replayed kinds (including loser count) must match: {seen:?}"
    );
}

/// A rejected `join_all` outcome's wire identity (`error_type`, message)
/// survives the checkpoint round-trip: the replayed `Err`
/// carries the SAME recorded wire record the live outcome carried, not a
/// synthetic untyped reconstruction (issue #41).
#[tokio::test]
async fn join_all_rejected_wire_identity_survives_replay() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let good = ctx
                        .step(|_| async { Ok("fine".to_owned()) })
                        .name("good")
                        .future();
                    let bad = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-settled".into()) })
                        .name("bad-settled")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let settled = ctx.join_all([good, bad]).name("collect").await?;
                    let rejected_wires: Vec<String> = settled
                        .iter()
                        .filter_map(|outcome| match outcome {
                            Err(err) => Some(format!(
                                "{}:{}",
                                err.wire()
                                    .and_then(durable::WireError::error_type)
                                    .unwrap_or("<none>"),
                                err.wire()
                                    .and_then(durable::WireError::error_message)
                                    .unwrap_or("<none>"),
                            )),
                            Ok(_) => None,
                        })
                        .collect();
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(rejected_wires.join("|"));
                    }

                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;
                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert!(
        seen.len() >= 2,
        "the settled set must be observed live and on replay: {seen:?}"
    );
    assert!(
        seen[0].contains("boom-settled") && !seen[0].starts_with("<none>"),
        "the live rejected outcome carries a typed wire record: {seen:?}"
    );
    assert!(
        seen.windows(2).all(|w| w[0] == w[1]),
        "live and replayed rejected wire identities must match: {seen:?}"
    );
}

/// Renders one loser's complete wire failure record, whether the loser is
/// the live error itself (an `OperationError` carrying its recorded wire
/// record) or a replay-reconstructed `ReplayedFailure`.
fn describe_loser(source: &(dyn std::error::Error + 'static)) -> String {
    let wire = source
        .downcast_ref::<durable::OperationError>()
        .and_then(|op| op.wire().cloned())
        .or_else(|| {
            source
                .downcast_ref::<durable::ReplayedFailure>()
                .map(|replayed| replayed.wire().clone())
        });
    wire.map_or_else(
        || "no-wire".to_owned(),
        |w| {
            format!(
                "type={:?} msg={:?} data={:?} trace={:?}",
                w.error_type(),
                w.error_message(),
                w.error_data(),
                w.stack_trace()
            )
        },
    )
}

/// Each `select_ok` loser's error identity survives replay individually:
/// the live invocation and the replayed invocation observe the SAME
/// per-loser `error_type`, message, `error_data`, and `stack_trace` for
/// every input, not clones of the aggregate record.
#[tokio::test]
async fn select_ok_all_failed_loser_identities_survive_replay() {
    let observed: Arc<Mutex<Vec<Vec<String>>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let first = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-first".into()) })
                        .name("first")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();
                    let second = ctx
                        .step(|_| async { Err::<String, durable::BoxError>("boom-second".into()) })
                        .name("second")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let err = match ctx.select_ok([first, second]).name("all-fail").await {
                        Ok(winner) => {
                            return Err(format!("select_ok unexpectedly won: {winner}").into());
                        }
                        Err(err) => err,
                    };
                    let OperationErrorKind::Combinator(ce) = err.kind() else {
                        return Err(format!("expected a combinator error: {err:?}").into());
                    };
                    if !matches!(ce.kind(), CombinatorErrorKind::AllFailed { .. }) {
                        return Err(format!("expected AllFailed: {:?}", ce.kind()).into());
                    }
                    let losers: Vec<String> = ce
                        .failures()
                        .iter()
                        .map(|loser| describe_loser(&**loser))
                        .collect();
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(losers);
                    }

                    // Suspend so the next invocation REPLAYS the failed
                    // select_ok from its checkpoint record.
                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;

                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert!(
        seen.len() >= 2,
        "the losers must be observed live and on replay: {} observation(s)",
        seen.len()
    );
    for (i, losers) in seen.iter().enumerate() {
        assert_eq!(losers.len(), 2, "invocation {i} must observe both losers");
        assert!(
            losers[0].contains("boom-first"),
            "invocation {i} loser 0 keeps its own message: {}",
            losers[0]
        );
        assert!(
            losers[1].contains("boom-second"),
            "invocation {i} loser 1 keeps its own message: {}",
            losers[1]
        );
        assert_ne!(
            losers[0], losers[1],
            "invocation {i} losers must be individual records, not clones"
        );
    }
    // Live and replayed observations are identical, field for field,
    // loser for loser.
    assert!(
        seen.windows(2).all(|w| w[0] == w[1]),
        "live and replayed losers must be indistinguishable: {seen:#?}"
    );
}

/// A rejected `join_all` item has the same error kind on the first run and
/// on replay: `ChildContext` on both, not the failed input's own `Step`
/// kind on the first run (issue #111).
#[tokio::test]
async fn join_all_rejection_kind_matches_live_and_replay() {
    let observed: Arc<Mutex<Vec<(bool, String)>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let good = ctx.step(|_| async { Ok(1_u32) }).name("good").future();
                    let bad = ctx
                        .step(|_| async { Err::<u32, durable::BoxError>("boom".into()) })
                        .name("bad")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let settled = ctx.join_all([good, bad]).name("collect").await?;
                    let family = settled
                        .iter()
                        .find_map(|outcome| match outcome {
                            Err(err) => Some(match err.kind() {
                                OperationErrorKind::Step(_) => "Step",
                                OperationErrorKind::ChildContext(_) => "ChildContext",
                                _ => "other",
                            }),
                            Ok(_) => None,
                        })
                        .unwrap_or("none");
                    if let Ok(mut seen) = observed.lock() {
                        seen.push((ctx.is_replaying(), family.to_owned()));
                    }

                    ctx.wait(Duration::from_secs(1)).name("suspend").await?;
                    Ok::<_, durable::BoxError>("done".to_owned())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert_eq!(seen.len(), 2, "one record per invocation: {seen:?}");
    assert!(
        seen.iter().all(|(_, family)| family == "ChildContext"),
        "the rejected item is a ChildContext error live and on replay: {seen:?}"
    );
}

/// A failing `join_all` input is reported as that input's inner `Err`,
/// never as the combinator's outer `Err`: the outer result is `Ok`, with
/// `Ok` at index 0 and `Err` at index 1 (issue #64).
#[tokio::test]
async fn join_all_input_failure_is_inner_err() {
    let observed: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let observed_clone = Arc::clone(&observed);

    let result = LocalRunner::new()
        .run(
            move |_event: (), ctx: durable::DurableContext| {
                let observed = Arc::clone(&observed_clone);
                async move {
                    let good = ctx.step(|_| async { Ok(1_u32) }).name("good").future();
                    let bad = ctx
                        .step(|_| async { Err::<u32, durable::BoxError>("boom".into()) })
                        .name("bad")
                        .retry_strategy(|_err, _attempt| RetryDecision::Stop)
                        .future();

                    let joined: Result<Vec<Result<u32, durable::OperationError>>, _> =
                        ctx.join_all([good, bad]).name("collect").await;
                    let rendered = match &joined {
                        Err(err) => format!("outer-err:{err}"),
                        Ok(items) => items
                            .iter()
                            .map(|item| match item {
                                Ok(value) => format!("ok:{value}"),
                                Err(err) => format!(
                                    "err:{}",
                                    err.wire()
                                        .and_then(durable::WireError::error_message)
                                        .unwrap_or("<none>")
                                ),
                            })
                            .collect::<Vec<_>>()
                            .join(","),
                    };
                    if let Ok(mut seen) = observed.lock() {
                        seen.push(rendered);
                    }
                    Ok::<_, durable::BoxError>(())
                }
            },
            (),
        )
        .await
        .expect("runner");

    assert!(
        result.is_success(),
        "handler should complete: {:?}",
        result.error_message()
    );
    let seen = observed.lock().expect("observation lock").clone();
    assert_eq!(seen, vec!["ok:1,err:boom".to_owned()]);
}