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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! The polling operation: [`WaitForConditionBuilder`], returned by
//! [`DurableContext::wait_for_condition`](crate::DurableContext::wait_for_condition),
//! plus its configuration ([`WaitStrategy`]) and the per-check decision
//! type ([`WaitDecision`]).
//!
//! The [wait-for-condition operation guide](https://docs.aws.amazon.com/durable-execution/sdk-reference/operations/wait-for-condition/)
//! describes this operation independently of any language SDK.

use std::future::{Future, IntoFuture};
use std::time::Duration;

use crate::BoxError;
use crate::Serdes;
use crate::context::DurableContext;
use crate::context::StepContext;
use crate::engine::OperationId;
use crate::error::OperationError;
use crate::future::DurableFuture;
use crate::serdes::JsonSerdes;

pub use crate::wait_for_condition::WaitDecision;

/// The wait-strategy state of a [`WaitForConditionBuilder`] that has no
/// strategy yet.
///
/// [`DurableContext::wait_for_condition`] returns a builder in this state.
/// A builder in this state cannot be awaited and has no
/// [`future`](WaitForConditionBuilder::future) or
/// [`spawn`](WaitForConditionBuilder::spawn) method: call
/// [`wait_strategy`](WaitForConditionBuilder::wait_strategy) or
/// [`wait_strategy_fn`](WaitForConditionBuilder::wait_strategy_fn) to move
/// it to [`WithWaitStrategy`].
pub struct NoWaitStrategy {
    _private: (),
}

impl std::fmt::Debug for NoWaitStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NoWaitStrategy").finish()
    }
}

/// The wait-strategy state of a [`WaitForConditionBuilder`] that holds a
/// wait strategy for the state type `S`.
///
/// [`wait_strategy`](WaitForConditionBuilder::wait_strategy) and
/// [`wait_strategy_fn`](WaitForConditionBuilder::wait_strategy_fn) return a
/// builder in this state. Only a builder in this state implements
/// [`IntoFuture`] and has [`future`](WaitForConditionBuilder::future) and
/// [`spawn`](WaitForConditionBuilder::spawn).
pub struct WithWaitStrategy<S> {
    strategy: crate::wait_for_condition::WaitStrategyFn<S>,
}

impl<S> std::fmt::Debug for WithWaitStrategy<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WithWaitStrategy").finish_non_exhaustive()
    }
}

/// Builder for a wait-for-condition operation.
///
/// Created by [`DurableContext::wait_for_condition`]. A wait strategy is
/// required: set it with [`wait_strategy`](Self::wait_strategy) (a bounded
/// [`WaitStrategy`] configuration) or
/// [`wait_strategy_fn`](Self::wait_strategy_fn) (a custom closure). After
/// each check, the strategy decides whether the operation completes,
/// continues polling after a delay, or exhausts.
///
/// The builder is generic over the check closure `F` and its future
/// `Fut`; both parameters are inferred at the call site and never written
/// by users. `SD` is the state's serdes, [`JsonSerdes`] unless
/// [`serdes`](Self::serdes) replaces it. `WS` is the wait-strategy state:
/// [`NoWaitStrategy`] when the builder is created, and
/// [`WithWaitStrategy<S>`] once either strategy setter has run.
///
/// Only a builder in the [`WithWaitStrategy<S>`] state implements
/// [`IntoFuture`] and has [`future`](Self::future) and
/// [`spawn`](Self::spawn), so code that awaits, converts or spawns a
/// builder without a strategy fails to compile. [`name`](Self::name) and
/// [`serdes`](Self::serdes) keep the strategy state, in any order.
///
/// # Examples
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use aws_durable_execution_sdk::builders::wait_for_condition::WaitDecision;
/// use serde::{Serialize, Deserialize};
/// use std::time::Duration;
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct State { ready: bool }
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     ctx.wait_for_condition(
///         |_, state: State| async move { Ok(State { ready: true }) },
///         State { ready: false },
///     ).name("wait-ready")
///      .wait_strategy_fn(|state: State, _attempt| {
///          if state.ready {
///              WaitDecision::complete()
///          } else {
///              WaitDecision::continue_with(Duration::from_secs(5))
///          }
///      })
///      .await?;
///     Ok(())
/// }
/// ```
///
/// [`serdes`](Self::serdes) and [`name`](Self::name) after the strategy
/// keep it:
///
/// ```no_run
/// use aws_durable_execution_sdk as durable;
/// use aws_durable_execution_sdk::builders::wait_for_condition::WaitDecision;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let state: i32 = ctx
///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
///         .wait_strategy_fn(|_state: i32, _attempt| WaitDecision::complete())
///         .serdes(durable::JsonSerdes)
///         .name("poll")
///         .await?;
///     assert!(state >= 1);
///     Ok(())
/// }
/// ```
///
/// Awaiting a builder without a strategy fails to compile:
///
/// ```compile_fail,E0277
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let state: i32 = ctx
///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
///         .name("poll")
///         .await?;
///     assert!(state >= 1);
///     Ok(())
/// }
/// ```
///
/// A builder without a strategy has no `future` method, also after
/// [`serdes`](Self::serdes):
///
/// ```compile_fail,E0599
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let future: durable::DurableFuture<i32> = ctx
///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
///         .serdes(durable::JsonSerdes)
///         .name("poll")
///         .future();
///     let state = future.await?;
///     assert!(state >= 1);
///     Ok(())
/// }
/// ```
///
/// A builder without a strategy has no `spawn` method:
///
/// ```compile_fail,E0599
/// use aws_durable_execution_sdk as durable;
///
/// async fn handler(
///     _event: serde_json::Value,
///     ctx: durable::DurableContext,
/// ) -> Result<(), durable::BoxError> {
///     let handle: durable::DurableFuture<i32> = ctx
///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
///         .name("poll")
///         .spawn();
///     let state = handle.await?;
///     assert!(state >= 1);
///     Ok(())
/// }
/// ```
#[must_use = "wait-for-condition builders do nothing unless configured with a wait strategy and awaited or spawned"]
#[non_exhaustive]
pub struct WaitForConditionBuilder<S, F, Fut, SD = JsonSerdes, WS = NoWaitStrategy> {
    ctx: DurableContext,
    op_id: OperationId,
    name: Option<String>,
    initial_state: S,
    wait_strategy: WS,
    serdes: SD,
    check: F,
    _marker: std::marker::PhantomData<fn() -> Fut>,
}

impl<S, F, Fut, SD, WS> std::fmt::Debug for WaitForConditionBuilder<S, F, Fut, SD, WS> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaitForConditionBuilder")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl<S, F, Fut> WaitForConditionBuilder<S, F, Fut>
where
    S: Clone + Send + Sync + 'static,
    F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
{
    /// Creates a new builder (internal), in the [`NoWaitStrategy`] state.
    /// Taking the check closure here keeps the field non-optional: a
    /// builder without a check is unrepresentable.
    pub(crate) fn new_internal(
        ctx: DurableContext,
        op_id: OperationId,
        initial_state: S,
        check: F,
    ) -> Self {
        Self {
            ctx,
            op_id,
            name: None,
            initial_state,
            wait_strategy: NoWaitStrategy { _private: () },
            serdes: JsonSerdes,
            check,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<S, F, Fut, SD, WS> WaitForConditionBuilder<S, F, Fut, SD, WS>
where
    S: Clone + Send + Sync + 'static,
    F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
{
    /// Sets a human-readable name for this operation.
    ///
    /// Keeps the builder's wait-strategy state.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Returns this builder in the [`WithWaitStrategy`] state, holding
    /// `strategy`.
    fn with_strategy(
        self,
        strategy: crate::wait_for_condition::WaitStrategyFn<S>,
    ) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>> {
        WaitForConditionBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            initial_state: self.initial_state,
            wait_strategy: WithWaitStrategy { strategy },
            serdes: self.serdes,
            check: self.check,
            _marker: std::marker::PhantomData,
        }
    }

    /// Sets the wait strategy from a [`WaitStrategy`] configuration.
    ///
    /// The configuration carries a completion predicate over the state, an
    /// attempt cap, and exponential-backoff delay shaping. After each check,
    /// the derived strategy returns [`WaitDecision::Complete`] when the
    /// predicate matches the new state, [`WaitDecision::Exhausted`] once
    /// `max_attempts` checks have run without the predicate matching, and
    /// [`WaitDecision::Continue`] with the computed backoff delay otherwise.
    ///
    /// Returns the builder in the [`WithWaitStrategy`] state, which can be
    /// awaited, converted with [`future`](Self::future) or started with
    /// [`spawn`](Self::spawn). A second call of this method or of
    /// [`wait_strategy_fn`](Self::wait_strategy_fn) replaces the existing
    /// strategy.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    /// use aws_durable_execution_sdk::builders::wait_for_condition::WaitStrategy;
    /// use std::time::Duration;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<i32, durable::BoxError> {
    ///     let done = ctx
    ///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
    ///         .wait_strategy(
    ///             WaitStrategy::builder(|state: &i32| *state >= 3)
    ///                 .max_attempts(10)
    ///                 .initial_delay(Duration::from_secs(2))
    ///                 .max_delay(Duration::from_secs(30))
    ///                 .build(),
    ///         )
    ///         .await?;
    ///     Ok(done)
    /// }
    /// ```
    pub fn wait_strategy(
        self,
        strategy: WaitStrategy<S>,
    ) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>> {
        self.with_strategy(Box::new(move |state: S, attempt: u32| {
            strategy.decide(&state, attempt)
        }))
    }

    /// Sets a custom wait strategy closure.
    ///
    /// The strategy receives the current (deserialized) state and the
    /// attempt number (starting at 1), and returns a [`WaitDecision`].
    ///
    /// The closure is responsible for termination: return
    /// [`WaitDecision::complete`] when the condition is met, and bound the
    /// polling with [`WaitDecision::exhausted`] (for example once `attempt`
    /// reaches a cap) so the operation cannot poll until the execution
    /// times out. Prefer [`wait_strategy`](Self::wait_strategy) when a
    /// predicate plus attempt cap expresses the condition: it makes the
    /// bound impossible to forget.
    ///
    /// Returns the builder in the [`WithWaitStrategy`] state, which can be
    /// awaited, converted with [`future`](Self::future) or started with
    /// [`spawn`](Self::spawn). A second call of this method or of
    /// [`wait_strategy`](Self::wait_strategy) replaces the existing
    /// strategy.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use aws_durable_execution_sdk as durable;
    /// use aws_durable_execution_sdk::builders::wait_for_condition::WaitDecision;
    /// use std::time::Duration;
    ///
    /// async fn handler(
    ///     _event: serde_json::Value,
    ///     ctx: durable::DurableContext,
    /// ) -> Result<i32, durable::BoxError> {
    ///     let done = ctx
    ///         .wait_for_condition(|_step_ctx, state: i32| async move { Ok(state + 1) }, 0_i32)
    ///         .wait_strategy_fn(|state: i32, _attempt| {
    ///             if state >= 3 {
    ///                 WaitDecision::complete()
    ///             } else {
    ///                 WaitDecision::continue_with(Duration::from_secs(1))
    ///             }
    ///         })
    ///         .await?;
    ///     Ok(done)
    /// }
    /// ```
    pub fn wait_strategy_fn<W>(
        self,
        strategy: W,
    ) -> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
    where
        W: Fn(S, u32) -> WaitDecision + Send + Sync + 'static,
    {
        self.with_strategy(Box::new(strategy))
    }

    /// Sets a custom serializer/deserializer for the state.
    ///
    /// Replaces the builder's serdes type parameter with `SD2`, which must
    /// implement [`Serdes<S>`](crate::Serdes) for this operation's state
    /// type: attaching a serdes for a different type fails at compile
    /// time. To share one instance across operations, wrap it in an
    /// [`Arc`](std::sync::Arc) and clone the `Arc` handle into each builder.
    ///
    /// Keeps the builder's wait-strategy state: a serdes neither sets nor
    /// removes the required wait strategy.
    pub fn serdes<SD2>(self, serdes: SD2) -> WaitForConditionBuilder<S, F, Fut, SD2, WS>
    where
        SD2: Serdes<S>,
    {
        WaitForConditionBuilder {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            initial_state: self.initial_state,
            wait_strategy: self.wait_strategy,
            serdes,
            check: self.check,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<S, F, Fut, SD> WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
where
    S: Clone + Send + Sync + 'static,
    F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
    SD: Serdes<S>,
{
    /// Converts this builder into a [`DurableFuture`] without starting it.
    ///
    /// Available once a wait strategy is set.
    ///
    /// [`DurableFuture`] is the one input type the combinators
    /// ([`DurableContext::try_join_all`], [`DurableContext::join_all`],
    /// [`DurableContext::select_ok`], and [`DurableContext::race`]) accept,
    /// so `.future()` is how operations of different kinds join or race
    /// together. It does not start the operation: whatever awaits the
    /// returned future drives it, and a combinator drops the losers.
    ///
    /// A combinator begins its `.future()` inputs' start phases, in input
    /// order, before its own start step. This operation first serializes
    /// its input, so the combinator polls it once on its own task, and does
    /// not wait for its `START`: its `START` and its start hook can come
    /// after the combinator's. A replay of the combinator's final record
    /// starts no `.future()` input.
    ///
    /// A handle that [`.spawn()`](Self::spawn) returned already runs on its
    /// own task. A combinator that receives it never starts it again, and
    /// it keeps running independently: when the combinator resolves first,
    /// it does not cancel the handle, and the handle's result is dropped.
    pub fn future(self) -> DurableFuture<S> {
        <Self as IntoFuture>::into_future(self)
    }

    /// Eagerly spawns the operation on a tokio task.
    ///
    /// Available once a wait strategy is set.
    ///
    /// The returned [`DurableFuture`] is already running; this is the
    /// replay-safe alternative to bare `tokio::spawn` for durable
    /// operations.
    ///
    /// Dropping the returned future loses only the result: the operation
    /// runs until it settles. The SDK stops it earlier only when the scope
    /// it was started in closes, such as a child context whose body
    /// returned, or when the invocation ends. The SDK also stops the
    /// `.future()` inputs a combinator started. A stopped task stops at its
    /// next `.await`, and its record can stay `STARTED`. The SDK cannot stop
    /// code between two `.await`s, `spawn_blocking` work, tasks or threads
    /// the handler starts itself, or a request already sent to another
    /// service.
    ///
    /// The SDK refreshes the condition while it waits for its next check
    /// whether or not anything polls the returned future, so its next check
    /// runs in the same invocation when its delay ends while other work
    /// runs.
    ///
    /// Unlike `.spawn()` of a step, a wait or a child context, `.spawn()`
    /// of a `wait_for_condition` runs no start step on the caller's task: the spawned task
    /// runs the whole operation, including the `START`, so that `START` can
    /// follow updates the caller sends after `.spawn()` returns. The
    /// caller's task ownership is checked before the operation is built,
    /// not on the spawned task, so that error wins over a replay mismatch:
    /// a `.spawn()` from a task or thread that does not own the context
    /// fails the execution with a context usage error, returns a handle
    /// that resolves to the task-ownership error, queues no `START` and
    /// runs no body.
    ///
    /// # Errors
    ///
    /// When the invocation coordinator was created without a Tokio runtime,
    /// the returned future resolves to an error and the operation records
    /// nothing.
    pub fn spawn(self) -> DurableFuture<S> {
        spawn_terminal!(self)
    }
}

impl<S, F, Fut, SD> IntoFuture for WaitForConditionBuilder<S, F, Fut, SD, WithWaitStrategy<S>>
where
    S: Clone + Send + Sync + 'static,
    F: Fn(StepContext, S) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<S, BoxError>> + Send + 'static,
    SD: Serdes<S>,
{
    type Output = Result<S, OperationError>;
    type IntoFuture = DurableFuture<S>;

    fn into_future(self) -> Self::IntoFuture {
        use crate::wait_for_condition::WaitForConditionExecution;

        preflight_identity!(self, "Step", crate::wait_for_condition::WFC_SUB_TYPE);

        let gate = self.ctx.clone();

        let execution = WaitForConditionExecution {
            ctx: self.ctx,
            op_id: self.op_id,
            name: self.name,
            initial_state: self.initial_state,
            wait_strategy: self.wait_strategy.strategy,
            serdes: self.serdes,
            check: self.check,
        };

        DurableFuture::for_first_poll_operation(&gate, execution.execute())
    }
}

/// Configuration for the wait strategy used by
/// [`DurableContext::wait_for_condition`].
///
/// Carries the three things a bounded poll needs: a **completion
/// predicate** over the state (the operation completes when it returns
/// `true`), an attempt cap (**`max_attempts`**: reaching it without the
/// predicate matching fails the operation with a `MaxChecksExceeded`
/// error), and exponential-backoff **delay shaping** (`initial_delay`,
/// `max_delay`, `backoff_rate`, `jitter`) for the suspension between
/// checks.
///
/// The predicate is required at construction: [`WaitStrategy::builder`]
/// takes it as its argument, so a strategy that polls forever cannot be
/// constructed. The remaining knobs default to 60 attempts, a 5 second
/// initial delay, a 5 minute maximum delay, a 1.5 backoff rate, and
/// [`JitterStrategy::Full`](crate::builders::JitterStrategy), matching the
/// JS and Python SDK defaults.
///
/// The delay before check `n + 1` is `initial_delay * backoff_rate^(n - 1)`
/// capped at `max_delay`, jittered per
/// [`JitterStrategy`](crate::builders::JitterStrategy), and rounded to
/// the nearest whole second with a one-second minimum, for every jitter
/// mode, as in the JS and Go SDKs. A delay that a custom
/// [`wait_strategy_fn`](WaitForConditionBuilder::wait_strategy_fn) closure
/// returns is rounded up to whole seconds instead, with the same one-second
/// minimum, so it never ends early.
///
/// Read values back through the accessors.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::wait_for_condition::WaitStrategy;
/// use std::time::Duration;
///
/// let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
///     .max_attempts(10)
///     .initial_delay(Duration::from_secs(2))
///     .build();
/// assert_eq!(strategy.max_attempts(), 10);
/// // Unset knobs keep the JS/Python-aligned defaults.
/// assert_eq!(strategy.max_delay(), Duration::from_mins(5));
/// assert!((strategy.backoff_rate() - 1.5).abs() < f64::EPSILON);
/// ```
#[non_exhaustive]
// Fields are private so the struct can grow without breaking callers;
// see the Rust API Guidelines on structs with private fields:
// https://rust-lang.github.io/api-guidelines/future-proofing.html#c-struct-private
pub struct WaitStrategy<S> {
    /// Predicate over the state; `true` completes the operation.
    completion_predicate: std::sync::Arc<dyn Fn(&S) -> bool + Send + Sync>,
    /// Total number of checks allowed before the operation exhausts.
    max_attempts: u32,
    /// Initial delay between condition checks.
    initial_delay: Duration,
    /// Maximum delay between condition checks.
    max_delay: Duration,
    /// Backoff multiplier applied after each check.
    backoff_rate: f64,
    /// Jitter applied to each computed delay.
    jitter: crate::builders::JitterStrategy,
}

/// Default `max_attempts`, aligned with the JS and Python SDKs.
const DEFAULT_MAX_ATTEMPTS: u32 = 60;
/// Default `initial_delay`, aligned with the JS and Python SDKs.
const DEFAULT_INITIAL_DELAY: Duration = Duration::from_secs(5);
/// Default `max_delay`, aligned with the JS and Python SDKs.
const DEFAULT_MAX_DELAY: Duration = Duration::from_mins(5);
/// Default `backoff_rate`, aligned with the JS and Python SDKs.
const DEFAULT_BACKOFF_RATE: f64 = 1.5;

impl<S> std::fmt::Debug for WaitStrategy<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaitStrategy")
            .field("max_attempts", &self.max_attempts)
            .field("initial_delay", &self.initial_delay)
            .field("max_delay", &self.max_delay)
            .field("backoff_rate", &self.backoff_rate)
            .field("jitter", &self.jitter)
            .finish_non_exhaustive()
    }
}

impl<S> Clone for WaitStrategy<S> {
    fn clone(&self) -> Self {
        Self {
            completion_predicate: std::sync::Arc::clone(&self.completion_predicate),
            max_attempts: self.max_attempts,
            initial_delay: self.initial_delay,
            max_delay: self.max_delay,
            backoff_rate: self.backoff_rate,
            jitter: self.jitter,
        }
    }
}

impl<S> WaitStrategy<S> {
    /// Creates a new [`WaitStrategyBuilder`] from the required completion
    /// predicate.
    ///
    /// The predicate receives the state each check produced and returns
    /// `true` when the condition is met, which completes the operation.
    /// Taking it here, rather than through an optional setter, makes an
    /// unbounded strategy unrepresentable. Knobs left unset keep the
    /// JS/Python-aligned defaults (60 attempts, 5s initial delay, 5min
    /// maximum delay, 1.5 backoff rate, full jitter).
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::builders::wait_for_condition::WaitStrategy;
    ///
    /// let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
    ///     .backoff_rate(2.0)
    ///     .build();
    /// assert!((strategy.backoff_rate() - 2.0).abs() < f64::EPSILON);
    /// assert_eq!(strategy.max_attempts(), 60);
    /// ```
    pub fn builder<P>(completion_predicate: P) -> WaitStrategyBuilder<S>
    where
        P: Fn(&S) -> bool + Send + Sync + 'static,
    {
        WaitStrategyBuilder {
            completion_predicate: std::sync::Arc::new(completion_predicate),
            max_attempts: None,
            initial_delay: None,
            max_delay: None,
            backoff_rate: None,
            jitter: None,
        }
    }

    /// Returns the total number of checks allowed before the operation
    /// exhausts.
    pub fn max_attempts(&self) -> u32 {
        self.max_attempts
    }

    /// Returns the initial delay between condition checks.
    pub fn initial_delay(&self) -> Duration {
        self.initial_delay
    }

    /// Returns the maximum delay between condition checks.
    pub fn max_delay(&self) -> Duration {
        self.max_delay
    }

    /// Returns the backoff multiplier applied after each check.
    pub fn backoff_rate(&self) -> f64 {
        self.backoff_rate
    }

    /// Returns the jitter applied to each computed delay.
    pub fn jitter(&self) -> crate::builders::JitterStrategy {
        self.jitter
    }

    /// Computes the wait decision after a check produced `state` on the
    /// 1-based attempt `attempt`.
    ///
    /// Order matters: the predicate is consulted first, so a condition
    /// satisfied on the final allowed check completes rather than
    /// exhausting. Exhaustion carries the attempt count in its reason.
    pub(crate) fn decide(&self, state: &S, attempt: u32) -> WaitDecision {
        if (self.completion_predicate)(state) {
            return WaitDecision::Complete;
        }
        if attempt >= self.max_attempts {
            return WaitDecision::exhausted(format!(
                "max attempts exceeded: {attempt} checks completed (max_attempts = {})",
                self.max_attempts
            ));
        }

        // Exponential backoff: initial * rate^(attempt-1), capped at max,
        // jittered, then rounded to the nearest whole second with a
        // one-second minimum: see `crate::step::quantize_delay`.
        let exponent = i32::try_from(attempt).unwrap_or(1) - 1;
        let base = (self.initial_delay.as_secs_f64() * self.backoff_rate.powi(exponent))
            .min(self.max_delay.as_secs_f64());
        let jittered = match self.jitter {
            crate::builders::JitterStrategy::None => base,
            // Half jitter: base/2 plus random in [0, base/2] => [base/2, base].
            crate::builders::JitterStrategy::Half => {
                base / 2.0 + crate::step::rand_full_jitter(base / 2.0)
            }
            // Full jitter: random in [0, base].
            crate::builders::JitterStrategy::Full => crate::step::rand_full_jitter(base),
        };
        WaitDecision::continue_with(crate::step::quantize_delay(jittered))
    }
}

/// Builder for [`WaitStrategy`].
///
/// Created by [`WaitStrategy::builder`], which takes the required
/// completion predicate. Follows the Rust API Guidelines C-BUILDER
/// pattern: all methods consume and return `self` for chaining, and knobs
/// left unset keep the JS/Python-aligned defaults (60 attempts, 5s initial
/// delay, 5min maximum delay, 1.5 backoff rate,
/// [`JitterStrategy::Full`](crate::builders::JitterStrategy)).
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::builders::JitterStrategy;
/// use aws_durable_execution_sdk::builders::wait_for_condition::WaitStrategy;
/// use std::time::Duration;
///
/// let strategy = WaitStrategy::builder(|state: &u32| *state > 0)
///     .max_attempts(20)
///     .initial_delay(Duration::from_millis(500))
///     .max_delay(Duration::from_secs(10))
///     .backoff_rate(3.0)
///     .jitter(JitterStrategy::None)
///     .build();
/// assert_eq!(strategy.max_delay(), Duration::from_secs(10));
/// ```
#[must_use = "builders do nothing unless .build() is called"]
#[non_exhaustive]
pub struct WaitStrategyBuilder<S> {
    completion_predicate: std::sync::Arc<dyn Fn(&S) -> bool + Send + Sync>,
    max_attempts: Option<u32>,
    initial_delay: Option<Duration>,
    max_delay: Option<Duration>,
    backoff_rate: Option<f64>,
    jitter: Option<crate::builders::JitterStrategy>,
}

impl<S> std::fmt::Debug for WaitStrategyBuilder<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WaitStrategyBuilder")
            .field("max_attempts", &self.max_attempts)
            .field("initial_delay", &self.initial_delay)
            .field("max_delay", &self.max_delay)
            .field("backoff_rate", &self.backoff_rate)
            .field("jitter", &self.jitter)
            .finish_non_exhaustive()
    }
}

impl<S> Clone for WaitStrategyBuilder<S> {
    fn clone(&self) -> Self {
        Self {
            completion_predicate: std::sync::Arc::clone(&self.completion_predicate),
            max_attempts: self.max_attempts,
            initial_delay: self.initial_delay,
            max_delay: self.max_delay,
            backoff_rate: self.backoff_rate,
            jitter: self.jitter,
        }
    }
}

impl<S> WaitStrategyBuilder<S> {
    /// Sets the total number of checks allowed before the operation fails
    /// with a `MaxChecksExceeded` error.
    ///
    /// The cap counts checks, so `max_attempts(1)` runs the check once and
    /// exhausts if the predicate is not satisfied by its state.
    pub fn max_attempts(mut self, max_attempts: u32) -> Self {
        self.max_attempts = Some(max_attempts);
        self
    }

    /// Sets the initial delay between condition checks, prior to jitter.
    pub fn initial_delay(mut self, delay: Duration) -> Self {
        self.initial_delay = Some(delay);
        self
    }

    /// Sets the maximum delay between condition checks, prior to jitter.
    pub fn max_delay(mut self, delay: Duration) -> Self {
        self.max_delay = Some(delay);
        self
    }

    /// Sets the backoff multiplier applied after each check.
    pub fn backoff_rate(mut self, rate: f64) -> Self {
        self.backoff_rate = Some(rate);
        self
    }

    /// Sets the jitter applied to each computed delay.
    pub fn jitter(mut self, jitter: crate::builders::JitterStrategy) -> Self {
        self.jitter = Some(jitter);
        self
    }

    /// Builds the [`WaitStrategy`], filling unset knobs with the
    /// JS/Python-aligned defaults.
    #[must_use]
    pub fn build(self) -> WaitStrategy<S> {
        WaitStrategy {
            completion_predicate: self.completion_predicate,
            max_attempts: self.max_attempts.unwrap_or(DEFAULT_MAX_ATTEMPTS),
            initial_delay: self.initial_delay.unwrap_or(DEFAULT_INITIAL_DELAY),
            max_delay: self.max_delay.unwrap_or(DEFAULT_MAX_DELAY),
            backoff_rate: self.backoff_rate.unwrap_or(DEFAULT_BACKOFF_RATE),
            jitter: self.jitter.unwrap_or_default(),
        }
    }
}

#[cfg(test)]
#[expect(clippy::panic)] // reason: test assertions on unexpected variants
mod tests {
    use super::*;
    use crate::builders::JitterStrategy;

    /// The `WaitStrategy` builder sets each knob independently, and unset
    /// knobs keep the JS/Python-aligned defaults (60 attempts, 5s initial
    /// delay, 5min maximum delay, 1.5 backoff rate, full jitter).
    #[test]
    fn wait_strategy_builder_overrides_only_what_is_set() {
        let partial = WaitStrategy::builder(|state: &i32| *state >= 3)
            .initial_delay(Duration::from_secs(2))
            .build();
        assert_eq!(partial.initial_delay(), Duration::from_secs(2));
        assert_eq!(partial.max_attempts(), 60);
        assert_eq!(partial.max_delay(), Duration::from_mins(5));
        assert!((partial.backoff_rate() - 1.5).abs() < f64::EPSILON);
        assert_eq!(partial.jitter(), JitterStrategy::Full);

        let full = WaitStrategy::builder(|state: &i32| *state >= 3)
            .max_attempts(7)
            .initial_delay(Duration::from_millis(500))
            .max_delay(Duration::from_secs(10))
            .backoff_rate(3.0)
            .jitter(JitterStrategy::Half)
            .build();
        assert_eq!(full.max_attempts(), 7);
        assert_eq!(full.initial_delay(), Duration::from_millis(500));
        assert_eq!(full.max_delay(), Duration::from_secs(10));
        assert!((full.backoff_rate() - 3.0).abs() < f64::EPSILON);
        assert_eq!(full.jitter(), JitterStrategy::Half);
    }

    /// A state satisfying the completion predicate yields `Complete`, and
    /// the predicate wins over exhaustion, so a condition satisfied on the
    /// final allowed check completes rather than exhausting.
    #[test]
    fn predicate_satisfied_yields_complete() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
            .max_attempts(5)
            .build();

        assert!(matches!(strategy.decide(&3, 1), WaitDecision::Complete));
        assert!(matches!(strategy.decide(&100, 2), WaitDecision::Complete));
        // Attempt at (and past) the cap still completes when the predicate
        // is satisfied.
        assert!(matches!(strategy.decide(&3, 5), WaitDecision::Complete));
        assert!(matches!(strategy.decide(&3, 6), WaitDecision::Complete));
    }

    /// Reaching `max_attempts` without the predicate matching yields
    /// `Exhausted`, and the reason carries the attempt count.
    #[test]
    fn max_attempts_reached_yields_exhausted_with_attempt_count() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 3)
            .max_attempts(3)
            .jitter(JitterStrategy::None)
            .build();

        // Below the cap: continue.
        assert!(matches!(
            strategy.decide(&0, 2),
            WaitDecision::Continue { .. }
        ));

        // At the cap: exhausted, with the attempt count in the reason.
        match strategy.decide(&0, 3) {
            WaitDecision::Exhausted { reason } => {
                assert!(
                    reason.contains("3 checks"),
                    "reason must carry the attempt count: {reason}"
                );
                assert!(
                    reason.contains("max attempts exceeded"),
                    "reason must name the cause: {reason}"
                );
            }
            other => panic!("expected Exhausted at the cap, got {other:?}"),
        }
    }

    /// With `JitterStrategy::None` the schedule is deterministic: the first
    /// delay is `initial_delay`, each subsequent delay grows by
    /// `backoff_rate`, the sequence caps at `max_delay`, and sub-second
    /// results rise to the one-second minimum.
    #[test]
    fn deterministic_schedule_respects_backoff_and_max_delay() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
            .max_attempts(60)
            .initial_delay(Duration::from_secs(2))
            .max_delay(Duration::from_secs(10))
            .backoff_rate(3.0)
            .jitter(JitterStrategy::None)
            .build();

        let delay_of = |attempt: u32| match strategy.decide(&0, attempt) {
            WaitDecision::Continue { delay } => delay,
            other => panic!("expected Continue below the cap, got {other:?}"),
        };

        // attempt 1 → initial (2s); attempt 2 → 2s * 3 = 6s;
        // attempt 3 → 18s, capped at max_delay (10s).
        assert_eq!(delay_of(1), Duration::from_secs(2));
        assert_eq!(delay_of(2), Duration::from_secs(6));
        assert_eq!(delay_of(3), Duration::from_secs(10));
        assert_eq!(delay_of(9), Duration::from_secs(10));

        // Sub-second base delays rise to the one-second minimum.
        let tiny = WaitStrategy::builder(|state: &i32| *state >= 100)
            .initial_delay(Duration::from_millis(100))
            .jitter(JitterStrategy::None)
            .build();
        match tiny.decide(&0, 1) {
            WaitDecision::Continue { delay } => assert_eq!(delay, Duration::from_secs(1)),
            other => panic!("expected Continue, got {other:?}"),
        }
    }

    /// Full jitter draws from `[0, base]` (quantized, min 1s), and the
    /// delay never exceeds `max_delay` even deep into the schedule.
    #[test]
    fn full_jitter_delays_stay_within_bounds() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
            .initial_delay(Duration::from_secs(10))
            .max_delay(Duration::from_secs(30))
            .backoff_rate(2.0)
            .jitter(JitterStrategy::Full)
            .build();

        for _ in 0..50 {
            // Attempt 1: base = 10s. Full jitter in [0, 10], min 1s.
            match strategy.decide(&0, 1) {
                WaitDecision::Continue { delay } => {
                    assert!(
                        delay >= Duration::from_secs(1) && delay <= Duration::from_secs(10),
                        "full-jitter delay {delay:?} outside [1s, base]"
                    );
                }
                other => panic!("expected Continue, got {other:?}"),
            }
            // Attempt 20: base capped at max_delay (30s).
            match strategy.decide(&0, 20) {
                WaitDecision::Continue { delay } => {
                    assert!(
                        delay <= Duration::from_secs(30),
                        "full-jitter delay {delay:?} exceeds max_delay"
                    );
                }
                other => panic!("expected Continue, got {other:?}"),
            }
        }
    }

    /// Half jitter draws from `[base / 2, base]`, and the documented lower
    /// bound survives quantization.
    #[test]
    fn half_jitter_delays_stay_within_bounds() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
            .initial_delay(Duration::from_secs(10))
            .max_delay(Duration::from_secs(30))
            .jitter(JitterStrategy::Half)
            .build();

        for _ in 0..50 {
            // Attempt 1: base = 10s. Half jitter in [5, 10].
            match strategy.decide(&0, 1) {
                WaitDecision::Continue { delay } => {
                    assert!(
                        delay >= Duration::from_secs(5) && delay <= Duration::from_secs(10),
                        "half-jitter delay {delay:?} outside [base/2, base]"
                    );
                }
                other => panic!("expected Continue, got {other:?}"),
            }
        }
    }

    /// `wait_strategy` installs a strategy derived from the config: the
    /// three outcomes (`Complete` / `Continue` / `Exhausted`) flow through
    /// the installed closure exactly as `decide` produces them.
    #[test]
    fn wait_strategy_installs_config_derived_strategy() {
        let ctx = DurableContext::test_context();

        let builder = ctx
            .wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
            .wait_strategy(
                WaitStrategy::builder(|state: &i32| *state >= 3)
                    .max_attempts(4)
                    .initial_delay(Duration::from_secs(2))
                    .max_delay(Duration::from_secs(10))
                    .backoff_rate(3.0)
                    .jitter(JitterStrategy::None)
                    .build(),
            );

        let strategy = &builder.wait_strategy.strategy;

        // Predicate satisfied → Complete.
        assert!(matches!(strategy(3_i32, 1), WaitDecision::Complete));
        // Predicate unmet below the cap → Continue with the backoff delay.
        match strategy(0_i32, 2) {
            WaitDecision::Continue { delay } => assert_eq!(delay, Duration::from_secs(6)),
            other => panic!("expected Continue, got {other:?}"),
        }
        // Predicate unmet at the cap → Exhausted.
        assert!(matches!(strategy(0_i32, 4), WaitDecision::Exhausted { .. }));
    }

    /// A second strategy setter replaces the first, in both directions,
    /// and `name` and `serdes` between the setters keep the
    /// `WithWaitStrategy` state.
    #[test]
    fn second_strategy_replaces_first() {
        let ctx = DurableContext::test_context();

        // `wait_strategy_fn`, then `wait_strategy`: the config wins.
        let builder: WaitForConditionBuilder<_, _, _, JsonSerdes, WithWaitStrategy<i32>> = ctx
            .wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
            .wait_strategy_fn(|_state, _attempt| WaitDecision::exhausted("first"))
            .name("poll")
            .serdes(JsonSerdes)
            .wait_strategy(WaitStrategy::builder(|_state: &i32| true).build());
        assert!(matches!(
            (builder.wait_strategy.strategy)(0, 1),
            WaitDecision::Complete
        ));

        // `wait_strategy`, then `wait_strategy_fn`: the closure wins.
        let builder: WaitForConditionBuilder<_, _, _, JsonSerdes, WithWaitStrategy<i32>> = ctx
            .wait_for_condition(|_sc, state: i32| async move { Ok(state) }, 0_i32)
            .wait_strategy(WaitStrategy::builder(|_state: &i32| true).build())
            .serdes(JsonSerdes)
            .name("poll")
            .wait_strategy_fn(|_state, _attempt| WaitDecision::exhausted("second"));
        match (builder.wait_strategy.strategy)(0, 1) {
            WaitDecision::Exhausted { reason } => assert_eq!(reason, "second"),
            other => panic!("expected Exhausted, got {other:?}"),
        }
    }

    /// The wait strategy rounds a computed delay to the nearest whole
    /// second, as the retry path does: 1.1 s schedules 1 s, 2.2 s
    /// schedules 2 s, 2.25 s schedules 2 s, and 2.5 s schedules 3 s.
    #[test]
    fn wait_strategy_rounds_to_nearest() {
        let delay_of =
            |strategy: &WaitStrategy<i32>, attempt: u32| match strategy.decide(&0, attempt) {
                WaitDecision::Continue { delay } => delay,
                other => panic!("expected Continue, got {other:?}"),
            };

        // The retry config's default backoff rate is 2.0; the wait
        // strategy's is 1.5. Set 2.0 so both tests run the same schedule.
        let config = WaitStrategy::builder(|s: &i32| *s >= 100)
            .initial_delay(Duration::from_millis(1100))
            .backoff_rate(2.0)
            .jitter(JitterStrategy::None)
            .build();
        assert_eq!(delay_of(&config, 1), Duration::from_secs(1));
        // 1.1 * 2 = 2.2 s.
        assert_eq!(delay_of(&config, 2), Duration::from_secs(2));

        // 1 * 1.5^2 = 2.25 s.
        let slow = WaitStrategy::builder(|s: &i32| *s >= 100)
            .initial_delay(Duration::from_secs(1))
            .backoff_rate(1.5)
            .jitter(JitterStrategy::None)
            .build();
        assert_eq!(delay_of(&slow, 3), Duration::from_secs(2));

        let half = WaitStrategy::builder(|s: &i32| *s >= 100)
            .initial_delay(Duration::from_millis(2500))
            .jitter(JitterStrategy::None)
            .build();
        assert_eq!(delay_of(&half, 1), Duration::from_secs(3));
    }

    /// End-to-end through `decide`: with `Full` jitter the sample lands in
    /// `[0, base]`, so after quantization every delay is a whole second
    /// in `[1s, round(base)]`, never below the one-second minimum.
    #[test]
    fn full_jitter_decide_never_rounds_below_one_second() {
        let strategy = WaitStrategy::builder(|state: &i32| *state >= 100)
            // base for attempt 1 is 1s, so full-jitter samples are all
            // fractional in [0, 1]; the one-second minimum must yield 1s.
            .initial_delay(Duration::from_secs(1))
            .jitter(JitterStrategy::Full)
            .build();

        for _ in 0..50 {
            match strategy.decide(&0, 1) {
                WaitDecision::Continue { delay } => {
                    assert_eq!(
                        delay,
                        Duration::from_secs(1),
                        "sample in [0, 1] must quantize to exactly 1s"
                    );
                }
                other => panic!("expected Continue, got {other:?}"),
            }
        }
    }
}