qubit-retry 0.3.1

Retry module, providing a feature-complete, type-safe retry management system with support for multiple delay strategies and event listeners
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
/*******************************************************************************
 *
 *    Copyright (c) 2025 - 2026.
 *    Haixing Hu, Qubit Co. Ltd.
 *
 *    All rights reserved.
 *
 ******************************************************************************/

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

use qubit_retry::{
    AttemptContext, AttemptFailure, Delay, RetryDecision, RetryError, RetryExecutor,
};

use crate::support::{NonCloneValue, TestError};

/// Verifies synchronous success does not require success values to be cloneable.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when success handling requires extra
/// traits or emits the wrong event count.
#[test]
fn test_run_returns_success_without_requiring_success_traits() {
    let success_events = Arc::new(AtomicUsize::new(0));
    let success_events_for_listener = Arc::clone(&success_events);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(3)
        .delay(Delay::none())
        .on_success(move |event| {
            assert_eq!(event.attempts, 1);
            success_events_for_listener.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("executor should be built");

    let value = executor
        .run(|| {
            Ok(NonCloneValue {
                value: "ready".to_string(),
            })
        })
        .expect("operation should succeed");

    assert_eq!(value.value, "ready");
    assert_eq!(success_events.load(Ordering::SeqCst), 1);
}

/// Verifies synchronous retry sleeps on non-zero delays and honors retry_if.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when the retry branch does not reach
/// success after the configured delay.
#[test]
fn test_run_uses_nonzero_sleep_and_retry_if_retry_branch() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .delay(Delay::fixed(Duration::from_millis(1)))
        .retry_if(|_: &TestError, _: &AttemptContext| true)
        .build()
        .expect("executor should be built");

    let result = executor.run(|| {
        let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
        if attempt == 1 {
            Err(TestError("sleep-before-retry"))
        } else {
            Ok("slept")
        }
    });

    assert_eq!(result.expect("retry should eventually succeed"), "slept");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

/// Verifies synchronous retry continues until success and emits retry events.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when attempts or retry event payloads are
/// incorrect.
#[test]
fn test_run_retries_until_success_and_emits_retry_events() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let retry_events = Arc::new(Mutex::new(Vec::new()));
    let retry_events_for_listener = Arc::clone(&retry_events);
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(4)
        .delay(Delay::none())
        .on_retry(move |event, failure| {
            if let AttemptFailure::Error(error) = failure {
                retry_events_for_listener
                    .lock()
                    .expect("retry event list should be lockable")
                    .push((event.attempt, event.max_attempts, event.next_delay, error.0));
            }
        })
        .build()
        .expect("executor should be built");

    let result = executor.run(|| {
        let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
        if attempt < 3 {
            Err(TestError("transient"))
        } else {
            Ok("done")
        }
    });

    assert_eq!(result.expect("retry should eventually succeed"), "done");
    assert_eq!(attempts.load(Ordering::SeqCst), 3);
    assert_eq!(
        *retry_events
            .lock()
            .expect("retry event list should be lockable"),
        vec![
            (1, 4, Duration::ZERO, "transient"),
            (2, 4, Duration::ZERO, "transient")
        ]
    );
}

/// Verifies retry_if can abort and preserve the original application error.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when abort events or preserved errors are
/// incorrect.
#[test]
fn test_retry_if_can_abort_and_preserve_original_error() {
    let abort_events = Arc::new(AtomicUsize::new(0));
    let abort_events_for_listener = Arc::clone(&abort_events);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(3)
        .delay(Delay::none())
        .retry_if(|error: &TestError, _: &AttemptContext| error.0 == "retry")
        .on_abort(move |event, failure| {
            assert_eq!(event.attempts, 1);
            assert!(matches!(failure, AttemptFailure::Error(TestError("fatal"))));
            abort_events_for_listener.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("executor should be built");

    let error = executor
        .run(|| -> Result<(), TestError> { Err(TestError("fatal")) })
        .expect_err("fatal error should abort retries");

    assert_eq!(abort_events.load(Ordering::SeqCst), 1);
    assert_eq!(error.attempts(), 1);
    assert_eq!(error.last_error(), Some(&TestError("fatal")));
    assert_eq!(error.into_last_error(), Some(TestError("fatal")));
}

/// Verifies classifiers can inspect attempt context before deciding.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when context values or abort decisions are
/// incorrect.
#[test]
fn test_classify_error_can_use_attempt_context() {
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(4)
        .delay(Delay::none())
        .classify_error(|_, context| {
            assert!(context.attempt <= context.max_attempts);
            if context.attempt < 2 {
                RetryDecision::Retry
            } else {
                RetryDecision::Abort
            }
        })
        .build()
        .expect("executor should be built");

    let error = executor
        .run(|| -> Result<(), TestError> { Err(TestError("still-bad")) })
        .expect_err("classifier should abort on second attempt");

    assert!(matches!(error, RetryError::Aborted { attempts: 2, .. }));
}

/// Verifies attempt exhaustion emits a failure event and preserves last error.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when exhaustion metadata or failure events
/// are incorrect.
#[test]
fn test_attempts_exceeded_emits_failure_event_and_preserves_last_error() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let failures = Arc::new(Mutex::new(Vec::new()));
    let failures_for_listener = Arc::clone(&failures);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .delay(Delay::none())
        .on_failure(move |event, failure| {
            let failure = match failure {
                Some(AttemptFailure::Error(error)) => error.0,
                _ => "missing",
            };
            failures_for_listener
                .lock()
                .expect("failure event list should be lockable")
                .push((event.attempts, failure));
        })
        .build()
        .expect("executor should be built");

    let error = executor
        .run(|| -> Result<(), TestError> {
            let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
            if attempt == 1 {
                Err(TestError("first"))
            } else {
                Err(TestError("second"))
            }
        })
        .expect_err("attempt limit should be exceeded");

    assert!(matches!(
        error,
        RetryError::AttemptsExceeded {
            attempts: 2,
            max_attempts: 2,
            ..
        }
    ));
    assert_eq!(error.last_error(), Some(&TestError("second")));
    assert_eq!(
        *failures
            .lock()
            .expect("failure event list should be lockable"),
        vec![(2, "second")]
    );
}

/// Verifies zero elapsed budget can stop before the first attempt.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when the operation runs or failure
/// metadata is incorrect.
#[test]
fn test_max_elapsed_can_stop_before_first_attempt() {
    let failures = Arc::new(Mutex::new(Vec::new()));
    let failures_for_listener = Arc::clone(&failures);
    let executor = RetryExecutor::<TestError>::builder()
        .max_elapsed(Some(Duration::ZERO))
        .on_failure(move |event, failure| {
            failures_for_listener
                .lock()
                .expect("failure event list should be lockable")
                .push((event.attempts, failure.is_none()));
        })
        .build()
        .expect("executor should be built");

    let error = executor
        .run(|| -> Result<(), TestError> { panic!("operation must not run") })
        .expect_err("elapsed budget should stop before first attempt");

    assert!(matches!(
        error,
        RetryError::MaxElapsedExceeded {
            attempts: 0,
            last_failure: None,
            ..
        }
    ));
    assert_eq!(
        *failures
            .lock()
            .expect("failure event list should be lockable"),
        vec![(0, true)]
    );
}

/// Verifies elapsed budget stops when the next retry sleep would exceed it.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when retry events are emitted or the wrong
/// terminal error is returned.
#[test]
fn test_max_elapsed_stops_when_retry_sleep_would_exceed_budget() {
    let retry_events = Arc::new(AtomicUsize::new(0));
    let retry_events_for_listener = Arc::clone(&retry_events);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(3)
        .max_elapsed(Some(Duration::from_millis(1)))
        .delay(Delay::fixed(Duration::from_millis(10)))
        .on_retry(move |_, _| {
            retry_events_for_listener.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("executor should be built");

    let error = executor
        .run(|| -> Result<(), TestError> { Err(TestError("late")) })
        .expect_err("elapsed budget should reject retry sleep");

    assert_eq!(retry_events.load(Ordering::SeqCst), 0);
    assert!(matches!(
        error,
        RetryError::MaxElapsedExceeded {
            attempts: 1,
            last_failure: Some(AttemptFailure::Error(TestError("late"))),
            ..
        }
    ));
}

/// Verifies elapsed budget allows retry sleeps that remain within the budget.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when a retry inside the elapsed budget is
/// rejected or the retry event is missing.
#[test]
fn test_max_elapsed_allows_retry_sleep_within_budget() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let retry_events = Arc::new(AtomicUsize::new(0));
    let retry_events_for_listener = Arc::clone(&retry_events);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .max_elapsed(Some(Duration::from_millis(100)))
        .delay(Delay::fixed(Duration::from_millis(1)))
        .on_retry(move |_, _| {
            retry_events_for_listener.fetch_add(1, Ordering::SeqCst);
        })
        .build()
        .expect("executor should be built");

    let result = executor
        .run(|| {
            let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
            if attempt == 1 {
                Err(TestError("within-budget"))
            } else {
                Ok("retried")
            }
        })
        .expect("retry inside elapsed budget should succeed");

    assert_eq!(result, "retried");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
    assert_eq!(retry_events.load(Ordering::SeqCst), 1);
}

/// Verifies asynchronous retry continues until success.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when async retry attempts or returned
/// values are incorrect.
#[tokio::test]
async fn test_run_async_retries_until_success() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(3)
        .delay(Delay::none())
        .build()
        .expect("executor should be built");

    let result = executor
        .run_async(|| {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
                if attempt == 1 {
                    Err(TestError("retry"))
                } else {
                    Ok(NonCloneValue {
                        value: "async-ready".to_string(),
                    })
                }
            }
        })
        .await
        .expect("async retry should eventually succeed");

    assert_eq!(result.value, "async-ready");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

/// Verifies zero elapsed budget stops async execution before the first attempt.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when the async operation runs or the wrong
/// terminal error is returned.
#[tokio::test]
async fn test_run_async_can_stop_before_first_attempt() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_elapsed(Some(Duration::ZERO))
        .build()
        .expect("executor should be built");

    let error = executor
        .run_async(|| {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                attempts_for_operation.fetch_add(1, Ordering::SeqCst);
                Ok::<_, TestError>("must-not-run")
            }
        })
        .await
        .expect_err("elapsed budget should stop before first async attempt");

    assert_eq!(attempts.load(Ordering::SeqCst), 0);
    assert!(matches!(
        error,
        RetryError::MaxElapsedExceeded { attempts: 0, .. }
    ));
}

/// Verifies async retry sleeps on non-zero delays between attempts.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when async retry does not eventually
/// succeed after the configured delay.
#[tokio::test]
async fn test_run_async_uses_nonzero_sleep_between_attempts() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .delay(Delay::fixed(Duration::from_millis(1)))
        .build()
        .expect("executor should be built");

    let result = executor
        .run_async(|| {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
                if attempt == 1 {
                    Err(TestError("async-sleep"))
                } else {
                    Ok("async-slept")
                }
            }
        })
        .await
        .expect("async retry should eventually succeed");

    assert_eq!(result, "async-slept");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

/// Verifies async execution returns a terminal error from a failed attempt.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when attempt exhaustion metadata is
/// incorrect.
#[tokio::test]
async fn test_run_async_returns_finished_error_from_failed_attempt() {
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(1)
        .delay(Delay::none())
        .build()
        .expect("executor should be built");

    let error = executor
        .run_async(|| async { Err::<(), TestError>(TestError("async-exhausted")) })
        .await
        .expect_err("single failed attempt should exhaust retries");

    assert!(matches!(
        error,
        RetryError::AttemptsExceeded {
            attempts: 1,
            max_attempts: 1,
            last_failure: AttemptFailure::Error(TestError("async-exhausted")),
            ..
        }
    ));
}

/// Verifies timed async attempts can retry after timeout and then succeed.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when timeout retry events or attempt
/// counts are incorrect.
#[tokio::test]
async fn test_run_async_with_timeout_can_retry_and_succeed() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let retry_timeouts = Arc::new(AtomicUsize::new(0));
    let retry_timeouts_for_listener = Arc::clone(&retry_timeouts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .delay(Delay::fixed(Duration::from_millis(1)))
        .on_retry(move |_, failure| {
            if matches!(failure, AttemptFailure::AttemptTimeout { .. }) {
                retry_timeouts_for_listener.fetch_add(1, Ordering::SeqCst);
            }
        })
        .build()
        .expect("executor should be built");

    let result = executor
        .run_async_with_timeout(Duration::from_millis(5), || {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
                if attempt == 1 {
                    tokio::time::sleep(Duration::from_millis(30)).await;
                    Ok("too-late")
                } else {
                    Ok("ok")
                }
            }
        })
        .await
        .expect("timeout retry should eventually succeed");

    assert_eq!(result, "ok");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
    assert_eq!(retry_timeouts.load(Ordering::SeqCst), 1);
}

/// Verifies timed async attempts retry operation errors with sleep.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when operation errors are not retried
/// under the per-attempt timeout wrapper.
#[tokio::test]
async fn test_run_async_with_timeout_can_retry_operation_errors_with_sleep() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(2)
        .delay(Delay::fixed(Duration::from_millis(1)))
        .build()
        .expect("executor should be built");

    let result = executor
        .run_async_with_timeout(Duration::from_millis(50), || {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                let attempt = attempts_for_operation.fetch_add(1, Ordering::SeqCst) + 1;
                if attempt == 1 {
                    Err(TestError("retry-error"))
                } else {
                    Ok("timeout-error-retried")
                }
            }
        })
        .await
        .expect("operation error should be retried before timeout");

    assert_eq!(result, "timeout-error-retried");
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

/// Verifies timed async execution preserves operation errors on exhaustion.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when the terminal error does not preserve
/// the operation error.
#[tokio::test]
async fn test_run_async_with_timeout_returns_finished_error_from_operation_error() {
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(1)
        .delay(Delay::none())
        .build()
        .expect("executor should be built");

    let error = executor
        .run_async_with_timeout(Duration::from_millis(50), || async {
            Err::<(), TestError>(TestError("timeout-operation-error"))
        })
        .await
        .expect_err("single operation error should exhaust retries");

    assert!(matches!(
        error,
        RetryError::AttemptsExceeded {
            attempts: 1,
            max_attempts: 1,
            last_failure: AttemptFailure::Error(TestError("timeout-operation-error")),
            ..
        }
    ));
}

/// Verifies zero elapsed budget stops timed async execution before attempts.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when the timed operation runs or the wrong
/// terminal error is returned.
#[tokio::test]
async fn test_run_async_with_timeout_can_stop_before_first_attempt() {
    let attempts = Arc::new(AtomicUsize::new(0));
    let attempts_for_operation = Arc::clone(&attempts);
    let executor = RetryExecutor::<TestError>::builder()
        .max_elapsed(Some(Duration::ZERO))
        .build()
        .expect("executor should be built");

    let error = executor
        .run_async_with_timeout(Duration::from_millis(50), || {
            let attempts_for_operation = Arc::clone(&attempts_for_operation);
            async move {
                attempts_for_operation.fetch_add(1, Ordering::SeqCst);
                Ok::<_, TestError>("must-not-run")
            }
        })
        .await
        .expect_err("elapsed budget should stop before first timed attempt");

    assert_eq!(attempts.load(Ordering::SeqCst), 0);
    assert!(matches!(
        error,
        RetryError::MaxElapsedExceeded { attempts: 0, .. }
    ));
}

/// Verifies timed async exhaustion returns timeout failure metadata.
///
/// # Parameters
/// This test has no parameters.
///
/// # Returns
/// This test returns nothing.
///
/// # Errors
/// The test fails through assertions when timeout exhaustion does not return an
/// attempt-timeout failure.
#[tokio::test]
async fn test_run_async_with_timeout_exhaustion_returns_timeout_failure() {
    let executor = RetryExecutor::<TestError>::builder()
        .max_attempts(1)
        .delay(Delay::none())
        .build()
        .expect("executor should be built");

    let error = executor
        .run_async_with_timeout(Duration::from_millis(2), || async {
            tokio::time::sleep(Duration::from_millis(20)).await;
            Ok::<(), TestError>(())
        })
        .await
        .expect_err("timed out attempt should exhaust retries");

    assert!(matches!(
        error,
        RetryError::AttemptsExceeded {
            attempts: 1,
            max_attempts: 1,
            last_failure: AttemptFailure::AttemptTimeout { .. },
            ..
        }
    ));
    assert_eq!(error.into_last_error(), None);
}