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
//! Early completion of a batch: an item that is still running or parked
//! when the completion rule ends the batch is reported as `Started`, in the
//! live invocation and on replay, and a custom completion reason survives
//! replay.

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

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

use aws_durable_execution_sdk as durable;
use durable::builders::map_parallel::{CompletionConfig, CompletionDecision, CompletionOutcome};
use durable::test_util::LocalRunner;

/// The item statuses each invocation saw, formatted with `{:?}`.
type Seen = Arc<Mutex<Vec<Vec<String>>>>;

/// Runs `map([0, 1, 2])` named `m` with `min_successful(2)`. Every item
/// runs one step that returns `"x".repeat(size)`; item 2 first waits 5 s.
/// After the batch, the handler records the item statuses, then waits 1 s,
/// so the batch is replayed in a second invocation. Returns what each
/// invocation recorded.
async fn run_parked_item_batch(size: usize) -> Vec<Vec<String>> {
    let seen: Seen = Arc::new(Mutex::new(Vec::new()));
    let handler_seen = Arc::clone(&seen);
    let result = LocalRunner::new()
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let seen = Arc::clone(&handler_seen);
                async move {
                    let batch = ctx
                        .map(vec![0_u32, 1, 2], move |child, item, _idx| async move {
                            if item == 2 {
                                child.wait(Duration::from_secs(5)).name("park").await?;
                            }
                            let value = child
                                .step(move |_| async move { Ok("x".repeat(size)) })
                                .name("value")
                                .await?;
                            Ok(value)
                        })
                        .name("m")
                        .completion(CompletionConfig::with_min_successful(2))
                        .await_batch()
                        .await?;
                    let statuses = batch
                        .items
                        .iter()
                        .map(|item| format!("{:?}", item.status))
                        .collect();
                    seen.lock().expect("lock").push(statuses);
                    ctx.wait(Duration::from_secs(1)).name("after").await?;
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert!(result.is_success(), "the execution succeeds: {result}");
    seen.lock().expect("lock").clone()
}

const PARKED_STARTED: [&str; 3] = ["Succeeded", "Succeeded", "Started"];

#[tokio::test]
async fn parked_item_is_started_live_and_on_replay_small() {
    assert_eq!(
        run_parked_item_batch(10).await,
        [PARKED_STARTED, PARKED_STARTED],
        "the live invocation and the replay report the parked item as Started"
    );
}

#[tokio::test]
async fn parked_item_is_started_live_and_on_replay_oversized() {
    // Two 150 KiB results exceed the batch record limit, so the batch
    // records its decision record and the replay reads the started set
    // from it.
    assert_eq!(
        run_parked_item_batch(150 * 1024).await,
        [PARKED_STARTED, PARKED_STARTED],
        "the live invocation and the replay report the parked item as Started"
    );
}

/// The reason and status each invocation saw.
type Outcomes = Arc<Mutex<Vec<(String, String)>>>;

/// Runs `map([0, 1, 2])` with `max_concurrency(1)` and a predicate that
/// completes with `outcome` once two items have settled. Every item runs one
/// step that returns `"x".repeat(size)`. After the batch, the handler
/// records the reason and the status, then waits 1 s, so the batch is
/// replayed in a second invocation. Returns what each invocation recorded.
async fn run_custom_completion(size: usize, outcome: CompletionOutcome) -> Vec<(String, String)> {
    let seen: Outcomes = Arc::new(Mutex::new(Vec::new()));
    let handler_seen = Arc::clone(&seen);
    let result = LocalRunner::new()
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let seen = Arc::clone(&handler_seen);
                async move {
                    let batch = ctx
                        .map(vec![0_u32, 1, 2], move |child, _item, _idx| async move {
                            let value = child
                                .step(move |_| async move { Ok("x".repeat(size)) })
                                .name("value")
                                .await?;
                            Ok(value)
                        })
                        .name("m")
                        .max_concurrency(1)
                        .completion(CompletionConfig::with_completion_predicate(move |stats| {
                            if stats.settled() >= 2 {
                                CompletionDecision::complete(outcome)
                            } else {
                                CompletionDecision::Continue
                            }
                        }))
                        .await_batch()
                        .await?;
                    seen.lock().expect("lock").push((
                        batch.reason.as_str().to_owned(),
                        format!("{:?}", batch.status()),
                    ));
                    ctx.wait(Duration::from_secs(1)).name("after").await?;
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert!(result.is_success(), "the execution succeeds: {result}");
    seen.lock().expect("lock").clone()
}

fn twice(reason: &str, status: &str) -> [(String, String); 2] {
    let entry = (reason.to_owned(), status.to_owned());
    [entry.clone(), entry]
}

#[tokio::test]
async fn custom_succeeded_survives_small_replay() {
    assert_eq!(
        run_custom_completion(10, CompletionOutcome::Succeeded).await,
        twice("CUSTOM_COMPLETION_SUCCEEDED", "Succeeded"),
        "the live invocation and the replay record the same reason"
    );
}

#[tokio::test]
async fn custom_failed_survives_small_replay() {
    assert_eq!(
        run_custom_completion(10, CompletionOutcome::Failed).await,
        twice("CUSTOM_COMPLETION_FAILED", "Failed"),
        "the live invocation and the replay record the same reason"
    );
}

#[tokio::test]
async fn custom_failed_survives_oversized_replay() {
    // Two 150 KiB results exceed the batch record limit, so the batch
    // records its decision record and the replay reads the reason from it.
    assert_eq!(
        run_custom_completion(150 * 1024, CompletionOutcome::Failed).await,
        twice("CUSTOM_COMPLETION_FAILED", "Failed"),
        "the live invocation and the replay record the same reason"
    );
}

/// What each invocation saw: the reason, and how many times the predicate
/// had been called in the whole run when the batch returned.
type Calls = Arc<Mutex<Vec<(String, usize)>>>;

/// Runs `map([0, 1, 2])` named `m` with `max_concurrency(1)`, `nesting`,
/// and a predicate that completes as failed once two items have settled.
/// Every item runs two steps that return `size` bytes each, and returns
/// both joined. After the
/// batch, the handler records the reason and the predicate call count,
/// then waits 1 s, so the batch is replayed in a second invocation.
async fn run_counted_predicate(
    nesting: durable::builders::map_parallel::NestingMode,
    size: usize,
) -> Vec<(String, usize)> {
    let seen: Calls = Arc::new(Mutex::new(Vec::new()));
    let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let handler_seen = Arc::clone(&seen);
    let handler_calls = Arc::clone(&calls);
    let result = LocalRunner::new()
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let seen = Arc::clone(&handler_seen);
                let calls = Arc::clone(&handler_calls);
                let predicate_calls = Arc::clone(&calls);
                async move {
                    let batch = ctx
                        .map(vec![0_u32, 1, 2], move |child, _item, _idx| async move {
                            let first = child
                                .step(move |_| async move { Ok("x".repeat(size)) })
                                .name("first")
                                .await?;
                            let second = child
                                .step(move |_| async move { Ok("y".repeat(size)) })
                                .name("second")
                                .await?;
                            Ok(first + &second)
                        })
                        .name("m")
                        .max_concurrency(1)
                        .nesting(nesting)
                        .completion(CompletionConfig::with_completion_predicate(move |stats| {
                            predicate_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                            if stats.settled() >= 2 {
                                CompletionDecision::complete(CompletionOutcome::Failed)
                            } else {
                                CompletionDecision::Continue
                            }
                        }))
                        .await_batch()
                        .await?;
                    seen.lock().expect("lock").push((
                        batch.reason.as_str().to_owned(),
                        calls.load(std::sync::atomic::Ordering::SeqCst),
                    ));
                    ctx.wait(Duration::from_secs(1)).name("after").await?;
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert!(result.is_success(), "the execution succeeds: {result}");
    seen.lock().expect("lock").clone()
}

/// Asserts that the replay recorded the live reason, and that the
/// predicate was not called again while the batch was rebuilt.
fn assert_rebuild_skips_predicate(seen: &[(String, usize)]) {
    assert_eq!(seen.len(), 2, "two invocations: {seen:?}");
    let (live_reason, live_calls) = seen.first().expect("live invocation");
    let (replay_reason, replay_calls) = seen.get(1).expect("replay invocation");
    assert_eq!(live_reason, "CUSTOM_COMPLETION_FAILED");
    assert_eq!(
        replay_reason, live_reason,
        "the replay reads the recorded reason"
    );
    assert!(*live_calls > 0, "the live run asks the predicate");
    assert_eq!(
        replay_calls, live_calls,
        "rebuilding the completed batch calls the predicate no more"
    );
}

#[tokio::test]
async fn flat_oversized_rebuild_does_not_call_predicate() {
    // Two 160 KiB item results exceed the batch record limit, so the batch
    // records its decision record. Flat items have no child records, so
    // the replay rebuilds the batch by re-running the recorded items.
    let seen = run_counted_predicate(
        durable::builders::map_parallel::NestingMode::Flat,
        80 * 1024,
    )
    .await;
    assert_rebuild_skips_predicate(&seen);
}

#[tokio::test]
async fn oversized_child_rebuild_does_not_call_predicate() {
    // A 300 KiB item result exceeds the child record limit, so each child
    // records ReplayChildren and the replay rebuilds the batch by
    // re-running the recorded items under the decision record.
    let seen = run_counted_predicate(
        durable::builders::map_parallel::NestingMode::Normal,
        150 * 1024,
    )
    .await;
    assert_rebuild_skips_predicate(&seen);
}

/// An invalid percentage is rejected while the `CompletionConfig` is
/// built, so no batch starts with it and no record stays `STARTED`. The
/// handler runs a map only when construction succeeded, records each
/// construction error, then runs a valid map.
#[tokio::test]
async fn invalid_percentage_starts_no_batch() {
    let errors: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let handler_errors = Arc::clone(&errors);
    let result = LocalRunner::new()
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let errors = Arc::clone(&handler_errors);
                async move {
                    let attempts = [
                        (
                            "invalid-constructor",
                            CompletionConfig::with_tolerated_failure_percentage(150.0),
                        ),
                        (
                            "invalid-builder",
                            CompletionConfig::builder()
                                .tolerated_failure_percentage(150.0)
                                .build(),
                        ),
                    ];
                    for (name, built) in attempts {
                        match built {
                            Ok(config) => {
                                ctx.map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
                                    .name(name)
                                    .completion(config)
                                    .await?;
                            }
                            Err(err) => errors.lock().expect("lock").push(err.to_string()),
                        }
                    }
                    ctx.map(vec![1_u32], |_child, item, _idx| async move { Ok(item) })
                        .name("ok")
                        .completion(CompletionConfig::with_tolerated_failure_percentage(100.0)?)
                        .await?;
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert!(result.is_success(), "the execution succeeds: {result}");
    assert_eq!(result.invocation_count(), 1);
    let expected =
        "invalid CompletionConfig: tolerated_failure_percentage must be 0-100, got 150".to_owned();
    assert_eq!(
        *errors.lock().expect("lock"),
        [expected.clone(), expected],
        "both construction paths return the same error"
    );
    assert!(result.operation("invalid-constructor").is_none());
    assert!(result.operation("invalid-builder").is_none());
    assert_eq!(
        result.operation("ok").expect("the valid map ran").status(),
        durable::OperationStatus::Succeeded
    );
    assert!(
        result
            .operations()
            .iter()
            .all(|op| op.status() != durable::OperationStatus::Started),
        "no operation stays STARTED: {result}"
    );
}

/// A lossless result serdes that prefixes 300 KiB and removes it on read,
/// so every batch record it stores is over the 256 KiB limit.
struct PaddedSerdes;

/// The length of the padding [`PaddedSerdes`] adds.
const PAD: usize = 300 * 1024;

impl durable::Serdes<String> for PaddedSerdes {
    fn serialize(
        &self,
        value: String,
        _context: durable::serdes::SerdesContext,
    ) -> impl Future<Output = Result<String, durable::BoxError>> + Send {
        std::future::ready(Ok(format!("{}{value}", " ".repeat(PAD))))
    }

    fn deserialize(
        &self,
        wire: String,
        _context: durable::serdes::SerdesContext,
    ) -> impl Future<Output = Result<String, durable::BoxError>> + Send {
        std::future::ready(
            wire.get(PAD..)
                .map(str::to_owned)
                .ok_or_else(|| "the payload has no padding".into()),
        )
    }
}

/// A map over an empty input stores the oversized summary, and the next
/// invocation replays it.
#[tokio::test]
async fn empty_map_with_oversized_result_replays_after_a_wait() {
    let result = LocalRunner::new()
        .run(
            |_event: serde_json::Value, ctx: durable::DurableContext| async move {
                let values = ctx
                    .map(Vec::<u32>::new(), |_, item, _| async move { Ok(item) })
                    .name("b")
                    .result_serdes(PaddedSerdes)
                    .await?;
                ctx.wait(Duration::from_secs(1)).name("after").await?;
                Ok::<_, durable::BoxError>(values.len())
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    let op = result.operation("b").expect("record b");
    assert!(
        matches!(
            op.details(),
            durable::test_util::TestOperationDetails::Context(c) if c.replay_children()
        ),
        "the record is the oversized summary"
    );
    assert!(result.is_success(), "{result} {:?}", result.error_message());
    assert_eq!(result.output(), Some(&0));
}

/// Runs `map([0, 1, 2])` named `b` with `nesting`, a predicate that
/// completes the batch before its first item starts, and `PaddedSerdes`,
/// then waits 1 s. Returns the item count and the reason each invocation
/// saw.
async fn completed_before_first_dispatch(
    nesting: durable::builders::map_parallel::NestingMode,
) -> Vec<(usize, &'static str)> {
    let seen: Arc<Mutex<Vec<(usize, &'static str)>>> = Arc::default();
    let handler_seen = Arc::clone(&seen);
    let result = LocalRunner::new()
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let seen = Arc::clone(&handler_seen);
                async move {
                    let batch = ctx
                        .map(vec![0_u32, 1, 2], |_, item, _| async move { Ok(item) })
                        .name("b")
                        .nesting(nesting)
                        .completion(CompletionConfig::with_completion_predicate(|_| {
                            CompletionDecision::complete(CompletionOutcome::Succeeded)
                        }))
                        .result_serdes(PaddedSerdes)
                        .await_batch()
                        .await?;
                    let seen_now = (batch.items.len(), batch.reason.as_str());
                    seen.lock().expect("lock").push(seen_now);
                    ctx.wait(Duration::from_secs(1)).name("after").await?;
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert!(result.is_success(), "{result} {:?}", result.error_message());
    std::mem::take(&mut *seen.lock().expect("lock"))
}

/// Both invocations see the same empty batch.
#[tokio::test]
async fn map_completed_before_first_dispatch_with_oversized_result_replays() {
    let nesting = durable::builders::map_parallel::NestingMode::Normal;
    assert_eq!(
        completed_before_first_dispatch(nesting).await,
        vec![(0, "CUSTOM_COMPLETION_SUCCEEDED"); 2]
    );
}

/// A `Flat` batch replays the same summary through the coordinator.
#[tokio::test]
async fn flat_map_completed_before_first_dispatch_with_oversized_result_replays() {
    let nesting = durable::builders::map_parallel::NestingMode::Flat;
    assert_eq!(
        completed_before_first_dispatch(nesting).await,
        vec![(0, "CUSTOM_COMPLETION_SUCCEEDED"); 2]
    );
}

/// An empty map whose predicate completes it stores the oversized summary
/// with that reason. The next invocation replays the recorded reason and
/// does not ask the predicate again, with either nesting.
#[tokio::test]
async fn empty_batch_replay_uses_recorded_reason_without_reinvoking_predicate() {
    for nesting in [
        durable::builders::map_parallel::NestingMode::Normal,
        durable::builders::map_parallel::NestingMode::Flat,
    ] {
        let seen: Calls = Arc::new(Mutex::new(Vec::new()));
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let (handler_seen, handler_calls) = (Arc::clone(&seen), Arc::clone(&calls));
        let result = LocalRunner::new()
            .run(
                move |_event: serde_json::Value, ctx: durable::DurableContext| {
                    let seen = Arc::clone(&handler_seen);
                    let calls = Arc::clone(&handler_calls);
                    let predicate_calls = Arc::clone(&calls);
                    async move {
                        let batch = ctx
                            .map(Vec::<u32>::new(), |_, item, _| async move { Ok(item) })
                            .name("b")
                            .nesting(nesting)
                            .completion(CompletionConfig::with_completion_predicate(move |_| {
                                predicate_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                                CompletionDecision::complete(CompletionOutcome::Succeeded)
                            }))
                            .result_serdes(PaddedSerdes)
                            .await_batch()
                            .await?;
                        seen.lock().expect("lock").push((
                            batch.reason.as_str().to_owned(),
                            calls.load(std::sync::atomic::Ordering::SeqCst),
                        ));
                        ctx.wait(Duration::from_secs(1)).name("after").await?;
                        Ok::<_, durable::BoxError>(())
                    }
                },
                serde_json::Value::Null,
            )
            .await
            .expect("runner");
        assert!(result.is_success(), "{result} {:?}", result.error_message());
        assert_eq!(
            *seen.lock().expect("lock"),
            vec![("CUSTOM_COMPLETION_SUCCEEDED".to_owned(), 1); 2],
            "{nesting:?}: the replay reads the recorded reason and asks nothing"
        );
    }
}

/// Runs `map([0, 1])` with `max_concurrency(2)` and `completion`: item 1
/// fails, and item 0 returns `Ok(7)` after item 1 failed. The batch's own
/// outcome write fails retryably once, so a second invocation resumes the
/// batch from the two recorded item outcomes, which the helper asserts.
/// Returns, for each invocation that got past the batch, its number and
/// what it saw: the reason from `.await_batch()`, or, with `values`, the
/// result of `.await` as `Ok(<values>)` or `Err(<the error's recorded
/// message>)`.
async fn resumed_batch(completion: CompletionConfig, values: bool) -> Vec<(usize, String)> {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let calls = Arc::new(Mutex::new(0_usize));
    let (handler_seen, handler_calls) = (Arc::clone(&seen), Arc::clone(&calls));
    let result = LocalRunner::new()
        .max_invocations(4)
        // Calls 1 and 2 hold the STARTs and the two item outcomes; call 3 is
        // the batch's own outcome.
        .fail_checkpoints_after_retryable(2, 1)
        .run(
            move |_event: serde_json::Value, ctx: durable::DurableContext| {
                let (seen, calls, completion) = (
                    Arc::clone(&handler_seen),
                    Arc::clone(&handler_calls),
                    completion.clone(),
                );
                async move {
                    let invocation = {
                        let mut n = calls.lock().expect("lock");
                        *n += 1;
                        *n
                    };
                    let failed = Arc::new(tokio::sync::Notify::new());
                    let map = ctx
                        .map(vec![0_u32, 1], move |_child, item, _idx| {
                            let failed = Arc::clone(&failed);
                            async move {
                                if item == 1 {
                                    failed.notify_one();
                                    return Err::<u32, durable::BoxError>("item 1 fails".into());
                                }
                                failed.notified().await;
                                Ok(7)
                            }
                        })
                        .max_concurrency(2)
                        .completion(completion);
                    let outcome = if values {
                        match map.await {
                            Ok(values) => format!("Ok({values:?})"),
                            Err(err) => {
                                let wire = err.wire();
                                let message = wire.and_then(durable::WireError::error_message);
                                format!("Err({})", message.unwrap_or_default())
                            }
                        }
                    } else {
                        map.await_batch().await?.reason.as_str().to_owned()
                    };
                    seen.lock().expect("lock").push((invocation, outcome));
                    Ok::<_, durable::BoxError>(())
                }
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert_eq!(
        result.invocation_count(),
        2,
        "the batch outcome write failed once"
    );
    let items: Vec<_> = ["map-item-0", "map-item-1"]
        .iter()
        .map(|name| result.operation(name).expect("the item record").status())
        .collect();
    assert_eq!(
        items,
        [
            durable::OperationStatus::Succeeded,
            durable::OperationStatus::Failed
        ],
        "invocation 1 recorded both item outcomes"
    );
    std::mem::take(&mut *seen.lock().expect("lock"))
}

/// `min_successful(1)` with a tolerance of 0 failures.
fn min_one_no_failure() -> CompletionConfig {
    CompletionConfig::builder()
        .min_successful(1)
        .tolerated_failure_count(0)
        .build()
        .expect("valid completion config")
}

/// Live, item 1's failure settles first and exceeds the tolerance of 0. The
/// resumed batch decides the same on the two recorded outcomes, although
/// item 0's success comes first in index order.
#[tokio::test]
async fn resumed_batch_checks_the_failure_tolerance_on_every_recorded_outcome() {
    assert_eq!(
        resumed_batch(min_one_no_failure(), false).await,
        [(2, "FAILURE_TOLERANCE_EXCEEDED".to_owned())]
    );
}

/// The resumed `.await` returns the recorded failure, not the values.
#[tokio::test]
async fn resumed_batch_await_returns_the_recorded_failure() {
    assert_eq!(
        resumed_batch(min_one_no_failure(), true).await,
        [(2, "Err(item 1 fails)".to_owned())]
    );
}

/// Every item has a recorded outcome, so the resumed batch records
/// `ALL_COMPLETED`, as the live batch does, and not `MIN_SUCCESSFUL_REACHED`.
#[tokio::test]
async fn resumed_batch_with_every_outcome_recorded_is_all_completed() {
    assert_eq!(
        resumed_batch(CompletionConfig::with_min_successful(1), false).await,
        [(2, "ALL_COMPLETED".to_owned())]
    );
}

/// A concurrent batch with no recorded item evaluates no threshold before
/// its first settle: `min_successful(0)` completes at item 0's settle.
#[tokio::test]
async fn concurrent_min_successful_zero_completes_at_first_settle() {
    let result = LocalRunner::new()
        .run(
            |_event: serde_json::Value, ctx: durable::DurableContext| async move {
                let batch = ctx
                    .map(vec![0_u32, 1], |_child, item, _idx| async move {
                        if item == 1 {
                            std::future::pending::<()>().await;
                        }
                        Ok(item)
                    })
                    .max_concurrency(2)
                    .completion(CompletionConfig::with_min_successful(0))
                    .await_batch()
                    .await?;
                let statuses: Vec<String> = batch
                    .items
                    .iter()
                    .map(|i| format!("{:?}", i.status))
                    .collect();
                Ok::<_, durable::BoxError>((batch.reason.as_str().to_owned(), statuses))
            },
            serde_json::Value::Null,
        )
        .await
        .expect("runner");
    assert_eq!(
        result.output().expect("output"),
        &(
            "MIN_SUCCESSFUL_REACHED".to_owned(),
            vec!["Succeeded".to_owned(), "Started".to_owned()]
        )
    );
}