Skip to content

Commit c0853ce

Browse files
authored
test(deliveries): prove a delivery survives a replica killed mid-send (#302)
Epic #26 lists under "Done when": *"A test delivery channel survives a replica being killed mid-send."* Until now, the only coverage faked a dead worker at the repository level. No test ran the real worker loop on two replicas and killed one of them in the middle of `send`. This PR adds that test. Replicas A and B each run the real delivery workers on their own database pool, both against one test database. A's sender hangs in `send`. The test runs twice: - **Killed:** it drops A's workers, which aborts their tasks and closes A's pool, the closest in-process stand-in for SIGKILL. - **Late:** it lets A finish with a refusal after B has already delivered. Both runs check three things: - B sends the delivery with the same ID, the one used as `jti`/`Message-ID`. - B sends only after A's lease expires. - The row ends `succeeded` with no error, so A's late refusal was discarded. To keep the test fast without a 60 s sleep, the lease is now a `Sender::LEASE` constant. It still defaults to 60 s; only the test sender shortens it, to 1 s. That is the only production change. Proof: `just db test` passes all 16 delivery tests, and the new one takes about 3 s. I also broke the queue on purpose twice to check the test catches it: - Removing the claim-token check from `finish`: the late run fails with `(Failed, Some("HTTP 403"))`. - Removing the lease check from `claim`: the killed run fails, because B delivers after 0.07 s instead of waiting for the lease. Reviewed with review-loop: 1 round with 2× GPT-6.1 Sol and Claude Opus 5.5. Verdict: approved > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT-6.1 Sol and Claude Opus 5.5 (via T3 Code)
1 parent 1d4f08d commit c0853ce

3 files changed

Lines changed: 112 additions & 9 deletions

File tree

‎apps/auth-service/src/deliveries/mod.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,6 @@ use thiserror::Error;
3333
use tokio::task::JoinSet;
3434
use tracing::Instrument;
3535

36-
/// How long a worker holds a claimed delivery: well beyond [`SEND_TIMEOUT`].
37-
const LEASE: Duration = Duration::from_mins(1);
3836
/// The longest one send may take, connecting and reading the response included.
3937
const SEND_TIMEOUT: Duration = Duration::from_secs(10);
4038
/// How long an idle worker waits before looking for due deliveries again.
@@ -54,6 +52,9 @@ pub(crate) trait Sender: Send + Sync + 'static {
5452
/// How long after its creation a delivery keeps being retried. A retryable
5553
/// failure that would retry later than this fails it instead.
5654
const MAX_AGE: Duration;
55+
/// How long a worker holds a claimed delivery: well beyond [`SEND_TIMEOUT`].
56+
/// Tests shorten it to see another replica take over a stalled attempt.
57+
const LEASE: Duration = Duration::from_mins(1);
5758

5859
/// Attempts to send `delivery`. Every attempt carries the same
5960
/// [`Delivery::id`], so the receiver can recognize a repeat. Uses
@@ -217,7 +218,7 @@ impl<S: Sender> Worker<S> {
217218
let claimed = tokio::select! {
218219
biased;
219220
() = shutdown.requested() => return,
220-
claimed = deliveries.claim::<S::Channel>(LEASE) => claimed,
221+
claimed = deliveries.claim::<S::Channel>(S::LEASE) => claimed,
221222
};
222223
match claimed {
223224
Ok(Some(delivery)) => {

‎apps/auth-service/src/deliveries/tests.rs‎

Lines changed: 106 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use axum::{
1111
use piquel_common::{DeliveryId, UserId, events::DomainEvent};
1212
use piquel_repository::{DatabaseTransaction, DeliveryStatus, DeliverySummary, NewDelivery};
1313
use std::{marker::PhantomData, net::IpAddr, sync::Mutex};
14+
use tokio::sync::{Notify, mpsc};
1415

1516
/// A retryable failure without `Retry-After`.
1617
const UNAVAILABLE: DeliveryError = DeliveryError::Retryable {
@@ -287,6 +288,8 @@ worker_channels! {
287288
Resent = "test_worker_resent";
288289
/// What an attempt and an idle worker export.
289290
Traced = "test_worker_traced";
291+
/// A replica killed, or stalled, while it sends.
292+
Killed = "test_worker_killed";
290293
}
291294

292295
/// How [`Recorder`] answers a delivery.
@@ -298,6 +301,8 @@ enum Behavior {
298301
Refused,
299302
/// Permanently refused on the first attempt, accepted after.
300303
RefusedOnce,
304+
/// Accepted.
305+
Accepted,
301306
}
302307

303308
/// Sends channel `C`'s deliveries, keeping the ID each attempt carried.
@@ -322,7 +327,7 @@ impl<C: Channel<Recipient = Behavior, Payload = ()>> Sender for Recorder<C> {
322327
}),
323328
Behavior::Refused => Err(refused),
324329
Behavior::RefusedOnce if first => Err(refused),
325-
Behavior::RefusedOnce => Ok(()),
330+
Behavior::RefusedOnce | Behavior::Accepted => Ok(()),
326331
})
327332
}
328333
}
@@ -331,6 +336,14 @@ impl<C: Channel<Recipient = Behavior, Payload = ()>> Sender for Recorder<C> {
331336
/// sending `C`, whose attempts are recorded in the returned list.
332337
async fn workers<C: Channel<Recipient = Behavior, Payload = ()>>()
333338
-> (Database, Jobs, Arc<Mutex<Vec<DeliveryId>>>) {
339+
let database = cleared::<C>().await;
340+
let attempts = Arc::default();
341+
let jobs = Jobs::replica(Recorder::<C>(Arc::clone(&attempts), PhantomData)).await;
342+
(database, jobs, attempts)
343+
}
344+
345+
/// A database with no pending delivery left on `C` by an earlier run.
346+
async fn cleared<C: Channel>() -> Database {
334347
let database = Replicas::database().await;
335348
for summary in database
336349
.deliveries()
@@ -344,10 +357,18 @@ async fn workers<C: Channel<Recipient = Behavior, Payload = ()>>()
344357
.await
345358
.expect("clear");
346359
}
347-
let attempts = Arc::default();
348-
let mut jobs = Jobs::new();
349-
jobs.deliveries(Recorder::<C>(Arc::clone(&attempts), PhantomData), &database);
350-
(database, jobs, attempts)
360+
database
361+
}
362+
363+
impl Jobs {
364+
/// One replica's workers sending with `sender`, on a pool only they hold:
365+
/// dropping them aborts their tasks and closes its connections, as killing the
366+
/// replica's process would.
367+
async fn replica<S: Sender>(sender: S) -> Self {
368+
let mut jobs = Self::new();
369+
jobs.deliveries(sender, &Replicas::database().await);
370+
jobs
371+
}
351372
}
352373

353374
/// Queues a delivery on `C` that the receiver answers with `behavior`.
@@ -492,3 +513,83 @@ async fn a_resent_delivery_carries_the_same_id() {
492513
"both sends carry the delivery's ID"
493514
);
494515
}
516+
517+
/// Replica A's sender: reports the ID its attempt carries, hangs until `release`,
518+
/// then refuses the delivery. Its lease is short, so a stalled attempt outlives it.
519+
struct Stalled {
520+
/// Receives each attempt's delivery ID as its send starts.
521+
entered: mpsc::UnboundedSender<DeliveryId>,
522+
/// Ends the hanging sends.
523+
release: Arc<Notify>,
524+
}
525+
526+
impl Sender for Stalled {
527+
type Channel = Killed;
528+
const MAX_AGE: Duration = Duration::from_hours(1);
529+
const LEASE: Duration = Duration::from_secs(1);
530+
531+
async fn send(&self, delivery: &Delivery<Killed>) -> Result<(), DeliveryError> {
532+
self.entered.send(delivery.id).expect("the test listens");
533+
self.release.notified().await;
534+
Err(DeliveryError::Permanent(Failure::Status(
535+
StatusCode::FORBIDDEN,
536+
)))
537+
}
538+
}
539+
540+
/// A delivery whose replica is killed mid-send, or stalls there, is sent by the
541+
/// other replica, with the same ID, once its lease expires. A stalled replica's
542+
/// late outcome, here a refusal, is discarded.
543+
#[tokio::test]
544+
#[ignore = "requires TEST_DATABASE_URL"]
545+
async fn a_delivery_survives_its_replica_dying_mid_send() {
546+
for killed in [true, false] {
547+
let database = cleared::<Killed>().await;
548+
let (entered, mut sends) = mpsc::unbounded_channel();
549+
let release = Arc::new(Notify::new());
550+
let a = Jobs::replica(Stalled {
551+
entered,
552+
release: Arc::clone(&release),
553+
})
554+
.await;
555+
let id = queue::<Killed>(&database, Behavior::Accepted).await;
556+
let first = tokio::time::timeout(Duration::from_secs(10), sends.recv()).await;
557+
assert_eq!(first, Ok(Some(id)), "A sends the delivery");
558+
let sent = Arc::default();
559+
let b = Jobs::replica(Recorder::<Killed>(Arc::clone(&sent), PhantomData)).await;
560+
let a = if killed {
561+
drop(a);
562+
None
563+
} else {
564+
Some(a)
565+
};
566+
567+
let delivered = wait_for::<Killed, _>(&database, |listed| {
568+
find(listed, id).filter(|d| d.status == DeliveryStatus::Succeeded)
569+
})
570+
.await;
571+
if let Some(a) = a {
572+
release.notify_waiters();
573+
a.shutdown().await.expect("A's late attempt ends");
574+
}
575+
b.shutdown().await.expect("no worker panicked");
576+
577+
let finished = delivered.finished_at.expect("finished") - delivered.created_at;
578+
assert!(
579+
finished >= TimeDelta::from_std(Stalled::LEASE).expect("lease"),
580+
"B waits for A's lease: {finished}, killed: {killed}"
581+
);
582+
assert_eq!(*sent.lock().expect("sent"), [id], "B sends the same ID");
583+
let listed = database
584+
.deliveries()
585+
.list(None, Some(Killed::NAME), 1000)
586+
.await
587+
.expect("list");
588+
let summary = find(&listed, id).expect("the delivery");
589+
assert_eq!(
590+
(summary.status, summary.last_error),
591+
(DeliveryStatus::Succeeded, None),
592+
"A's late refusal is discarded, killed: {killed}"
593+
);
594+
}
595+
}

‎docs/architecture/delivery-queue.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ Auth-service owns sending: the workers, the retry policy and the HTTP client
2323
but before recording the outcome lets its lease expire, and another worker sends
2424
the delivery again. Every attempt carries the same delivery ID, which receivers
2525
use to deduplicate: it is the `jti` of logout tokens and SETs, and the source of
26-
an email's `Message-ID`.
26+
an email's `Message-ID`. Auth-service's `deliveries/tests.rs` kills a replica
27+
mid-send, and stalls another past its lease, to check this end to end.
2728
- **Ordered per key.** Deliveries that share an ordering key are sent one at a
2829
time, in the order their transactions committed, whatever the replicas' clocks
2930
say. A failed one holds back the rest until an operator retries or cancels it,

0 commit comments

Comments
 (0)