diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index 161d6f8a..47eba34c 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -342,6 +342,7 @@ dependencies = [ "file-rotate", "fs2", "futures", + "humantime", "libc", "mime_guess", "muse-code-sdk", @@ -1040,6 +1041,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + [[package]] name = "hyper" version = "1.11.0" diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 9328cc3a..765114e9 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -57,6 +57,7 @@ rusqlite = { version = "0.41", features = ["bundled", "fallible_uint"] } serde_rusqlite = "0.44" weak-table = "0.4" file-rotate = "0.8" +humantime = "2" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading"] } diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 45352166..b96ab3de 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -361,11 +361,14 @@ reaches its size limit. Turn endings, explicit flushes, and daemon shutdown drai available traces without waiting for that interval. Local event logs and transcript copies contain conversation content. Credentials -are excluded from saved routing settings. Storage can grow as sessions accumulate -messages or uploads remain pending. Space used by completed delivery records is -reused, so a database file may keep its previous size after delivery catches up. -Completed sessions become eligible for cleanup after seven days without changes; -unfinished work is retained for recovery. +are excluded from saved routing settings. Storage holds events until they are +translated and spans until every destination accepts them; space they used is +returned to the file system. Spans a destination has accepted none of for the +retention period, such as spans it keeps rejecting, are discarded, as is the +storage of a completed session left unchanged that long. Retention defaults to +seven days; set `BT_TRACE_RETENTION` (or `serve --retention`) to a duration +such as `12h`, `2d` or `1h 30m` to bound disk use more tightly. Cleanup runs +hourly, so expired data is removed by the next pass after it expires. ## Platform and integration coverage diff --git a/bt-daemon/docs/protocol.md b/bt-daemon/docs/protocol.md index 7c88dc6d..a5eac922 100644 --- a/bt-daemon/docs/protocol.md +++ b/bt-daemon/docs/protocol.md @@ -483,7 +483,13 @@ profiles, organizations, and destinations while sharing one daemon. duplicate spans, and a route never receives another route's rows. What remains after delivery is only the continuation and small per-span metadata a resumed session needs; storage of a session that owes nothing is deleted - once it has been inactive for 7 days. Activity is recorded by capture, + once it has been inactive for the retention period (`--retention`, or + `BT_TRACE_RETENTION`, a duration such as `7d`, `12h` or `90m`; default 7 + days). GC runs hourly. A route that has + delivered nothing for that long, such as one whose destination keeps + rejecting its spans, is stopped and its undelivered SpanOps are discarded; + a later event starts it again from the current output. GC returns the space + of deleted rows to the file system. Activity is recorded by capture, translation and delivery, never by opening storage. NDJSON journals written by earlier daemons are read only to import them, at their original positions, and are then deleted; their delivery ledgers are deleted. @@ -498,13 +504,13 @@ profiles, organizations, and destinations while sharing one daemon. session's transcript rather than to its transcript times its turn count. Entries written before mirroring instead carry the whole transcript inline as `_bt_transcript_snapshot`, which translators still accept. Mirrors are - GC'd after 7 days once no retained session references them. + GC'd after the retention period once no retained session references them. - **Managed-run acceptance records.** Alongside session storage, each accepted event that carries a `managed_run_id` also appends `{session_id, route}` to `/managed-runs/.ndjson`. `managed_run.flush` reads this record when the daemon that accepted the events has since restarted or idle-exited, so flush accounting for a child process tree survives a daemon - generation change. GC'd after 7 days. + generation change. GC'd after the retention period. - **Deterministic span ids.** Translators derive span ids as UUIDv5 over stable keys (`session_id`, `turn_id`, `call_id`, …) so a replayed re-emit merges server-side (`_is_merge`) instead of duplicating. diff --git a/bt-daemon/src/args.rs b/bt-daemon/src/args.rs index 1d813851..3f77bd30 100644 --- a/bt-daemon/src/args.rs +++ b/bt-daemon/src/args.rs @@ -9,6 +9,13 @@ use std::path::PathBuf; use crate::agents::{self, Agent, Identity}; use crate::wire; +/// How long `serve` keeps undelivered output and idle session state. +pub(crate) const DEFAULT_RETENTION: std::time::Duration = + std::time::Duration::from_secs(7 * 24 * 60 * 60); + +/// Sets the retention when `--retention` is not given. +pub(crate) const RETENTION_ENV: &str = "BT_TRACE_RETENTION"; + /// Arguments for `serve`. #[derive(Debug, Clone, Args)] pub struct ServeArgs { @@ -27,6 +34,45 @@ pub struct ServeArgs { /// retirement. #[arg(long, default_value_t = 30)] pub session_idle_timeout_secs: u64, + /// Discard output a destination has not accepted, and session state left + /// idle, after this long, such as `7d`, `12h` or `90m`. Lower it to bound + /// disk use more tightly when a destination keeps rejecting spans. + /// Defaults to `BT_TRACE_RETENTION`, or 7 days. + #[arg(long, value_parser = parse_retention)] + pub retention: Option, +} + +impl ServeArgs { + /// How long undelivered output and idle session state are kept. + pub(crate) fn retention(&self) -> std::time::Duration { + resolve_retention(self.retention, crate::env::var(RETENTION_ENV)) + } +} + +/// A positive human-readable duration, such as `7d`, `12h` or `1h 30m`. +fn parse_retention(value: &str) -> Result { + match humantime::parse_duration(value.trim()) { + Ok(retention) if !retention.is_zero() => Ok(retention), + Ok(_) => Err("retention must be longer than zero".into()), + Err(error) => Err(format!( + "{error}; expected a duration such as 7d, 12h or 90m" + )), + } +} + +/// The explicit flag, else a usable duration from the environment, else the +/// default. +fn resolve_retention( + flag: Option, + env: Option, +) -> std::time::Duration { + flag.or_else(|| { + let value = env?; + parse_retention(&value) + .inspect_err(|error| tracing::warn!(%value, "ignoring {RETENTION_ENV}: {error}")) + .ok() + }) + .unwrap_or(DEFAULT_RETENTION) } /// Arguments for `hook`. @@ -310,6 +356,7 @@ pub enum RunSource { mod tests { use super::*; use clap::Parser; + use std::time::Duration; #[derive(Debug, Parser)] struct ImportCli { @@ -327,6 +374,43 @@ mod tests { fn serve_defaults_to_short_journal_backed_session_retirement() { let args = ServeCli::try_parse_from(["test"]).unwrap().args; assert_eq!(args.session_idle_timeout_secs, 30); + assert_eq!(args.retention, None); + } + + #[test] + fn retention_accepts_human_readable_durations() { + let args = ServeCli::try_parse_from(["test", "--retention", "12h"]) + .unwrap() + .args; + assert_eq!(args.retention, Some(Duration::from_secs(12 * 60 * 60))); + for (value, expected) in [("7d", 7 * 24 * 60), ("10m", 10), (" 1h 30m ", 90)] { + assert_eq!( + parse_retention(value), + Ok(Duration::from_secs(expected * 60)), + "{value}" + ); + } + for rejected in ["", "0s", "7", "seven days", "-1h"] { + assert!(parse_retention(rejected).is_err(), "{rejected:?}"); + assert!( + ServeCli::try_parse_from(["test", "--retention", rejected]).is_err(), + "{rejected:?}" + ); + } + } + + #[test] + fn retention_prefers_the_flag_then_a_usable_environment_value() { + let hour = Duration::from_secs(60 * 60); + assert_eq!(resolve_retention(Some(hour), Some("5d".into())), hour); + assert_eq!(resolve_retention(None, Some("2h".into())), 2 * hour); + for unusable in [None, Some("0s"), Some("5")] { + assert_eq!( + resolve_retention(None, unusable.map(String::from)), + DEFAULT_RETENTION, + "{unusable:?}" + ); + } } #[test] diff --git a/bt-daemon/src/collections/session.rs b/bt-daemon/src/collections/session.rs index c8b2ac83..69ce51df 100644 --- a/bt-daemon/src/collections/session.rs +++ b/bt-daemon/src/collections/session.rs @@ -3,8 +3,8 @@ //! Everything that spans both collections, such as handing an input's //! translation over or deciding the session owes nothing, lives here. use super::span_ops::{ - decode_roots, detach_attachments, encode_roots, prune, save_metadata, store_attachments, - Translated, + decode_roots, detach_attachments, encode_roots, prune, save_metadata, stalled, + store_attachments, Translated, }; use super::store::{select, One, SessionStorage, NOW_MS}; use crate::pipeline::live::{Record, SharedOp}; @@ -238,35 +238,36 @@ impl SessionStorage { /// Expire what a live session no longer uses once `retention` passes: /// capture identities, metadata of spans that ended or were never - /// completed, and heads that were registered for output but never - /// subscribed (such as a route whose credentials never resolved) and have - /// owed it that long. Ops no remaining head needs are then deleted. A - /// subscribed head held by a failure is kept for recovery, and so is every - /// route named in `live`, which has an active delivery. + /// completed, and the heads of [`stalled`](Self::stalled) routes. Ops no + /// remaining head needs are then deleted. Every route named in `live`, + /// which has an active delivery, is kept. pub async fn expire(&self, retention: Duration, live: Vec) -> anyhow::Result<()> { let retention = i64::try_from(retention.as_millis()).unwrap_or(i64::MAX); self.write(move |tx| { - let cutoff: i64 = tx.one(&format!("SELECT {NOW_MS}-?"), [retention])?; - tx.execute("DELETE FROM captured WHERE at_ms(0))?; - rows.collect::, _>>()? - }; - for route in stuck.into_iter().filter(|route| !live.contains(route)) { - tracing::warn!(%route, "undelivered output expired for a route that never subscribed"); - tx.execute("DELETE FROM heads WHERE route=?", [route])?; - } - prune(tx) - }) - .await + let cutoff: i64 = tx.one(&format!("SELECT {NOW_MS}-?"), [retention])?; + tx.execute("DELETE FROM captured WHERE at_ms = + tx.one("SELECT failure FROM heads WHERE route=?", [&route])?; + tracing::warn!(%route, ?failure, "undelivered output expired for a stalled route"); + tx.execute("DELETE FROM heads WHERE route=?", [route])?; + expired = true; + } + if expired && tx.one::("SELECT count(*) FROM heads", [])? == 0 { + // Everything stored was owed only to expired routes. + tx.execute("DELETE FROM ops", [])?; + } + prune(tx) + }) + .await } } diff --git a/bt-daemon/src/collections/span_ops.rs b/bt-daemon/src/collections/span_ops.rs index 473dbedd..aef9175e 100644 --- a/bt-daemon/src/collections/span_ops.rs +++ b/bt-daemon/src/collections/span_ops.rs @@ -229,6 +229,16 @@ pub(super) fn prune(db: &Connection) -> anyhow::Result<()> { Ok(()) } +/// Heads that have owed output since before `cutoff` without delivering any. +pub(super) fn stalled(db: &Connection, cutoff: i64) -> anyhow::Result> { + let mut query = db.prepare( + "SELECT route FROM heads WHERE progress_ms(0))?; + Ok(rows.collect::, _>>()?) +} + /// Heads selected by `filter` that are the same route as `route`, by key. fn same_heads(db: &Connection, filter: &str, route: &SessionRoute) -> anyhow::Result> { let mut query = db.prepare(&format!("SELECT route FROM heads WHERE {filter}"))?; @@ -425,7 +435,6 @@ impl SessionStorage { ), [&key], )?; - tx.execute("UPDATE heads SET subscribed=1 WHERE route=?", [&key])?; Ok(tx.one("SELECT position FROM heads WHERE route=?", [key])?) }) .await?; @@ -515,6 +524,27 @@ impl SessionStorage { .await } + /// Routes that have owed output for `retention` without delivering any of + /// it: a route whose credentials never resolved, or one held by a failure + /// that was never corrected. Their output can no longer be expected to + /// arrive. + pub async fn stalled( + &self, + retention: std::time::Duration, + ) -> anyhow::Result> { + let retention = i64::try_from(retention.as_millis()).unwrap_or(i64::MAX); + let routes = self + .run(move |db| { + let cutoff: i64 = db.one(&format!("SELECT {NOW_MS}-?"), [retention])?; + stalled(db, cutoff) + }) + .await?; + Ok(routes + .iter() + .map(|route| serde_json::from_str(route)) + .collect::>()?) + } + pub async fn routes(&self) -> anyhow::Result> { self.run(|db| { let mut query = db.prepare("SELECT route FROM heads ORDER BY route")?; diff --git a/bt-daemon/src/collections/store.rs b/bt-daemon/src/collections/store.rs index c168ef54..55ada8fc 100644 --- a/bt-daemon/src/collections/store.rs +++ b/bt-daemon/src/collections/store.rs @@ -50,8 +50,8 @@ impl Inner { fn close(&mut self) { if let Some(connection) = self.connection.get_mut().take() { // Reclaim a bounded number of free pages and leave no WAL behind. - if let Err(error) = connection - .execute_batch("PRAGMA incremental_vacuum(256); PRAGMA wal_checkpoint(TRUNCATE)") + if let Err(error) = incremental_vacuum(&connection, "PRAGMA incremental_vacuum(256)") + .and_then(|()| connection.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")) { tracing::warn!(%error, path = %self.path.display(), "session storage could not be compacted on close"); } @@ -123,6 +123,26 @@ impl SessionStorage { .await? } + /// Return the space of deleted rows to the file system. Deleting rows + /// only frees pages inside the file. Databases created before incremental + /// auto-vacuum was enabled are rebuilt once to turn it on; afterwards + /// free pages are released incrementally. + pub async fn compact(&self) -> anyhow::Result<()> { + self.run(|db| { + if db.one::("PRAGMA freelist_count", [])? == 0 { + return Ok(()); + } + if db.one::("PRAGMA auto_vacuum", [])? == 0 { + db.execute_batch("PRAGMA auto_vacuum=INCREMENTAL; VACUUM")?; + } else { + incremental_vacuum(db, "PRAGMA incremental_vacuum")?; + } + db.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?; + Ok(()) + }) + .await + } + /// Hold the storage lock, blocking every operation until released. #[cfg(test)] pub fn lock_storage(&self) -> impl Drop + '_ { @@ -254,6 +274,15 @@ pub(super) fn select( Ok(rows.collect::>()?) } +/// Incremental vacuum frees one page per step, so it must be stepped to the +/// end; `execute_batch` steps each statement only once. +fn incremental_vacuum(db: &Connection, pragma: &str) -> rusqlite::Result<()> { + let mut statement = db.prepare(pragma)?; + let mut rows = statement.query([])?; + while rows.next()?.is_some() {} + Ok(()) +} + /// Read the first column of the one row a query selects. pub(super) trait One { fn one(&self, sql: &str, params: impl Params) -> rusqlite::Result; diff --git a/bt-daemon/src/collections/tests.rs b/bt-daemon/src/collections/tests.rs index 0a23e3b3..e3de1129 100644 --- a/bt-daemon/src/collections/tests.rs +++ b/bt-daemon/src/collections/tests.rs @@ -1,6 +1,7 @@ //! Storage behavior shared by the concrete collections. use super::inspect::{Fault, Inspector, Table}; use super::span_ops::Translated; +use super::store::One; use super::*; use crate::journal::{journal_path, source_journal_path}; use crate::translate::{SpanOp, SpanRow}; @@ -323,6 +324,13 @@ async fn a_live_session_expires_only_what_it_no_longer_uses() { .position; // A route registered for output whose delivery never starts. events.register(&route("unsubscribed")).await.unwrap(); + // A route whose destination keeps rejecting what it is sent. + events.subscribe(&route("rejected")).await.unwrap(); + let rejected = serde_json::to_string(&route("rejected")).unwrap(); + events + .set_failure(&rejected, Some("413 Request Too Long".into())) + .await + .unwrap(); let span = |id: &str, end_ms: Option| { SpanOp::Insert(SpanRow { span_id: id.into(), @@ -353,17 +361,24 @@ async fn a_live_session_expires_only_what_it_no_longer_uses() { let key = serde_json::to_string(&route("delivered")).unwrap(); events.remove_through(&key, delivered, tail).await.unwrap(); let db = Inspector::session(temp.path(), "debug", "session").unwrap(); - assert_eq!( - db.count(Table::Ops), - 2, - "the unsubscribed head holds output" - ); + assert_eq!(db.count(Table::Ops), 2, "undelivered heads hold output"); + assert!(events.stalled(retention).await.unwrap().is_empty()); db.age(retention + std::time::Duration::from_secs(60)) .unwrap(); + let mut stalled: Vec<_> = events + .stalled(retention) + .await + .unwrap() + .into_iter() + .flat_map(|route| route.tags) + .collect(); + stalled.sort(); + assert_eq!(stalled, ["rejected", "unsubscribed"]); let unsubscribed = serde_json::to_string(&route("unsubscribed")).unwrap(); events.expire(retention, vec![unsubscribed]).await.unwrap(); assert_eq!(db.count(Table::Heads), 2, "a live route is never expired"); + assert_eq!(db.count(Table::Ops), 2); events.expire(retention, Vec::new()).await.unwrap(); assert_eq!(db.count(Table::Heads), 1); @@ -375,3 +390,47 @@ async fn a_live_session_expires_only_what_it_no_longer_uses() { "an expired capture identity is recorded again" ); } + +#[tokio::test] +async fn compaction_returns_deleted_space_to_the_file_system() { + let temp = tempfile::tempdir().unwrap(); + let path = super::inspect::session_path(temp.path(), "debug", "session"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + // Earlier daemons created storage without incremental auto-vacuum. + rusqlite::Connection::open(&path) + .unwrap() + .execute_batch("PRAGMA auto_vacuum=NONE; CREATE TABLE filler(value BLOB)") + .unwrap(); + let raw = || rusqlite::Connection::open(&path).unwrap(); + let pragma = |name: &str| raw().one::(&format!("PRAGMA {name}"), []).unwrap(); + let size = || std::fs::metadata(&path).unwrap().len(); + let churn = || { + raw() + .execute_batch( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i<1000) + INSERT INTO filler SELECT randomblob(4096) FROM n; + DELETE FROM filler; PRAGMA wal_checkpoint(TRUNCATE);", + ) + .unwrap() + }; + let storage = SessionStorage::at(&path).await.unwrap(); + assert_eq!(pragma("auto_vacuum"), 0); + + churn(); + let bloated = size(); + assert!(pragma("freelist_count") > 0); + storage.compact().await.unwrap(); + assert_eq!( + pragma("auto_vacuum"), + 2, + "rebuilt with incremental auto-vacuum" + ); + assert_eq!(pragma("freelist_count"), 0); + assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size()); + + churn(); + assert!(pragma("freelist_count") > 0); + storage.compact().await.unwrap(); + assert_eq!(pragma("freelist_count"), 0); + assert!(size() < bloated / 4, "{} of {bloated} bytes remain", size()); +} diff --git a/bt-daemon/src/collections/upgrade.rs b/bt-daemon/src/collections/upgrade.rs index 5ce122fd..c89f77af 100644 --- a/bt-daemon/src/collections/upgrade.rs +++ b/bt-daemon/src/collections/upgrade.rs @@ -99,8 +99,7 @@ pub(super) fn migrate(db: &Connection) -> anyhow::Result<()> { ALTER TABLE span_state ADD COLUMN touched_ms INTEGER NOT NULL DEFAULT 0; UPDATE span_state SET touched_ms={NOW_MS}; ALTER TABLE heads ADD COLUMN progress_ms INTEGER NOT NULL DEFAULT 0; - ALTER TABLE heads ADD COLUMN subscribed INTEGER NOT NULL DEFAULT 0; - UPDATE heads SET progress_ms={NOW_MS}, subscribed=1;" + UPDATE heads SET progress_ms={NOW_MS};" ))?; if version < 6 { // One bounded pass extracts the metadata a schema-5 channel kept diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 763e21b1..77e70cc5 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -34,6 +34,7 @@ pub(crate) const DAEMON_TUNING_ENV_VARS: &[&str] = &[ crate::daemon_log::MAX_MB_ENV, crate::daemon_log::LEVEL_ENV, crate::daemon_log::STDERR_LEVEL_ENV, + crate::args::RETENTION_ENV, ]; pub(crate) fn canonical_env_name(deprecated: &str) -> String { diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 00c1119b..b6e22ec4 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -4,8 +4,9 @@ use super::*; use futures::TryStreamExt; -/// How long recovery state is kept on disk. -pub(super) const RETENTION: Duration = Duration::from_secs(7 * 24 * 60 * 60); +/// The retention `serve` uses unless told otherwise. +#[cfg(test)] +pub(super) const RETENTION: Duration = crate::args::DEFAULT_RETENTION; /// How often that retention is enforced while the daemon keeps running. pub(super) const GC_INTERVAL: Duration = Duration::from_secs(60 * 60); @@ -19,17 +20,22 @@ pub(super) async fn collect_garbage(daemon: &Daemon) { Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => tracing::warn!(%error, "legacy delivery ledger cleanup failed"), } - journal::gc_old_managed_runs(&daemon.data_dir, RETENTION).await; + journal::gc_old_managed_runs(&daemon.data_dir, daemon.retention).await; // Protect references held by every retained session, including sessions // still inside retention and sessions with no registered heads. let Ok(protected) = retained_references(&daemon.data_dir).await else { return; }; - crate::transcript_mirror::gc_old_mirrors(&daemon.data_dir, RETENTION, &protected).await; - gc_old_correlation_dir(&daemon.data_dir.join("correlation"), RETENTION, &protected).await; + crate::transcript_mirror::gc_old_mirrors(&daemon.data_dir, daemon.retention, &protected).await; + gc_old_correlation_dir( + &daemon.data_dir.join("correlation"), + daemon.retention, + &protected, + ) + .await; gc_old_correlation_dir( &daemon.data_dir.join("correlation/parents"), - RETENTION, + daemon.retention, &protected, ) .await; @@ -68,11 +74,22 @@ pub(super) async fn collect_session(daemon: &Daemon, path: &std::path::Path) -> // Output storage that no captured input ever claimed has no owner to // complete it. Keep it only while it may still be in use. drop(session); - if old(path, RETENTION).await { + if old(path, daemon.retention).await { crate::collections::SessionStorage::remove(path).await?; } return Ok(()); }; + // A route that has delivered nothing for the whole retention period, such + // as one whose spans its destination keeps rejecting, is expired below. + // Stop its delivery first; retirement takes the session lock itself. + for route in session.stalled(daemon.retention).await? { + let Ok(key) = DeliveryKey::new(&source, &session_id, &route) else { + continue; + }; + if daemon.sessions.lock().contains_key(&key) { + daemon.retire_session(&key).await; + } + } let namespace = crate::ids::session_namespace(&source, &session_id); let lock = daemon.session_lock(&source, &session_id); let _guard = lock.lock().await; @@ -95,7 +112,8 @@ pub(super) async fn collect_session(daemon: &Daemon, path: &std::path::Path) -> .filter(|key| key.source == source && key.session_id == session_id) .map(|key| key.route.clone()) .collect(); - session.expire(RETENTION, live).await?; + session.expire(daemon.retention, live).await?; + session.compact().await?; if daemon.open_storage.lock().contains_key(&namespace) || daemon.translations.lock().contains_key(&namespace) { @@ -113,7 +131,7 @@ pub(super) async fn collect_session(daemon: &Daemon, path: &std::path::Path) -> // trace instead of re-creating it, so keep it until the session goes cold. // Output that no destination ever subscribed to can never be delivered. let complete = routes.is_empty() || session.complete().await?; - if !complete || session.status().await?.idle_for <= RETENTION { + if !complete || session.status().await?.idle_for <= daemon.retention { return Ok(()); } drop(session); @@ -423,6 +441,7 @@ mod tests { debug_serve_options("test", root), root.into(), Some(startup), + RETENTION, ), ready, ) @@ -639,7 +658,7 @@ mod tests { let (ready, startup) = oneshot::channel(); let mut opts = debug_serve_options("test", tmp.path()); opts.auth_provider = Some(Arc::new(TestAuth)); - let daemon = Daemon::new_with_startup(opts, tmp.path().into(), Some(startup)); + let daemon = Daemon::new_with_startup(opts, tmp.path().into(), Some(startup), RETENTION); let mut fixtures = DistributedFixtures::new(); let parent = ProcessTree::root(1000); let child = ProcessTree::child(1002, 1001, &parent); @@ -696,12 +715,13 @@ mod tests { } #[tokio::test] - async fn completed_inactive_sessions_are_removed_and_every_obligation_retains_one() { + async fn completed_inactive_sessions_are_removed_and_every_current_obligation_retains_one() { for scenario in [ "no_heads", "unresolved", "second_unresolved", "held", + "rejected", "source_held", "untranslated", "active", @@ -742,7 +762,7 @@ mod tests { second.tags.insert("second".into()); Cursor::open(&events, &second).await.unwrap(); } - if scenario != "unresolved" { + if !matches!(scenario, "unresolved" | "rejected") { head.next_batch(8) .await .unwrap() @@ -752,7 +772,7 @@ mod tests { .ok() .unwrap(); } - if scenario == "held" { + if matches!(scenario, "held" | "rejected") { events .set_failure(&head.route, Some("held".into())) .await @@ -785,8 +805,12 @@ mod tests { .unwrap(); } collect_sessions(&daemon).await; - // Output no destination subscribed to can never be delivered. - let complete = matches!(scenario, "complete" | "no_heads"); + // Output that no destination has accepted for the whole retention + // period is expired with the route that owed it. + let complete = matches!( + scenario, + "complete" | "no_heads" | "unresolved" | "second_unresolved" | "rejected" + ); assert_eq!(storage.exists(), !complete, "{scenario}"); for sidecar in ["sqlite-wal", "sqlite-shm"] { assert!( @@ -798,6 +822,85 @@ mod tests { } } + #[tokio::test] + async fn a_live_route_held_by_a_failure_expires_after_retention() { + use crate::pipeline::recovery::Failure; + let tmp = tempfile::tempdir().unwrap(); + let route = SessionRoute { + destination: Some(crate::wire::TraceDestination::ProjectLogs { + project_id: Some("test-project".into()), + project_name: None, + }), + ..Default::default() + }; + let env = event("rejected", route.clone()); + let spans = + crate::collections::SessionStorage::open(tmp.path(), &env.source, &env.session_id) + .await + .unwrap(); + let through = spans.append(&env, None).await.unwrap().unwrap().through; + spans + .translated( + through, + vec![SpanOp::Insert(SpanRow { + span_id: "rejected".into(), + root_span_id: "rejected".into(), + end_ms: Some(1), + ..Default::default() + })], + ) + .await + .unwrap(); + Cursor::open(&spans, &route).await.unwrap(); + let lease = TestAuth + .resolve(&route.auth, AuthResolveReason::Initial) + .await + .unwrap(); + // A rejection that no new settings correct, such as a span too large + // for its destination. + let failure = Failure::legacy( + "413 Request Too Long".into(), + 1, + &route.with_auth(lease.auth), + ); + let key = serde_json::to_string(&route).unwrap(); + spans + .set_failure(&key, Some(serde_json::to_string(&failure).unwrap())) + .await + .unwrap(); + + let mut options = debug_serve_options("test", tmp.path()); + options.auth_provider = Some(Arc::new(TestAuth)); + let daemon = Daemon::new(options, tmp.path().into()); + super::super::recovery::recover_unprocessed_journals(&daemon).await; + daemon.ingress_barrier().await; + let delivery = DeliveryKey::new(&env.source, &env.session_id, &route).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while !daemon.sessions.lock().contains_key(&delivery) { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + + let path = + crate::collections::inspect::session_path(tmp.path(), &env.source, &env.session_id); + let db = crate::collections::inspect::Inspector::open(&path).unwrap(); + collect_sessions(&daemon).await; + assert!(daemon.sessions.lock().contains_key(&delivery)); + assert_eq!(db.heads().len(), 1, "a recent failure is kept for recovery"); + + db.age(RETENTION + Duration::from_secs(3600)).unwrap(); + collect_sessions(&daemon).await; + assert!( + !daemon.sessions.lock().contains_key(&delivery), + "the held delivery is stopped" + ); + assert!(db.heads().is_empty()); + assert_eq!(db.count(crate::collections::inspect::Table::Ops), 0); + drain_all(&daemon).await; + } + #[tokio::test] async fn retained_inputs_protect_only_their_reconstruction_references() { for routed in [true, false] { diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index 1a541088..773d3a3c 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -108,6 +108,8 @@ type StorageSlot = Arc>; pub struct Daemon { version: String, data_dir: PathBuf, + /// How long undelivered and idle state is kept on disk. + retention: Duration, translators: Arc, sink_factory: Arc, auth_provider: Option>, @@ -153,19 +155,21 @@ pub struct Daemon { impl Daemon { #[cfg(test)] fn new(opts: ServeOptions, data_dir: PathBuf) -> Arc { - Self::new_with_startup(opts, data_dir, None) + Self::new_with_startup(opts, data_dir, None, maintenance::RETENTION) } fn new_with_startup( opts: ServeOptions, data_dir: PathBuf, startup: Option>, + retention: Duration, ) -> Arc { let (ingress_tx, ingress_rx) = mpsc::channel(INGRESS_QUEUE_CAPACITY); let startup_cutoffs = startup.as_ref().map(|_| HashMap::new()); let daemon = Arc::new(Daemon { version: opts.version, data_dir, + retention, translators: opts.translators, sink_factory: opts.sink_factory, auth_provider: opts.auth_provider, @@ -267,7 +271,8 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { tracing::info!(socket = %socket.display(), "bt-daemon listening"); let (ready, startup) = oneshot::channel(); - let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup)); + let retention = args.retention(); + let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup), retention); let idle_timeout = Duration::from_secs(args.idle_timeout_secs); let session_idle_timeout = Duration::from_secs(args.session_idle_timeout_secs); let recovery_daemon = daemon.clone(); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index 75676bf8..f5709781 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -1368,6 +1368,7 @@ mod tests { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let options = ServeOptions { version: "test".into(), diff --git a/bt-daemon/tests/cursor_pipeline.rs b/bt-daemon/tests/cursor_pipeline.rs index 2f84551d..ffbb051f 100644 --- a/bt-daemon/tests/cursor_pipeline.rs +++ b/bt-daemon/tests/cursor_pipeline.rs @@ -272,6 +272,7 @@ async fn start_with_sink( socket: Some(socket.into()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let mut options = debug_serve_options("test", data); options.auth_provider = Some(Arc::new(TestAuth)); diff --git a/bt-daemon/tests/distributed_tracing.rs b/bt-daemon/tests/distributed_tracing.rs index 02e65314..752f24d4 100644 --- a/bt-daemon/tests/distributed_tracing.rs +++ b/bt-daemon/tests/distributed_tracing.rs @@ -3414,6 +3414,7 @@ async fn spawn_daemon_with_timeouts( data_dir: Some(data_dir), idle_timeout_secs, session_idle_timeout_secs, + retention: None, }; let daemon = tokio::spawn(async move { let _ = run_serve(args, opts).await; diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index a114434b..7361d113 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -324,6 +324,7 @@ async fn start_routed_daemon( data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let mut opts = debug_serve_options("test", &data_dir); opts.auth_provider = Some(provider); @@ -374,6 +375,7 @@ async fn start_daemon_at_with( data_dir: Some(data_dir), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let opts = ServeOptions { version: "test".to_string(), @@ -455,6 +457,7 @@ async fn start_daemon() -> ( data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, // disable the watchdog for the test session_idle_timeout_secs: 0, + retention: None, }; let mut opts = debug_serve_options("test", &data_dir); opts.auth_provider = Some(Arc::new(TestAuthProvider { @@ -498,6 +501,7 @@ async fn start_tracking_daemon( data_dir: Some(data_dir), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(async move { let _ = run_serve(args, opts).await; @@ -525,6 +529,7 @@ async fn start_slow_daemon() -> (PathBuf, tokio::task::JoinHandle<()>, tempfile: data_dir: Some(data_dir), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(async move { let _ = run_serve(args, opts).await; @@ -564,6 +569,7 @@ async fn start_gated_daemon( data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(async move { let _ = run_serve(args, opts).await; @@ -578,6 +584,7 @@ async fn start_daemon_at(data_dir: PathBuf, socket: PathBuf) -> tokio::task::Joi data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let mut opts = debug_serve_options("test", &data_dir); opts.auth_provider = Some(Arc::new(TestAuthProvider { @@ -638,6 +645,7 @@ async fn rejected_flush_retries_the_span_journal_before_checkpointing() { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let opts = ServeOptions { version: "test".into(), @@ -1769,6 +1777,7 @@ async fn a_second_server_detects_the_existing_daemon() { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let result = tokio::time::timeout( Duration::from_secs(2), @@ -2225,6 +2234,7 @@ async fn start_daemon_with_session_ttl( data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: ttl_secs, + retention: None, }; let mut opts = debug_serve_options("test", &data_dir); opts.auth_provider = Some(Arc::new(TestAuthProvider { @@ -2261,6 +2271,7 @@ async fn start_claude_recording_daemon( data_dir: Some(data_dir), idle_timeout_secs: 0, session_idle_timeout_secs, + retention: None, }; let opts = ServeOptions { version: "test".into(), @@ -2791,6 +2802,7 @@ async fn managed_run_parent_continues_trace_through_live_hooks() { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(run_serve(args, opts)); wait_for(&socket).await; @@ -3256,6 +3268,7 @@ async fn start_grok_debug_daemon_at( data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let opts = ServeOptions { version: env!("CARGO_PKG_VERSION").into(), @@ -3839,6 +3852,7 @@ async fn missing_credentials_recover_without_another_native_event() { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(async move { run_serve(args, options).await.unwrap() }); wait_for(&socket).await; @@ -4047,6 +4061,7 @@ async fn clean_shutdown_delivers_the_shared_retirement_tail_to_every_route() { data_dir: Some(data_dir.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let handle = tokio::spawn(async move { run_serve(args, opts).await.unwrap() }); wait_for(&socket).await; @@ -4222,6 +4237,7 @@ async fn changed_settings_resume_the_original_rejected_route_through_ingress() { data_dir: Some(data.clone()), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; tokio::spawn(async move { run_serve(args, opts).await.unwrap() }) }; @@ -4574,6 +4590,7 @@ async fn managed_run_flush_shares_one_budget_and_returns_pending_counts() { data_dir: Some(data_dir), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }, options, ) diff --git a/bt-daemon/tests/root_provenance.rs b/bt-daemon/tests/root_provenance.rs index a57e6fa1..af0bd5aa 100644 --- a/bt-daemon/tests/root_provenance.rs +++ b/bt-daemon/tests/root_provenance.rs @@ -94,6 +94,7 @@ impl Daemon { data_dir: Some(tmp.join("data")), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let opts = ServeOptions { version: version.into(), diff --git a/bt-daemon/tests/support/import_daemon.rs b/bt-daemon/tests/support/import_daemon.rs index d01f3620..da21eddf 100644 --- a/bt-daemon/tests/support/import_daemon.rs +++ b/bt-daemon/tests/support/import_daemon.rs @@ -67,6 +67,7 @@ pub async fn target(output: &Path, config: Option) -> ImportTarge data_dir: Some(root.join("data")), idle_timeout_secs: 0, session_idle_timeout_secs: 0, + retention: None, }; let options = ServeOptions { version: "test".into(),