Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/maintenance-purge-in-flight.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
---

fix(maintenance): keep a timed-out purge and wait on it, instead of starting another (#1103)

A retention purge that outlived its 5 s cap was detached, not stopped: the pass returned, the loop cleared its running flag, and every later tick started another purge, so a store whose cleanup was slower than the interval accumulated purges competing for the same database. The worker now holds the timed-out purge. The next pass waits on it again (with the same cap) instead of starting a second one, and reports its counts if it finishes then; only once it has finished does a pass start a new purge. A purge that finishes between passes has its result logged rather than lost. The loop logs each pass's outcome. A purge that never returns now holds retention until it does or the relay restarts, rather than being joined by a new purge every tick; each pass that waits on it logs how many passes it has waited. Rust-only; no published package changes.
165 changes: 139 additions & 26 deletions crates/nostream-services/src/workers/maintenance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,22 @@
//! concurrently and is awaited last, capped at [`CLEAR_OLD_EVENTS_TIMEOUT_MS`]. A pass error
//! is logged and leaves the loop running; a tick that lands while a pass is still running is
//! skipped.
//!
//! A purge that outlives its cap is kept, not detached (#1103): the next pass waits on it again
//! rather than starting a second one, so a store whose cleanup is slower than the interval has
//! one purge running, never one per tick. The capture detaches it (`Promise.race` cannot cancel
//! the losing promise); this is a deliberate divergence. The cost is that a purge that never
//! returns holds retention until it does or the relay restarts — nothing aborts it, because
//! cancelling a store write midway is not a decision for this loop — so every pass that waits on
//! it logs how many passes it has waited.

use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use chrono::{DateTime, Utc};
use tokio::task::JoinHandle;

use nostream_config::Settings;
use nostream_config::settings::Nip05Mode;
Expand Down Expand Up @@ -52,15 +61,26 @@ pub const DEFAULT_NIP05_MAX_CONSECUTIVE_FAILURES: i32 = 20;
/// The delivery-log retention when settings omit it (`src/app/maintenance-worker.ts:288`).
pub const DEFAULT_DELIVERY_LOG_RETENTION_DAYS: i64 = 30;

/// What one pass did, for the loop's log line and for the tests that pin the steps: whether the
/// purge outlived its cap, and the counts the store answered when it completed. A failed or
/// timed-out purge has no counts — zeros there would read as a pass that found nothing to do.
/// What one pass did, for the loop's log line and for the tests that pin the steps: whether it
/// started a purge or waited on one an earlier pass started, whether that purge outlived the
/// cap, and the counts the store answered when it completed. A failed or timed-out purge has no
/// counts — zeros there would read as a pass that found nothing to do.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PassOutcome {
pub purge_started: bool,
pub purge_timed_out: bool,
pub counts: Option<EventPurgeCounts>,
}

/// A purge the worker owns, so a timed-out one is still known to be running.
type PurgeHandle = JoinHandle<Result<EventPurgeCounts, ServicesError>>;

/// A purge that outlived its pass, and how many passes have timed out waiting on it.
struct OutstandingPurge {
handle: PurgeHandle,
passes_waited: u64,
}

/// The four steps, so a test can instrument their order without a store or a network.
pub trait MaintenanceTasks: Send + Sync {
fn clear_old_events(
Expand All @@ -83,6 +103,8 @@ pub struct MaintenanceWorker {
interval: Duration,
purge_timeout: Duration,
running: AtomicBool,
/// A purge that outlived its pass's cap and has not been seen to finish.
outstanding_purge: Mutex<Option<OutstandingPurge>>,
}

impl MaintenanceWorker {
Expand All @@ -99,13 +121,50 @@ impl MaintenanceWorker {
interval,
purge_timeout,
running: AtomicBool::new(false),
outstanding_purge: Mutex::new(None),
}
}

/// One pass, in the capture's order.
///
/// The purge is the one an earlier pass left running, when there is one; otherwise this
/// pass starts it. Passes must not overlap or be cancelled midway — [`Self::run`] runs one
/// at a time, to completion. Between taking the held purge and storing it back, its handle
/// lives only in this pass: a pass dropped there detaches it again (the purge keeps running,
/// untracked, and the next pass starts another), and an overlapping pass finds no held purge
/// and starts its own.
pub async fn run_pass(&self) -> PassOutcome {
let purge_tasks = Arc::clone(&self.tasks);
let purge = tokio::spawn(async move { purge_tasks.clear_old_events().await });
let (mut purge, passes_waited, purge_started) = match self.take_outstanding_purge() {
Some(previous) if !previous.handle.is_finished() => {
// On the first wait and every tenth after it, so a purge that never returns
// does not write a warning every minute; the cap's own error is per pass.
if previous.passes_waited == 1 || previous.passes_waited % 10 == 0 {
tracing::warn!(
passes_waited = previous.passes_waited,
"the previous retention purge is still running; this pass waits on it instead of starting another"
);
} else {
tracing::debug!(
passes_waited = previous.passes_waited,
"the previous retention purge is still running"
);
}

(previous.handle, previous.passes_waited, false)
}
finished => {
// It ended between passes: its result is already there and nothing awaits it,
// so read it now rather than lose it.
if let Some(previous) = finished {
log_late_purge(previous.handle.await);
}

let purge_tasks = Arc::clone(&self.tasks);
let purge = tokio::spawn(async move { purge_tasks.clear_old_events().await });

(purge, 0, true)
}
};

// Give the purge its first poll so the order is the capture's: started, then the
// remaining steps, then awaited.
Expand All @@ -125,32 +184,67 @@ impl MaintenanceWorker {
tracing::error!(error = %error, "Unable to walk pending invoices");
}

let (purge_timed_out, counts) = match tokio::time::timeout(self.purge_timeout, purge).await
{
Ok(Ok(Ok(counts))) => (false, Some(counts)),
Ok(Ok(Err(error))) => {
tracing::error!(error = %error, "unable to clear old events");
(false, None)
}
Ok(Err(error)) => {
tracing::error!(error = %error, "the retention task ended abnormally");
(false, None)
}
Err(_) => {
tracing::error!(
timeout_ms = self.purge_timeout.as_millis(),
"unable to clear old events: clearOldEvents timed out"
);
(true, None)
}
};
let (purge_timed_out, counts) =
match tokio::time::timeout(self.purge_timeout, &mut purge).await {
Ok(Ok(Ok(counts))) => (false, Some(counts)),
Ok(Ok(Err(error))) => {
tracing::error!(error = %error, "unable to clear old events");
(false, None)
}
Ok(Err(error)) => {
tracing::error!(error = %error, "the retention task ended abnormally");
(false, None)
}
Err(_) => {
tracing::error!(
timeout_ms = self.purge_timeout.as_millis(),
"unable to clear old events: clearOldEvents timed out"
);
// Keep it: dropping the handle would detach a purge that is still working.
self.store_outstanding_purge(OutstandingPurge {
handle: purge,
passes_waited: passes_waited.saturating_add(1),
});
(true, None)
}
};

PassOutcome {
purge_started,
purge_timed_out,
counts,
}
}

fn take_outstanding_purge(&self) -> Option<OutstandingPurge> {
self.outstanding_purge
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}

/// Holds a timed-out purge. The slot is empty here unless two passes overlapped; then the
/// other pass's purge is kept rather than overwritten, since dropping a handle detaches a
/// purge that is still working — the defect this slot exists to remove — and this one is
/// left untracked instead, loudly.
fn store_outstanding_purge(&self, purge: OutstandingPurge) {
let mut slot = self
.outstanding_purge
.lock()
.unwrap_or_else(PoisonError::into_inner);

debug_assert!(slot.is_none(), "two maintenance passes overlapped");

if slot.is_some() {
tracing::error!(
"two maintenance passes overlapped; a timed-out retention purge is no longer tracked"
);
return;
}

*slot = Some(purge);
}

fn payments_enabled(&self) -> bool {
self.settings
.payments
Expand All @@ -175,14 +269,33 @@ impl MaintenanceWorker {
continue;
}

self.run_pass().await;
let outcome = self.run_pass().await;
self.running.store(false, Ordering::SeqCst);
tracing::debug!(?outcome, "maintenance pass finished");
}
}
}
}
}

/// Logs the result of a purge that finished after its own pass stopped waiting for it.
fn log_late_purge(result: Result<Result<EventPurgeCounts, ServicesError>, tokio::task::JoinError>) {
match result {
Ok(Ok(counts)) => tracing::info!(
deleted = counts.deleted,
expired = counts.expired,
retained = counts.retained,
"a retention purge that outlived its pass finished"
),
Ok(Err(error)) => {
tracing::error!(error = %error, "unable to clear old events");
}
Err(error) => {
tracing::error!(error = %error, "the retention task ended abnormally");
}
}
}

/// The production steps, over the stores and the two services.
pub struct MaintenanceRunner {
settings: Arc<Settings>,
Expand Down
Loading
Loading