Skip to content

Commit 3489cb2

Browse files
committed
feat(auth): cleanup that keeps failing raises an alert
When a cleanup pass failed, it only logged the error, so expired state, personal data past its retention and finished deliveries could stay indefinitely without anyone hearing of it. Now the third failed pass in a row on a replica raises the cleanup_failing alert, and the next pass that works clears it. One failure may be the database's passing failure, so it raises nothing.
1 parent d6d5694 commit 3489cb2

5 files changed

Lines changed: 148 additions & 67 deletions

File tree

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

Lines changed: 75 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,8 @@ struct Cleanup {
277277
budget: Duration,
278278
/// Passes in a row on this replica that ran out of time.
279279
overruns: Streak,
280+
/// Passes in a row on this replica that failed.
281+
failures: Streak,
280282
}
281283

282284
impl Cleanup {
@@ -286,6 +288,9 @@ impl Cleanup {
286288
/// alert is raised: the next pass picks up what one leaves, so a single
287289
/// burst is no problem.
288290
const BEHIND_AFTER: u32 = 3;
291+
/// Passes in a row that fail before the [`Alert::CleanupFailing`] alert is
292+
/// raised: a single one may be the database's passing failure.
293+
const FAILING_AFTER: u32 = 3;
289294

290295
/// Pause between full batches, allowing live requests to use the pool.
291296
const PAUSE: Duration = Duration::from_millis(100);
@@ -297,41 +302,20 @@ impl Cleanup {
297302
Self {
298303
budget: Self::BUDGET,
299304
overruns: Streak::new(Self::BEHIND_AFTER),
305+
failures: Streak::new(Self::FAILING_AFTER),
300306
}
301307
}
302308

303-
/// Runs one batch and returns how many rows it changed. Abandoning stuck keys
304-
/// needs a transaction of its own, so its locks last until it decides.
305-
async fn batch(connection: &mut ExclusiveConnection) -> Result<u64, DatabaseError> {
306-
let mut tx = connection.begin().await?;
307-
let abandoned = tx.abandon_stuck_deliveries(Self::BATCH_SIZE).await?;
308-
tx.commit().await?;
309-
let purged = connection
310-
.maintenance()
311-
.purge_expired_auth_state(Self::BATCH_SIZE)
312-
.await?;
313-
Ok(abandoned + purged)
314-
}
315-
}
316-
317-
impl ExclusiveJob for Cleanup {
318-
const NAME: &'static str = "cleanup";
319-
const LOCK: LockKey = LockKey::Cleanup;
320-
const EVERY: Duration = Duration::from_mins(5);
321-
type Error = DatabaseError;
322-
323-
/// Stops after the current batch once shutdown is requested. The
324-
/// [`Self::BEHIND_AFTER`]th pass in a row that runs out of time raises the
325-
/// [`Alert::CleanupBehind`] alert, and one that deletes everything due clears
326-
/// it.
327-
async fn run(
309+
/// Drains one pass, until it finds nothing, runs out of time or shutdown is
310+
/// requested. Returns whether it ran out of time, or `None` when shutdown
311+
/// stopped it.
312+
async fn drain(
328313
&self,
329314
connection: &mut ExclusiveConnection,
330315
shutdown: &Shutdown,
331-
) -> Result<(), DatabaseError> {
316+
) -> Result<Option<bool>, DatabaseError> {
332317
let started = Instant::now();
333318
let deadline = started + self.budget;
334-
// Whether the pass fell behind, unless shutdown stopped it.
335319
let mut behind = Some(false);
336320
let mut changed = Self::batch(connection).await?;
337321
while changed > 0 {
@@ -353,24 +337,80 @@ impl ExclusiveJob for Cleanup {
353337
changed = Self::batch(connection).await?;
354338
}
355339
CLEANUP_DURATION.record(started.elapsed().as_secs_f64(), &());
356-
let Some(behind) = behind else {
357-
return Ok(());
340+
Ok(behind)
341+
}
342+
343+
/// Changes the alerts after a pass that ended with `drained`, and returns
344+
/// how it ended. The [`Self::FAILING_AFTER`]th pass in a row that fails
345+
/// raises [`Alert::CleanupFailing`], and one that works clears it. The
346+
/// [`Self::BEHIND_AFTER`]th in a row that runs out of time raises
347+
/// [`Alert::CleanupBehind`], and one that deletes everything due clears it. A
348+
/// pass that shutdown stopped changes neither.
349+
async fn ended(
350+
&self,
351+
connection: &mut ExclusiveConnection,
352+
drained: Result<Option<bool>, DatabaseError>,
353+
) -> Result<(), DatabaseError> {
354+
let behind = match drained {
355+
Ok(Some(behind)) => behind,
356+
Ok(None) => return Ok(()),
357+
Err(error) => {
358+
let alert = Alert::CleanupFailing {};
359+
self.failures
360+
.failed(connection, JobName::Cleanup, alert)
361+
.await;
362+
return Err(error);
363+
}
358364
};
359-
if !behind {
365+
self.failures.reset();
366+
let fell_behind = if behind {
367+
self.overruns.extend()
368+
} else {
360369
self.overruns.reset();
361-
} else if !self.overruns.extend() {
362-
return Ok(());
363-
}
370+
false
371+
};
364372
let mut tx = connection.begin().await?;
365373
let context = EventContext::system(JobName::Cleanup);
366374
let mut alerts = Alerts::new(&mut tx, &context);
367-
if behind {
375+
alerts.clear(AlertKind::CleanupFailing).await?;
376+
if fell_behind {
368377
alerts.raise(Alert::CleanupBehind {}).await?;
369-
} else {
378+
} else if !behind {
370379
alerts.clear(AlertKind::CleanupBehind).await?;
371380
}
372381
tx.commit().await
373382
}
383+
384+
/// Runs one batch and returns how many rows it changed. Abandoning stuck keys
385+
/// needs a transaction of its own, so its locks last until it decides.
386+
async fn batch(connection: &mut ExclusiveConnection) -> Result<u64, DatabaseError> {
387+
let mut tx = connection.begin().await?;
388+
let abandoned = tx.abandon_stuck_deliveries(Self::BATCH_SIZE).await?;
389+
tx.commit().await?;
390+
let purged = connection
391+
.maintenance()
392+
.purge_expired_auth_state(Self::BATCH_SIZE)
393+
.await?;
394+
Ok(abandoned + purged)
395+
}
396+
}
397+
398+
impl ExclusiveJob for Cleanup {
399+
const NAME: &'static str = "cleanup";
400+
const LOCK: LockKey = LockKey::Cleanup;
401+
const EVERY: Duration = Duration::from_mins(5);
402+
type Error = DatabaseError;
403+
404+
/// Stops after the current batch once shutdown is requested. Raises and
405+
/// clears its alerts as [`Self::ended`] says.
406+
async fn run(
407+
&self,
408+
connection: &mut ExclusiveConnection,
409+
shutdown: &Shutdown,
410+
) -> Result<(), DatabaseError> {
411+
let drained = self.drain(connection, shutdown).await;
412+
self.ended(connection, drained).await
413+
}
374414
}
375415

376416
/// Runs in a row on this replica that ended one way, such as cleanup passes that

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

Lines changed: 51 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -233,37 +233,15 @@ async fn failing_purges_raise_their_alert_until_none_fail() {
233233
#[ignore = "requires TEST_DATABASE_URL"]
234234
async fn cleanup_that_keeps_falling_behind_raises_its_alert() {
235235
let database = crate::admin::tests::Harness::isolated().await.database;
236-
// The database crate's lock tests take the same lock, on the same cluster.
237-
let mut lock = tokio::time::timeout(Duration::from_secs(30), async {
238-
loop {
239-
if let Some(lock) = database
240-
.try_exclusive(LockKey::Cleanup)
241-
.await
242-
.expect("lock")
243-
{
244-
return lock;
245-
}
246-
tokio::time::sleep(Duration::from_millis(20)).await;
247-
}
248-
})
249-
.await
250-
.expect("the cleanup lock");
236+
let mut lock = cleanup_lock(&database).await;
251237
let shutdown = Shutdown(watch::Sender::new(false).subscribe());
252238
// Out of time as soon as it deletes anything.
253239
let cleanup = Cleanup {
254240
budget: Duration::ZERO,
255241
overruns: Streak::new(Cleanup::BEHIND_AFTER),
242+
failures: Streak::new(Cleanup::FAILING_AFTER),
256243
};
257-
let current = async || {
258-
let mut tx = database.begin().await.expect("transaction");
259-
let current = tx
260-
.alerts()
261-
.current(AlertKind::CleanupBehind)
262-
.await
263-
.expect("current");
264-
tx.commit().await.expect("commit");
265-
current.and_then(|current| current.alert)
266-
};
244+
let current = async || current_alert(&database, AlertKind::CleanupBehind).await;
267245
for pass in 1..=Cleanup::BEHIND_AFTER {
268246
// An expired invitation, for the pass to delete.
269247
let digest = UserId::new().as_uuid().as_u128().to_be_bytes().repeat(2);
@@ -281,3 +259,51 @@ async fn cleanup_that_keeps_falling_behind_raises_its_alert() {
281259
assert_eq!(current().await, None);
282260
lock.release().await.expect("release");
283261
}
262+
263+
/// The third cleanup pass in a row that fails raises the alert of cleanup
264+
/// failing, and a pass that works clears it.
265+
#[tokio::test]
266+
#[ignore = "requires TEST_DATABASE_URL"]
267+
async fn cleanup_that_keeps_failing_raises_its_alert() {
268+
let database = crate::admin::tests::Harness::isolated().await.database;
269+
let mut lock = cleanup_lock(&database).await;
270+
let shutdown = Shutdown(watch::Sender::new(false).subscribe());
271+
let cleanup = Cleanup::new();
272+
let current = async || current_alert(&database, AlertKind::CleanupFailing).await;
273+
for pass in 1..=Cleanup::FAILING_AFTER {
274+
let failed = Err(DatabaseError::NotFound);
275+
assert!(cleanup.ended(&mut lock, failed).await.is_err());
276+
let raised = (pass == Cleanup::FAILING_AFTER).then_some(Alert::CleanupFailing {});
277+
assert_eq!(current().await, raised, "after pass {pass}");
278+
}
279+
cleanup.run(&mut lock, &shutdown).await.expect("run");
280+
assert_eq!(current().await, None);
281+
lock.release().await.expect("release");
282+
}
283+
284+
/// Takes cleanup's lock on `database`, which the database crate's lock tests
285+
/// also take, on the same cluster.
286+
async fn cleanup_lock(database: &Database) -> ExclusiveConnection {
287+
tokio::time::timeout(Duration::from_secs(30), async {
288+
loop {
289+
if let Some(lock) = database
290+
.try_exclusive(LockKey::Cleanup)
291+
.await
292+
.expect("lock")
293+
{
294+
return lock;
295+
}
296+
tokio::time::sleep(Duration::from_millis(20)).await;
297+
}
298+
})
299+
.await
300+
.expect("the cleanup lock")
301+
}
302+
303+
/// What the current alert of `kind` on `database` says, if one is current.
304+
async fn current_alert(database: &Database, kind: AlertKind) -> Option<Alert> {
305+
let mut tx = database.begin().await.expect("transaction");
306+
let current = tx.alerts().current(kind).await.expect("current");
307+
tx.commit().await.expect("commit");
308+
current.and_then(|current| current.alert)
309+
}

‎crates/common/src/alerts.rs‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ crate::str_enum! {
2424
CleanupBehind = "cleanup_behind",
2525
/// See [`Alert::VerificationFailing`].
2626
VerificationFailing = "verification_failing",
27+
/// See [`Alert::CleanupFailing`].
28+
CleanupFailing = "cleanup_failing",
2729
}
2830
}
2931

@@ -50,6 +52,8 @@ pub enum Alert {
5052
/// Auth's verifier keeps failing to verify the audit chain, finding it
5153
/// neither broken nor intact, so nothing checks the history meanwhile.
5254
VerificationFailing {},
55+
/// Cleanup passes keep failing, so nothing that is due is deleted.
56+
CleanupFailing {},
5357
}
5458

5559
impl Alert {
@@ -65,22 +69,24 @@ impl Alert {
6569
Self::PurgesFailing {} => AlertKind::PurgesFailing,
6670
Self::CleanupBehind {} => AlertKind::CleanupBehind,
6771
Self::VerificationFailing {} => AlertKind::VerificationFailing,
72+
Self::CleanupFailing {} => AlertKind::CleanupFailing,
6873
}
6974
}
7075

7176
/// Its payload version inside a recorded event. A new kind, or a new
7277
/// [`ChainProblem`], is one older releases cannot decode, so it fails to
7378
/// compile here until it is given the next version: [`Self::CheckpointRefused`]
7479
/// came in the second, [`Self::PurgesFailing`] in the third and
75-
/// [`Self::CleanupBehind`] in the fourth and [`Self::VerificationFailing`] in
76-
/// the fifth.
80+
/// [`Self::CleanupBehind`] in the fourth, [`Self::VerificationFailing`] in
81+
/// the fifth and [`Self::CleanupFailing`] in the sixth.
7782
#[must_use]
7883
pub const fn version(&self) -> i16 {
7984
match self {
8085
Self::CheckpointRefused(_) => 2,
8186
Self::PurgesFailing {} => 3,
8287
Self::CleanupBehind {} => 4,
8388
Self::VerificationFailing {} => 5,
89+
Self::CleanupFailing {} => 6,
8490
Self::AuditChainBroken(ChainBreak { problem, .. }) => match problem {
8591
ChainProblem::MissingEvent
8692
| ChainProblem::EventBeforeAnchor
@@ -103,6 +109,7 @@ impl Alert {
103109
Self::PurgesFailing {} => "Accounts keep failing to be purged",
104110
Self::CleanupBehind {} => "Cleanup is falling behind",
105111
Self::VerificationFailing {} => "The audit chain can't be verified",
112+
Self::CleanupFailing {} => "Cleanup keeps failing",
106113
}
107114
}
108115

@@ -141,6 +148,11 @@ impl Alert {
141148
the database failing. auth-service audit verify shows the same error. It \
142149
clears once a verification is recorded."
143150
.to_owned(),
151+
Self::CleanupFailing {} => "Cleanup passes keep failing, so expired sign-in state, \
152+
personal data past its retention and finished deliveries stay in the \
153+
database, and stuck deliveries hold back the ones behind them. The logs of \
154+
the cleanup job say why. It clears once a pass works."
155+
.to_owned(),
144156
}
145157
}
146158
}

‎crates/ui/src/admin/events.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -441,9 +441,10 @@ impl EventRow<'_> {
441441
Alert::AuditChainBroken(broken) | Alert::CheckpointRefused(broken) => description
442442
.with("position", broken.position)
443443
.with("problem", broken.problem),
444-
Alert::PurgesFailing {} | Alert::CleanupBehind {} | Alert::VerificationFailing {} => {
445-
description
446-
}
444+
Alert::PurgesFailing {}
445+
| Alert::CleanupBehind {}
446+
| Alert::VerificationFailing {}
447+
| Alert::CleanupFailing {} => description,
447448
}
448449
}
449450

‎docs/dev/architecture/database.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,8 @@ also deletes finished deliveries: succeeded ones after 7 days, failed or cancell
198198
ones after 30. Deleting a failed ordered delivery cancels the ones behind it.
199199
The third pass in a row on one replica that runs out of its minute raises the `cleanup_behind`
200200
alert, since the next pass picks up what one leaves, and a pass that deletes
201-
everything due clears it. Jobs like it that must run
201+
everything due clears it. Likewise, the third pass in a row that fails raises
202+
`cleanup_failing`, and a pass that works clears it. Jobs like it that must run
202203
on one replica at a time call `Database::try_exclusive(LockKey)`, which takes a
203204
session-level advisory lock on a dedicated connection outside the pool. The lock
204205
ends with that connection, even when the job is cancelled or the process dies, so
@@ -593,7 +594,8 @@ changes neither.
593594
The sealer raises `checkpoint_refused` when it refuses to sign a checkpoint over
594595
events that no longer match, and clears it once they match again. The account
595596
purge raises `purges_failing` while accounts keep failing to be purged, and
596-
cleanup raises `cleanup_behind` once its passes keep running out of time. The
597+
cleanup raises `cleanup_behind` once its passes keep running out of time, and
598+
`cleanup_failing` once they keep failing. The
597599
verifier raises `verification_failing` once its runs keep failing, and a
598600
recorded verification clears it. The jobs count runs in a row with `Streak`,
599601
on each replica.

0 commit comments

Comments
 (0)