hexeract-outbox 0.5.0

Transactional outbox pattern primitives for the Hexeract messaging framework
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use hexeract_core::CorrelationId;
use hexeract_core::HandlerContext;
use hexeract_core::MessageId;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

use crate::Event;
use crate::Handler;
use crate::OutboxEnvelope;
use crate::OutboxError;

/// Pinned, boxed, send future returned by trait object methods.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Backend-agnostic contract for the outbox storage operations driven by
/// [`OutboxWorker`].
///
/// The split between [`Self::Client`] and [`Self::Tx`] keeps the trait
/// idiomatic: the connection guard is owned by the worker's polling
/// cycle, and the transaction borrows from it for the duration of the
/// cycle. Backends that follow the `Pool` + `Transaction` pattern
/// (deadpool_postgres, sqlx, ...) map onto this trait directly.
///
/// Implemented via `async_trait` (boxed futures) to work around the
/// current Rust limitation around HRTB inference on GATs (see
/// rust-lang/rust#100013). The runtime cost is one heap allocation per
/// trait method call, negligible at the outbox dispatch cadence.
#[async_trait::async_trait]
pub trait OutboxStore: Send + Sync + 'static {
    /// Pooled connection guard owned by the worker for one polling cycle.
    type Client: Send;
    /// Transaction borrowed from a [`Self::Client`].
    type Tx<'tx>: Send
    where
        Self: 'tx;

    /// Acquire a connection from the underlying pool.
    async fn acquire(&self) -> Result<Self::Client, OutboxError>;

    /// Open a transaction borrowing from the given connection.
    async fn begin<'a>(&self, client: &'a mut Self::Client) -> Result<Self::Tx<'a>, OutboxError>;

    /// Poll a batch of pending envelopes, locking them via `FOR UPDATE SKIP LOCKED`.
    ///
    /// Envelopes that have reached or exceeded `max_attempts`, or whose
    /// `next_retry_at` is in the future, are excluded.
    async fn poll<'a>(
        &self,
        tx: &mut Self::Tx<'a>,
        batch_size: usize,
        max_attempts: u32,
    ) -> Result<Vec<OutboxEnvelope>, OutboxError>;

    /// Mark an envelope as successfully delivered.
    async fn mark_delivered<'a>(
        &self,
        tx: &mut Self::Tx<'a>,
        event_id: Uuid,
    ) -> Result<(), OutboxError>;

    /// Mark an envelope as failed, recording the error and the backoff delay
    /// before the next retry.
    ///
    /// `retry_in` is the delay from *now*; the backend adds it to its own
    /// database clock when persisting `next_retry_at`, so retry scheduling is
    /// not affected by skew between the worker host and the database host.
    /// The attempt counter is advanced by [`Self::claim`], not here.
    async fn mark_failed<'a>(
        &self,
        tx: &mut Self::Tx<'a>,
        event_id: Uuid,
        error: &str,
        retry_in: Duration,
    ) -> Result<(), OutboxError>;

    /// Commit the transaction.
    async fn commit<'a>(&self, tx: Self::Tx<'a>) -> Result<(), OutboxError>;

    /// Move an envelope that has exhausted its retry budget to the dead-letter store.
    ///
    /// Called by the worker after [`Self::mark_failed`] when
    /// `attempts + 1 >= max_attempts`. The default implementation is a no-op so
    /// backends that do not persist dead-lettered envelopes need not override it.
    /// Called within the same transaction as `mark_failed` — both succeed or both
    /// roll back.
    async fn mark_dead_lettered<'a>(
        &self,
        _tx: &mut Self::Tx<'a>,
        _event_id: Uuid,
        _error: &str,
    ) -> Result<(), OutboxError> {
        Ok(())
    }

    /// Claim a batch of envelopes: advance the soft lease and consume one
    /// retry slot.
    ///
    /// Called within the same transaction as [`Self::poll`], immediately
    /// after the batch is fetched. The backend sets `next_retry_at` to its own
    /// database clock plus `lease_for` (so the lease window is immune to
    /// app/DB clock skew) and increments `attempts` by one. The worker commits
    /// the transaction right after this call so `FOR UPDATE SKIP LOCKED`
    /// row-level locks are released promptly. Competing workers skip envelopes
    /// whose `next_retry_at` is in the future, so the claiming worker can
    /// dispatch outside the lock without risking concurrent re-delivery.
    ///
    /// Incrementing `attempts` here (rather than only on failure) is what
    /// makes a worker crash between claim and acknowledgement safe: the
    /// attempt is already counted, so a poison envelope eventually reaches the
    /// dead-letter threshold instead of being redelivered forever.
    ///
    /// The default implementation is a no-op. Backends that neither lease nor
    /// track attempts in storage need not override it.
    async fn claim<'a>(
        &self,
        _tx: &mut Self::Tx<'a>,
        _event_ids: &[Uuid],
        _lease_for: Duration,
    ) -> Result<(), OutboxError> {
        Ok(())
    }
}

/// Type-erased handler that the worker dispatches to.
///
/// Most users do not implement this trait directly; they use
/// [`TypedHandler`] to adapt a typed [`Handler<E>`] into an erased one
/// the worker can store in a registry keyed by `event_type`.
pub trait ErasedHandler: Send + Sync + 'static {
    /// Event type this handler reacts to, matching [`Event::EVENT_TYPE`].
    fn event_type(&self) -> &'static str;

    /// Decode the envelope and dispatch to the underlying typed handler.
    fn handle<'a>(
        &'a self,
        envelope: &'a OutboxEnvelope,
        ctx: &'a HandlerContext,
    ) -> BoxFuture<'a, Result<(), OutboxError>>;
}

/// Adapter that lifts a typed [`Handler<E>`] into an [`ErasedHandler`].
pub struct TypedHandler<E, H>
where
    E: Event,
    H: Handler<E>,
{
    handler: Arc<H>,
    _phantom: PhantomData<fn() -> E>,
}

impl<E, H> TypedHandler<E, H>
where
    E: Event,
    H: Handler<E>,
{
    /// Wrap a freshly owned handler.
    #[must_use]
    pub fn new(handler: H) -> Self {
        Self {
            handler: Arc::new(handler),
            _phantom: PhantomData,
        }
    }

    /// Wrap a handler already shared behind an `Arc`.
    #[must_use]
    pub fn shared(handler: Arc<H>) -> Self {
        Self {
            handler,
            _phantom: PhantomData,
        }
    }
}

impl<E, H> ErasedHandler for TypedHandler<E, H>
where
    E: Event,
    H: Handler<E>,
{
    fn event_type(&self) -> &'static str {
        E::EVENT_TYPE
    }

    fn handle<'a>(
        &'a self,
        envelope: &'a OutboxEnvelope,
        ctx: &'a HandlerContext,
    ) -> BoxFuture<'a, Result<(), OutboxError>> {
        Box::pin(async move {
            let event: E = envelope.decode()?;
            self.handler.handle(event, ctx).await.map_err(Into::into)
        })
    }
}

/// Tuning parameters for an [`OutboxWorker`].
#[derive(Debug, Clone)]
pub struct OutboxWorkerConfig {
    /// Sleep duration between empty polls.
    pub poll_interval: Duration,
    /// Maximum number of envelopes returned by a single poll.
    pub batch_size: usize,
    /// Number of attempts allowed before an envelope stops being polled.
    pub max_attempts: u32,
    /// Base delay for the exponential backoff applied after a failed dispatch.
    ///
    /// The actual delay before attempt `n` is:
    /// `min(retry_max_delay, retry_base_delay × 2^n)`
    ///
    /// When [`Self::jitter`] is `true` (the default), a uniform random value
    /// in `[0, computed_delay]` is drawn instead (full-jitter strategy), which
    /// spreads retries across the window and avoids thundering-herd spikes.
    pub retry_base_delay: Duration,
    /// Upper bound on the computed backoff delay.
    ///
    /// Caps `retry_base_delay × 2^n` so retries never wait longer than this
    /// value regardless of the attempt count.
    pub retry_max_delay: Duration,
    /// Apply full jitter to the backoff delay.
    ///
    /// When `true` (the default), the worker draws a uniform random value in
    /// `[0, capped_delay]` instead of using the deterministic exponential.
    /// Set to `false` to get a predictable delay (useful in tests or
    /// environments where all workers share the same retry schedule).
    pub jitter: bool,
    /// Minimum delay applied between consecutive non-empty poll cycles.
    ///
    /// A full batch otherwise loops with no delay, busy-spinning the store
    /// under a sustained backlog. This floor paces back-to-back non-empty
    /// cycles without affecting the empty-poll path (which still waits for
    /// [`Self::poll_interval`]). Set it to [`Duration::ZERO`] to disable
    /// pacing and restore the previous tight-loop behavior.
    pub min_cycle_delay: Duration,
    /// Per-envelope handler deadline and soft-lease unit.
    ///
    /// Two related roles:
    ///
    /// - **Hard timeout.** Each handler invocation is wrapped in a
    ///   `tokio::time::timeout` of this duration. A handler that exceeds it has
    ///   its cancellation token signalled and the dispatch is recorded as a
    ///   failed attempt ([`OutboxError::DispatchTimeout`]), so a hung handler
    ///   cannot stall the worker.
    /// - **Lease unit.** After polling a batch, the worker leases the whole
    ///   batch by setting `next_retry_at` to the database clock plus
    ///   `batch_size x dispatch_timeout`, then commits immediately. This
    ///   releases the `FOR UPDATE SKIP LOCKED` row-level locks before dispatch
    ///   begins while keeping the lease alive across the worst-case sequential
    ///   dispatch of every envelope in the batch, so competing workers do not
    ///   re-pick a tail envelope mid-batch.
    ///
    /// Set it to the worst-case duration of a *single* handler; the
    /// `batch_size` multiplier for the lease is applied internally, so do not
    /// pre-multiply it yourself.
    ///
    /// [`OutboxError::DispatchTimeout`]: crate::OutboxError::DispatchTimeout
    pub dispatch_timeout: Duration,
}

impl Default for OutboxWorkerConfig {
    fn default() -> Self {
        Self {
            poll_interval: Duration::from_millis(100),
            batch_size: 10,
            max_attempts: 5,
            retry_base_delay: Duration::from_secs(1),
            retry_max_delay: Duration::from_secs(300),
            jitter: true,
            min_cycle_delay: Duration::from_millis(5),
            dispatch_timeout: Duration::from_secs(30),
        }
    }
}

impl OutboxWorkerConfig {
    /// Compute the next retry delay for an envelope that has failed `attempts` times.
    ///
    /// Uses bounded exponential backoff: `min(retry_max_delay, retry_base_delay × 2^attempts)`.
    /// When [`Self::jitter`] is `true`, returns a uniform random value in
    /// `[0, computed_delay]` (full-jitter strategy).
    ///
    /// The computation is overflow-safe: `checked_shl` returns `None` when the
    /// shift overflows, in which case the factor falls back to `u32::MAX`, and
    /// `Duration::saturating_mul` clamps the result instead of panicking.
    #[must_use]
    pub fn next_retry_delay(&self, attempts: u32) -> Duration {
        let factor = 1u32.checked_shl(attempts).unwrap_or(u32::MAX);
        let capped = self
            .retry_base_delay
            .saturating_mul(factor)
            .min(self.retry_max_delay);
        if self.jitter {
            let nanos = capped.as_nanos();
            // fastrand::u64 covers the full jitter range; clamp to u64::MAX nanos
            // (~584 years) to handle theoretical caps beyond that bound.
            let nanos_u64 = u64::try_from(nanos).unwrap_or(u64::MAX);
            Duration::from_nanos(fastrand::u64(0..=nanos_u64))
        } else {
            capped
        }
    }
}

/// Worker that polls the outbox in a loop and dispatches envelopes to
/// their registered handlers.
///
/// Generic over any [`OutboxStore`] backend. The worker takes ownership
/// of the store and a registry mapping `event_type` to its
/// [`ErasedHandler`], then [`Self::start`] spawns the polling task and
/// returns a [`JoinHandle`].
pub struct OutboxWorker<S>
where
    S: OutboxStore,
{
    store: S,
    handlers: Arc<HashMap<&'static str, Arc<dyn ErasedHandler>>>,
    config: OutboxWorkerConfig,
}

impl<S> OutboxWorker<S>
where
    S: OutboxStore,
{
    /// Build a new worker.
    #[must_use]
    pub fn new(
        store: S,
        handlers: HashMap<&'static str, Arc<dyn ErasedHandler>>,
        config: OutboxWorkerConfig,
    ) -> Self {
        Self {
            store,
            handlers: Arc::new(handlers),
            config,
        }
    }

    /// Returns the polling loop as a boxed `Send` future that the caller spawns.
    ///
    /// The future resolves to `Ok(())` once the supplied
    /// [`CancellationToken`] is cancelled. Transient store errors are
    /// logged via `tracing` and the loop continues. Typical usage:
    ///
    /// ```ignore
    /// let cancel = CancellationToken::new();
    /// let join = tokio::spawn(worker.run(cancel.clone()));
    /// // ...
    /// cancel.cancel();
    /// join.await??;
    /// ```
    ///
    /// The return type is boxed to work around a current Rust compiler
    /// limitation around HRTB inference on GATs (see rust-lang/rust#100013).
    pub fn run(
        self,
        cancel: CancellationToken,
    ) -> Pin<Box<dyn Future<Output = Result<(), OutboxError>> + Send>>
    where
        for<'a> S::Tx<'a>: Send,
    {
        Box::pin(async move {
            while !cancel.is_cancelled() {
                let sleep_for = match self.poll_cycle(&cancel).await {
                    Ok(0) => Some(self.config.poll_interval),
                    Ok(_) => {
                        if self.config.min_cycle_delay.is_zero() {
                            None
                        } else {
                            Some(self.config.min_cycle_delay)
                        }
                    }
                    Err(err) => {
                        tracing::error!(
                            error = ?err,
                            "outbox worker poll cycle failed, sleeping before retry"
                        );
                        Some(self.config.poll_interval)
                    }
                };
                if let Some(delay) = sleep_for {
                    // Race the sleep against cancellation so a shutdown during
                    // a long poll_interval is observed promptly instead of
                    // after the full delay elapses (#231).
                    tokio::select! {
                        () = tokio::time::sleep(delay) => {}
                        () = cancel.cancelled() => break,
                    }
                }
            }
            Ok(())
        })
    }

    async fn poll_cycle(&self, cancel: &CancellationToken) -> Result<usize, OutboxError> {
        // Phase 1 — claim (short transaction: SQL only, no handler I/O)
        // The FOR UPDATE SKIP LOCKED locks are held only for the SELECT +
        // the claim UPDATE, then released at commit. Competing workers can
        // immediately pick up other rows.
        let envelopes = {
            let mut client = self.store.acquire().await?;
            let mut tx = self.store.begin(&mut client).await?;
            let batch = self
                .store
                .poll(&mut tx, self.config.batch_size, self.config.max_attempts)
                .await?;
            if !batch.is_empty() {
                let ids: Vec<Uuid> = batch.iter().map(|e| e.event_id).collect();
                self.store
                    .claim(&mut tx, &ids, self.lease_for(ids.len()))
                    .await?;
            }
            self.store.commit(tx).await?;
            batch
        };
        let count = envelopes.len();

        // Phase 2 — dispatch + ack (one transaction per envelope, outside the poll lock)
        for envelope in &envelopes {
            // Isolate per-envelope settle failures: a transient DB error while
            // acking one envelope must not abandon the rest of the claimed
            // batch (those rows would otherwise wait out the whole lease before
            // being retried). Log and continue (#231).
            if let Err(err) = self.dispatch_and_settle(envelope, cancel).await {
                tracing::error!(
                    event_id = %envelope.event_id,
                    event_type = %envelope.event_type,
                    error = ?err,
                    "failed to settle outbox envelope; continuing with the rest of the batch"
                );
            }
        }

        Ok(count)
    }

    /// Soft-lease duration covering the worst-case sequential dispatch of a
    /// whole claimed batch.
    ///
    /// A single batch is claimed once, then its envelopes are dispatched
    /// sequentially. The lease must therefore outlast `batch_len` back-to-back
    /// dispatches, each bounded by `dispatch_timeout`; sizing it as merely
    /// `dispatch_timeout` lets the tail envelopes' lease expire mid-batch and a
    /// competing worker double-dispatch them (#215).
    fn lease_for(&self, batch_len: usize) -> Duration {
        let factor = u32::try_from(batch_len.max(1)).unwrap_or(u32::MAX);
        self.config.dispatch_timeout.saturating_mul(factor)
    }

    /// Dispatch a single envelope and settle its outcome in its own
    /// transaction.
    async fn dispatch_and_settle(
        &self,
        envelope: &OutboxEnvelope,
        cancel: &CancellationToken,
    ) -> Result<(), OutboxError> {
        match self.dispatch(envelope, cancel).await {
            Ok(()) => {
                let mut client = self.store.acquire().await?;
                let mut tx = self.store.begin(&mut client).await?;
                self.store
                    .mark_delivered(&mut tx, envelope.event_id)
                    .await?;
                self.store.commit(tx).await?;
            }
            Err(err) => {
                let message = err.to_string();
                tracing::warn!(
                    event_id = %envelope.event_id,
                    event_type = %envelope.event_type,
                    error = %message,
                    "outbox handler dispatch failed"
                );
                let retry_in = self.config.next_retry_delay(envelope.attempts);
                let mut client = self.store.acquire().await?;
                let mut tx = self.store.begin(&mut client).await?;
                self.store
                    .mark_failed(&mut tx, envelope.event_id, &message, retry_in)
                    .await?;
                if envelope.attempts + 1 >= self.config.max_attempts {
                    tracing::error!(
                        event_id = %envelope.event_id,
                        event_type = %envelope.event_type,
                        attempts = envelope.attempts + 1,
                        "outbox envelope exhausted retry budget, moving to dead letter"
                    );
                    self.store
                        .mark_dead_lettered(&mut tx, envelope.event_id, &message)
                        .await?;
                }
                self.store.commit(tx).await?;
            }
        }
        Ok(())
    }

    async fn dispatch(
        &self,
        envelope: &OutboxEnvelope,
        cancel: &CancellationToken,
    ) -> Result<(), OutboxError> {
        let Some(handler) = self.handlers.get(envelope.event_type.as_str()) else {
            return Err(OutboxError::MissingHandler {
                event_type: envelope.event_type.clone(),
            });
        };

        // Stable across retries: both IDs are pinned to the envelope's
        // immutable event_id so every dispatch attempt of the same row
        // presents an identical context to the handler.
        //
        // A child token lets a dispatch timeout cancel only this handler
        // without tearing down the worker's shared token; the child is still
        // cancelled if the parent (worker) token is cancelled.
        let ctx = HandlerContext::new(
            MessageId::from(envelope.event_id),
            CorrelationId::from(envelope.event_id),
        )
        .with_cancellation(cancel.child_token());

        tracing::debug!(
            event_id = %envelope.event_id,
            event_type = %envelope.event_type,
            "dispatching outbox envelope"
        );

        // Enforce dispatch_timeout as a hard deadline so a hung handler cannot
        // stall the worker forever (#229). The cancellation token is signalled
        // first so a cooperative handler can unwind before the future is
        // dropped.
        match tokio::time::timeout(self.config.dispatch_timeout, handler.handle(envelope, &ctx))
            .await
        {
            Ok(result) => result,
            Err(_elapsed) => {
                ctx.cancellation.cancel();
                Err(OutboxError::DispatchTimeout {
                    event_id: envelope.event_id,
                    event_type: envelope.event_type.clone(),
                    timeout: self.config.dispatch_timeout,
                })
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Deserialize;
    use serde::Serialize;
    use std::sync::Mutex;
    use std::sync::atomic::AtomicBool;
    use std::sync::atomic::Ordering;

    #[derive(Debug, Serialize, Deserialize, PartialEq)]
    struct UserRegistered {
        user_id: Uuid,
    }

    impl Event for UserRegistered {
        const EVENT_TYPE: &'static str = "users.registered";
    }

    struct RecordingHandler {
        seen: Arc<Mutex<Vec<Uuid>>>,
    }

    impl Handler<UserRegistered> for RecordingHandler {
        type Error = OutboxError;
        async fn handle(
            &self,
            event: UserRegistered,
            _ctx: &HandlerContext,
        ) -> Result<(), Self::Error> {
            self.seen.lock().unwrap().push(event.user_id);
            Ok(())
        }
    }

    struct ContextCapturingHandler {
        captured_ids: Arc<Mutex<Vec<MessageId>>>,
    }

    impl Handler<UserRegistered> for ContextCapturingHandler {
        type Error = OutboxError;
        async fn handle(
            &self,
            _event: UserRegistered,
            ctx: &HandlerContext,
        ) -> Result<(), Self::Error> {
            self.captured_ids.lock().unwrap().push(ctx.message_id);
            Ok(())
        }
    }

    struct FailingHandler;
    impl Handler<UserRegistered> for FailingHandler {
        type Error = OutboxError;
        async fn handle(
            &self,
            _event: UserRegistered,
            _ctx: &HandlerContext,
        ) -> Result<(), Self::Error> {
            Err(OutboxError::Internal("forced".into()))
        }
    }

    fn fresh_envelope(user_id: Uuid) -> OutboxEnvelope {
        let publisher_test_event = UserRegistered { user_id };
        OutboxEnvelope::new(Uuid::new_v4(), &publisher_test_event).unwrap()
    }

    #[tokio::test]
    async fn typed_handler_decodes_envelope_and_calls_inner_handler() {
        let seen = Arc::new(Mutex::new(Vec::<Uuid>::new()));
        let handler = TypedHandler::new(RecordingHandler {
            seen: Arc::clone(&seen),
        });
        let erased: Arc<dyn ErasedHandler> = Arc::new(handler);

        let user_id = Uuid::from_u128(42);
        let envelope = fresh_envelope(user_id);
        let ctx = HandlerContext::new(MessageId::new(), CorrelationId::new());

        erased
            .handle(&envelope, &ctx)
            .await
            .expect("erased dispatch must succeed");

        assert_eq!(seen.lock().unwrap().as_slice(), &[user_id]);
    }

    #[tokio::test]
    async fn typed_handler_propagates_handler_error_as_outbox_error() {
        let handler = TypedHandler::new(FailingHandler);
        let erased: Arc<dyn ErasedHandler> = Arc::new(handler);

        let envelope = fresh_envelope(Uuid::nil());
        let ctx = HandlerContext::new(MessageId::new(), CorrelationId::new());

        let err = erased.handle(&envelope, &ctx).await.expect_err("must fail");
        assert!(matches!(err, OutboxError::Internal(_)));
    }

    #[test]
    fn typed_handler_reports_event_type_from_const() {
        let handler = TypedHandler::new(RecordingHandler {
            seen: Arc::new(Mutex::new(Vec::new())),
        });
        assert_eq!(handler.event_type(), "users.registered");
    }

    #[test]
    fn default_config_has_expected_values() {
        let cfg = OutboxWorkerConfig::default();
        assert_eq!(cfg.poll_interval, Duration::from_millis(100));
        assert_eq!(cfg.batch_size, 10);
        assert_eq!(cfg.max_attempts, 5);
        assert_eq!(cfg.retry_base_delay, Duration::from_secs(1));
        assert_eq!(cfg.retry_max_delay, Duration::from_secs(300));
        assert!(cfg.jitter);
        assert_eq!(cfg.min_cycle_delay, Duration::from_millis(5));
        assert_eq!(cfg.dispatch_timeout, Duration::from_secs(30));
    }

    fn deterministic_config(base: Duration, max: Duration) -> OutboxWorkerConfig {
        OutboxWorkerConfig {
            retry_base_delay: base,
            retry_max_delay: max,
            jitter: false,
            ..OutboxWorkerConfig::default()
        }
    }

    #[test]
    fn backoff_grows_exponentially_without_jitter() {
        let cfg = deterministic_config(Duration::from_secs(1), Duration::from_secs(300));
        assert_eq!(cfg.next_retry_delay(0), Duration::from_secs(1));
        assert_eq!(cfg.next_retry_delay(1), Duration::from_secs(2));
        assert_eq!(cfg.next_retry_delay(2), Duration::from_secs(4));
        assert_eq!(cfg.next_retry_delay(3), Duration::from_secs(8));
    }

    #[test]
    fn backoff_caps_at_max_delay() {
        let cfg = deterministic_config(Duration::from_secs(1), Duration::from_secs(30));
        assert_eq!(cfg.next_retry_delay(10), Duration::from_secs(30));
        assert_eq!(cfg.next_retry_delay(100), Duration::from_secs(30));
    }

    #[test]
    fn backoff_overflow_safe_for_large_attempts() {
        let cfg = deterministic_config(Duration::from_secs(1), Duration::from_secs(300));
        let delay = cfg.next_retry_delay(64);
        assert_eq!(
            delay,
            Duration::from_secs(300),
            "overflow must saturate at cap"
        );
    }

    #[test]
    fn backoff_jitter_stays_within_bounds() {
        let base = Duration::from_secs(1);
        let max = Duration::from_secs(30);
        let cfg = OutboxWorkerConfig {
            retry_base_delay: base,
            retry_max_delay: max,
            jitter: true,
            ..OutboxWorkerConfig::default()
        };
        for attempts in 0u32..8 {
            let delay = cfg.next_retry_delay(attempts);
            let cap = base
                .saturating_mul(1u32.checked_shl(attempts).unwrap_or(u32::MAX))
                .min(max);
            assert!(
                delay <= cap,
                "attempt {attempts}: jittered delay {delay:?} must be <= cap {cap:?}"
            );
        }
    }

    /// Store that records the virtual instant of the first empty poll so a
    /// test can assert non-empty cycles were paced.
    #[derive(Clone)]
    struct PacingStore {
        pending: Arc<Mutex<Vec<OutboxEnvelope>>>,
        empty_poll_at: Arc<Mutex<Option<tokio::time::Instant>>>,
    }

    impl PacingStore {
        fn new(initial: Vec<OutboxEnvelope>) -> Self {
            Self {
                pending: Arc::new(Mutex::new(initial)),
                empty_poll_at: Arc::new(Mutex::new(None)),
            }
        }
    }

    #[async_trait::async_trait]
    impl OutboxStore for PacingStore {
        type Client = MockClient;
        type Tx<'tx> = MockTx;

        async fn acquire(&self) -> Result<Self::Client, OutboxError> {
            Ok(MockClient)
        }

        async fn begin<'a>(
            &self,
            _client: &'a mut Self::Client,
        ) -> Result<Self::Tx<'a>, OutboxError> {
            Ok(MockTx)
        }

        async fn poll<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            batch_size: usize,
            _max_attempts: u32,
        ) -> Result<Vec<OutboxEnvelope>, OutboxError> {
            let mut pending = self.pending.lock().unwrap();
            let take = batch_size.min(pending.len());
            let batch: Vec<OutboxEnvelope> = pending.drain(..take).collect();
            if batch.is_empty() {
                let mut slot = self.empty_poll_at.lock().unwrap();
                if slot.is_none() {
                    *slot = Some(tokio::time::Instant::now());
                }
            }
            Ok(batch)
        }

        async fn mark_delivered<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            _event_id: Uuid,
        ) -> Result<(), OutboxError> {
            Ok(())
        }

        async fn mark_failed<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            _event_id: Uuid,
            _error: &str,
            _retry_in: Duration,
        ) -> Result<(), OutboxError> {
            Ok(())
        }

        async fn commit<'a>(&self, _tx: Self::Tx<'a>) -> Result<(), OutboxError> {
            Ok(())
        }
    }

    #[tokio::test(start_paused = true)]
    async fn run_paces_consecutive_non_empty_cycles() {
        let non_empty_cycles: u32 = 4;
        let envelopes: Vec<OutboxEnvelope> = (0..non_empty_cycles)
            .map(|i| fresh_envelope(Uuid::from_u128(u128::from(i) + 1)))
            .collect();
        let store = PacingStore::new(envelopes);
        let empty_poll_at = Arc::clone(&store.empty_poll_at);

        let delay = Duration::from_millis(10);
        let config = OutboxWorkerConfig {
            poll_interval: Duration::from_secs(3600),
            batch_size: 1,
            min_cycle_delay: delay,
            ..OutboxWorkerConfig::default()
        };

        let registry = registry_with(vec![Arc::new(TypedHandler::new(RecordingHandler {
            seen: Arc::new(Mutex::new(Vec::new())),
        }))]);
        let worker = OutboxWorker::new(store, registry, config);

        let cancel = CancellationToken::new();
        let start = tokio::time::Instant::now();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(delay * non_empty_cycles + Duration::from_millis(1)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let empty_at = empty_poll_at
            .lock()
            .unwrap()
            .expect("the loop should have reached the empty poll");
        assert_eq!(
            empty_at.duration_since(start),
            delay * non_empty_cycles,
            "each non-empty cycle must be paced by min_cycle_delay before the empty poll"
        );
    }

    /// `MockStore` lets us drive the worker without a real database in
    /// unit tests. Integration testing of the SQL semantics happens in
    /// `hexeract-outbox-sql` via testcontainers.
    #[derive(Clone)]
    struct MockStore {
        pending: Arc<Mutex<Vec<OutboxEnvelope>>>,
        delivered: Arc<Mutex<Vec<Uuid>>>,
        failed: Arc<Mutex<Vec<(Uuid, String)>>>,
        dead_lettered: Arc<Mutex<Vec<Uuid>>>,
        claimed: Arc<Mutex<Vec<Uuid>>>,
        fail_claim: Arc<AtomicBool>,
        /// When set, `mark_delivered` returns an error for this event id once,
        /// simulating a transient ack failure (used to test batch isolation).
        fail_mark_delivered_for: Arc<Mutex<Option<Uuid>>>,
    }

    impl MockStore {
        fn new(initial: Vec<OutboxEnvelope>) -> Self {
            Self {
                pending: Arc::new(Mutex::new(initial)),
                delivered: Arc::new(Mutex::new(Vec::new())),
                failed: Arc::new(Mutex::new(Vec::new())),
                dead_lettered: Arc::new(Mutex::new(Vec::new())),
                claimed: Arc::new(Mutex::new(Vec::new())),
                fail_claim: Arc::new(AtomicBool::new(false)),
                fail_mark_delivered_for: Arc::new(Mutex::new(None)),
            }
        }
    }

    struct MockClient;
    struct MockTx;

    #[async_trait::async_trait]
    impl OutboxStore for MockStore {
        type Client = MockClient;
        type Tx<'tx> = MockTx;

        async fn acquire(&self) -> Result<Self::Client, OutboxError> {
            Ok(MockClient)
        }

        async fn begin<'a>(
            &self,
            _client: &'a mut Self::Client,
        ) -> Result<Self::Tx<'a>, OutboxError> {
            Ok(MockTx)
        }

        async fn poll<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            batch_size: usize,
            _max_attempts: u32,
        ) -> Result<Vec<OutboxEnvelope>, OutboxError> {
            let mut pending = self.pending.lock().unwrap();
            let take = batch_size.min(pending.len());
            Ok(pending.drain(..take).collect())
        }

        async fn mark_delivered<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            event_id: Uuid,
        ) -> Result<(), OutboxError> {
            {
                let mut slot = self.fail_mark_delivered_for.lock().unwrap();
                if *slot == Some(event_id) {
                    *slot = None;
                    return Err(OutboxError::PoolTimeout);
                }
            }
            self.delivered.lock().unwrap().push(event_id);
            Ok(())
        }

        async fn mark_failed<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            event_id: Uuid,
            error: &str,
            _retry_in: Duration,
        ) -> Result<(), OutboxError> {
            self.failed
                .lock()
                .unwrap()
                .push((event_id, error.to_owned()));
            Ok(())
        }

        async fn mark_dead_lettered<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            event_id: Uuid,
            _error: &str,
        ) -> Result<(), OutboxError> {
            self.dead_lettered.lock().unwrap().push(event_id);
            Ok(())
        }

        async fn commit<'a>(&self, _tx: Self::Tx<'a>) -> Result<(), OutboxError> {
            Ok(())
        }

        async fn claim<'a>(
            &self,
            _tx: &mut Self::Tx<'a>,
            event_ids: &[Uuid],
            _lease_for: Duration,
        ) -> Result<(), OutboxError> {
            if self.fail_claim.load(Ordering::Relaxed) {
                return Err(OutboxError::Internal("claim failed".into()));
            }
            self.claimed.lock().unwrap().extend_from_slice(event_ids);
            Ok(())
        }
    }

    fn registry_with(
        handlers: Vec<Arc<dyn ErasedHandler>>,
    ) -> HashMap<&'static str, Arc<dyn ErasedHandler>> {
        let mut map = HashMap::new();
        for handler in handlers {
            map.insert(handler.event_type(), handler);
        }
        map
    }

    #[tokio::test]
    async fn worker_dispatches_pending_envelopes_and_marks_delivered() {
        let envelopes = vec![
            fresh_envelope(Uuid::from_u128(1)),
            fresh_envelope(Uuid::from_u128(2)),
        ];
        let event_ids: Vec<Uuid> = envelopes.iter().map(|e| e.event_id).collect();
        let store = MockStore::new(envelopes);

        let seen = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(RecordingHandler {
            seen: Arc::clone(&seen),
        }));
        let registry = registry_with(vec![handler]);

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        assert_eq!(seen.lock().unwrap().len(), 2);
        assert_eq!(
            store.delivered.lock().unwrap().as_slice(),
            event_ids.as_slice()
        );
        assert!(store.failed.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn worker_marks_failed_when_handler_errors() {
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let event_id = envelope.event_id;
        let store = MockStore::new(vec![envelope]);

        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(FailingHandler));
        let registry = registry_with(vec![handler]);

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        assert!(store.delivered.lock().unwrap().is_empty());
        let failed = store.failed.lock().unwrap();
        assert_eq!(failed.len(), 1);
        assert_eq!(failed[0].0, event_id);
        assert!(failed[0].1.contains("forced"));
    }

    #[tokio::test]
    async fn worker_marks_failed_when_no_handler_registered() {
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let event_id = envelope.event_id;
        let store = MockStore::new(vec![envelope]);

        let registry = HashMap::new();

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let failed = store.failed.lock().unwrap();
        assert_eq!(failed.len(), 1);
        assert_eq!(failed[0].0, event_id);
        assert!(failed[0].1.contains("no handler"));
    }

    #[tokio::test]
    async fn worker_dead_letters_envelope_when_max_attempts_exhausted() {
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let event_id = envelope.event_id;
        let store = MockStore::new(vec![envelope]);

        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(FailingHandler));
        let registry = registry_with(vec![handler]);

        let config = OutboxWorkerConfig {
            max_attempts: 1,
            batch_size: 1,
            ..OutboxWorkerConfig::default()
        };
        let worker = OutboxWorker::new(store.clone(), registry, config);
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let failed = store.failed.lock().unwrap();
        assert_eq!(failed.len(), 1);
        assert_eq!(failed[0].0, event_id);
        let dead = store.dead_lettered.lock().unwrap();
        assert_eq!(dead.as_slice(), &[event_id]);
    }

    #[tokio::test]
    async fn worker_does_not_dead_letter_before_attempts_exhausted() {
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let event_id = envelope.event_id;
        let store = MockStore::new(vec![envelope]);

        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(FailingHandler));
        let registry = registry_with(vec![handler]);

        let config = OutboxWorkerConfig {
            max_attempts: 3,
            batch_size: 1,
            ..OutboxWorkerConfig::default()
        };
        let worker = OutboxWorker::new(store.clone(), registry, config);
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let failed = store.failed.lock().unwrap();
        assert_eq!(failed.len(), 1);
        assert_eq!(failed[0].0, event_id);
        assert!(
            store.dead_lettered.lock().unwrap().is_empty(),
            "should not dead-letter when attempts(1) < max_attempts(3)"
        );
    }

    #[tokio::test]
    async fn worker_claims_envelopes_before_dispatch() {
        let envelopes = vec![
            fresh_envelope(Uuid::from_u128(1)),
            fresh_envelope(Uuid::from_u128(2)),
        ];
        let expected_ids: Vec<Uuid> = envelopes.iter().map(|e| e.event_id).collect();
        let store = MockStore::new(envelopes);

        let seen = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(RecordingHandler {
            seen: Arc::clone(&seen),
        }));
        let registry = registry_with(vec![handler]);

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let claimed = store.claimed.lock().unwrap();
        assert_eq!(
            claimed.as_slice(),
            expected_ids.as_slice(),
            "claim must be called with all polled ids"
        );
    }

    #[tokio::test]
    async fn worker_does_not_claim_when_batch_is_empty() {
        let store = MockStore::new(Vec::new());
        let registry = HashMap::new();

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(150)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        assert!(
            store.claimed.lock().unwrap().is_empty(),
            "claim must not be called when no envelopes are polled"
        );
    }

    #[tokio::test]
    async fn worker_aborts_poll_cycle_when_claim_fails_without_dispatching() {
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let store = MockStore::new(vec![envelope]);
        store.fail_claim.store(true, Ordering::Relaxed);

        let seen = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(RecordingHandler {
            seen: Arc::clone(&seen),
        }));
        let registry = registry_with(vec![handler]);

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        assert!(
            seen.lock().unwrap().is_empty(),
            "handler must not be called when claim fails"
        );
        assert!(
            store.delivered.lock().unwrap().is_empty(),
            "envelope must not be marked delivered when claim fails"
        );
        assert!(
            store.claimed.lock().unwrap().is_empty(),
            "claim ids must not be recorded when claim returns an error"
        );
    }

    #[tokio::test]
    async fn worker_derives_context_ids_from_event_id_stable_across_retries() {
        let event_id = Uuid::from_u128(99);
        let e1 = OutboxEnvelope::new(
            event_id,
            &UserRegistered {
                user_id: Uuid::from_u128(1),
            },
        )
        .unwrap();
        let e2 = OutboxEnvelope::new(
            event_id,
            &UserRegistered {
                user_id: Uuid::from_u128(2),
            },
        )
        .unwrap();
        let store = MockStore::new(vec![e1, e2]);

        let captured_ids = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn ErasedHandler> =
            Arc::new(TypedHandler::new(ContextCapturingHandler {
                captured_ids: Arc::clone(&captured_ids),
            }));
        let registry = registry_with(vec![handler]);

        let worker = OutboxWorker::new(store.clone(), registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let ids = captured_ids.lock().unwrap();
        assert_eq!(ids.len(), 2, "both envelopes must be dispatched");
        assert_eq!(
            ids[0], ids[1],
            "message_id must be identical across dispatches of the same event_id"
        );
        assert_eq!(
            ids[0],
            MessageId::from(event_id),
            "message_id must equal MessageId::from(event_id)"
        );
    }

    #[tokio::test]
    async fn worker_stops_promptly_on_cancellation() {
        let store = MockStore::new(Vec::new());
        let registry = HashMap::new();
        let worker = OutboxWorker::new(store, registry, OutboxWorkerConfig::default());
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        cancel.cancel();
        let started = std::time::Instant::now();
        join.await.unwrap().unwrap();
        assert!(
            started.elapsed() < Duration::from_secs(1),
            "worker took {:?} to stop",
            started.elapsed()
        );
    }

    /// Handler that never resolves, used to prove `dispatch_timeout` is
    /// enforced as a hard deadline (#229).
    struct HangingHandler;
    impl Handler<UserRegistered> for HangingHandler {
        type Error = OutboxError;
        async fn handle(
            &self,
            _event: UserRegistered,
            _ctx: &HandlerContext,
        ) -> Result<(), Self::Error> {
            std::future::pending::<()>().await;
            unreachable!("hanging handler never resolves")
        }
    }

    #[tokio::test(start_paused = true)]
    async fn worker_enforces_dispatch_timeout_on_a_hung_handler() {
        // #229: a handler that never returns must not stall the worker. With
        // dispatch_timeout enforced, the envelope is marked failed instead.
        let envelope = fresh_envelope(Uuid::from_u128(1));
        let event_id = envelope.event_id;
        let store = MockStore::new(vec![envelope]);

        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(HangingHandler));
        let registry = registry_with(vec![handler]);

        let config = OutboxWorkerConfig {
            dispatch_timeout: Duration::from_millis(50),
            batch_size: 1,
            ..OutboxWorkerConfig::default()
        };
        let worker = OutboxWorker::new(store.clone(), registry, config);
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        // Advance virtual time well past the dispatch timeout.
        tokio::time::sleep(Duration::from_millis(500)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        let failed = store.failed.lock().unwrap();
        assert_eq!(failed.len(), 1, "hung handler must be recorded as failed");
        assert_eq!(failed[0].0, event_id);
        assert!(
            failed[0].1.contains("timed out"),
            "failure must be the dispatch timeout, got {:?}",
            failed[0].1
        );
        assert!(
            store.delivered.lock().unwrap().is_empty(),
            "a timed-out envelope must not be marked delivered"
        );
    }

    #[tokio::test]
    async fn worker_settles_remaining_batch_when_one_ack_fails() {
        // #231: a transient ack failure on one envelope must not abandon the
        // rest of the claimed batch.
        let e1 = fresh_envelope(Uuid::from_u128(1));
        let e2 = fresh_envelope(Uuid::from_u128(2));
        let id1 = e1.event_id;
        let id2 = e2.event_id;
        let store = MockStore::new(vec![e1, e2]);
        *store.fail_mark_delivered_for.lock().unwrap() = Some(id1);

        let seen = Arc::new(Mutex::new(Vec::new()));
        let handler: Arc<dyn ErasedHandler> = Arc::new(TypedHandler::new(RecordingHandler {
            seen: Arc::clone(&seen),
        }));
        let registry = registry_with(vec![handler]);

        let config = OutboxWorkerConfig {
            batch_size: 2,
            ..OutboxWorkerConfig::default()
        };
        let worker = OutboxWorker::new(store.clone(), registry, config);
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        tokio::time::sleep(Duration::from_millis(200)).await;
        cancel.cancel();
        join.await.unwrap().unwrap();

        // The first envelope's ack failed (transient), but the second must
        // still have been dispatched and marked delivered.
        let delivered = store.delivered.lock().unwrap();
        assert!(
            delivered.contains(&id2),
            "second envelope must be delivered despite the first ack failing, got {delivered:?}"
        );
        assert!(
            seen.lock().unwrap().len() >= 2,
            "both envelopes must have been dispatched to the handler"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn worker_observes_cancellation_during_a_long_poll_interval() {
        // #231 defect 1: cancellation arriving during the poll sleep must be
        // observed promptly, not after the full poll_interval elapses.
        let store = MockStore::new(Vec::new());
        let registry = HashMap::new();
        let config = OutboxWorkerConfig {
            poll_interval: Duration::from_secs(3600),
            ..OutboxWorkerConfig::default()
        };
        let worker = OutboxWorker::new(store, registry, config);
        let cancel = CancellationToken::new();
        let join = tokio::spawn(worker.run(cancel.clone()));

        // Let the worker reach the sleep, then cancel mid-sleep.
        tokio::time::sleep(Duration::from_millis(1)).await;
        cancel.cancel();

        // Without racing the sleep against cancellation this would hang for the
        // full hour of virtual time; with the fix it returns immediately.
        tokio::time::timeout(Duration::from_secs(1), join)
            .await
            .expect("worker must stop without waiting out the poll interval")
            .unwrap()
            .unwrap();
    }

    #[test]
    fn lease_for_scales_with_batch_size() {
        // #215: the batch lease must cover the worst-case sequential dispatch
        // of the whole batch, i.e. batch_len * dispatch_timeout.
        let config = OutboxWorkerConfig {
            dispatch_timeout: Duration::from_secs(30),
            ..OutboxWorkerConfig::default()
        };
        let store = MockStore::new(Vec::new());
        let worker = OutboxWorker::new(store, HashMap::new(), config);

        assert_eq!(worker.lease_for(1), Duration::from_secs(30));
        assert_eq!(worker.lease_for(10), Duration::from_secs(300));
        // An empty batch is never claimed, but the helper must stay safe.
        assert_eq!(worker.lease_for(0), Duration::from_secs(30));
    }
}