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
7 changes: 7 additions & 0 deletions bt-daemon/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bt-daemon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
13 changes: 8 additions & 5 deletions bt-daemon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 9 additions & 3 deletions bt-daemon/docs/protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
`<data_dir>/managed-runs/<managed_run_id>.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.
84 changes: 84 additions & 0 deletions bt-daemon/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<std::time::Duration>,
}

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<std::time::Duration, String> {
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<std::time::Duration>,
env: Option<String>,
) -> 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`.
Expand Down Expand Up @@ -310,6 +356,7 @@ pub enum RunSource {
mod tests {
use super::*;
use clap::Parser;
use std::time::Duration;

#[derive(Debug, Parser)]
struct ImportCli {
Expand All @@ -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]
Expand Down
59 changes: 30 additions & 29 deletions bt-daemon/src/collections/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<String>) -> 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<?", [cutoff])?;
tx.execute("DELETE FROM origins WHERE ended_ms<?", [cutoff])?;
tx.execute(
"DELETE FROM span_state WHERE touched_ms<? AND (kind='tool' OR end_ms IS NOT NULL)",
[cutoff],
)?;
let stuck = {
let mut query = tx.prepare(
"SELECT route FROM heads WHERE subscribed=0 AND progress_ms<?
AND position<(SELECT op_tail FROM session WHERE id=1)",
)?;
let rows = query.query_map([cutoff], |r| r.get::<_, String>(0))?;
rows.collect::<Result<Vec<_>, _>>()?
};
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<?", [cutoff])?;
tx.execute("DELETE FROM origins WHERE ended_ms<?", [cutoff])?;
tx.execute(
"DELETE FROM span_state WHERE touched_ms<? AND (kind='tool' OR end_ms IS NOT NULL)",
[cutoff],
)?;
let mut expired = false;
for route in stalled(tx, cutoff)?
.into_iter()
.filter(|route| !live.contains(route))
{
let failure: Option<String> =
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::<i64>("SELECT count(*) FROM heads", [])? == 0 {
// Everything stored was owed only to expired routes.
tx.execute("DELETE FROM ops", [])?;
}
prune(tx)
})
.await
}
}
32 changes: 31 additions & 1 deletion bt-daemon/src/collections/span_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<String>> {
let mut query = db.prepare(
"SELECT route FROM heads WHERE progress_ms<?
AND position<(SELECT op_tail FROM session WHERE id=1)",
)?;
let rows = query.query_map([cutoff], |r| r.get::<_, String>(0))?;
Ok(rows.collect::<Result<Vec<_>, _>>()?)
}

/// Heads selected by `filter` that are the same route as `route`, by key.
fn same_heads(db: &Connection, filter: &str, route: &SessionRoute) -> anyhow::Result<Vec<String>> {
let mut query = db.prepare(&format!("SELECT route FROM heads WHERE {filter}"))?;
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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<Vec<SessionRoute>> {
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::<Result<_, _>>()?)
}

pub async fn routes(&self) -> anyhow::Result<Vec<SessionRoute>> {
self.run(|db| {
let mut query = db.prepare("SELECT route FROM heads ORDER BY route")?;
Expand Down
33 changes: 31 additions & 2 deletions bt-daemon/src/collections/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down Expand Up @@ -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::<i64>("PRAGMA freelist_count", [])? == 0 {
return Ok(());
}
if db.one::<i64>("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 + '_ {
Expand Down Expand Up @@ -254,6 +274,15 @@ pub(super) fn select<T: serde::de::DeserializeOwned>(
Ok(rows.collect::<Result<_, _>>()?)
}

/// 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<T: FromSql>(&self, sql: &str, params: impl Params) -> rusqlite::Result<T>;
Expand Down
Loading
Loading