diff --git a/.changeset/maintenance-purge-in-flight.md b/.changeset/maintenance-purge-in-flight.md new file mode 100644 index 000000000..5c71ca7e8 --- /dev/null +++ b/.changeset/maintenance-purge-in-flight.md @@ -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. diff --git a/crates/nostream-services/src/workers/maintenance.rs b/crates/nostream-services/src/workers/maintenance.rs index 1140129fa..c5a03adc1 100644 --- a/crates/nostream-services/src/workers/maintenance.rs +++ b/crates/nostream-services/src/workers/maintenance.rs @@ -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; @@ -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, } +/// A purge the worker owns, so a timed-out one is still known to be running. +type PurgeHandle = JoinHandle>; + +/// 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( @@ -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>, } impl MaintenanceWorker { @@ -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. @@ -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 { + 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 @@ -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, 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, diff --git a/crates/nostream-services/tests/maintenance.rs b/crates/nostream-services/tests/maintenance.rs index cf03740af..de3c9cc47 100644 --- a/crates/nostream-services/tests/maintenance.rs +++ b/crates/nostream-services/tests/maintenance.rs @@ -7,7 +7,7 @@ use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, LazyLock, Mutex}; use std::time::Duration; use nostream_config::settings::{ @@ -28,6 +28,7 @@ use nostream_services::testing; use nostream_services::unavailable::ServiceStores; use nostream_services::workers::maintenance::{ MaintenanceRunner, MaintenanceTasks, MaintenanceWorker, NIP05_REVERIFICATION_BATCH_SIZE, + PassOutcome, }; use nostream_storage::repositories::{ EventPurgeCounts, EventRepository, NotificationDeliveryLogRepository, @@ -282,6 +283,178 @@ async fn a_slow_purge_that_outlives_the_timeout_does_not_fail_the_pass() { ); } +fn purge_starts(tasks: &ScriptedTasks) -> usize { + tasks + .entries() + .iter() + .filter(|entry| *entry == "purge started") + .count() +} + +#[tokio::test] +async fn a_purge_still_running_is_awaited_by_the_next_pass_not_started_again() { + let gate = Arc::new(Semaphore::new(0)); + let tasks = ScriptedTasks::new(Arc::clone(&gate), None); + let worker = MaintenanceWorker::new( + Arc::new(testing::settings()), + Arc::clone(&tasks) as Arc, + Duration::from_secs(60), + Duration::from_millis(20), + ); + + let first = worker.run_pass().await; + let second = worker.run_pass().await; + + assert!(first.purge_timed_out && first.purge_started); + assert!( + second.purge_timed_out && !second.purge_started, + "the second pass waits on the first purge: {second:?}" + ); + assert_eq!(purge_starts(&tasks), 1, "one purge, however many passes"); + + // Released before the third pass polls it: that pass is the one that sees it finish, and + // it reports the purge's counts rather than starting another. This relies on the + // single-threaded test runtime: the purge cannot run between `add_permits` and the pass's + // first check, so the pass finds it unfinished and waits on it. + gate.add_permits(1); + let third = worker.run_pass().await; + + assert_eq!( + third, + PassOutcome { + purge_started: false, + purge_timed_out: false, + counts: Some(scripted_counts()), + } + ); + assert_eq!(purge_starts(&tasks), 1); + + // With nothing outstanding, the next pass starts a purge of its own. + gate.add_permits(1); + let fourth = worker.run_pass().await; + + assert!(fourth.purge_started && !fourth.purge_timed_out); + assert_eq!(purge_starts(&tasks), 2); +} + +/// Captures the formatted log so a test can assert on a line, installing the subscriber once for +/// the whole binary. Events from the tests running alongside this one land here too; an assertion +/// names the line it wants rather than the buffer's contents. +static CAPTURED_LOGS: LazyLock>>> = LazyLock::new(|| { + let buffer = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&buffer); + tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::INFO) + .with_writer(move || CapturedWriter(Arc::clone(&sink))) + .try_init() + .ok(); + buffer +}); + +struct CapturedWriter(Arc>>); + +impl std::io::Write for CapturedWriter { + fn write(&mut self, buffer: &[u8]) -> std::io::Result { + self.0 + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .extend_from_slice(buffer); + Ok(buffer.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn captured_text() -> String { + let buffer = CAPTURED_LOGS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .clone(); + String::from_utf8(buffer).unwrap_or_default() +} + +/// The finished purge's counts are read and logged rather than lost. Deleting the +/// `log_late_purge(previous.handle.await)` call leaves every other assertion in this file passing; +/// this one names the line that call writes. +#[tokio::test] +async fn a_purge_that_finished_between_passes_is_read_and_a_new_one_starts() { + // Installs the capturing subscriber before the first pass, so the late line is captured. + let _ = captured_text(); + + let gate = Arc::new(Semaphore::new(0)); + let tasks = ScriptedTasks::new(Arc::clone(&gate), None); + let worker = MaintenanceWorker::new( + Arc::new(testing::settings()), + Arc::clone(&tasks) as Arc, + Duration::from_secs(60), + Duration::from_millis(20), + ); + + let first = worker.run_pass().await; + assert!(first.purge_timed_out && first.purge_started); + + // Let the held purge run to completion before the next pass looks at it. + gate.add_permits(1); + for _ in 0..10 { + tokio::task::yield_now().await; + } + assert!(tasks.entries().contains(&"purge finished".to_owned())); + + gate.add_permits(1); + let second = worker.run_pass().await; + + assert!( + second.purge_started, + "the finished purge is read and a fresh one starts: {second:?}" + ); + assert_eq!(second.counts, Some(scripted_counts())); + assert_eq!(purge_starts(&tasks), 2); + + let captured = captured_text(); + assert!( + captured.contains("a retention purge that outlived its pass finished"), + "the finished purge's result is logged rather than lost: {captured}" + ); + assert!( + captured.contains("deleted=2") && captured.contains("expired=3"), + "the line carries the purge's own counts, not the fresh purge's: {captured}" + ); +} + +#[tokio::test] +async fn ticks_during_a_slow_purge_do_not_pile_up_purges() { + let gate = Arc::new(Semaphore::new(0)); + let tasks = ScriptedTasks::new(Arc::clone(&gate), None); + let shutdown = ShutdownState::new(); + let worker = Arc::new(MaintenanceWorker::new( + Arc::new(testing::settings()), + Arc::clone(&tasks) as Arc, + Duration::from_millis(20), + Duration::from_millis(5), + )); + + let task = tokio::spawn(Arc::clone(&worker).run(shutdown.clone())); + tokio::time::sleep(Duration::from_millis(200)).await; + + let passes = tasks.passes.load(Ordering::SeqCst); + assert!(passes >= 3, "the passes keep running, got {passes}"); + assert_eq!( + purge_starts(&tasks), + 1, + "{passes} passes share the one purge that has not finished" + ); + + shutdown.begin_draining(); + tokio::time::timeout(Duration::from_secs(2), task) + .await + .expect("the worker stops") + .expect("join") + .expect("Ok"); +} + #[tokio::test] async fn the_pass_order_is_the_captures() { let tasks = ScriptedTasks::new(Arc::new(Semaphore::new(0)), Some(Duration::from_millis(30))); diff --git a/docs/rewrite/decisions/0019-maintenance-tools-and-the-run-record.md b/docs/rewrite/decisions/0019-maintenance-tools-and-the-run-record.md index 1c7c6d346..bd1d3b708 100644 --- a/docs/rewrite/decisions/0019-maintenance-tools-and-the-run-record.md +++ b/docs/rewrite/decisions/0019-maintenance-tools-and-the-run-record.md @@ -53,10 +53,15 @@ The alternative — `PassOutcome { counts: EventPurgeCounts }` with zeros on fai because a timed-out purge that reports `{0,0,0}` is indistinguishable from a pass that found nothing to do, and the operator reading the record would believe the second. -**Cost:** one `Option` the loop still discards — `run_pass`'s outcome is dropped at the tick, so -the counts are observable only through `run_pass`'s return value and the door's own call. The -value exists for the tests and for the next reader of the pass; the loop's cadence and its -four-step order are untouched. +**Cost:** one `Option` no consumer reads — the loop logs `run_pass`'s outcome at `debug!` and +keeps nothing of it, so the counts are observable only through `run_pass`'s return value, that +log line and the door's own call. A log line is not a record: nothing reads it back, which is why +D3 still needs a writer. The value exists for the tests and for the next reader of the pass; the +loop's cadence and its four-step order are untouched. + +*Amended by #1103:* `PassOutcome` also carries `purge_started` and `purge_timed_out` — a pass may +wait on a purge an earlier pass left running instead of starting its own, and the outcome says +which — and the loop's `debug!` line above replaced the bare discard. ### D2 — `maintenance_run` runs the purge step through `MaintenanceService`, in the answering process, with no cap of its own @@ -89,9 +94,9 @@ The alternatives cost more than the fact is worth here: a file needs a writer in `MaintenanceWorker` (which has no clock and no path), a TTL policy and a second writer rule beside the audit file's; a sixth key in the published document costs an amendment to ADR 0016's five-key shape plus a writer at the loop, which already holds what the key would report — -`MaintenanceWorker`'s tick calls `run_pass` and discards its `PassOutcome` -(`crates/nostream-services/src/workers/maintenance.rs:178`), so the counts are produced and -dropped rather than absent. +`MaintenanceWorker`'s tick calls `run_pass` and keeps nothing of its `PassOutcome` beyond a +`debug!` line (`crates/nostream-services/src/workers/maintenance.rs`, `run`), so the counts are +produced and dropped rather than absent. **Cost:** the record is **this process's own**. A door run beside a daemon is a supported deployment, not an excluded one: the stdio mode is its own process over the same config