From c0658831fa42c410d6f6dd8723ebcd99ad11c91f Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 14 Nov 2026 00:55:10 +0800 Subject: [PATCH 1/6] Rotate serve.log by size A spawned daemon's standard streams are appended to serve.log forever, and it reached gigabytes on long-lived installs. Once the log passes 10 MiB its newest 10 MiB are kept as serve.log.1 and it is truncated in place, both before a daemon is spawned and every minute while one runs. The running daemon writes through an inherited append handle, so truncation (rather than renaming the file away from that handle) works on every platform. Co-Authored-By: Claude Opus 5.5 --- bt-daemon/src/client.rs | 6 +- bt-daemon/src/lib.rs | 1 + bt-daemon/src/serve_log.rs | 87 +++++++++++++++++++++++++++++ bt-daemon/src/server/maintenance.rs | 20 +++++++ bt-daemon/src/server/mod.rs | 1 + 5 files changed, 110 insertions(+), 5 deletions(-) create mode 100644 bt-daemon/src/serve_log.rs diff --git a/bt-daemon/src/client.rs b/bt-daemon/src/client.rs index bdcf154e..293a1b4a 100644 --- a/bt-daemon/src/client.rs +++ b/bt-daemon/src/client.rs @@ -191,11 +191,7 @@ fn spawn_daemon(host: &HostInfo, socket: &Path, data_dir_arg: Option<&Path>) -> .map(Path::to_path_buf) .unwrap_or_else(|| crate::paths::data_dir(None)); let _ = crate::paths::ensure_private_dir(&data_dir); - let log = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(data_dir.join("serve.log")) - .ok(); + let log = crate::serve_log::open(&data_dir).ok(); #[cfg(windows)] { diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index dd42434d..604afbd9 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -31,6 +31,7 @@ mod pipeline; mod plugin_diagnostics; pub(crate) mod process; mod route; +mod serve_log; mod server; mod settings; mod setup; diff --git a/bt-daemon/src/serve_log.rs b/bt-daemon/src/serve_log.rs new file mode 100644 index 00000000..a47e964a --- /dev/null +++ b/bt-daemon/src/serve_log.rs @@ -0,0 +1,87 @@ +//! `serve.log`, where a spawned daemon's standard streams are redirected. +//! +//! A daemon may run for days, so the log is bounded where it is written: once +//! it outgrows [`MAX_BYTES`] its newest bytes are kept as `serve.log.1` and it +//! starts again. The running daemon writes through an inherited handle that +//! always appends at the end of the file, so the file is truncated in place +//! rather than renamed away from that handle. + +use std::fs::{File, OpenOptions}; +use std::io::{Seek, SeekFrom}; +use std::path::{Path, PathBuf}; + +/// Rotate once the log grows past this size. One earlier generation of the +/// same size is kept. +pub(crate) const MAX_BYTES: u64 = 10 * 1024 * 1024; + +fn path(data_dir: &Path) -> PathBuf { + data_dir.join("serve.log") +} + +/// Open the log for a new daemon's standard streams, rotating it first. +pub(crate) fn open(data_dir: &Path) -> std::io::Result { + if let Err(error) = rotate(data_dir) { + eprintln!("bt-daemon: serve.log rotation failed: {error}"); + } + OpenOptions::new() + .create(true) + .append(true) + .open(path(data_dir)) +} + +/// Keep the newest [`MAX_BYTES`] of an oversized log as `serve.log.1` and +/// empty the log. +pub(crate) fn rotate(data_dir: &Path) -> std::io::Result<()> { + let path = path(data_dir); + let mut log = match OpenOptions::new().read(true).write(true).open(&path) { + Ok(log) => log, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + let len = log.metadata()?.len(); + if len <= MAX_BYTES { + return Ok(()); + } + log.seek(SeekFrom::Start(len - MAX_BYTES))?; + std::io::copy(&mut log, &mut File::create(path.with_extension("log.1"))?)?; + log.set_len(0) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn an_oversized_log_keeps_its_newest_bytes_and_starts_again() { + let dir = tempfile::tempdir().unwrap(); + // The daemon's handle, opened before rotation. + let mut daemon = open(dir.path()).unwrap(); + daemon.write_all(&vec![b'.'; MAX_BYTES as usize]).unwrap(); + daemon.write_all(b"newest\n").unwrap(); + rotate(dir.path()).unwrap(); + + let previous = std::fs::read(dir.path().join("serve.log.1")).unwrap(); + assert_eq!(previous.len() as u64, MAX_BYTES); + assert!(previous.ends_with(b"newest\n")); + daemon.write_all(b"after\n").unwrap(); + assert_eq!( + std::fs::read(dir.path().join("serve.log")).unwrap(), + b"after\n", + "the running daemon keeps appending to the emptied log" + ); + } + + #[test] + fn a_log_within_its_bound_is_left_alone() { + let dir = tempfile::tempdir().unwrap(); + rotate(dir.path()).unwrap(); + open(dir.path()).unwrap().write_all(b"line\n").unwrap(); + rotate(dir.path()).unwrap(); + assert_eq!( + std::fs::read(dir.path().join("serve.log")).unwrap(), + b"line\n" + ); + assert!(!dir.path().join("serve.log.1").exists()); + } +} diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 275c928f..2d2d01fd 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -301,6 +301,26 @@ pub(super) fn spawn_gc(daemon: Arc) { }); } +/// How often a running daemon bounds the log its standard streams write to. +const LOG_ROTATION_INTERVAL: Duration = Duration::from_secs(60); + +pub(super) fn spawn_log_rotation(daemon: Arc) { + tokio::spawn(async move { + loop { + tokio::select! { + _ = daemon.shutdown.notified() => return, + _ = tokio::time::sleep(LOG_ROTATION_INTERVAL) => {} + } + let data_dir = daemon.data_dir.clone(); + match tokio::task::spawn_blocking(move || crate::serve_log::rotate(&data_dir)).await { + Ok(Ok(())) => {} + Ok(Err(error)) => tracing::warn!(%error, "serve.log rotation failed"), + Err(error) => tracing::warn!(%error, "serve.log rotation did not run"), + } + } + }); +} + pub(super) fn spawn_idle_watchdog(daemon: Arc, idle_timeout: Duration) { if idle_timeout.is_zero() { return; // 0 disables the watchdog (useful in tests) diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index 2b25a34f..bcd43278 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -266,6 +266,7 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { let (ready, startup) = oneshot::channel(); let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup)); + spawn_log_rotation(daemon.clone()); 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(); From a22000620532e6ea145fcd704ee6f672fcaf8cf4 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 14 Nov 2026 01:02:57 +0800 Subject: [PATCH 2/6] Make the serve.log rotation size configurable BRAINTRUST_DAEMON_LOG_MAX_MB sets the limit in MiB (default 10). Both the spawning hook and the running daemon read it, so it is an environment variable rather than a serve flag the spawner cannot see. An unset, zero or unparsable value keeps the default, so the log stays bounded. Co-Authored-By: Claude Opus 5.5 --- bt-daemon/README.md | 3 ++ bt-daemon/src/serve_log.rs | 62 +++++++++++++++++++++-------- bt-daemon/src/server/maintenance.rs | 7 +++- 3 files changed, 55 insertions(+), 17 deletions(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index f58e1eca..c35f773b 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -296,6 +296,9 @@ echo '{"session_id":"s1","hook_event_name":"Stop"}' | ./bt-daemon/target ``` The first `hook` spawns the daemon detached; it idles out after 5 minutes. +A spawned daemon logs to `serve.log` in the data directory. Once that file +passes 10 MiB its newest 10 MiB are kept as `serve.log.1` and it starts again; +set `BRAINTRUST_DAEMON_LOG_MAX_MB` to change the limit. `import ` has a different purpose from restart recovery. It locates the native transcript in the selected agent's standard diff --git a/bt-daemon/src/serve_log.rs b/bt-daemon/src/serve_log.rs index a47e964a..2154cecf 100644 --- a/bt-daemon/src/serve_log.rs +++ b/bt-daemon/src/serve_log.rs @@ -1,8 +1,9 @@ //! `serve.log`, where a spawned daemon's standard streams are redirected. //! //! A daemon may run for days, so the log is bounded where it is written: once -//! it outgrows [`MAX_BYTES`] its newest bytes are kept as `serve.log.1` and it -//! starts again. The running daemon writes through an inherited handle that +//! it outgrows its limit its newest bytes are kept as `serve.log.1` and it +//! starts again. The limit is [`DEFAULT_MAX_MB`] MiB unless +//! `BRAINTRUST_DAEMON_LOG_MAX_MB` sets another whole number of MiB. The running daemon writes through an inherited handle that //! always appends at the end of the file, so the file is truncated in place //! rather than renamed away from that handle. @@ -10,9 +11,24 @@ use std::fs::{File, OpenOptions}; use std::io::{Seek, SeekFrom}; use std::path::{Path, PathBuf}; -/// Rotate once the log grows past this size. One earlier generation of the -/// same size is kept. -pub(crate) const MAX_BYTES: u64 = 10 * 1024 * 1024; +/// Rotate once the log grows past this many MiB. One earlier generation of +/// the same size is kept. +pub(crate) const DEFAULT_MAX_MB: u64 = 10; + +const MAX_MB_ENV: &str = "BRAINTRUST_DAEMON_LOG_MAX_MB"; + +/// The configured limit in bytes. An unset, unparsable or zero value uses the +/// default, so the log stays bounded. +pub(crate) fn max_bytes() -> u64 { + limit(crate::env::var(MAX_MB_ENV).as_deref()) +} + +fn limit(mb: Option<&str>) -> u64 { + mb.and_then(|value| value.trim().parse::().ok()) + .filter(|mb| *mb > 0) + .unwrap_or(DEFAULT_MAX_MB) + .saturating_mul(1024 * 1024) +} fn path(data_dir: &Path) -> PathBuf { data_dir.join("serve.log") @@ -20,7 +36,7 @@ fn path(data_dir: &Path) -> PathBuf { /// Open the log for a new daemon's standard streams, rotating it first. pub(crate) fn open(data_dir: &Path) -> std::io::Result { - if let Err(error) = rotate(data_dir) { + if let Err(error) = rotate(data_dir, max_bytes()) { eprintln!("bt-daemon: serve.log rotation failed: {error}"); } OpenOptions::new() @@ -29,9 +45,9 @@ pub(crate) fn open(data_dir: &Path) -> std::io::Result { .open(path(data_dir)) } -/// Keep the newest [`MAX_BYTES`] of an oversized log as `serve.log.1` and -/// empty the log. -pub(crate) fn rotate(data_dir: &Path) -> std::io::Result<()> { +/// Keep the newest `max_bytes` of an oversized log as `serve.log.1` and empty +/// the log. +pub(crate) fn rotate(data_dir: &Path, max_bytes: u64) -> std::io::Result<()> { let path = path(data_dir); let mut log = match OpenOptions::new().read(true).write(true).open(&path) { Ok(log) => log, @@ -39,10 +55,10 @@ pub(crate) fn rotate(data_dir: &Path) -> std::io::Result<()> { Err(error) => return Err(error), }; let len = log.metadata()?.len(); - if len <= MAX_BYTES { + if len <= max_bytes { return Ok(()); } - log.seek(SeekFrom::Start(len - MAX_BYTES))?; + log.seek(SeekFrom::Start(len - max_bytes))?; std::io::copy(&mut log, &mut File::create(path.with_extension("log.1"))?)?; log.set_len(0) } @@ -52,17 +68,19 @@ mod tests { use super::*; use std::io::Write; + const LIMIT: u64 = 1024; + #[test] fn an_oversized_log_keeps_its_newest_bytes_and_starts_again() { let dir = tempfile::tempdir().unwrap(); // The daemon's handle, opened before rotation. let mut daemon = open(dir.path()).unwrap(); - daemon.write_all(&vec![b'.'; MAX_BYTES as usize]).unwrap(); + daemon.write_all(&vec![b'.'; LIMIT as usize]).unwrap(); daemon.write_all(b"newest\n").unwrap(); - rotate(dir.path()).unwrap(); + rotate(dir.path(), LIMIT).unwrap(); let previous = std::fs::read(dir.path().join("serve.log.1")).unwrap(); - assert_eq!(previous.len() as u64, MAX_BYTES); + assert_eq!(previous.len() as u64, LIMIT); assert!(previous.ends_with(b"newest\n")); daemon.write_all(b"after\n").unwrap(); assert_eq!( @@ -72,12 +90,24 @@ mod tests { ); } + #[test] + fn the_limit_is_a_positive_number_of_mib() { + assert_eq!(limit(Some(" 50 ")), 50 * 1024 * 1024); + for unusable in [None, Some(""), Some("0"), Some("-1"), Some("10MB")] { + assert_eq!( + limit(unusable), + DEFAULT_MAX_MB * 1024 * 1024, + "{unusable:?}" + ); + } + } + #[test] fn a_log_within_its_bound_is_left_alone() { let dir = tempfile::tempdir().unwrap(); - rotate(dir.path()).unwrap(); + rotate(dir.path(), LIMIT).unwrap(); open(dir.path()).unwrap().write_all(b"line\n").unwrap(); - rotate(dir.path()).unwrap(); + rotate(dir.path(), LIMIT).unwrap(); assert_eq!( std::fs::read(dir.path().join("serve.log")).unwrap(), b"line\n" diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 2d2d01fd..410fe4b1 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -312,7 +312,12 @@ pub(super) fn spawn_log_rotation(daemon: Arc) { _ = tokio::time::sleep(LOG_ROTATION_INTERVAL) => {} } let data_dir = daemon.data_dir.clone(); - match tokio::task::spawn_blocking(move || crate::serve_log::rotate(&data_dir)).await { + let max_bytes = crate::serve_log::max_bytes(); + match tokio::task::spawn_blocking(move || { + crate::serve_log::rotate(&data_dir, max_bytes) + }) + .await + { Ok(Ok(())) => {} Ok(Err(error)) => tracing::warn!(%error, "serve.log rotation failed"), Err(error) => tracing::warn!(%error, "serve.log rotation did not run"), From 417cb0273d4556173ab23f5e73885065aeda0305 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 14 Nov 2026 01:05:46 +0800 Subject: [PATCH 3/6] Name the log size variable BT_TRACE_LOG_MAX_MB Daemon tuning variables use the BT_TRACE_ prefix. The env prefix test now allows them by name. Co-Authored-By: Claude Opus 5.5 --- bt-daemon/README.md | 2 +- bt-daemon/src/env.rs | 13 ++++++++++--- bt-daemon/src/serve_log.rs | 11 ++++++----- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index c35f773b..f7b2a0a1 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -298,7 +298,7 @@ echo '{"session_id":"s1","hook_event_name":"Stop"}' | ./bt-daemon/target The first `hook` spawns the daemon detached; it idles out after 5 minutes. A spawned daemon logs to `serve.log` in the data directory. Once that file passes 10 MiB its newest 10 MiB are kept as `serve.log.1` and it starts again; -set `BRAINTRUST_DAEMON_LOG_MAX_MB` to change the limit. +set `BT_TRACE_LOG_MAX_MB` to change the limit. `import ` has a different purpose from restart recovery. It locates the native transcript in the selected agent's standard diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 1ea1592e..6b5b8d0d 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -1,13 +1,17 @@ //! User-facing environment variables use the `BRAINTRUST_` prefix, matching //! `bt` and the Braintrust SDKs. Read them through [`var_os`] so that the //! deprecated `BT_` names keep working until support is removed. +//! +//! Variables that tune the trace daemon itself, such as `BT_TRACE_LOG_MAX_MB`, +//! use the `BT_TRACE_` prefix instead. They have no deprecated aliases and are +//! read directly. use std::ffi::{OsStr, OsString}; /// Pre-`BRAINTRUST_` names of tracing env vars. Each `BT_` is still /// honored as an alias for `BRAINTRUST_` until support is removed in a /// major release. Do not add entries: new env vars must use the `BRAINTRUST_` -/// prefix. +/// prefix, or `BT_TRACE_` for daemon tuning. /// /// `BT_TRACE_MANAGED_RUN_ID` and `BT_TRACE_INVOCATION_SETTINGS` are not listed: /// they are the internal protocol `bt trace run` uses to configure its child @@ -91,8 +95,9 @@ mod tests { } /// New user-facing env vars must use the `BRAINTRUST_` prefix. Every - /// `BT_*` name in the crate must be a deprecated alias or internal protocol, - /// and every deprecated alias must map to a name the crate reads. + /// `BT_*` name in the crate must be a deprecated alias, internal protocol + /// or daemon tuning, and every deprecated alias must map to a name the + /// crate reads. #[test] fn env_vars_use_braintrust_prefix() { const INTERNAL: &[&str] = &[ @@ -102,6 +107,8 @@ mod tests { "BT_TRACE_CURSOR_USER_HOOK", // Fallback for `BRAINTRUST_BT_BIN` in the Cursor hook launchers. "BT_BIN", + // Daemon tuning. + "BT_TRACE_LOG_MAX_MB", ]; let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut sources = String::new(); diff --git a/bt-daemon/src/serve_log.rs b/bt-daemon/src/serve_log.rs index 2154cecf..ddaffb11 100644 --- a/bt-daemon/src/serve_log.rs +++ b/bt-daemon/src/serve_log.rs @@ -3,9 +3,10 @@ //! A daemon may run for days, so the log is bounded where it is written: once //! it outgrows its limit its newest bytes are kept as `serve.log.1` and it //! starts again. The limit is [`DEFAULT_MAX_MB`] MiB unless -//! `BRAINTRUST_DAEMON_LOG_MAX_MB` sets another whole number of MiB. The running daemon writes through an inherited handle that -//! always appends at the end of the file, so the file is truncated in place -//! rather than renamed away from that handle. +//! `BT_TRACE_LOG_MAX_MB` sets another whole number of MiB. The running daemon +//! writes through an inherited handle that always appends at the end of the +//! file, so the file is truncated in place rather than renamed away from that +//! handle. use std::fs::{File, OpenOptions}; use std::io::{Seek, SeekFrom}; @@ -15,12 +16,12 @@ use std::path::{Path, PathBuf}; /// the same size is kept. pub(crate) const DEFAULT_MAX_MB: u64 = 10; -const MAX_MB_ENV: &str = "BRAINTRUST_DAEMON_LOG_MAX_MB"; +const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; /// The configured limit in bytes. An unset, unparsable or zero value uses the /// default, so the log stays bounded. pub(crate) fn max_bytes() -> u64 { - limit(crate::env::var(MAX_MB_ENV).as_deref()) + limit(std::env::var(MAX_MB_ENV).ok().as_deref()) } fn limit(mb: Option<&str>) -> u64 { From 0bf02f9089bbcce31841a3123931b58809ea250c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 14 Nov 2026 01:07:30 +0800 Subject: [PATCH 4/6] Read BT_TRACE_LOG_MAX_MB through the env module Daemon tuning variables are declared in env.rs and read through crate::env like every other variable. AGENTS.md describes the BT_TRACE_ prefix for them. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 ++++-- bt-daemon/src/env.rs | 21 ++++++++++++++------- bt-daemon/src/serve_log.rs | 4 ++-- 3 files changed, 20 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5c759dc7..acd2eaf8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,8 +57,10 @@ and daemon detachment have explicit exceptions; do not reuse them for background work. Clippy and Oxlint enforce use of these helpers in CI. User-facing environment variables must use the `BRAINTRUST_` prefix (for -example `BRAINTRUST_DAEMON_SOCKET`), matching `bt` and the Braintrust SDKs. Do -not add new `BT_*` names. Read them through `bt-daemon/src/env.rs`; +example `BRAINTRUST_DAEMON_SOCKET`), matching `bt` and the Braintrust SDKs. +Variables that tune the trace daemon itself use the `BT_TRACE_` prefix (for +example `BT_TRACE_LOG_MAX_MB`) and are listed in `DAEMON_TUNING_ENV_VARS`. Do +not add other `BT_*` names. Read every variable through `bt-daemon/src/env.rs`; `DEPRECATED_BT_ENV_VARS` there only keeps old names working. `BT_TRACE_MANAGED_RUN_ID` and `BT_TRACE_INVOCATION_SETTINGS` remain the internal protocol between `bt trace run` and its child processes. diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 6b5b8d0d..456d4055 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -2,16 +2,16 @@ //! `bt` and the Braintrust SDKs. Read them through [`var_os`] so that the //! deprecated `BT_` names keep working until support is removed. //! -//! Variables that tune the trace daemon itself, such as `BT_TRACE_LOG_MAX_MB`, -//! use the `BT_TRACE_` prefix instead. They have no deprecated aliases and are -//! read directly. +//! Variables that tune the trace daemon itself use the `BT_TRACE_` prefix +//! instead and are listed in `DAEMON_TUNING_ENV_VARS`. They are read through +//! [`var_os`] like every other variable. use std::ffi::{OsStr, OsString}; /// Pre-`BRAINTRUST_` names of tracing env vars. Each `BT_` is still /// honored as an alias for `BRAINTRUST_` until support is removed in a /// major release. Do not add entries: new env vars must use the `BRAINTRUST_` -/// prefix, or `BT_TRACE_` for daemon tuning. +/// prefix, or be daemon tuning listed in `DAEMON_TUNING_ENV_VARS`. /// /// `BT_TRACE_MANAGED_RUN_ID` and `BT_TRACE_INVOCATION_SETTINGS` are not listed: /// they are the internal protocol `bt trace run` uses to configure its child @@ -27,6 +27,11 @@ pub(crate) const DEPRECATED_BT_ENV_VARS: &[&str] = &[ "BT_TRACE_PI_PLUGIN_SPEC", ]; +/// Variables that tune the trace daemon itself rather than what it traces. +/// The prefix test below holds every `BT_*` name to this list. +#[cfg(test)] +pub(crate) const DAEMON_TUNING_ENV_VARS: &[&str] = &[crate::serve_log::MAX_MB_ENV]; + pub(crate) fn canonical_env_name(deprecated: &str) -> String { let name = deprecated.strip_prefix("BT_").unwrap_or(deprecated); format!("BRAINTRUST_{name}") @@ -107,8 +112,6 @@ mod tests { "BT_TRACE_CURSOR_USER_HOOK", // Fallback for `BRAINTRUST_BT_BIN` in the Cursor hook launchers. "BT_BIN", - // Daemon tuning. - "BT_TRACE_LOG_MAX_MB", ]; let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut sources = String::new(); @@ -124,7 +127,11 @@ mod tests { let unexpected: BTreeSet<_> = pattern .find_iter(&sources) .map(|m| m.as_str()) - .filter(|name| !DEPRECATED_BT_ENV_VARS.contains(name) && !INTERNAL.contains(name)) + .filter(|name| { + !DEPRECATED_BT_ENV_VARS.contains(name) + && !INTERNAL.contains(name) + && !DAEMON_TUNING_ENV_VARS.contains(name) + }) .collect(); assert!( unexpected.is_empty(), diff --git a/bt-daemon/src/serve_log.rs b/bt-daemon/src/serve_log.rs index ddaffb11..77f58212 100644 --- a/bt-daemon/src/serve_log.rs +++ b/bt-daemon/src/serve_log.rs @@ -16,12 +16,12 @@ use std::path::{Path, PathBuf}; /// the same size is kept. pub(crate) const DEFAULT_MAX_MB: u64 = 10; -const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; +pub(crate) const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; /// The configured limit in bytes. An unset, unparsable or zero value uses the /// default, so the log stays bounded. pub(crate) fn max_bytes() -> u64 { - limit(std::env::var(MAX_MB_ENV).ok().as_deref()) + limit(crate::env::var(MAX_MB_ENV).as_deref()) } fn limit(mb: Option<&str>) -> u64 { From 7619db28d9ea458fd0af69c12fe53faaaebba0d9 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 17 Nov 2026 00:08:38 +0800 Subject: [PATCH 5/6] Log the daemon through one rotating tracing subscriber The daemon installs one subscriber with two outputs: newline-delimited JSON to daemon.log at debug (BT_TRACE_LOG_LEVEL) and plain text to stderr at warn, or debug with --verbose (BT_TRACE_STDERR_LEVEL). Panics are logged through it too. Logs rotate by rename and reopen instead of copy and truncate, which lost the start of each generation and anything written between the copy and the truncate. daemon.log rotates in its writer when the next line would pass BT_TRACE_LOG_MAX_MB; serve.log, which now only receives stderr, is rotated by the hook before it spawns a daemon. Each rotation replaces .1, and the two files together hold the latest log in order. Per-event "event received" and "event accepted" logs move to debug: at info they wrote two stderr lines for every hook event. Co-Authored-By: Claude Opus 5.5 --- bt-daemon/Cargo.lock | 13 + bt-daemon/Cargo.toml | 2 +- bt-daemon/README.md | 11 +- bt-daemon/src/client.rs | 2 +- bt-daemon/src/daemon_log.rs | 375 ++++++++++++++++++++++++++++ bt-daemon/src/env.rs | 6 +- bt-daemon/src/lib.rs | 8 +- bt-daemon/src/main.rs | 20 +- bt-daemon/src/serve_log.rs | 118 --------- bt-daemon/src/server/ingress.rs | 4 +- bt-daemon/src/server/maintenance.rs | 25 -- bt-daemon/src/server/mod.rs | 1 - bt-daemon/src/trace_runtime.rs | 17 +- 13 files changed, 431 insertions(+), 171 deletions(-) create mode 100644 bt-daemon/src/daemon_log.rs delete mode 100644 bt-daemon/src/serve_log.rs diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index bafb41f1..af7091a9 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -2440,6 +2440,16 @@ dependencies = [ "tracing-core", ] +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + [[package]] name = "tracing-subscriber" version = "0.3.23" @@ -2450,12 +2460,15 @@ dependencies = [ "nu-ansi-term", "once_cell", "regex-automata", + "serde", + "serde_json", "sharded-slab", "smallvec", "thread_local", "tracing", "tracing-core", "tracing-log", + "tracing-serde", ] [[package]] diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 87b69444..d936f957 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -45,7 +45,7 @@ thiserror = "2" tempfile = "3" tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time", "process", "signal", "fs"] } tracing = "0.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } +tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } uuid = { version = "1", features = ["v4", "v5"] } rusqlite = { version = "0.37", features = ["bundled"] } diff --git a/bt-daemon/README.md b/bt-daemon/README.md index f7b2a0a1..45352166 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -296,9 +296,14 @@ echo '{"session_id":"s1","hook_event_name":"Stop"}' | ./bt-daemon/target ``` The first `hook` spawns the daemon detached; it idles out after 5 minutes. -A spawned daemon logs to `serve.log` in the data directory. Once that file -passes 10 MiB its newest 10 MiB are kept as `serve.log.1` and it starts again; -set `BT_TRACE_LOG_MAX_MB` to change the limit. +The daemon logs newline-delimited JSON to `daemon.log` in the data directory +at `debug`, and plain text to standard error at `warn` (`debug` with +`--verbose`). A spawned daemon's standard error is `serve.log`, so that file +holds only warnings and anything printed before logging starts. +`BT_TRACE_LOG_LEVEL` and `BT_TRACE_STDERR_LEVEL` override either filter in +`RUST_LOG` syntax. Each file is renamed to `.1`, replacing the previous +generation, once it would pass 10 MiB (`BT_TRACE_LOG_MAX_MB`), so the two +together hold the latest log in order. `import ` has a different purpose from restart recovery. It locates the native transcript in the selected agent's standard diff --git a/bt-daemon/src/client.rs b/bt-daemon/src/client.rs index 57eefd8a..5386befe 100644 --- a/bt-daemon/src/client.rs +++ b/bt-daemon/src/client.rs @@ -191,7 +191,7 @@ fn spawn_daemon(host: &HostInfo, socket: &Path, data_dir_arg: Option<&Path>) -> .map(Path::to_path_buf) .unwrap_or_else(|| crate::paths::data_dir(None)); let _ = crate::paths::ensure_private_dir(&data_dir); - let log = crate::serve_log::open(&data_dir).ok(); + let log = crate::daemon_log::open_serve_log(&data_dir).ok(); #[cfg(windows)] { diff --git a/bt-daemon/src/daemon_log.rs b/bt-daemon/src/daemon_log.rs new file mode 100644 index 00000000..8df626de --- /dev/null +++ b/bt-daemon/src/daemon_log.rs @@ -0,0 +1,375 @@ +//! The daemon's logging. Everything it logs goes through one `tracing` +//! subscriber with two outputs: +//! +//! - `daemon.log` in the data directory: newline-delimited JSON at `debug` +//! (`BT_TRACE_LOG_LEVEL`), for diagnosis after the fact. +//! - standard error: plain text at `warn`, or `debug` with `--verbose` +//! (`BT_TRACE_STDERR_LEVEL`). A spawned daemon's standard streams go to +//! `serve.log`, which therefore only holds warnings and anything printed +//! before logging starts. +//! +//! Both files are bounded by rename-and-reopen rotation: once a file would +//! outgrow its limit (`BT_TRACE_LOG_MAX_MB` MiB, default [`DEFAULT_MAX_MB`]), +//! it is renamed to `.1`, replacing the previous generation, and a fresh +//! file is started. Every line lands whole in one generation or the next. +//! `daemon.log` rotates as it is written; `serve.log` rotates before a daemon +//! is spawned, since the daemon writes it through an inherited handle. +//! +//! The global subscriber can be set once per process, so a host that installs +//! its own must not do so before running the daemon command. + +use parking_lot::{Mutex, MutexGuard}; +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt, EnvFilter, Layer}; + +/// Rotate once a log would grow past this many MiB. One earlier generation of +/// the same size is kept. +pub(crate) const DEFAULT_MAX_MB: u64 = 10; +pub(crate) const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; +/// Filter for `daemon.log`, in `RUST_LOG` syntax. +pub(crate) const LEVEL_ENV: &str = "BT_TRACE_LOG_LEVEL"; +/// Filter for standard error, in `RUST_LOG` syntax. +pub(crate) const STDERR_LEVEL_ENV: &str = "BT_TRACE_STDERR_LEVEL"; + +/// The configured size limit in bytes. An unset, unparsable or zero value +/// uses the default, so logs stay bounded. +pub(crate) fn max_bytes() -> u64 { + limit(crate::env::var(MAX_MB_ENV).as_deref()) +} + +fn limit(mb: Option<&str>) -> u64 { + mb.and_then(|value| value.trim().parse::().ok()) + .filter(|mb| *mb > 0) + .unwrap_or(DEFAULT_MAX_MB) + .saturating_mul(1024 * 1024) +} + +/// Install the daemon's subscriber. Returns `false` if the process already +/// has one, which then keeps receiving the daemon's events. +pub(crate) fn init(data_dir: &Path, verbose: bool) -> bool { + let (subscriber, errors) = subscriber( + RotatingFile::new(data_dir.join("daemon.log"), max_bytes()), + std::io::stderr, + // A spawned daemon's stderr is `serve.log`, which must stay plain. + std::io::IsTerminal::is_terminal(&std::io::stderr()), + verbose, + ); + if tracing::subscriber::set_global_default(subscriber).is_err() { + return false; + } + for error in errors { + tracing::warn!("{error}"); + } + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + tracing::error!(panic = %info, "daemon panicked"); + previous(info); + })); + true +} + +/// The daemon's subscriber, and any filter settings it had to reject. +fn subscriber( + file: RotatingFile, + stderr: E, + ansi: bool, + verbose: bool, +) -> (impl tracing::Subscriber + Send + Sync, Vec) +where + E: for<'a> MakeWriter<'a> + Send + Sync + 'static, +{ + let (file_filter, file_error) = filter(LEVEL_ENV, "debug"); + let (stderr_filter, stderr_error) = + filter(STDERR_LEVEL_ENV, if verbose { "debug" } else { "warn" }); + let subscriber = tracing_subscriber::registry() + .with( + tracing_subscriber::fmt::layer() + .json() + .with_writer(file) + .with_filter(file_filter), + ) + .with( + tracing_subscriber::fmt::layer() + .with_ansi(ansi) + .with_writer(stderr) + .with_filter(stderr_filter), + ); + ( + subscriber, + [file_error, stderr_error].into_iter().flatten().collect(), + ) +} + +/// The filter named by `env`, or `default` with the reason it was rejected. +fn filter(env: &str, default: &str) -> (EnvFilter, Option) { + parse_filter(env, crate::env::var(env), default) +} + +fn parse_filter(env: &str, value: Option, default: &str) -> (EnvFilter, Option) { + match value { + Some(value) => match EnvFilter::try_new(&value) { + Ok(filter) => (filter, None), + Err(error) => ( + EnvFilter::new(default), + Some(format!("ignoring {env}={value:?}: {error}")), + ), + }, + None => (EnvFilter::new(default), None), + } +} + +/// Open `serve.log` for a new daemon's standard streams, rotating it first. +/// No writer of this process holds it, so renaming it away is safe; a daemon +/// still exiting keeps writing into the rotated generation. +pub(crate) fn open_serve_log(data_dir: &Path) -> std::io::Result { + let path = data_dir.join("serve.log"); + let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); + if len > max_bytes() { + if let Err(error) = rotate(&path) { + tracing::warn!(%error, "serve.log rotation failed"); + } + } + append(&path) +} + +fn append(path: &Path) -> std::io::Result { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + OpenOptions::new().create(true).append(true).open(path) +} + +/// Rename `path` to `.1`, replacing the previous generation. A virus +/// scanner or indexer can briefly hold a file on Windows, so a failed rename +/// is retried a few times before giving up. +fn rotate(path: &Path) -> std::io::Result<()> { + let mut rotated = path.as_os_str().to_owned(); + rotated.push(".1"); + let mut attempt = 0; + loop { + match std::fs::rename(path, &rotated) { + Ok(()) => return Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(_) if attempt < 3 => { + attempt += 1; + std::thread::sleep(std::time::Duration::from_millis(10 * attempt)); + } + Err(error) => return Err(error), + } + } +} + +/// A log file that rotates by renaming itself once a write would take it past +/// its limit. `tracing` writes each event with one call, so rotation happens +/// between whole lines. +#[derive(Clone)] +pub(crate) struct RotatingFile(Arc>); + +struct State { + path: PathBuf, + max_bytes: u64, + file: Option, + written: u64, +} + +impl RotatingFile { + pub(crate) fn new(path: PathBuf, max_bytes: u64) -> Self { + Self(Arc::new(Mutex::new(State { + path, + max_bytes, + file: None, + written: 0, + }))) + } +} + +impl State { + fn file(&mut self) -> std::io::Result<&mut File> { + let file = match self.file.take() { + Some(file) => file, + None => { + let file = append(&self.path)?; + self.written = file.metadata()?.len(); + file + } + }; + Ok(self.file.insert(file)) + } + + fn write_line(&mut self, line: &[u8]) -> std::io::Result<()> { + self.file()?; + if self.written > 0 && self.written + line.len() as u64 > self.max_bytes { + self.file = None; + // Keep writing to the current generation if it cannot move. + let _ = rotate(&self.path); + } + self.file()?.write_all(line)?; + self.written += line.len() as u64; + Ok(()) + } +} + +pub(crate) struct Writer<'a>(MutexGuard<'a, State>); + +impl Write for Writer<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.write_line(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + match self.0.file.as_mut() { + Some(file) => file.flush(), + None => Ok(()), + } + } +} + +impl<'a> MakeWriter<'a> for RotatingFile { + type Writer = Writer<'a>; + + fn make_writer(&'a self) -> Self::Writer { + Writer(self.0.lock()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(file: &RotatingFile, line: &str) { + file.make_writer().write_all(line.as_bytes()).unwrap(); + } + + fn read(path: &Path) -> String { + std::fs::read_to_string(path).unwrap_or_default() + } + + #[test] + fn rotation_keeps_every_line_across_generations() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + let rotated = dir.path().join("daemon.log.1"); + let file = RotatingFile::new(path.clone(), 30); + let lines: Vec = (0..6).map(|i| format!("line {i:02} ......\n")).collect(); + for line in &lines[..3] { + write(&file, line); + } + // Two 15-byte lines fit in 30 bytes, so the third starts a new file. + assert_eq!(read(&rotated), lines[..2].concat()); + assert_eq!(read(&path), lines[2]); + for line in &lines[3..] { + write(&file, line); + } + // A later rotation replaces the earlier generation; the two files + // still read as one continuous log. + assert_eq!(read(&rotated) + &read(&path), lines[2..].concat()); + } + + #[test] + fn a_line_longer_than_the_limit_is_still_written() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + let file = RotatingFile::new(path.clone(), 4); + write(&file, "longer than the limit\n"); + assert_eq!(read(&path), "longer than the limit\n"); + } + + #[test] + fn writing_resumes_an_existing_log_and_counts_its_size() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + std::fs::write(&path, "earlier daemon\n").unwrap(); + let file = RotatingFile::new(path.clone(), 20); + write(&file, "this daemon\n"); + assert_eq!(read(&dir.path().join("daemon.log.1")), "earlier daemon\n"); + assert_eq!(read(&path), "this daemon\n"); + } + + #[test] + fn serve_log_rotates_before_a_daemon_is_spawned() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("serve.log"); + std::fs::write( + &path, + vec![b'.'; (DEFAULT_MAX_MB * 1024 * 1024 + 1) as usize], + ) + .unwrap(); + let mut log = open_serve_log(dir.path()).unwrap(); + log.write_all(b"new daemon\n").unwrap(); + assert_eq!(read(&path), "new daemon\n"); + assert_eq!( + std::fs::metadata(dir.path().join("serve.log.1")) + .unwrap() + .len(), + DEFAULT_MAX_MB * 1024 * 1024 + 1 + ); + // Within the limit, the log is appended to as before. + drop(log); + open_serve_log(dir.path()) + .unwrap() + .write_all(b"again\n") + .unwrap(); + assert_eq!(read(&path), "new daemon\nagain\n"); + } + + #[test] + fn each_output_has_its_own_level_and_format() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("daemon.log"); + let stderr = RotatingFile::new(dir.path().join("stderr"), u64::MAX); + let (subscriber, errors) = subscriber( + RotatingFile::new(path.clone(), u64::MAX), + stderr, + false, + false, + ); + assert!(errors.is_empty()); + tracing::subscriber::with_default(subscriber, || { + tracing::debug!(session_id = "s", "event received"); + tracing::warn!("delivery failed"); + }); + let lines: Vec = read(&path) + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(lines.len(), 2, "the file records debug and above"); + assert_eq!(lines[0]["fields"]["message"], "event received"); + assert_eq!(lines[0]["fields"]["session_id"], "s"); + let stderr = read(&dir.path().join("stderr")); + assert!(stderr.contains("delivery failed"), "{stderr}"); + assert!( + !stderr.contains("event received"), + "stderr records warn and above" + ); + assert!(serde_json::from_str::(stderr.trim()).is_err()); + } + + #[test] + fn the_limit_is_a_positive_number_of_mib() { + assert_eq!(limit(Some(" 50 ")), 50 * 1024 * 1024); + for unusable in [None, Some(""), Some("0"), Some("-1"), Some("10MB")] { + assert_eq!( + limit(unusable), + DEFAULT_MAX_MB * 1024 * 1024, + "{unusable:?}" + ); + } + } + + #[test] + fn an_unusable_filter_falls_back_to_its_default() { + let (filter, error) = parse_filter(LEVEL_ENV, Some("bt_daemon=trace,warn".into()), "debug"); + assert_eq!(filter.to_string(), "bt_daemon=trace,warn"); + assert!(error.is_none()); + let (filter, error) = parse_filter(LEVEL_ENV, Some("bt_daemon=[".into()), "debug"); + assert_eq!(filter.to_string(), "debug"); + assert!(error.unwrap().starts_with("ignoring BT_TRACE_LOG_LEVEL")); + let (filter, error) = parse_filter(LEVEL_ENV, None, "debug"); + assert_eq!(filter.to_string(), "debug"); + assert!(error.is_none()); + } +} diff --git a/bt-daemon/src/env.rs b/bt-daemon/src/env.rs index 456d4055..763e21b1 100644 --- a/bt-daemon/src/env.rs +++ b/bt-daemon/src/env.rs @@ -30,7 +30,11 @@ pub(crate) const DEPRECATED_BT_ENV_VARS: &[&str] = &[ /// Variables that tune the trace daemon itself rather than what it traces. /// The prefix test below holds every `BT_*` name to this list. #[cfg(test)] -pub(crate) const DAEMON_TUNING_ENV_VARS: &[&str] = &[crate::serve_log::MAX_MB_ENV]; +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, +]; pub(crate) fn canonical_env_name(deprecated: &str) -> String { let name = deprecated.strip_prefix("BT_").unwrap_or(deprecated); diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 9191bc9f..cdcfa094 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -18,6 +18,7 @@ mod client; mod codex_hooks; mod command_output; mod correlation; +mod daemon_log; mod dispatch; mod env; mod hook; @@ -30,7 +31,6 @@ mod pipeline; mod plugin_diagnostics; pub(crate) mod process; mod route; -mod serve_log; mod server; mod settings; mod setup; @@ -51,6 +51,12 @@ pub use args::{ HookArgs, ImportArgs, ImportSource, ParentObjectType, RunArgs, RunHookCommand, RunSource, ServeArgs, StatusArgs, }; +/// Install the daemon's logging: JSON to `daemon.log` in `data_dir` and plain +/// text to standard error, each with its own level and both rotated by size. +/// Returns `false` if the process already has a global subscriber. +pub fn init_daemon_logging(data_dir: &std::path::Path, verbose: bool) -> bool { + daemon_log::init(data_dir, verbose) +} pub use client::{ flush_managed_run, flush_session, forward_envelope, run_status, shutdown_daemon, HostInfo, }; diff --git a/bt-daemon/src/main.rs b/bt-daemon/src/main.rs index eb6118d5..37e76ba4 100644 --- a/bt-daemon/src/main.rs +++ b/bt-daemon/src/main.rs @@ -229,15 +229,18 @@ fn host_info() -> HostInfo { #[tokio::main] async fn main() { - tracing_subscriber::fmt() - .with_env_filter( - tracing_subscriber::EnvFilter::try_from_default_env() - .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), - ) - .with_writer(std::io::stderr) - .init(); - let cli = Cli::parse(); + // `serve` logs as the embedded daemon does; other development commands + // log to standard error. + if !matches!(cli.command, Command::Serve { .. }) { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_writer(std::io::stderr) + .init(); + } match cli.command { Command::Serve { args, @@ -246,6 +249,7 @@ async fn main() { app_url, } => { let data_dir = paths::data_dir(args.data_dir.as_deref()); + bt_daemon::init_daemon_logging(&data_dir, false); let mut opts = if debug_sink { debug_serve_options(VERSION, &data_dir) } else { diff --git a/bt-daemon/src/serve_log.rs b/bt-daemon/src/serve_log.rs deleted file mode 100644 index 77f58212..00000000 --- a/bt-daemon/src/serve_log.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! `serve.log`, where a spawned daemon's standard streams are redirected. -//! -//! A daemon may run for days, so the log is bounded where it is written: once -//! it outgrows its limit its newest bytes are kept as `serve.log.1` and it -//! starts again. The limit is [`DEFAULT_MAX_MB`] MiB unless -//! `BT_TRACE_LOG_MAX_MB` sets another whole number of MiB. The running daemon -//! writes through an inherited handle that always appends at the end of the -//! file, so the file is truncated in place rather than renamed away from that -//! handle. - -use std::fs::{File, OpenOptions}; -use std::io::{Seek, SeekFrom}; -use std::path::{Path, PathBuf}; - -/// Rotate once the log grows past this many MiB. One earlier generation of -/// the same size is kept. -pub(crate) const DEFAULT_MAX_MB: u64 = 10; - -pub(crate) const MAX_MB_ENV: &str = "BT_TRACE_LOG_MAX_MB"; - -/// The configured limit in bytes. An unset, unparsable or zero value uses the -/// default, so the log stays bounded. -pub(crate) fn max_bytes() -> u64 { - limit(crate::env::var(MAX_MB_ENV).as_deref()) -} - -fn limit(mb: Option<&str>) -> u64 { - mb.and_then(|value| value.trim().parse::().ok()) - .filter(|mb| *mb > 0) - .unwrap_or(DEFAULT_MAX_MB) - .saturating_mul(1024 * 1024) -} - -fn path(data_dir: &Path) -> PathBuf { - data_dir.join("serve.log") -} - -/// Open the log for a new daemon's standard streams, rotating it first. -pub(crate) fn open(data_dir: &Path) -> std::io::Result { - if let Err(error) = rotate(data_dir, max_bytes()) { - eprintln!("bt-daemon: serve.log rotation failed: {error}"); - } - OpenOptions::new() - .create(true) - .append(true) - .open(path(data_dir)) -} - -/// Keep the newest `max_bytes` of an oversized log as `serve.log.1` and empty -/// the log. -pub(crate) fn rotate(data_dir: &Path, max_bytes: u64) -> std::io::Result<()> { - let path = path(data_dir); - let mut log = match OpenOptions::new().read(true).write(true).open(&path) { - Ok(log) => log, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(error), - }; - let len = log.metadata()?.len(); - if len <= max_bytes { - return Ok(()); - } - log.seek(SeekFrom::Start(len - max_bytes))?; - std::io::copy(&mut log, &mut File::create(path.with_extension("log.1"))?)?; - log.set_len(0) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::io::Write; - - const LIMIT: u64 = 1024; - - #[test] - fn an_oversized_log_keeps_its_newest_bytes_and_starts_again() { - let dir = tempfile::tempdir().unwrap(); - // The daemon's handle, opened before rotation. - let mut daemon = open(dir.path()).unwrap(); - daemon.write_all(&vec![b'.'; LIMIT as usize]).unwrap(); - daemon.write_all(b"newest\n").unwrap(); - rotate(dir.path(), LIMIT).unwrap(); - - let previous = std::fs::read(dir.path().join("serve.log.1")).unwrap(); - assert_eq!(previous.len() as u64, LIMIT); - assert!(previous.ends_with(b"newest\n")); - daemon.write_all(b"after\n").unwrap(); - assert_eq!( - std::fs::read(dir.path().join("serve.log")).unwrap(), - b"after\n", - "the running daemon keeps appending to the emptied log" - ); - } - - #[test] - fn the_limit_is_a_positive_number_of_mib() { - assert_eq!(limit(Some(" 50 ")), 50 * 1024 * 1024); - for unusable in [None, Some(""), Some("0"), Some("-1"), Some("10MB")] { - assert_eq!( - limit(unusable), - DEFAULT_MAX_MB * 1024 * 1024, - "{unusable:?}" - ); - } - } - - #[test] - fn a_log_within_its_bound_is_left_alone() { - let dir = tempfile::tempdir().unwrap(); - rotate(dir.path(), LIMIT).unwrap(); - open(dir.path()).unwrap().write_all(b"line\n").unwrap(); - rotate(dir.path(), LIMIT).unwrap(); - assert_eq!( - std::fs::read(dir.path().join("serve.log")).unwrap(), - b"line\n" - ); - assert!(!dir.path().join("serve.log.1").exists()); - } -} diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index c74c2eb9..e9a4be37 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -268,7 +268,7 @@ pub(super) async fn accept_resolved_event( let session_id = env.session_id.clone(); let managed_run_id = env.managed_run_id.clone(); let route = env.route.clone(); - tracing::info!(source, event, session_id, "event received"); + tracing::debug!(source, event, session_id, "event received"); let session_lock = daemon.dispatch_lock(&source, &session_id); let _session_guard = session_lock.lock().await; @@ -312,7 +312,7 @@ pub(super) async fn accept_resolved_event( .persist_managed_run_session(&managed_run_id, delivery_key, &route) .await; } - tracing::info!(source, event, session_id, "event accepted") + tracing::debug!(source, event, session_id, "event accepted") } Err(error) => tracing::warn!(source, event, session_id, %error, "event rejected"), } diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 36daa359..5738c84a 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -308,31 +308,6 @@ pub(super) fn spawn_gc(daemon: Arc) { }); } -/// How often a running daemon bounds the log its standard streams write to. -const LOG_ROTATION_INTERVAL: Duration = Duration::from_secs(60); - -pub(super) fn spawn_log_rotation(daemon: Arc) { - tokio::spawn(async move { - loop { - tokio::select! { - _ = daemon.shutdown.notified() => return, - _ = tokio::time::sleep(LOG_ROTATION_INTERVAL) => {} - } - let data_dir = daemon.data_dir.clone(); - let max_bytes = crate::serve_log::max_bytes(); - match tokio::task::spawn_blocking(move || { - crate::serve_log::rotate(&data_dir, max_bytes) - }) - .await - { - Ok(Ok(())) => {} - Ok(Err(error)) => tracing::warn!(%error, "serve.log rotation failed"), - Err(error) => tracing::warn!(%error, "serve.log rotation did not run"), - } - } - }); -} - pub(super) fn spawn_idle_watchdog(daemon: Arc, idle_timeout: Duration) { if idle_timeout.is_zero() { return; // 0 disables the watchdog (useful in tests) diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index bcd43278..2b25a34f 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -266,7 +266,6 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { let (ready, startup) = oneshot::channel(); let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup)); - spawn_log_rotation(daemon.clone()); 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 d3269cca..45938ba5 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -211,15 +211,12 @@ fn host_info(host: &TraceHostContext) -> HostInfo { } } -fn init_daemon_logging(verbose: bool) { - let fallback = if verbose { "debug" } else { "info" }; - let filter = tracing_subscriber::EnvFilter::new(fallback); - if let Err(error) = tracing_subscriber::fmt() - .with_env_filter(filter) - .with_writer(std::io::stderr) - .try_init() - { - eprintln!("bt trace daemon logging unavailable: {error}"); +fn init_daemon_logging(data_dir: Option<&std::path::Path>, verbose: bool) { + let data_dir = paths::data_dir(data_dir); + if !crate::daemon_log::init(&data_dir, verbose) { + // A host installed a process-wide subscriber first; it can only be + // set once, so the daemon's events stay with the host's. + tracing::warn!("a logging subscriber is already installed; daemon logs go to it"); } } @@ -688,7 +685,7 @@ pub async fn run_trace(args: TraceArgs, host: TraceHostContext) -> anyhow::Resul print_output(output, host.output_format) } TraceCommand::Daemon(serve_args) => { - init_daemon_logging(host.verbose); + init_daemon_logging(serve_args.data_dir.as_deref(), host.verbose); run_serve(serve_args, serve_options(&host)).await } TraceCommand::Hook(hook_args) => { From 1b8fa333b3953a8ee7cb03d6d81f8b0b27f3eb8f Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 17 Nov 2026 00:28:57 +0800 Subject: [PATCH 6/6] Rotate daemon logs with file-rotate Replace the hand-written rotating writer with file-rotate. daemon.log is a size-limited FileRotate behind the subscriber's writer, and the hook rotates serve.log with the same configuration before spawning a daemon. Each keeps one earlier generation as .1. Co-Authored-By: Claude Opus 5.5 --- bt-daemon/Cargo.lock | 59 +++++++++++ bt-daemon/Cargo.toml | 1 + bt-daemon/src/daemon_log.rs | 203 +++++++----------------------------- 3 files changed, 100 insertions(+), 163 deletions(-) diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index af7091a9..3415aad3 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.4" @@ -305,6 +311,7 @@ dependencies = [ "bytes", "chrono", "clap", + "file-rotate", "fs2", "libc", "muse-code-sdk", @@ -496,6 +503,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossbeam" version = "0.8.4" @@ -675,12 +691,33 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "file-rotate" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e8e2fa049328a1f3295991407a88585805d126dfaadf74b9fe8c194c730aafc" +dependencies = [ + "chrono", + "flate2", +] + [[package]] name = "find-msvc-tools" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1347,6 +1384,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.2" @@ -2121,6 +2168,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -2995,6 +3048,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index d936f957..483d2fa4 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -48,6 +48,7 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } uuid = { version = "1", features = ["v4", "v5"] } rusqlite = { version = "0.37", features = ["bundled"] } +file-rotate = "0.8" [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/src/daemon_log.rs b/bt-daemon/src/daemon_log.rs index 8df626de..2ce8fe82 100644 --- a/bt-daemon/src/daemon_log.rs +++ b/bt-daemon/src/daemon_log.rs @@ -8,21 +8,19 @@ //! `serve.log`, which therefore only holds warnings and anything printed //! before logging starts. //! -//! Both files are bounded by rename-and-reopen rotation: once a file would -//! outgrow its limit (`BT_TRACE_LOG_MAX_MB` MiB, default [`DEFAULT_MAX_MB`]), -//! it is renamed to `.1`, replacing the previous generation, and a fresh -//! file is started. Every line lands whole in one generation or the next. -//! `daemon.log` rotates as it is written; `serve.log` rotates before a daemon -//! is spawned, since the daemon writes it through an inherited handle. +//! Both files are rotated by `file-rotate` once they pass +//! `BT_TRACE_LOG_MAX_MB` MiB (default [`DEFAULT_MAX_MB`]), keeping one earlier +//! generation as `.1`. `daemon.log` rotates as it is written; `serve.log` +//! rotates before a daemon is spawned, since the daemon writes it through an +//! inherited handle. //! //! The global subscriber can be set once per process, so a host that installs //! its own must not do so before running the daemon command. -use parking_lot::{Mutex, MutexGuard}; +use file_rotate::{compression::Compression, suffix::AppendCount, ContentLimit, FileRotate}; use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::path::Path; +use std::sync::Mutex; use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt, EnvFilter, Layer}; /// Rotate once a log would grow past this many MiB. One earlier generation of @@ -51,7 +49,7 @@ fn limit(mb: Option<&str>) -> u64 { /// has one, which then keeps receiving the daemon's events. pub(crate) fn init(data_dir: &Path, verbose: bool) -> bool { let (subscriber, errors) = subscriber( - RotatingFile::new(data_dir.join("daemon.log"), max_bytes()), + Mutex::new(rotating(&data_dir.join("daemon.log"))), std::io::stderr, // A spawned daemon's stderr is `serve.log`, which must stay plain. std::io::IsTerminal::is_terminal(&std::io::stderr()), @@ -72,13 +70,14 @@ pub(crate) fn init(data_dir: &Path, verbose: bool) -> bool { } /// The daemon's subscriber, and any filter settings it had to reject. -fn subscriber( - file: RotatingFile, +fn subscriber( + file: F, stderr: E, ansi: bool, verbose: bool, ) -> (impl tracing::Subscriber + Send + Sync, Vec) where + F: for<'a> MakeWriter<'a> + Send + Sync + 'static, E: for<'a> MakeWriter<'a> + Send + Sync + 'static, { let (file_filter, file_error) = filter(LEVEL_ENV, "debug"); @@ -121,172 +120,55 @@ fn parse_filter(env: &str, value: Option, default: &str) -> (EnvFilter, } } +/// A log at `path` that rotates once it passes the configured size, keeping +/// one earlier generation as `.1`. +fn rotating(path: &Path) -> FileRotate { + FileRotate::new( + path, + AppendCount::new(1), + ContentLimit::BytesSurpassed(usize::try_from(max_bytes()).unwrap_or(usize::MAX)), + Compression::None, + None, + ) +} + /// Open `serve.log` for a new daemon's standard streams, rotating it first. -/// No writer of this process holds it, so renaming it away is safe; a daemon -/// still exiting keeps writing into the rotated generation. +/// A daemon still exiting keeps writing into the rotated generation. pub(crate) fn open_serve_log(data_dir: &Path) -> std::io::Result { + std::fs::create_dir_all(data_dir)?; let path = data_dir.join("serve.log"); let len = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); if len > max_bytes() { - if let Err(error) = rotate(&path) { + if let Err(error) = rotating(&path).rotate() { tracing::warn!(%error, "serve.log rotation failed"); } } - append(&path) -} - -fn append(path: &Path) -> std::io::Result { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } OpenOptions::new().create(true).append(true).open(path) } -/// Rename `path` to `.1`, replacing the previous generation. A virus -/// scanner or indexer can briefly hold a file on Windows, so a failed rename -/// is retried a few times before giving up. -fn rotate(path: &Path) -> std::io::Result<()> { - let mut rotated = path.as_os_str().to_owned(); - rotated.push(".1"); - let mut attempt = 0; - loop { - match std::fs::rename(path, &rotated) { - Ok(()) => return Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(_) if attempt < 3 => { - attempt += 1; - std::thread::sleep(std::time::Duration::from_millis(10 * attempt)); - } - Err(error) => return Err(error), - } - } -} - -/// A log file that rotates by renaming itself once a write would take it past -/// its limit. `tracing` writes each event with one call, so rotation happens -/// between whole lines. -#[derive(Clone)] -pub(crate) struct RotatingFile(Arc>); - -struct State { - path: PathBuf, - max_bytes: u64, - file: Option, - written: u64, -} - -impl RotatingFile { - pub(crate) fn new(path: PathBuf, max_bytes: u64) -> Self { - Self(Arc::new(Mutex::new(State { - path, - max_bytes, - file: None, - written: 0, - }))) - } -} - -impl State { - fn file(&mut self) -> std::io::Result<&mut File> { - let file = match self.file.take() { - Some(file) => file, - None => { - let file = append(&self.path)?; - self.written = file.metadata()?.len(); - file - } - }; - Ok(self.file.insert(file)) - } - - fn write_line(&mut self, line: &[u8]) -> std::io::Result<()> { - self.file()?; - if self.written > 0 && self.written + line.len() as u64 > self.max_bytes { - self.file = None; - // Keep writing to the current generation if it cannot move. - let _ = rotate(&self.path); - } - self.file()?.write_all(line)?; - self.written += line.len() as u64; - Ok(()) - } -} - -pub(crate) struct Writer<'a>(MutexGuard<'a, State>); - -impl Write for Writer<'_> { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.write_line(buf)?; - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - match self.0.file.as_mut() { - Some(file) => file.flush(), - None => Ok(()), - } - } -} - -impl<'a> MakeWriter<'a> for RotatingFile { - type Writer = Writer<'a>; - - fn make_writer(&'a self) -> Self::Writer { - Writer(self.0.lock()) - } -} - #[cfg(test)] mod tests { use super::*; - - fn write(file: &RotatingFile, line: &str) { - file.make_writer().write_all(line.as_bytes()).unwrap(); - } + use std::io::Write; fn read(path: &Path) -> String { std::fs::read_to_string(path).unwrap_or_default() } #[test] - fn rotation_keeps_every_line_across_generations() { + fn daemon_log_keeps_one_rotated_generation() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("daemon.log"); - let rotated = dir.path().join("daemon.log.1"); - let file = RotatingFile::new(path.clone(), 30); - let lines: Vec = (0..6).map(|i| format!("line {i:02} ......\n")).collect(); - for line in &lines[..3] { - write(&file, line); - } - // Two 15-byte lines fit in 30 bytes, so the third starts a new file. - assert_eq!(read(&rotated), lines[..2].concat()); - assert_eq!(read(&path), lines[2]); - for line in &lines[3..] { - write(&file, line); + let mut log = rotating(&path); + let line = vec![b'.'; 1024 * 1024]; + for _ in 0..(DEFAULT_MAX_MB * 3) { + log.write_all(&line).unwrap(); } - // A later rotation replaces the earlier generation; the two files - // still read as one continuous log. - assert_eq!(read(&rotated) + &read(&path), lines[2..].concat()); - } - - #[test] - fn a_line_longer_than_the_limit_is_still_written() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("daemon.log"); - let file = RotatingFile::new(path.clone(), 4); - write(&file, "longer than the limit\n"); - assert_eq!(read(&path), "longer than the limit\n"); - } - - #[test] - fn writing_resumes_an_existing_log_and_counts_its_size() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("daemon.log"); - std::fs::write(&path, "earlier daemon\n").unwrap(); - let file = RotatingFile::new(path.clone(), 20); - write(&file, "this daemon\n"); - assert_eq!(read(&dir.path().join("daemon.log.1")), "earlier daemon\n"); - assert_eq!(read(&path), "this daemon\n"); + log.flush().unwrap(); + let generations = std::fs::read_dir(dir.path()).unwrap().count(); + assert_eq!(generations, 2, "the current log and one rotated generation"); + assert!(dir.path().join("daemon.log.1").exists()); + assert!(std::fs::metadata(&path).unwrap().len() <= (DEFAULT_MAX_MB + 1) * 1024 * 1024); } #[test] @@ -320,13 +202,8 @@ mod tests { fn each_output_has_its_own_level_and_format() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("daemon.log"); - let stderr = RotatingFile::new(dir.path().join("stderr"), u64::MAX); - let (subscriber, errors) = subscriber( - RotatingFile::new(path.clone(), u64::MAX), - stderr, - false, - false, - ); + let stderr = Mutex::new(File::create(dir.path().join("stderr")).unwrap()); + let (subscriber, errors) = subscriber(Mutex::new(rotating(&path)), stderr, false, false); assert!(errors.is_empty()); tracing::subscriber::with_default(subscriber, || { tracing::debug!(session_id = "s", "event received");