From a477db1975c7adcb5477ee629f24750dbc75febe Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:00:52 +0800 Subject: [PATCH 01/12] Support system-wide tracing plugins --- bt-daemon/Cargo.toml | 2 +- bt-daemon/README.md | 22 ++++ .../command_output/doctor_command_output.rs | 15 +++ bt-daemon/src/command_output/tests.rs | 2 + bt-daemon/src/dispatch.rs | 2 + bt-daemon/src/lib.rs | 1 + bt-daemon/src/pipeline/consumer.rs | 108 +++++++++++++++++- bt-daemon/src/server/maintenance.rs | 9 +- bt-daemon/src/server/mod.rs | 15 ++- bt-daemon/src/server/sessions.rs | 1 + bt-daemon/src/system_trace_config.rs | 95 +++++++++++++++ bt-daemon/src/trace_runtime.rs | 16 +++ 12 files changed, 283 insertions(+), 5 deletions(-) create mode 100644 bt-daemon/src/system_trace_config.rs diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 56f728d7..eefe6329 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -60,7 +60,7 @@ 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"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading", "Win32_System_Com", "Win32_UI_Shell"] } [dev-dependencies] bt-daemon = { path = ".", features = ["test-support"] } diff --git a/bt-daemon/README.md b/bt-daemon/README.md index 04304027..a4577542 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -133,6 +133,28 @@ destination, flush mode, and metadata. Setup saves a stable `route.auth.profile_ production resolves and refreshes them through `bt`. `bt trace run` supplies a process-local settings overlay and never changes any of these files. +### System-wide mandatory plugins + +Administrators can configure mandatory span plugins for all users, agents, projects, +and invocations in `/etc/braintrust/trace.json` (macOS and Linux) or +`%ProgramData%\Braintrust\trace.json` (Windows): + +```json +{ + "span_plugins": ["/opt/company/braintrust/redact.mjs"] +} +``` + +Paths may be absolute or relative to this file. Mandatory plugins run first, +followed by route plugins; project and invocation options cannot remove them. +Protect the configuration and plugin files with system permissions. Each user must restart tracing +with `bt trace stop` after the configuration changes. `bt trace doctor ` +shows the system configuration and mandatory plugins. An invalid or unreadable +configuration prevents tracing from starting, and a plugin failure holds delivery. +An absent file leaves existing behavior unchanged. This protects delivery through +Braintrust tracing, not against a user who can bypass or replace the software. +Raw events and translated operations are stored locally before plugins run. + ### JavaScript span plugins `--plugin PATH` registers a synchronous ES module that transforms each diff --git a/bt-daemon/src/command_output/doctor_command_output.rs b/bt-daemon/src/command_output/doctor_command_output.rs index 4ac51171..4dd04590 100644 --- a/bt-daemon/src/command_output/doctor_command_output.rs +++ b/bt-daemon/src/command_output/doctor_command_output.rs @@ -8,6 +8,8 @@ pub struct DoctorCommandOutput { pub source: String, pub display_name: String, pub settings_path: PathBuf, + pub system_settings_path: PathBuf, + pub mandatory_span_plugins: Option>, pub settings_present: bool, #[serde(skip_serializing_if = "Option::is_none")] pub project_settings_path: Option, @@ -40,6 +42,19 @@ impl DoctorCommandOutput { self.route_source, route, ); + rendered.push_str(&format!( + "\nSystem tracing settings: {}\nMandatory span plugins: {}", + self.system_settings_path.display(), + match &self.mandatory_span_plugins { + None => "(unavailable)".into(), + Some(paths) if paths.is_empty() => "(none)".into(), + Some(paths) => paths + .iter() + .map(|path| path.display().to_string()) + .collect::>() + .join(", "), + } + )); if let Some(path) = &self.project_settings_path { rendered.push_str(&format!("\nProject settings: {}", path.display())); if !self.project_settings_fields.is_empty() { diff --git a/bt-daemon/src/command_output/tests.rs b/bt-daemon/src/command_output/tests.rs index 9c06e087..ad11b3e4 100644 --- a/bt-daemon/src/command_output/tests.rs +++ b/bt-daemon/src/command_output/tests.rs @@ -157,6 +157,8 @@ fn doctor_json_is_structured_and_contains_no_credentials() { source: "codex".into(), display_name: "Codex".into(), settings_path: PathBuf::from("/tmp/braintrust.json"), + system_settings_path: PathBuf::from("/etc/braintrust/trace.json"), + mandatory_span_plugins: Some(Vec::new()), settings_present: true, project_settings_path: None, project_settings_fields: Vec::new(), diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index a75875e4..1202df7b 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -76,6 +76,7 @@ pub(crate) struct SessionOptions { pub config: crate::wire::SessionConfig, pub route: crate::wire::SessionRoute, pub data_dir: PathBuf, + pub mandatory_span_plugins: Vec, pub translation: Arc, pub input: crate::pipeline::cursor::Cursor, pub auth_provider: Option>, @@ -120,6 +121,7 @@ impl Session { session_id: crate::ids::native_session_id(&options.session_id).to_owned(), version: options.bt_version, data_dir: options.data_dir, + mandatory_span_plugins: options.mandatory_span_plugins, config, route: options.route, counters: counters.clone(), diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 10d080ae..ba3dc359 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -40,6 +40,7 @@ mod setup; mod sink; mod span_processor; mod subprocess; +mod system_trace_config; mod trace_command; mod trace_runtime; mod transcript_import; diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index c4b801c1..7f01f77e 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -30,12 +30,14 @@ pub(crate) struct Consumer { task: Mutex>>, config: watch::Sender, stop: Arc, + mandatory_span_plugins: Vec, } pub(crate) struct ConsumerOptions { pub source: String, pub session_id: String, pub version: String, pub data_dir: PathBuf, + pub mandatory_span_plugins: Vec, pub route: SessionRoute, pub config: watch::Sender, pub counters: Arc, @@ -180,12 +182,18 @@ impl Consumer { options: ConsumerOptions, ) -> Arc { let config = options.config.clone(); + config.send_modify(|current| { + current + .span_plugins + .splice(0..0, options.mandatory_span_plugins.iter().cloned()); + }); let mut settings = config.subscribe(); let stop = Arc::new(Notify::new()); let handle = Arc::new(Self { task: Mutex::new(None), config: config.clone(), stop: stop.clone(), + mandatory_span_plugins: options.mandatory_span_plugins.clone(), }); let task = tokio::spawn(async move { let mut sink = None; @@ -346,7 +354,10 @@ impl Consumer { *handle.task.lock() = Some(task); handle } - pub fn configure(&self, config: SessionConfig) { + pub fn configure(&self, mut config: SessionConfig) { + config + .span_plugins + .splice(0..0, self.mandatory_span_plugins.iter().cloned()); self.config.send_if_modified(|current| { if serde_json::to_value(&*current).ok() == serde_json::to_value(&config).ok() { return false; @@ -438,6 +449,7 @@ mod tests { session_id: "test".into(), version: "test".into(), data_dir: dir.into(), + mandatory_span_plugins: Vec::new(), route: route.clone(), config: watch::channel(route.with_auth(BackendAuth { token: "never-persist-this".into(), @@ -500,6 +512,38 @@ mod tests { .await .unwrap(); } + #[tokio::test] + async fn system_plugins_run_before_route_plugins_and_survive_reconfiguration() { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let redactor = tmp.path().join("redact.mjs"); + let verify = tmp.path().join("verify.mjs"); + std::fs::write( + &redactor, + "export default span => ({...span, name: 'redacted'})", + ) + .unwrap(); + std::fs::write(&verify, "export default span => { if (span.name !== 'redacted') throw new Error('not redacted'); return span; }").unwrap(); + let route = SessionRoute { + span_plugins: vec![verify.clone()], + ..Default::default() + }; + let record = Arc::new(Recording::default()); + let mut opts = options(tmp.path(), &route, record.clone()); + opts.mandatory_span_plugins = vec![redactor.clone()]; + stored(&journal).await; + let (consumer, progress, _) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| progress.completed() == 1).await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 1); + let mut replacement = consumer.config.borrow().clone(); + replacement.span_plugins.clear(); + consumer.configure(replacement); + assert_eq!(consumer.config.borrow().span_plugins, [redactor]); + consumer.shutdown().await; + } + #[tokio::test] async fn transient_rejection_resubmits_consumed_batch_before_completing() { let tmp = tempfile::tempdir().unwrap(); @@ -736,6 +780,68 @@ mod tests { let _ = forward.await; drop(journal); } + #[tokio::test] + async fn system_plugin_failure_survives_restart_and_recovers_after_edit() { + let tmp = tempfile::tempdir().unwrap(); + let plugin = tmp.path().join("plugin.mjs"); + std::fs::write(&plugin, "export default () => {throw new Error('bad')}").unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + stored(&journal).await; + let route = SessionRoute::default(); + let key = serde_json::to_string(&route).unwrap(); + let record = Arc::new(Recording::default()); + let mut initial = options(tmp.path(), &route, record.clone()); + initial.mandatory_span_plugins = vec![plugin.clone()]; + let (consumer, _progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), initial); + wait_for(|| error.lock().is_some()).await; + consumer.shutdown().await; + let evidence = journal + .head(&key) + .await + .unwrap() + .and_then(|head| head.failure) + .unwrap(); + assert!(!evidence.contains("never-persist-this")); + // Restart with an ordinary channel between the durable source and the + // same consumer. Historical failure gating belongs to the source. + let mut opts = options(tmp.path(), &route, record.clone()); + opts.mandatory_span_plugins = vec![plugin.clone()]; + let subscription = Cursor::open(&journal, &route).await.unwrap().into_input( + opts.config.subscribe(), + opts.version.clone(), + opts.error.clone(), + opts.recovery.clone(), + ); + let progress = subscription.progress; + let mut input = subscription.input; + let (tx, rx) = tokio::sync::mpsc::channel(1); + let forward = tokio::spawn(async move { + while let Ok(Some(delivery)) = input.receive().await { + if tx.send(delivery).await.is_err() { + break; + } + } + }); + let consumer = Consumer::spawn(Box::new(rx), opts); + tokio::time::sleep(std::time::Duration::from_millis(600)).await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 0); + std::fs::write(&plugin, "export default span => span").unwrap(); + wait_for(|| progress.completed() == 1).await; + assert_eq!(record.accepted.load(Ordering::SeqCst), 1); + assert!(journal + .head(&key) + .await + .unwrap() + .and_then(|head| head.failure) + .is_none()); + consumer.shutdown().await; + forward.abort(); + let _ = forward.await; + drop(journal); + } struct RefreshAuth(Arc); #[async_trait::async_trait] impl AuthProvider for RefreshAuth { diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 5b56bf94..306cdde1 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -442,6 +442,7 @@ mod tests { root.into(), Some(startup), RETENTION, + Vec::new(), ), ready, ) @@ -817,7 +818,13 @@ 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), RETENTION); + let daemon = Daemon::new_with_startup( + opts, + tmp.path().into(), + Some(startup), + RETENTION, + Vec::new(), + ); let mut fixtures = DistributedFixtures::new(); let parent = ProcessTree::root(1000); let child = ProcessTree::child(1002, 1001, &parent); diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index 773d3a3c..488f90d5 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -110,6 +110,7 @@ pub struct Daemon { data_dir: PathBuf, /// How long undelivered and idle state is kept on disk. retention: Duration, + mandatory_span_plugins: Vec, translators: Arc, sink_factory: Arc, auth_provider: Option>, @@ -155,7 +156,7 @@ pub struct Daemon { impl Daemon { #[cfg(test)] fn new(opts: ServeOptions, data_dir: PathBuf) -> Arc { - Self::new_with_startup(opts, data_dir, None, maintenance::RETENTION) + Self::new_with_startup(opts, data_dir, None, maintenance::RETENTION, Vec::new()) } fn new_with_startup( @@ -163,6 +164,7 @@ impl Daemon { data_dir: PathBuf, startup: Option>, retention: Duration, + mandatory_span_plugins: Vec, ) -> Arc { let (ingress_tx, ingress_rx) = mpsc::channel(INGRESS_QUEUE_CAPACITY); let startup_cutoffs = startup.as_ref().map(|_| HashMap::new()); @@ -170,6 +172,7 @@ impl Daemon { version: opts.version, data_dir, retention, + mandatory_span_plugins, translators: opts.translators, sink_factory: opts.sink_factory, auth_provider: opts.auth_provider, @@ -244,6 +247,8 @@ fn now_ms() -> i64 { /// Bind the socket (handling a stale/rival socket), serve until shutdown, then /// drain sessions and remove the socket. pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { + let policy = + crate::system_trace_config::SystemTraceConfig::load(&crate::system_trace_config::path()?)?; let socket = paths::socket_path(args.socket.as_deref()); let data_dir = paths::data_dir(args.data_dir.as_deref()); paths::ensure_private_dir(&data_dir)?; @@ -272,7 +277,13 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { let (ready, startup) = oneshot::channel(); let retention = args.retention(); - let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup), retention); + let daemon = Daemon::new_with_startup( + opts, + data_dir, + Some(startup), + retention, + policy.span_plugins, + ); 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/server/sessions.rs b/bt-daemon/src/server/sessions.rs index 38321b35..ef1d4d1f 100644 --- a/bt-daemon/src/server/sessions.rs +++ b/bt-daemon/src/server/sessions.rs @@ -132,6 +132,7 @@ impl Daemon { bt_version: self.version.clone(), config, data_dir: self.data_dir.clone(), + mandatory_span_plugins: self.mandatory_span_plugins.clone(), }, self.sink_factory.clone(), ); diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs new file mode 100644 index 00000000..7a8995db --- /dev/null +++ b/bt-daemon/src/system_trace_config.rs @@ -0,0 +1,95 @@ +//! System-wide tracing policy, independent of user and project routes. +use anyhow::Context; +use serde::Deserialize; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Default, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct SystemTraceConfig { + #[serde(default)] + pub span_plugins: Vec, +} + +pub(crate) fn path() -> anyhow::Result { + #[cfg(windows)] + { + use std::os::windows::ffi::OsStringExt; + use windows_sys::Win32::System::Com::CoTaskMemFree; + use windows_sys::Win32::UI::Shell::{FOLDERID_ProgramData, SHGetKnownFolderPath}; + let mut raw = std::ptr::null_mut(); + // Windows allocates the returned UTF-16 string with CoTaskMemAlloc. + let status = unsafe { + SHGetKnownFolderPath(&FOLDERID_ProgramData, 0, std::ptr::null_mut(), &mut raw) + }; + anyhow::ensure!( + status >= 0 && !raw.is_null(), + "cannot resolve system tracing configuration directory (Windows error {status:#x})" + ); + let mut len = 0; + unsafe { + while *raw.add(len) != 0 { + len += 1; + } + let path = PathBuf::from(std::ffi::OsString::from_wide(std::slice::from_raw_parts( + raw, len, + ))); + CoTaskMemFree(raw.cast()); + Ok(path.join("Braintrust").join("trace.json")) + } + } + #[cfg(not(windows))] + { + Ok(PathBuf::from("/etc/braintrust/trace.json")) + } +} + +impl SystemTraceConfig { + pub fn load(path: &Path) -> anyhow::Result { + let raw = match std::fs::read(path) { + Ok(raw) => raw, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return Ok(Self::default()) + } + Err(error) => { + return Err(error).with_context(|| { + format!("read system tracing configuration {}", path.display()) + }) + } + }; + let mut config: Self = serde_json::from_slice(&raw) + .with_context(|| format!("parse system tracing configuration {}", path.display()))?; + let directory = path + .parent() + .context("system tracing configuration has no parent directory")?; + for plugin in &mut config.span_plugins { + if plugin.as_os_str().is_empty() { + anyhow::bail!("empty mandatory plugin path in {}", path.display()); + } + if plugin.is_relative() { + *plugin = directory.join(&*plugin); + } + } + Ok(config) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn loads_relative_paths_and_rejects_invalid_policy() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("trace.json"); + assert!(SystemTraceConfig::load(&path) + .unwrap() + .span_plugins + .is_empty()); + std::fs::write(&path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); + assert_eq!( + SystemTraceConfig::load(&path).unwrap().span_plugins, + [dir.path().join("redact.mjs")] + ); + std::fs::write(&path, r#"{"span_plugins":false}"#).unwrap(); + assert!(SystemTraceConfig::load(&path).is_err()); + } +} diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index d54137a5..b74fd481 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -533,6 +533,20 @@ async fn doctor_output_at( let settings_present = settings_path.exists(); let enabled = settings.tracing_enabled(); let mut warnings = Vec::new(); + let system_settings_path = crate::system_trace_config::path(); + let mandatory_span_plugins = match system_settings_path + .as_ref() + .map_err(|error| anyhow::anyhow!("{error:#}")) + .and_then(|path| crate::system_trace_config::SystemTraceConfig::load(path)) + { + Ok(config) => Some(config.span_plugins), + Err(error) => { + warnings.push(format!( + "system tracing settings could not be read: {error:#}" + )); + None + } + }; if !settings_present { warnings.push(format!( @@ -646,6 +660,8 @@ async fn doctor_output_at( source: source.into(), display_name: args.agent.identity().display_name.into(), settings_path, + system_settings_path: system_settings_path.unwrap_or_default(), + mandatory_span_plugins, settings_present, project_settings_path: None, project_settings_fields: Vec::new(), From f79f8669e46abb1493dc9fa06b64c14ea7da22e4 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:08:59 +0800 Subject: [PATCH 02/12] Reload system tracing configuration automatically --- bt-daemon/README.md | 5 +- bt-daemon/src/dispatch.rs | 4 +- bt-daemon/src/pipeline/consumer.rs | 140 ++++++++++++++++++++++----- bt-daemon/src/server/maintenance.rs | 4 +- bt-daemon/src/server/mod.rs | 19 ++-- bt-daemon/src/server/sessions.rs | 2 +- bt-daemon/src/system_trace_config.rs | 47 +++++++++ 7 files changed, 183 insertions(+), 38 deletions(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index a4577542..a1cf4520 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -147,10 +147,9 @@ and invocations in `/etc/braintrust/trace.json` (macOS and Linux) or Paths may be absolute or relative to this file. Mandatory plugins run first, followed by route plugins; project and invocation options cannot remove them. -Protect the configuration and plugin files with system permissions. Each user must restart tracing -with `bt trace stop` after the configuration changes. `bt trace doctor ` +Protect the configuration and plugin files with system permissions. Configuration changes are loaded automatically. `bt trace doctor ` shows the system configuration and mandatory plugins. An invalid or unreadable -configuration prevents tracing from starting, and a plugin failure holds delivery. +configuration or a plugin failure holds delivery until it is fixed. An absent file leaves existing behavior unchanged. This protects delivery through Braintrust tracing, not against a user who can bypass or replace the software. Raw events and translated operations are stored locally before plugins run. diff --git a/bt-daemon/src/dispatch.rs b/bt-daemon/src/dispatch.rs index 1202df7b..cfbdd32b 100644 --- a/bt-daemon/src/dispatch.rs +++ b/bt-daemon/src/dispatch.rs @@ -76,7 +76,7 @@ pub(crate) struct SessionOptions { pub config: crate::wire::SessionConfig, pub route: crate::wire::SessionRoute, pub data_dir: PathBuf, - pub mandatory_span_plugins: Vec, + pub system_policy: tokio::sync::watch::Receiver, pub translation: Arc, pub input: crate::pipeline::cursor::Cursor, pub auth_provider: Option>, @@ -121,7 +121,7 @@ impl Session { session_id: crate::ids::native_session_id(&options.session_id).to_owned(), version: options.bt_version, data_dir: options.data_dir, - mandatory_span_plugins: options.mandatory_span_plugins, + system_policy: options.system_policy, config, route: options.route, counters: counters.clone(), diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 7f01f77e..d0f77e04 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -30,14 +30,15 @@ pub(crate) struct Consumer { task: Mutex>>, config: watch::Sender, stop: Arc, - mandatory_span_plugins: Vec, + system_policy: watch::Receiver, + route_config: Arc>, } pub(crate) struct ConsumerOptions { pub source: String, pub session_id: String, pub version: String, pub data_dir: PathBuf, - pub mandatory_span_plugins: Vec, + pub system_policy: watch::Receiver, pub route: SessionRoute, pub config: watch::Sender, pub counters: Arc, @@ -176,24 +177,42 @@ impl ConsumerOptions { } } +fn apply_policy( + config: &watch::Sender, + route_config: &Mutex, + policy: &crate::system_trace_config::Policy, +) { + if let crate::system_trace_config::Policy::Valid(plugins) = policy { + let mut effective = route_config.lock().clone(); + effective.span_plugins.splice(0..0, plugins.iter().cloned()); + config.send_if_modified(|current| { + if serde_json::to_value(&*current).ok() == serde_json::to_value(&effective).ok() { + false + } else { + *current = effective; + true + } + }); + } +} + impl Consumer { pub fn spawn( mut input: Box>>, options: ConsumerOptions, ) -> Arc { let config = options.config.clone(); - config.send_modify(|current| { - current - .span_plugins - .splice(0..0, options.mandatory_span_plugins.iter().cloned()); - }); + let route_config = Arc::new(Mutex::new(config.borrow().clone())); + let mut policy = options.system_policy.clone(); + apply_policy(&config, &route_config, &policy.borrow()); let mut settings = config.subscribe(); let stop = Arc::new(Notify::new()); let handle = Arc::new(Self { task: Mutex::new(None), config: config.clone(), stop: stop.clone(), - mandatory_span_plugins: options.mandatory_span_plugins.clone(), + system_policy: options.system_policy.clone(), + route_config: route_config.clone(), }); let task = tokio::spawn(async move { let mut sink = None; @@ -203,6 +222,25 @@ impl Consumer { let mut recorded = None; let mut record_retry = 0; loop { + let current_policy = policy.borrow_and_update().clone(); + if let crate::system_trace_config::Policy::Invalid(error) = ¤t_policy { + *options.error.lock() = Some(format!("system tracing settings: {error}")); + tokio::select! { + _ = stop.notified() => break, + result = policy.changed() => if result.is_err() { break; }, + } + continue; + } + apply_policy(&config, &route_config, ¤t_policy); + { + let mut error = options.error.lock(); + if error + .as_ref() + .is_some_and(|message| message.starts_with("system tracing settings:")) + { + *error = None; + } + } if let Some(waiting) = held.take() { let (mut failure, work) = *waiting; let mut reported = failure.clone(); @@ -220,6 +258,7 @@ impl Consumer { _=stop.notified()=>break, _=tokio::time::sleep(std::time::Duration::from_millis(250))=>{}, result=settings.changed()=>if result.is_err() { break; }, + result=policy.changed()=>if result.is_err() { break; }, } let mut current = settings.borrow_and_update().clone(); if recorded.as_ref() != Some(&reported) @@ -246,6 +285,7 @@ impl Consumer { ))); continue; } + route_config.lock().auth = current.auth.clone(); config.send_replace(current.clone()); } match options @@ -269,6 +309,9 @@ impl Consumer { result=settings.changed()=> { return if result.is_err() { Ok(None) } else { Ok(Some(false)) }; }, + result=policy.changed()=> { + return if result.is_err() { Ok(None) } else { Ok(Some(false)) }; + }, }; let delivery = received.map_err(|error| match error.downcast::() { Ok(failure) => Box::new((failure, Work::Resubmit)), @@ -277,6 +320,15 @@ impl Consumer { let Some(delivery) = delivery else { return Ok(None); }; + let current_policy = policy.borrow().clone(); + if matches!( + current_policy, + crate::system_trace_config::Policy::Invalid(_) + ) { + drop(delivery); + return Ok(Some(false)); + } + apply_policy(&config, &route_config, ¤t_policy); let current = settings.borrow_and_update().clone(); let ops = delivery.value().as_slice(); let mut stopped = false; @@ -354,17 +406,13 @@ impl Consumer { *handle.task.lock() = Some(task); handle } - pub fn configure(&self, mut config: SessionConfig) { - config - .span_plugins - .splice(0..0, self.mandatory_span_plugins.iter().cloned()); - self.config.send_if_modified(|current| { - if serde_json::to_value(&*current).ok() == serde_json::to_value(&config).ok() { - return false; - } - *current = config; - true - }); + pub fn configure(&self, config: SessionConfig) { + *self.route_config.lock() = config; + apply_policy( + &self.config, + &self.route_config, + &self.system_policy.borrow(), + ); } pub async fn shutdown(&self) { self.stop.notify_one(); @@ -449,7 +497,7 @@ mod tests { session_id: "test".into(), version: "test".into(), data_dir: dir.into(), - mandatory_span_plugins: Vec::new(), + system_policy: crate::system_trace_config::fixed(Vec::new()), route: route.clone(), config: watch::channel(route.with_auth(BackendAuth { token: "never-persist-this".into(), @@ -532,7 +580,7 @@ mod tests { }; let record = Arc::new(Recording::default()); let mut opts = options(tmp.path(), &route, record.clone()); - opts.mandatory_span_plugins = vec![redactor.clone()]; + opts.system_policy = crate::system_trace_config::fixed(vec![redactor.clone()]); stored(&journal).await; let (consumer, progress, _) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); wait_for(|| progress.completed() == 1).await; @@ -544,6 +592,52 @@ mod tests { consumer.shutdown().await; } + #[tokio::test] + async fn system_policy_reloads_and_invalid_edits_hold_delivery_until_repaired() { + let tmp = tempfile::tempdir().unwrap(); + let policy_path = tmp.path().join("trace.json"); + let plugin = tmp.path().join("redact.mjs"); + std::fs::write( + &plugin, + "export default span => ({...span, name: 'redacted'})", + ) + .unwrap(); + std::fs::write(&policy_path, r#"{"span_plugins":[]}"#).unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let record = Arc::new(Recording::default()); + let mut opts = options(tmp.path(), &route, record.clone()); + opts.system_policy = crate::system_trace_config::watch(policy_path.clone()); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + std::fs::write(&policy_path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); + wait_for(|| consumer.config.borrow().span_plugins == [plugin.clone()]).await; + std::fs::write(&policy_path, "{").unwrap(); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|e| e.contains("system tracing settings")) + }) + .await; + stored(&journal).await; + tokio::time::sleep(std::time::Duration::from_millis(350)).await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 0); + std::fs::write(&policy_path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); + wait_for(|| error.lock().is_none()).await; + tokio::time::timeout( + std::time::Duration::from_secs(5), + progress.through(1, &error), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(record.submitted.load(Ordering::SeqCst), 1); + consumer.shutdown().await; + } + #[tokio::test] async fn transient_rejection_resubmits_consumed_batch_before_completing() { let tmp = tempfile::tempdir().unwrap(); @@ -793,7 +887,7 @@ mod tests { let key = serde_json::to_string(&route).unwrap(); let record = Arc::new(Recording::default()); let mut initial = options(tmp.path(), &route, record.clone()); - initial.mandatory_span_plugins = vec![plugin.clone()]; + initial.system_policy = crate::system_trace_config::fixed(vec![plugin.clone()]); let (consumer, _progress, error) = spawn(Cursor::open(&journal, &route).await.unwrap(), initial); wait_for(|| error.lock().is_some()).await; @@ -808,7 +902,7 @@ mod tests { // Restart with an ordinary channel between the durable source and the // same consumer. Historical failure gating belongs to the source. let mut opts = options(tmp.path(), &route, record.clone()); - opts.mandatory_span_plugins = vec![plugin.clone()]; + opts.system_policy = crate::system_trace_config::fixed(vec![plugin.clone()]); let subscription = Cursor::open(&journal, &route).await.unwrap().into_input( opts.config.subscribe(), opts.version.clone(), diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 306cdde1..f2ab900a 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -442,7 +442,7 @@ mod tests { root.into(), Some(startup), RETENTION, - Vec::new(), + crate::system_trace_config::fixed(Vec::new()), ), ready, ) @@ -823,7 +823,7 @@ mod tests { tmp.path().into(), Some(startup), RETENTION, - Vec::new(), + crate::system_trace_config::fixed(Vec::new()), ); let mut fixtures = DistributedFixtures::new(); let parent = ProcessTree::root(1000); diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index 488f90d5..f136290c 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -110,7 +110,7 @@ pub struct Daemon { data_dir: PathBuf, /// How long undelivered and idle state is kept on disk. retention: Duration, - mandatory_span_plugins: Vec, + system_policy: tokio::sync::watch::Receiver, translators: Arc, sink_factory: Arc, auth_provider: Option>, @@ -156,7 +156,13 @@ pub struct Daemon { impl Daemon { #[cfg(test)] fn new(opts: ServeOptions, data_dir: PathBuf) -> Arc { - Self::new_with_startup(opts, data_dir, None, maintenance::RETENTION, Vec::new()) + Self::new_with_startup( + opts, + data_dir, + None, + maintenance::RETENTION, + crate::system_trace_config::fixed(Vec::new()), + ) } fn new_with_startup( @@ -164,7 +170,7 @@ impl Daemon { data_dir: PathBuf, startup: Option>, retention: Duration, - mandatory_span_plugins: Vec, + system_policy: tokio::sync::watch::Receiver, ) -> Arc { let (ingress_tx, ingress_rx) = mpsc::channel(INGRESS_QUEUE_CAPACITY); let startup_cutoffs = startup.as_ref().map(|_| HashMap::new()); @@ -172,7 +178,7 @@ impl Daemon { version: opts.version, data_dir, retention, - mandatory_span_plugins, + system_policy, translators: opts.translators, sink_factory: opts.sink_factory, auth_provider: opts.auth_provider, @@ -247,8 +253,7 @@ fn now_ms() -> i64 { /// Bind the socket (handling a stale/rival socket), serve until shutdown, then /// drain sessions and remove the socket. pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { - let policy = - crate::system_trace_config::SystemTraceConfig::load(&crate::system_trace_config::path()?)?; + let policy_path = crate::system_trace_config::path()?; let socket = paths::socket_path(args.socket.as_deref()); let data_dir = paths::data_dir(args.data_dir.as_deref()); paths::ensure_private_dir(&data_dir)?; @@ -282,7 +287,7 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { data_dir, Some(startup), retention, - policy.span_plugins, + crate::system_trace_config::watch(policy_path), ); let idle_timeout = Duration::from_secs(args.idle_timeout_secs); let session_idle_timeout = Duration::from_secs(args.session_idle_timeout_secs); diff --git a/bt-daemon/src/server/sessions.rs b/bt-daemon/src/server/sessions.rs index ef1d4d1f..1d3065f0 100644 --- a/bt-daemon/src/server/sessions.rs +++ b/bt-daemon/src/server/sessions.rs @@ -132,7 +132,7 @@ impl Daemon { bt_version: self.version.clone(), config, data_dir: self.data_dir.clone(), - mandatory_span_plugins: self.mandatory_span_plugins.clone(), + system_policy: self.system_policy.clone(), }, self.sink_factory.clone(), ); diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index 7a8995db..cb0665b5 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -73,6 +73,53 @@ impl SystemTraceConfig { } } +/// Live system policy. An invalid policy prevents delivery until it is repaired. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum Policy { + Valid(Vec), + Invalid(String), +} + +impl Policy { + fn read(path: &Path) -> Self { + match SystemTraceConfig::load(path) { + Ok(config) => Self::Valid(config.span_plugins), + Err(error) => Self::Invalid(format!("{error:#}")), + } + } +} + +pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { + let (sender, receiver) = tokio::sync::watch::channel(Policy::read(&path)); + tokio::spawn(async move { + loop { + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + if sender.is_closed() { + break; + } + let next = Policy::read(&path); + sender.send_if_modified(|current| { + if *current == next { + false + } else { + *current = next; + true + } + }); + } + }); + receiver +} + +#[cfg(test)] +pub(crate) fn fixed(plugins: Vec) -> tokio::sync::watch::Receiver { + let (sender, receiver) = tokio::sync::watch::channel(Policy::Valid(plugins)); + tokio::spawn(async move { + sender.closed().await; + }); + receiver +} + #[cfg(test)] mod tests { use super::*; From 41812e39a51a2b01926aaf38a3a9f836deeb4512 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 19:25:05 +0800 Subject: [PATCH 03/12] Watch system tracing configuration for changes --- bt-daemon/Cargo.lock | 89 ++++++++++++++++ bt-daemon/Cargo.toml | 1 + bt-daemon/src/system_trace_config.rs | 149 ++++++++++++++++++++++++++- 3 files changed, 234 insertions(+), 5 deletions(-) diff --git a/bt-daemon/Cargo.lock b/bt-daemon/Cargo.lock index d402d3fc..7eda728b 100644 --- a/bt-daemon/Cargo.lock +++ b/bt-daemon/Cargo.lock @@ -344,6 +344,7 @@ dependencies = [ "libc", "mime_guess", "muse-code-sdk", + "notify", "parking_lot", "regex", "reqwest 0.12.28", @@ -1192,6 +1193,26 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "inotify" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592" +dependencies = [ + "bitflags", + "inotify-sys", + "libc", +] + +[[package]] +name = "inotify-sys" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" +dependencies = [ + "libc", +] + [[package]] name = "instant" version = "0.1.13" @@ -1289,6 +1310,26 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kqueue" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea" +dependencies = [ + "kqueue-sys", + "libc", +] + +[[package]] +name = "kqueue-sys" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" +dependencies = [ + "bitflags", + "libc", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -1399,6 +1440,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -1428,6 +1470,34 @@ dependencies = [ "libc", ] +[[package]] +name = "notify" +version = "8.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41a04a5f59df9322cc657286dd2d79f90816119b22c5f847607c850110205ab" +dependencies = [ + "bitflags", + "inotify", + "kqueue", + "libc", + "log", + "mio", + "notify-types", + "objc2-core-foundation", + "objc2-core-services", + "walkdir", + "windows-sys 0.61.2", +] + +[[package]] +name = "notify-types" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbd044e85df3d939d8e32a1c35a3b737c7d0a4eeb7acd737bd207644e00f4e5f" +dependencies = [ + "bitflags", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -1465,6 +1535,25 @@ dependencies = [ "libc", ] +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-core-services" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "once_cell" version = "1.21.4" diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index eefe6329..8ea62126 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -29,6 +29,7 @@ braintrust-sdk-rust = { git = "https://github.com/braintrustdata/braintrust-sdk- braintrust-api-client = { git = "https://github.com/braintrustdata/braintrust-sdk-rust", rev = "b29025a725125f56d97232464500f065d98dfe5d" } base64 = "0.22" mime_guess = "2" +notify = "8.2" anyhow = "1" muse-code-sdk = "=1.4.12" parking_lot = "0.12" diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index cb0665b5..28cf8cc9 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -89,15 +89,81 @@ impl Policy { } } +// Notification backends may report canonical paths even when the configured +// location contains a symlink, and the final path may not exist yet. +fn canonical_location(path: &Path) -> PathBuf { + path.ancestors() + .find_map(|ancestor| { + let root = ancestor.canonicalize().ok()?; + Some(root.join(path.strip_prefix(ancestor).ok()?)) + }) + .unwrap_or_else(|| path.to_path_buf()) +} + pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { - let (sender, receiver) = tokio::sync::watch::channel(Policy::read(&path)); + use notify::{RecursiveMode, Watcher}; + + let (sender, receiver) = tokio::sync::watch::channel(Policy::Invalid( + "system tracing configuration watch is starting".into(), + )); + let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel(); tokio::spawn(async move { + let mut watcher = match notify::recommended_watcher(move |event| { + let _ = events_tx.send(event); + }) { + Ok(watcher) => watcher, + Err(error) => { + sender.send_replace(Policy::Invalid(format!( + "cannot watch system tracing configuration: {error}" + ))); + return; + } + }; + let mut watched = Vec::::new(); loop { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - if sender.is_closed() { - break; + // Watch existing ancestors individually so a newly created or replaced + // configuration directory can be registered without a recursive watch. + let mut watch_error = None; + if let Some(parent) = path.parent() { + let directories: Vec = parent + .ancestors() + .filter(|directory| directory.is_dir()) + .take(2) + .map(Path::to_path_buf) + .collect(); + for directory in &directories { + if watched.contains(directory) { + continue; + } + match watcher.watch(directory, RecursiveMode::NonRecursive) { + Ok(()) => watched.push(directory.clone()), + Err(error) => { + watch_error = + Some(format!("cannot watch {}: {error}", directory.display())); + break; + } + } + } + if watch_error.is_none() { + let mut index = 0; + while index < watched.len() { + if directories.contains(&watched[index]) { + index += 1; + continue; + } + let removed = watched.remove(index); + if let Err(error) = watcher.unwatch(&removed) { + tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); + } + } + } + } else { + watch_error = Some("system tracing configuration has no parent directory".into()); } - let next = Policy::read(&path); + let next = match watch_error { + Some(error) => Policy::Invalid(error), + None => Policy::read(&path), + }; sender.send_if_modified(|current| { if *current == next { false @@ -106,6 +172,39 @@ pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { true } }); + let canonical_target = canonical_location(&path); + loop { + tokio::select! { + _ = sender.closed() => return, + event = events_rx.recv() => match event { + None => { + sender.send_replace(Policy::Invalid("system tracing configuration watch stopped".into())); + return; + } + Some(Err(error)) => { + sender.send_replace(Policy::Invalid(format!("system tracing configuration watch failed: {error}"))); + break; + } + Some(Ok(event)) => { + if event.need_rescan() || event.paths.is_empty() || event.paths.iter().any(|changed| canonical_target.starts_with(changed) || changed == &canonical_target) { + for changed in &event.paths { + let mut index = 0; + while index < watched.len() { + let canonical = canonical_location(&watched[index]); + if canonical == *changed { + let removed = watched.remove(index); + if let Err(error) = watcher.unwatch(&removed) { + tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); + } + } else { index += 1; } + } + } + break; + } + } + } + } + } } }); receiver @@ -123,6 +222,46 @@ pub(crate) fn fixed(plugins: Vec) -> tokio::sync::watch::Receiver, expected: Policy) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + if *policy.borrow_and_update() == expected { + break; + } + policy.changed().await.unwrap(); + } + }) + .await + .unwrap(); + } + wait_for(&mut policy, Policy::Valid(Vec::new())).await; + std::fs::create_dir(&directory).unwrap(); + let staged = directory.join("new.json"); + std::fs::write(&staged, r#"{"span_plugins":["one.mjs"]}"#).unwrap(); + std::fs::rename(&staged, &path).unwrap(); + wait_for(&mut policy, Policy::Valid(vec![directory.join("one.mjs")])).await; + std::fs::write(&staged, r#"{"span_plugins":["two.mjs"]}"#).unwrap(); + std::fs::rename(&staged, &path).unwrap(); + wait_for(&mut policy, Policy::Valid(vec![directory.join("two.mjs")])).await; + std::fs::remove_dir_all(&directory).unwrap(); + wait_for(&mut policy, Policy::Valid(Vec::new())).await; + std::fs::create_dir(&directory).unwrap(); + std::fs::write(&path, r#"{"span_plugins":["three.mjs"]}"#).unwrap(); + wait_for( + &mut policy, + Policy::Valid(vec![directory.join("three.mjs")]), + ) + .await; + std::fs::write(&path, r#"{"span_plugins":["four.mjs"]}"#).unwrap(); + wait_for(&mut policy, Policy::Valid(vec![directory.join("four.mjs")])).await; + } + #[test] fn loads_relative_paths_and_rejects_invalid_policy() { let dir = tempfile::tempdir().unwrap(); From e7b7f5d0a3468033ca6ea1ca95dcb70ed3f53e4e Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 20:48:31 +0800 Subject: [PATCH 04/12] Harden global tracing plugin policy --- bt-daemon/README.md | 26 +- .../command_output/doctor_command_output.rs | 6 +- bt-daemon/src/command_output/tests.rs | 2 +- bt-daemon/src/pipeline/consumer.rs | 260 ++++++++++++++- bt-daemon/src/pipeline/cursor.rs | 3 + bt-daemon/src/pipeline/delivery.rs | 5 + bt-daemon/src/server/mod.rs | 17 +- bt-daemon/src/settings.rs | 47 ++- bt-daemon/src/setup/mod.rs | 19 +- bt-daemon/src/span_processor.rs | 71 ++-- bt-daemon/src/system_trace_config.rs | 307 +++++++++++++----- bt-daemon/src/trace_command.rs | 41 ++- bt-daemon/src/trace_runtime.rs | 4 +- src/plugins/opencode/content/src/config.ts | 1 + .../opencode/content/src/index.test.ts | 14 + .../opencode/content/src/tracing/plugin.ts | 11 +- src/plugins/pi/content/src/config.test.ts | 8 + src/plugins/pi/content/src/config.ts | 7 +- 18 files changed, 679 insertions(+), 170 deletions(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index a1cf4520..c2582e8f 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -92,12 +92,15 @@ user-level plugins, and their paths are relative to `.braintrust.json`: bt trace install claude --scope project --plugin ./scripts/redact.mjs ``` -Use `--no-inherit-plugins` to run only the project's plugins; use -`--inherit-plugins` to restore the default. A project configuration can execute +Use `--no-inherit-user-plugins` to omit the user-level plugins; use +`--inherit-user-plugins` to restore the default. The project setting is +`inherit_user_plugins`; the earlier `inherit_plugins` spelling remains supported. +If both are present, `inherit_user_plugins` takes precedence. The earlier `--no-inherit-plugins` and `--inherit-plugins` flags are also aliases. +A project configuration can execute the JavaScript plugins it names when tracing runs, so review them before using tracing in a repository. -Managed `bt trace run` takes precedence over both scopes. For example, +Managed `bt trace run` takes precedence over user and project settings. For example, `bt trace run codex --inherit` starts from user and project settings before applying invocation options; `--no-inherit-plugins` replaces the inherited plugin chain for that invocation. `bt trace doctor ` shows the current @@ -133,9 +136,9 @@ destination, flush mode, and metadata. Setup saves a stable `route.auth.profile_ production resolves and refreshes them through `bt`. `bt trace run` supplies a process-local settings overlay and never changes any of these files. -### System-wide mandatory plugins +### Global span plugins -Administrators can configure mandatory span plugins for all users, agents, projects, +Administrators can configure global span plugins for all users, agents, projects, and invocations in `/etc/braintrust/trace.json` (macOS and Linux) or `%ProgramData%\Braintrust\trace.json` (Windows): @@ -145,10 +148,11 @@ and invocations in `/etc/braintrust/trace.json` (macOS and Linux) or } ``` -Paths may be absolute or relative to this file. Mandatory plugins run first, +Paths may be absolute or relative to this file. Global plugins run first, followed by route plugins; project and invocation options cannot remove them. -Protect the configuration and plugin files with system permissions. Configuration changes are loaded automatically. `bt trace doctor ` -shows the system configuration and mandatory plugins. An invalid or unreadable +Protect the configuration and plugin files with system permissions. Configuration +changes are loaded automatically. `bt trace doctor ` shows the configured +global plugins. An invalid or unreadable configuration or a plugin failure holds delivery until it is fixed. An absent file leaves existing behavior unchanged. This protects delivery through Braintrust tracing, not against a user who can bypass or replace the software. @@ -221,7 +225,7 @@ bt trace install codex --plugin ./redact.mjs --plugin ./tag-ci.mjs merge with, plugins saved by `enable`: ```bash -# Only local.mjs runs; redact.mjs and tag-ci.mjs remain global enable behavior. +# local.mjs replaces the user-level redact.mjs and tag-ci.mjs for this run. bt trace run --plugin ./local.mjs codex -- "summarize this change" # Only sanitize-history.mjs transforms spans produced by this import. @@ -242,8 +246,8 @@ portable. The environment map is captured from the daemon process when each worker-local span processor is constructed. Plugins execute in bounded, thread-local QuickJS runtimes with no filesystem or network host APIs. Modules must be -self-contained and transforms must be stateless: module globals belong to a -worker thread, not a session. Every configured plugin is mandatory. A plugin +self-contained and transforms must be stateless: each plugin has its own JavaScript +context, and module globals belong to a worker thread, not a session. Every configured plugin is mandatory. A plugin failure holds the affected route at its earliest unresolved SpanOp; other routes continue independently. Calls have a one-second total budget, including input conversion, synchronous execution, and output conversion. Timeout diagnostics diff --git a/bt-daemon/src/command_output/doctor_command_output.rs b/bt-daemon/src/command_output/doctor_command_output.rs index 4dd04590..f6c9ec6e 100644 --- a/bt-daemon/src/command_output/doctor_command_output.rs +++ b/bt-daemon/src/command_output/doctor_command_output.rs @@ -9,7 +9,7 @@ pub struct DoctorCommandOutput { pub display_name: String, pub settings_path: PathBuf, pub system_settings_path: PathBuf, - pub mandatory_span_plugins: Option>, + pub global_span_plugins: Option>, pub settings_present: bool, #[serde(skip_serializing_if = "Option::is_none")] pub project_settings_path: Option, @@ -43,9 +43,9 @@ impl DoctorCommandOutput { route, ); rendered.push_str(&format!( - "\nSystem tracing settings: {}\nMandatory span plugins: {}", + "\nSystem tracing settings: {}\nGlobal span plugins (configured): {}", self.system_settings_path.display(), - match &self.mandatory_span_plugins { + match &self.global_span_plugins { None => "(unavailable)".into(), Some(paths) if paths.is_empty() => "(none)".into(), Some(paths) => paths diff --git a/bt-daemon/src/command_output/tests.rs b/bt-daemon/src/command_output/tests.rs index ad11b3e4..ba81ecf1 100644 --- a/bt-daemon/src/command_output/tests.rs +++ b/bt-daemon/src/command_output/tests.rs @@ -158,7 +158,7 @@ fn doctor_json_is_structured_and_contains_no_credentials() { display_name: "Codex".into(), settings_path: PathBuf::from("/tmp/braintrust.json"), system_settings_path: PathBuf::from("/etc/braintrust/trace.json"), - mandatory_span_plugins: Some(Vec::new()), + global_span_plugins: Some(Vec::new()), settings_present: true, project_settings_path: None, project_settings_fields: Vec::new(), diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index d0f77e04..323f4268 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -177,13 +177,24 @@ impl ConsumerOptions { } } +fn global_plugin_digests(policy: &crate::system_trace_config::Policy) -> Vec> { + match policy { + crate::system_trace_config::Policy::Valid(plugins) => plugins + .iter() + .map(|path| crate::span_processor::file_digest(path)) + .collect(), + _ => Vec::new(), + } +} + fn apply_policy( config: &watch::Sender, route_config: &Mutex, policy: &crate::system_trace_config::Policy, ) { if let crate::system_trace_config::Policy::Valid(plugins) = policy { - let mut effective = route_config.lock().clone(); + let route = route_config.lock(); + let mut effective = route.clone(); effective.span_plugins.splice(0..0, plugins.iter().cloned()); config.send_if_modified(|current| { if serde_json::to_value(&*current).ok() == serde_json::to_value(&effective).ok() { @@ -215,16 +226,40 @@ impl Consumer { route_config: route_config.clone(), }); let task = tokio::spawn(async move { - let mut sink = None; + let mut sink: Option = None; let mut pending = VecDeque::new(); let mut held: Option = None; let mut attempts = 0; let mut recorded = None; let mut record_retry = 0; + let mut previous_policy = None; loop { let current_policy = policy.borrow_and_update().clone(); - if let crate::system_trace_config::Policy::Invalid(error) = ¤t_policy { - *options.error.lock() = Some(format!("system tracing settings: {error}")); + let current_digests = global_plugin_digests(¤t_policy); + let current_revision = (current_policy.clone(), current_digests.clone()); + if previous_policy + .as_ref() + .is_some_and(|previous| previous != ¤t_revision) + && !pending.is_empty() + { + if let Some(previous) = sink.take() { + previous.shutdown().await; + } + pending.clear(); + held = None; + recorded = None; + attempts = 0; + } + previous_policy = Some(current_revision); + if matches!( + current_policy, + crate::system_trace_config::Policy::Starting + | crate::system_trace_config::Policy::Invalid(_) + ) { + input.pause(); + if let crate::system_trace_config::Policy::Invalid(error) = ¤t_policy { + *options.error.lock() = Some(format!("system tracing settings: {error}")); + } tokio::select! { _ = stop.notified() => break, result = policy.changed() => if result.is_err() { break; }, @@ -238,7 +273,7 @@ impl Consumer { .as_ref() .is_some_and(|message| message.starts_with("system tracing settings:")) { - *error = None; + *error = held.as_ref().map(|held| held.0.message()); } } if let Some(waiting) = held.take() { @@ -260,6 +295,12 @@ impl Consumer { result=settings.changed()=>if result.is_err() { break; }, result=policy.changed()=>if result.is_err() { break; }, } + if *policy.borrow() != current_policy + || global_plugin_digests(¤t_policy) != current_digests + { + held = Some(Box::new((failure, work))); + continue; + } let mut current = settings.borrow_and_update().clone(); if recorded.as_ref() != Some(&reported) || matches!( @@ -285,8 +326,13 @@ impl Consumer { ))); continue; } + if *policy.borrow() != current_policy { + held = Some(Box::new((failure, work))); + continue; + } route_config.lock().auth = current.auth.clone(); - config.send_replace(current.clone()); + apply_policy(&config, &route_config, ¤t_policy); + current = config.borrow().clone(); } match options .finish(&mut pending, &mut sink, ¤t, attempts, work) @@ -323,22 +369,33 @@ impl Consumer { let current_policy = policy.borrow().clone(); if matches!( current_policy, - crate::system_trace_config::Policy::Invalid(_) + crate::system_trace_config::Policy::Starting + | crate::system_trace_config::Policy::Invalid(_) ) { drop(delivery); return Ok(Some(false)); } apply_policy(&config, &route_config, ¤t_policy); let current = settings.borrow_and_update().clone(); + let creation = if sink.is_none() { + options + .sink(¤t) + .await + .map(|created| sink = Some(created)) + .map_err(|error| options.routing(&error, ¤t, attempts)) + } else { + Ok(()) + }; + if *policy.borrow() != current_policy + || global_plugin_digests(¤t_policy) != current_digests + { + drop(delivery); + return Ok(Some(false)); + } let ops = delivery.value().as_slice(); let mut stopped = false; let result = async { - if sink.is_none() { - sink = - Some(options.sink(¤t).await.map_err(|error| { - options.routing(&error, ¤t, attempts) - })?); - } + creation?; let routing = sink.as_mut().ok_or_else(|| { options.storage( &anyhow::anyhow!("configured sink is missing"), @@ -638,6 +695,183 @@ mod tests { consumer.shutdown().await; } + #[tokio::test] + async fn invalid_global_config_pauses_live_feed_and_replays_after_repair() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("trace.json"); + std::fs::write(&path, "{").unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let record = Arc::new(Recording::default()); + let mut opts = options(tmp.path(), &route, record.clone()); + opts.system_policy = crate::system_trace_config::watch(path.clone()); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|e| e.contains("system tracing settings")) + }) + .await; + tokio::time::timeout(std::time::Duration::from_secs(5), async { + for i in 0..40 { + journal + .translated( + 10 + i, + vec![SpanOp::Insert(SpanRow { + span_id: format!("{i}"), + root_span_id: "root".into(), + name: "event".into(), + ..Default::default() + })], + ) + .await + .unwrap(); + } + }) + .await + .expect("invalid policy must not block translation"); + assert_eq!(record.submitted.load(Ordering::SeqCst), 0); + std::fs::write(&path, "{}").unwrap(); + wait_for(|| error.lock().is_none()).await; + tokio::time::timeout( + std::time::Duration::from_secs(5), + progress.through(40, &error), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(record.accepted.load(Ordering::SeqCst), 40); + consumer.shutdown().await; + } + + #[tokio::test] + async fn repairing_global_config_restores_existing_plugin_failure() { + let tmp = tempfile::tempdir().unwrap(); + let config_path = tmp.path().join("trace.json"); + let plugin = tmp.path().join("fail.mjs"); + std::fs::write(&config_path, r#"{"span_plugins":["fail.mjs"]}"#).unwrap(); + std::fs::write( + &plugin, + "export default () => { throw new Error('plugin failed'); }", + ) + .unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let record = Arc::new(Recording::default()); + stored(&journal).await; + let mut opts = options(tmp.path(), &route, record); + opts.system_policy = crate::system_trace_config::watch(config_path.clone()); + let (consumer, _, error) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|e| e.contains("plugin failed")) + }) + .await; + std::fs::write(&config_path, "{").unwrap(); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|e| e.contains("system tracing settings")) + }) + .await; + std::fs::write(&config_path, r#"{"span_plugins":["fail.mjs"]}"#).unwrap(); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|e| e.contains("plugin failed")) + }) + .await; + consumer.shutdown().await; + } + + #[tokio::test] + async fn changing_global_plugins_replays_buffered_unacknowledged_spans() { + let tmp = tempfile::tempdir().unwrap(); + let config_path = tmp.path().join("trace.json"); + let plugin = tmp.path().join("guard.mjs"); + std::fs::write(&config_path, "{}").unwrap(); + std::fs::write(&plugin, "export default span => { if (span.name === 'one') throw new Error('blocked old span'); return span; }").unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let record = Arc::new(Recording::default()); + record.defer_until.store(2, Ordering::SeqCst); + stored(&journal).await; + let mut opts = options(tmp.path(), &route, record.clone()); + opts.system_policy = crate::system_trace_config::watch(config_path.clone()); + let (consumer, _progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| record.submitted.load(Ordering::SeqCst) == 1).await; + assert_eq!(record.accepted.load(Ordering::SeqCst), 0); + std::fs::write(&config_path, r#"{"span_plugins":["guard.mjs"]}"#).unwrap(); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|error| error.contains("blocked old span")) + }) + .await; + assert_eq!(record.accepted.load(Ordering::SeqCst), 0); + consumer.shutdown().await; + } + + #[tokio::test] + async fn editing_global_plugin_replays_buffered_spans_before_later_delivery() { + let tmp = tempfile::tempdir().unwrap(); + let plugin = tmp.path().join("guard.mjs"); + std::fs::write(&plugin, "export default span => span").unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let record = Arc::new(Recording::default()); + record.defer_until.store(2, Ordering::SeqCst); + stored(&journal).await; + let mut opts = options(tmp.path(), &route, record.clone()); + opts.system_policy = crate::system_trace_config::fixed(vec![plugin.clone()]); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| record.submitted.load(Ordering::SeqCst) == 1).await; + std::fs::write(&plugin, "export default span => { if (span.name === 'one') throw new Error('blocked old span'); return span; }").unwrap(); + journal + .translated( + 20, + vec![SpanOp::Insert(SpanRow { + span_id: "two".into(), + root_span_id: "one".into(), + name: "two".into(), + ..Default::default() + })], + ) + .await + .unwrap(); + let _ = tokio::time::timeout( + std::time::Duration::from_secs(5), + progress.through(2, &error), + ) + .await; + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|error| error.contains("blocked old span")) + }) + .await; + assert_eq!(record.accepted.load(Ordering::SeqCst), 0); + consumer.shutdown().await; + } + #[tokio::test] async fn transient_rejection_resubmits_consumed_batch_before_completing() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/cursor.rs b/bt-daemon/src/pipeline/cursor.rs index 4eeb83e2..2c351ee5 100644 --- a/bt-daemon/src/pipeline/cursor.rs +++ b/bt-daemon/src/pipeline/cursor.rs @@ -297,6 +297,9 @@ struct SharedCursor(Cursor); #[async_trait::async_trait] impl InputPort for SharedCursor { type Item = Vec; + fn pause(&mut self) { + self.0.live.control().pause(); + } async fn detach(&mut self) -> anyhow::Result<()> { self.0.session.detach(&self.0.route).await?; self.0.live.control().pause(); diff --git a/bt-daemon/src/pipeline/delivery.rs b/bt-daemon/src/pipeline/delivery.rs index 7c87818c..8b723860 100644 --- a/bt-daemon/src/pipeline/delivery.rs +++ b/bt-daemon/src/pipeline/delivery.rs @@ -66,6 +66,8 @@ impl Delivery { #[async_trait::async_trait] pub(crate) trait InputPort: Send { type Item: Send; + /// Pause live delivery while retaining durable replay obligations. + fn pause(&mut self) {} /// Permanently remove this subscription's delivery obligation. async fn detach(&mut self) -> anyhow::Result<()> { anyhow::bail!("input does not support route detachment") @@ -92,6 +94,9 @@ impl InputPort for mpsc::Receiver> { #[async_trait::async_trait] impl InputPort for Box { type Item = T::Item; + fn pause(&mut self) { + (**self).pause(); + } async fn detach(&mut self) -> anyhow::Result<()> { (**self).detach().await } diff --git a/bt-daemon/src/server/mod.rs b/bt-daemon/src/server/mod.rs index f136290c..339ca4a5 100644 --- a/bt-daemon/src/server/mod.rs +++ b/bt-daemon/src/server/mod.rs @@ -254,6 +254,15 @@ fn now_ms() -> i64 { /// drain sessions and remove the socket. pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { let policy_path = crate::system_trace_config::path()?; + let mut system_policy = crate::system_trace_config::watch(policy_path); + while matches!( + *system_policy.borrow_and_update(), + crate::system_trace_config::Policy::Starting + ) { + system_policy.changed().await.map_err(|_| { + anyhow::anyhow!("system tracing configuration watch stopped during startup") + })?; + } let socket = paths::socket_path(args.socket.as_deref()); let data_dir = paths::data_dir(args.data_dir.as_deref()); paths::ensure_private_dir(&data_dir)?; @@ -282,13 +291,7 @@ pub async fn run(args: ServeArgs, opts: ServeOptions) -> anyhow::Result<()> { let (ready, startup) = oneshot::channel(); let retention = args.retention(); - let daemon = Daemon::new_with_startup( - opts, - data_dir, - Some(startup), - retention, - crate::system_trace_config::watch(policy_path), - ); + let daemon = Daemon::new_with_startup(opts, data_dir, Some(startup), retention, system_policy); 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/settings.rs b/bt-daemon/src/settings.rs index 8954ce06..9bc04b3e 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -115,16 +115,20 @@ impl AgentSettings { } else { Self::default() }; - let inherit_plugins = object - .get("inherit_plugins") + let inherit_user_plugins = object + .get("inherit_user_plugins") + .or_else(|| object.get("inherit_plugins")) .map(|value| { value.as_bool().ok_or_else(|| { - anyhow::anyhow!("inherit_plugins in {} must be a boolean", path.display()) + anyhow::anyhow!( + "inherit_user_plugins in {} must be a boolean", + path.display() + ) }) }) .transpose()? .unwrap_or(true); - if !inherit_plugins { + if !inherit_user_plugins { if let Some(route) = &mut settings.route { route.span_plugins.clear(); } @@ -624,6 +628,41 @@ mod tests { .route .unwrap(); assert_eq!(route.span_plugins, [plugin.canonicalize().unwrap()]); + std::fs::write(&project, r#"{"inherit_user_plugins":false}"#).unwrap(); + assert!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap() + .span_plugins + .is_empty() + ); + std::fs::write( + &project, + r#"{"inherit_plugins":false,"inherit_user_plugins":true}"#, + ) + .unwrap(); + assert_eq!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap() + .span_plugins, + [PathBuf::from("user.mjs")] + ); + std::fs::write( + &project, + r#"{"inherit_plugins":true,"inherit_user_plugins":false}"#, + ) + .unwrap(); + assert!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap() + .span_plugins + .is_empty() + ); std::fs::write(&project, r#"{"inherit_plugins":false}"#).unwrap(); assert!( AgentSettings::load_hook_with_project(&user, Some(&project), None) diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 43cd3175..fade5278 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -174,11 +174,12 @@ fn write_project_setup_at( settings.insert(key.into(), Value::String(value.to_owned())); } } - if args.no_inherit_plugins { - settings.insert("inherit_plugins".into(), Value::Bool(false)); - } - if args.inherit_plugins { - settings.insert("inherit_plugins".into(), Value::Bool(true)); + if args.no_inherit_plugins || args.inherit_plugins { + settings.remove("inherit_plugins"); + settings.insert( + "inherit_user_plugins".into(), + Value::Bool(args.inherit_plugins), + ); } if !plugins.is_empty() { let route = settings @@ -485,6 +486,9 @@ mod tests { std::fs::create_dir(&plugins).unwrap(); std::fs::write(plugins.join("redact.mjs"), "export default span => span").unwrap(); args.plugin.push("plugins/redact.mjs".into()); + let mut legacy: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + legacy["inherit_plugins"] = Value::Bool(true); + std::fs::write(&path, serde_json::to_vec(&legacy).unwrap()).unwrap(); args.no_inherit_plugins = true; write_project_setup_at(&path, &args, &selection).unwrap(); let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); @@ -492,12 +496,13 @@ mod tests { value["route"]["span_plugins"], serde_json::json!(["plugins/redact.mjs"]) ); - assert_eq!(value["inherit_plugins"], false); + assert_eq!(value["inherit_user_plugins"], false); + assert!(value.get("inherit_plugins").is_none()); args.no_inherit_plugins = false; args.inherit_plugins = true; write_project_setup_at(&path, &args, &selection).unwrap(); let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - assert_eq!(value["inherit_plugins"], true); + assert_eq!(value["inherit_user_plugins"], true); args.plugin.clear(); args.plugin.push("bad.js".into()); assert!(write_project_setup_at(&path, &args, &selection).is_err()); diff --git a/bt-daemon/src/span_processor.rs b/bt-daemon/src/span_processor.rs index 2a60369a..7a3b858f 100644 --- a/bt-daemon/src/span_processor.rs +++ b/bt-daemon/src/span_processor.rs @@ -36,7 +36,7 @@ struct PluginTimeout { } thread_local! { - static ENGINE: RefCell> = const { RefCell::new(None) }; + static ENGINES: RefCell> = RefCell::new(HashMap::new()); } #[derive(Clone, Copy, Serialize)] @@ -341,14 +341,14 @@ fn process_inner( row.parent_span_ids.clone(), ); let mut failure = None; - ENGINE.with_borrow_mut(|slot| -> anyhow::Result<()> { - if slot.is_none() { - *slot = Some(Engine::new()?); - } - let engine = slot - .as_mut() - .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; + ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { for plugin in plugins { + if !engines.contains_key(plugin) { + engines.insert(plugin.clone(), Engine::new()?); + } + let engine = engines + .get_mut(plugin) + .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; if let Some(failed) = engine .failed_plugins .get(plugin) @@ -456,9 +456,9 @@ pub(crate) fn file_digest(path: &Path) -> Option<[u8; 32]> { } pub(crate) fn failed_digest(path: &Path) -> Option<[u8; 32]> { - ENGINE.with_borrow(|engine| { - engine - .as_ref()? + ENGINES.with_borrow(|engines| { + engines + .get(path)? .failed_plugins .get(path)? .fingerprint @@ -469,21 +469,21 @@ pub(crate) fn failed_digest(path: &Path) -> Option<[u8; 32]> { // Preserve the bytes actually loaded by predecessors, not a later filesystem // sample: an edit during a failing call must already qualify for recovery. pub(crate) fn chain_digests(paths: &[PathBuf], failed: &Path) -> Vec> { - ENGINE.with_borrow(|engine| { + ENGINES.with_borrow(|engines| { let mut reached_failure = false; paths .iter() .map(|path| { if path == failed { reached_failure = true; - engine - .as_ref() + engines + .get(path) .and_then(|engine| engine.failed_plugins.get(path)) .and_then(|failed| failed.fingerprint) .map(|fingerprint| fingerprint.digest) } else if !reached_failure { - engine - .as_ref() + engines + .get(path) .and_then(|engine| engine.modules.get(path)) .map(|module| module.fingerprint.digest) } else { @@ -497,15 +497,15 @@ pub(crate) fn chain_digests(paths: &[PathBuf], failed: &Path) -> Vec anyhow::Result<()> { - ENGINE.with_borrow_mut(|slot| -> anyhow::Result<()> { - if slot.is_none() { - *slot = Some(Engine::new()?); - } - let engine = slot - .as_mut() - .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; + ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { for plugin in plugins { - engine.load(plugin)?; + if !engines.contains_key(plugin) { + engines.insert(plugin.clone(), Engine::new()?); + } + engines + .get_mut(plugin) + .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))? + .load(plugin)?; } Ok(()) }) @@ -539,6 +539,29 @@ mod tests { } } + #[test] + fn plugins_cannot_change_other_plugins_javascript_globals() { + let dir = tempfile::tempdir().unwrap(); + let route = dir.path().join("route.mjs"); + let global = dir.path().join("global.mjs"); + std::fs::write( + &route, + "export default span => { Array.prototype.map = () => ['unsafe']; return span; }", + ) + .unwrap(); + std::fs::write( + &global, + "export default span => ({...span, name: ['safe'].map(x => x)[0]})", + ) + .unwrap(); + process(&[route], &SpanOp::Insert(row()), "debug", "one").unwrap(); + let result = process(&[global], &SpanOp::Insert(row()), "debug", "two").unwrap(); + let Some(SpanOp::Insert(output)) = result.op else { + panic!("expected processed span") + }; + assert_eq!(output.name, "safe"); + } + #[test] fn stop_signal_is_typed_and_does_not_poison_the_plugin() { let dir = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index 28cf8cc9..14493690 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -48,7 +48,29 @@ impl SystemTraceConfig { let raw = match std::fs::read(path) { Ok(raw) => raw, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Ok(Self::default()) + for entry in path.ancestors() { + match std::fs::symlink_metadata(entry) { + Ok(metadata) + if metadata.file_type().is_symlink() + && std::fs::metadata(entry).is_err() => + { + return Err(error).with_context(|| { + format!( + "broken system tracing configuration path {}", + entry.display() + ) + }); + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| { + format!("inspect system tracing configuration {}", entry.display()) + }) + } + } + } + return Ok(Self::default()); } Err(error) => { return Err(error).with_context(|| { @@ -63,7 +85,7 @@ impl SystemTraceConfig { .context("system tracing configuration has no parent directory")?; for plugin in &mut config.span_plugins { if plugin.as_os_str().is_empty() { - anyhow::bail!("empty mandatory plugin path in {}", path.display()); + anyhow::bail!("empty global plugin path in {}", path.display()); } if plugin.is_relative() { *plugin = directory.join(&*plugin); @@ -76,6 +98,7 @@ impl SystemTraceConfig { /// Live system policy. An invalid policy prevents delivery until it is repaired. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Policy { + Starting, Valid(Vec), Invalid(String), } @@ -103,103 +126,143 @@ fn canonical_location(path: &Path) -> PathBuf { pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { use notify::{RecursiveMode, Watcher}; - let (sender, receiver) = tokio::sync::watch::channel(Policy::Invalid( - "system tracing configuration watch is starting".into(), - )); - let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel(); + let (sender, receiver) = tokio::sync::watch::channel(Policy::Starting); tokio::spawn(async move { - let mut watcher = match notify::recommended_watcher(move |event| { - let _ = events_tx.send(event); - }) { - Ok(watcher) => watcher, - Err(error) => { - sender.send_replace(Policy::Invalid(format!( - "cannot watch system tracing configuration: {error}" - ))); - return; - } - }; - let mut watched = Vec::::new(); - loop { - // Watch existing ancestors individually so a newly created or replaced - // configuration directory can be registered without a recursive watch. - let mut watch_error = None; - if let Some(parent) = path.parent() { - let directories: Vec = parent - .ancestors() - .filter(|directory| directory.is_dir()) - .take(2) - .map(Path::to_path_buf) - .collect(); - for directory in &directories { - if watched.contains(directory) { - continue; - } - match watcher.watch(directory, RecursiveMode::NonRecursive) { - Ok(()) => watched.push(directory.clone()), - Err(error) => { - watch_error = - Some(format!("cannot watch {}: {error}", directory.display())); - break; + 'restart: loop { + let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut watcher = match notify::recommended_watcher(move |event| { + let _ = events_tx.send(event); + }) { + Ok(watcher) => watcher, + Err(error) => { + sender.send_replace(Policy::Invalid(format!( + "cannot watch system tracing configuration: {error}" + ))); + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue; + } + }; + let mut watched = Vec::::new(); + loop { + // Watch existing ancestors individually so a newly created or replaced + // configuration directory can be registered without a recursive watch. + let mut watch_error = None; + let canonical_target = match std::fs::read_link(&path) { + Ok(target) if target.is_absolute() => canonical_location(&target), + Ok(target) => canonical_location( + &path.parent().unwrap_or_else(|| Path::new(".")).join(target), + ), + Err(_) => canonical_location(&path), + }; + let configured_target = path + .parent() + .map(|parent| { + canonical_location(parent).join(path.file_name().unwrap_or_default()) + }) + .unwrap_or_else(|| path.clone()); + if let Some(parent) = path.parent() { + let mut directories = Vec::new(); + for location in [parent, canonical_target.parent().unwrap_or(parent)] { + for directory in location + .ancestors() + .filter(|directory| directory.is_dir()) + .take(2) + { + let directory = canonical_location(directory); + if !directories.contains(&directory) { + directories.push(directory); + } } } - } - if watch_error.is_none() { - let mut index = 0; - while index < watched.len() { - if directories.contains(&watched[index]) { - index += 1; + if directories.is_empty() { + watch_error = Some(format!( + "cannot watch an existing parent of {}", + path.display() + )); + } + for directory in &directories { + if watched.contains(directory) { continue; } - let removed = watched.remove(index); - if let Err(error) = watcher.unwatch(&removed) { - tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); + match watcher.watch(directory, RecursiveMode::NonRecursive) { + Ok(()) => watched.push(directory.clone()), + Err(error) => { + watch_error = + Some(format!("cannot watch {}: {error}", directory.display())); + break; + } + } + } + if watch_error.is_none() { + let mut index = 0; + while index < watched.len() { + if directories.contains(&watched[index]) { + index += 1; + continue; + } + let removed = watched.remove(index); + if let Err(error) = watcher.unwatch(&removed) { + tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); + } } } - } - } else { - watch_error = Some("system tracing configuration has no parent directory".into()); - } - let next = match watch_error { - Some(error) => Policy::Invalid(error), - None => Policy::read(&path), - }; - sender.send_if_modified(|current| { - if *current == next { - false } else { - *current = next; - true + watch_error = + Some("system tracing configuration has no parent directory".into()); } - }); - let canonical_target = canonical_location(&path); - loop { - tokio::select! { - _ = sender.closed() => return, - event = events_rx.recv() => match event { - None => { - sender.send_replace(Policy::Invalid("system tracing configuration watch stopped".into())); - return; - } - Some(Err(error)) => { - sender.send_replace(Policy::Invalid(format!("system tracing configuration watch failed: {error}"))); - break; - } - Some(Ok(event)) => { - if event.need_rescan() || event.paths.is_empty() || event.paths.iter().any(|changed| canonical_target.starts_with(changed) || changed == &canonical_target) { - for changed in &event.paths { - let mut index = 0; - while index < watched.len() { - let canonical = canonical_location(&watched[index]); - if canonical == *changed { - let removed = watched.remove(index); - if let Err(error) = watcher.unwatch(&removed) { - tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); - } - } else { index += 1; } + let failed = watch_error.is_some(); + let next = match watch_error { + Some(error) => Policy::Invalid(error), + None => Policy::read(&path), + }; + sender.send_if_modified(|current| { + if *current == next { + false + } else { + *current = next; + true + } + }); + if failed { + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue 'restart; + } + loop { + tokio::select! { + _ = sender.closed() => return, + event = events_rx.recv() => match event { + None => { + sender.send_replace(Policy::Invalid("system tracing configuration watch stopped".into())); + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue 'restart; + } + Some(Err(error)) => { + sender.send_replace(Policy::Invalid(format!("system tracing configuration watch failed: {error}"))); + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue 'restart; + } + Some(Ok(event)) => { + use notify::event::{AccessKind, AccessMode, EventKind}; + if !event.need_rescan() && matches!(event.kind, EventKind::Access(kind) if !matches!(kind, AccessKind::Close(AccessMode::Write))) { continue; } + if event.need_rescan() || event.paths.is_empty() || event.paths.iter().any(|changed| { + let entry = changed.parent().map(|parent| canonical_location(parent).join(changed.file_name().unwrap_or_default())).unwrap_or_else(|| changed.clone()); + let changed = canonical_location(changed); + canonical_target.starts_with(&changed) || configured_target.starts_with(&entry) + }) { + for changed in &event.paths { + let mut index = 0; + while index < watched.len() { + let canonical = canonical_location(&watched[index]); + if canonical == canonical_location(changed) { + let removed = watched.remove(index); + if let Err(error) = watcher.unwatch(&removed) { + tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); + } + } else { index += 1; } + } } + break; } - break; } } } @@ -262,6 +325,74 @@ mod tests { wait_for(&mut policy, Policy::Valid(vec![directory.join("four.mjs")])).await; } + #[cfg(unix)] + #[tokio::test] + async fn watches_symlink_target_and_holds_when_target_is_missing() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let config_dir = tmp.path().join("config"); + let target_dir = tmp.path().join("target"); + std::fs::create_dir(&config_dir).unwrap(); + std::fs::create_dir(&target_dir).unwrap(); + let config = config_dir.join("trace.json"); + let target = target_dir.join("policy.json"); + symlink(&target, &config).unwrap(); + assert!(SystemTraceConfig::load(&config).is_err()); + let mut policy = watch(config.clone()); + async fn wait( + policy: &mut tokio::sync::watch::Receiver, + predicate: impl Fn(&Policy) -> bool, + ) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + if predicate(&policy.borrow_and_update()) { + return; + } + policy.changed().await.unwrap(); + } + }) + .await + .unwrap(); + } + wait( + &mut policy, + |p| matches!(p, Policy::Invalid(message) if message.contains("broken")), + ) + .await; + std::fs::write(&target, r#"{"span_plugins":["one.mjs"]}"#).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("one.mjs")]) + }) + .await; + std::fs::write(&target, r#"{"span_plugins":["two.mjs"]}"#).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("two.mjs")]) + }) + .await; + std::fs::remove_file(&target).unwrap(); + wait( + &mut policy, + |p| matches!(p, Policy::Invalid(message) if message.contains("broken")), + ) + .await; + let other_dir = tmp.path().join("other"); + std::fs::create_dir(&other_dir).unwrap(); + let other = other_dir.join("new.json"); + std::fs::write(&other, r#"{"span_plugins":["new.mjs"]}"#).unwrap(); + let replacement = config_dir.join("replacement"); + symlink(&other, &replacement).unwrap(); + std::fs::rename(&replacement, &config).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("new.mjs")]) + }) + .await; + std::fs::write(&other, r#"{"span_plugins":["newer.mjs"]}"#).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("newer.mjs")]) + }) + .await; + } + #[test] fn loads_relative_paths_and_rejects_invalid_policy() { let dir = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/trace_command.rs b/bt-daemon/src/trace_command.rs index f60915e4..adad2876 100644 --- a/bt-daemon/src/trace_command.rs +++ b/bt-daemon/src/trace_command.rs @@ -118,11 +118,20 @@ pub struct SetupArgs { /// Tag applied to each root span. May be repeated or comma-separated. #[arg(long = "tag", global = true, value_delimiter = ',')] pub tags: Vec, - /// Replace inherited span plugins instead of appending to them. - #[arg(long, global = true, conflicts_with = "inherit_plugins")] + /// Replace inherited user span plugins instead of appending to them. + #[arg( + long = "no-inherit-user-plugins", + alias = "no-inherit-plugins", + global = true, + conflicts_with = "inherit_plugins" + )] pub no_inherit_plugins: bool, /// Restore inheritance of user-level span plugins. - #[arg(long, global = true)] + #[arg( + long = "inherit-user-plugins", + alias = "inherit-plugins", + global = true + )] pub inherit_plugins: bool, /// JavaScript span transform to persist for this agent. Repeat to compose /// transforms in order. @@ -143,11 +152,20 @@ pub struct EnableArgs { /// Tag applied to each root span. May be repeated or comma-separated. #[arg(long = "tag", global = true, value_delimiter = ',')] pub tags: Vec, - /// Replace inherited span plugins instead of appending to them. - #[arg(long, global = true, conflicts_with = "inherit_plugins")] + /// Replace inherited user span plugins instead of appending to them. + #[arg( + long = "no-inherit-user-plugins", + alias = "no-inherit-plugins", + global = true, + conflicts_with = "inherit_plugins" + )] pub no_inherit_plugins: bool, /// Restore inheritance of user-level span plugins. - #[arg(long, global = true)] + #[arg( + long = "inherit-user-plugins", + alias = "inherit-plugins", + global = true + )] pub inherit_plugins: bool, /// JavaScript span transform to persist. May be repeated. #[arg(long, global = true, value_name = "PATH")] @@ -461,6 +479,17 @@ mod tests { #[test] fn project_plugin_inheritance_flags_are_exclusive() { + for flag in [ + "--no-inherit-user-plugins", + "--no-inherit-plugins", + "--inherit-user-plugins", + "--inherit-plugins", + ] { + assert!( + Cli::try_parse_from(["bt", "install", "claude", "--scope", "project", flag]) + .is_ok() + ); + } assert!(Cli::try_parse_from([ "bt", "install", diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index b74fd481..f7ae4961 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -534,7 +534,7 @@ async fn doctor_output_at( let enabled = settings.tracing_enabled(); let mut warnings = Vec::new(); let system_settings_path = crate::system_trace_config::path(); - let mandatory_span_plugins = match system_settings_path + let global_span_plugins = match system_settings_path .as_ref() .map_err(|error| anyhow::anyhow!("{error:#}")) .and_then(|path| crate::system_trace_config::SystemTraceConfig::load(path)) @@ -661,7 +661,7 @@ async fn doctor_output_at( display_name: args.agent.identity().display_name.into(), settings_path, system_settings_path: system_settings_path.unwrap_or_default(), - mandatory_span_plugins, + global_span_plugins, settings_present, project_settings_path: None, project_settings_fields: Vec::new(), diff --git a/src/plugins/opencode/content/src/config.ts b/src/plugins/opencode/content/src/config.ts index 38fbb5b2..3ecbf37a 100644 --- a/src/plugins/opencode/content/src/config.ts +++ b/src/plugins/opencode/content/src/config.ts @@ -26,6 +26,7 @@ export interface PluginConfig { debug?: boolean; additional_metadata?: Record; tags?: string[]; + inherit_user_plugins?: boolean; inherit_plugins?: boolean; route?: DaemonSessionRoute; } diff --git a/src/plugins/opencode/content/src/index.test.ts b/src/plugins/opencode/content/src/index.test.ts index 06229060..33dcc83b 100644 --- a/src/plugins/opencode/content/src/index.test.ts +++ b/src/plugins/opencode/content/src/index.test.ts @@ -270,6 +270,20 @@ describe("BraintrustPlugin", () => { ); const replaced = loadConfig(await readPluginConfig({ directory: nested })); expect(replaced.route.span_plugins).toEqual([join(directory, "project.js")]); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ inherit_user_plugins: false }), + ); + expect(loadConfig(await readPluginConfig({ directory: nested })).route.span_plugins).toEqual( + [], + ); + writeFileSync( + join(project, ".braintrust.json"), + JSON.stringify({ inherit_user_plugins: true, inherit_plugins: false }), + ); + expect(loadConfig(await readPluginConfig({ directory: nested })).route.span_plugins).toEqual([ + "trusted.js", + ]); }); it("provides a trace-only managed entrypoint without data tools", async () => { diff --git a/src/plugins/opencode/content/src/tracing/plugin.ts b/src/plugins/opencode/content/src/tracing/plugin.ts index 249fedf7..abc659f3 100644 --- a/src/plugins/opencode/content/src/tracing/plugin.ts +++ b/src/plugins/opencode/content/src/tracing/plugin.ts @@ -28,14 +28,21 @@ export async function readPluginConfig(input: { } else { if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("project settings must be an object"); - const { route: projectRoute, inherit_plugins: inheritPlugins, ...safe } = parsed; + const { + route: projectRoute, + inherit_user_plugins: inheritUserPlugins, + inherit_plugins: legacyInheritPlugins, + ...safe + } = parsed; + const inheritPlugins = + inheritUserPlugins !== undefined ? inheritUserPlugins : legacyInheritPlugins; if ( projectRoute !== undefined && (!projectRoute || typeof projectRoute !== "object" || Array.isArray(projectRoute)) ) throw new TypeError("project route must be an object"); if (inheritPlugins !== undefined && typeof inheritPlugins !== "boolean") - throw new TypeError("inherit_plugins must be a boolean"); + throw new TypeError("inherit_user_plugins must be a boolean"); const userRoute = mergeProjectRoute( pluginConfig?.route, projectRoute, diff --git a/src/plugins/pi/content/src/config.test.ts b/src/plugins/pi/content/src/config.test.ts index 0b5eba7d..1e7eeb59 100644 --- a/src/plugins/pi/content/src/config.test.ts +++ b/src/plugins/pi/content/src/config.test.ts @@ -199,6 +199,14 @@ describe("loadConfig", () => { route: { span_plugins: ["scripts/project.mjs"] }, }); expect(loadConfig(cwd).route.span_plugins).toEqual([join(cwd, "scripts/project.mjs")]); + writeJson(path, { trace_to_braintrust: true, inherit_user_plugins: false }); + expect(loadConfig(cwd).route.span_plugins).toEqual([]); + writeJson(path, { + trace_to_braintrust: true, + inherit_user_plugins: true, + inherit_plugins: false, + }); + expect(loadConfig(cwd).route.span_plugins).toEqual(["user.mjs"]); }); it("prefers a canonical route over stale top-level routing", () => { diff --git a/src/plugins/pi/content/src/config.ts b/src/plugins/pi/content/src/config.ts index 4a13590d..987338c7 100644 --- a/src/plugins/pi/content/src/config.ts +++ b/src/plugins/pi/content/src/config.ts @@ -126,13 +126,16 @@ export function loadConfig(cwd = process.cwd()): PiConfig { try { const { route: projectRoute, - inherit_plugins: inheritPlugins, + inherit_user_plugins: inheritUserPlugins, + inherit_plugins: legacyInheritPlugins, ...safeProjectConfig } = projectConfig; + const inheritPlugins = + inheritUserPlugins !== undefined ? inheritUserPlugins : legacyInheritPlugins; if (projectRoute !== undefined && !record(projectRoute)) throw new TypeError("project route must be an object"); if (inheritPlugins !== undefined && typeof inheritPlugins !== "boolean") - throw new TypeError("inherit_plugins must be a boolean"); + throw new TypeError("inherit_user_plugins must be a boolean"); if (record(projectRoute) || inheritPlugins === false) { config.route = mergeProjectRoute( From c92288134a3e8eb02ac17e3bf8b826caf0af5f02 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 21:15:30 +0800 Subject: [PATCH 05/12] Address global tracing policy review --- bt-daemon/Cargo.toml | 3 + bt-daemon/README.md | 5 +- bt-daemon/src/lib.rs | 1 + bt-daemon/src/pipeline/consumer.rs | 42 +++- bt-daemon/src/regular_file.rs | 48 +++++ bt-daemon/src/settings.rs | 76 +++++-- bt-daemon/src/span_processor.rs | 287 ++++++++++++++++++--------- bt-daemon/src/system_trace_config.rs | 204 ++++++++++++++++--- 8 files changed, 527 insertions(+), 139 deletions(-) create mode 100644 bt-daemon/src/regular_file.rs diff --git a/bt-daemon/Cargo.toml b/bt-daemon/Cargo.toml index 8ea62126..198d868d 100644 --- a/bt-daemon/Cargo.toml +++ b/bt-daemon/Cargo.toml @@ -60,6 +60,9 @@ weak-table = "0.4" file-rotate = "0.8" humantime = "2" +[target.'cfg(unix)'.dependencies] +libc = "0.2" + [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Threading", "Win32_System_Com", "Win32_UI_Shell"] } diff --git a/bt-daemon/README.md b/bt-daemon/README.md index c2582e8f..a5625557 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -164,7 +164,8 @@ Raw events and translated operations are stored locally before plugins run. sink-neutral span row after translation and immediately before delivery. Repeat the flag to compose plugins from left to right. `enable` persists its ordered list for ordinary agent sessions. Managed runs and imports are isolated from that -list and use only the `--plugin` flags passed to their command. Each path is +list and use the `--plugin` flags passed to their command as route plugins. +Global plugins still run first. Each path is canonicalized to an absolute path before it is validated or stored. Each module must default-export a synchronous function. It receives a span and @@ -228,7 +229,7 @@ merge with, plugins saved by `enable`: # local.mjs replaces the user-level redact.mjs and tag-ci.mjs for this run. bt trace run --plugin ./local.mjs codex -- "summarize this change" -# Only sanitize-history.mjs transforms spans produced by this import. +# sanitize-history.mjs runs after any global plugins for this import. bt trace import codex SESSION_ID --plugin ./sanitize-history.mjs ``` diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index ba3dc359..dedce2dc 100644 --- a/bt-daemon/src/lib.rs +++ b/bt-daemon/src/lib.rs @@ -33,6 +33,7 @@ mod muse; mod pipeline; mod plugin_diagnostics; pub(crate) mod process; +mod regular_file; mod route; mod server; mod settings; diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 323f4268..39a331dd 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -241,6 +241,9 @@ impl Consumer { .as_ref() .is_some_and(|previous| previous != ¤t_revision) && !pending.is_empty() + && !held + .as_ref() + .is_some_and(|held| matches!(held.1, Work::Complete)) { if let Some(previous) = sink.take() { previous.shutdown().await; @@ -255,7 +258,10 @@ impl Consumer { current_policy, crate::system_trace_config::Policy::Starting | crate::system_trace_config::Policy::Invalid(_) - ) { + ) && !held + .as_ref() + .is_some_and(|held| matches!(held.1, Work::Complete)) + { input.pause(); if let crate::system_trace_config::Policy::Invalid(error) = ¤t_policy { *options.error.lock() = Some(format!("system tracing settings: {error}")); @@ -1044,6 +1050,40 @@ mod tests { assert_eq!(record.accepted.load(Ordering::SeqCst), 1); consumer.shutdown().await; } + #[tokio::test] + async fn policy_change_preserves_accepted_completion_receipts() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let journal = SessionStorage::at(&path).await.unwrap(); + stored(&journal).await; + let route = SessionRoute::default(); + let db = crate::collections::inspect::Inspector::open(&path).unwrap(); + db.inject(crate::collections::inspect::Fault::AdvanceHead) + .unwrap(); + let plugin = tmp.path().join("reject.mjs"); + std::fs::write( + &plugin, + "export default () => { throw new Error('new policy'); }", + ) + .unwrap(); + let record = Arc::new(Recording::default()); + let mut opts = options(tmp.path(), &route, record.clone()); + let (policy, receiver) = + watch::channel(crate::system_trace_config::Policy::Valid(Vec::new())); + opts.system_policy = receiver; + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + wait_for(|| error.lock().is_some()).await; + assert_eq!(record.accepted.load(Ordering::SeqCst), 1); + policy.send_replace(crate::system_trace_config::Policy::Valid(vec![plugin])); + db.clear(crate::collections::inspect::Fault::AdvanceHead) + .unwrap(); + wait_for(|| progress.completed() == 1).await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 1); + assert_eq!(record.accepted.load(Ordering::SeqCst), 1); + consumer.shutdown().await; + } + #[tokio::test] async fn plugin_hold_survives_restart_and_file_edit_recovers_without_native_input() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/regular_file.rs b/bt-daemon/src/regular_file.rs new file mode 100644 index 00000000..5042b8b6 --- /dev/null +++ b/bt-daemon/src/regular_file.rs @@ -0,0 +1,48 @@ +//! Read configuration and plugin files without blocking on special files. +use std::io::{self, Read}; +use std::path::Path; + +pub(crate) fn read(path: &Path) -> io::Result> { + let metadata = std::fs::metadata(path)?; + if !metadata.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "not a regular file", + )); + } + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + let mut file = options.open(path)?; + if !file.metadata()?.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "not a regular file", + )); + } + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + Ok(bytes) +} + +#[cfg(all(test, unix))] +mod tests { + #[test] + fn named_pipe_is_rejected_without_a_writer() { + use std::os::unix::ffi::OsStrExt; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("pipe"); + let name = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + assert_eq!( + super::read(&path).unwrap_err().kind(), + std::io::ErrorKind::InvalidData + ); + assert!(crate::system_trace_config::SystemTraceConfig::load(&path).is_err()); + assert!(crate::span_processor::file_digest(&path).is_none()); + } +} diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 9bc04b3e..4257cc0d 100644 --- a/bt-daemon/src/settings.rs +++ b/bt-daemon/src/settings.rs @@ -62,6 +62,45 @@ pub(crate) struct AgentSettings { pub extra: Map, } +#[derive(Deserialize)] +struct ProjectPluginInheritance { + #[serde(default, deserialize_with = "deserialize_inheritance_flag")] + inherit_user_plugins: Option, + #[serde(default, deserialize_with = "deserialize_inheritance_flag")] + inherit_plugins: Option, +} + +// Invalid legacy values must not override a valid canonical field. Consume +// them without retaining an opaque JSON value; validate whichever field wins. +#[derive(Deserialize)] +#[serde(untagged)] +enum InheritanceFlag { + Bool(bool), + Invalid(serde::de::IgnoredAny), +} + +fn deserialize_inheritance_flag<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + InheritanceFlag::deserialize(deserializer).map(Some) +} + +impl ProjectPluginInheritance { + fn inherited(&self) -> anyhow::Result { + match self + .inherit_user_plugins + .as_ref() + .or(self.inherit_plugins.as_ref()) + { + Some(InheritanceFlag::Bool(value)) => Ok(*value), + Some(InheritanceFlag::Invalid(_)) => { + anyhow::bail!("inherit_user_plugins must be a boolean") + } + None => Ok(true), + } + } +} + impl AgentSettings { pub(crate) fn load_for_hook_payload( source: &str, @@ -115,19 +154,11 @@ impl AgentSettings { } else { Self::default() }; - let inherit_user_plugins = object - .get("inherit_user_plugins") - .or_else(|| object.get("inherit_plugins")) - .map(|value| { - value.as_bool().ok_or_else(|| { - anyhow::anyhow!( - "inherit_user_plugins in {} must be a boolean", - path.display() - ) - }) - }) - .transpose()? - .unwrap_or(true); + let inheritance: ProjectPluginInheritance = serde_json::from_str(&raw) + .with_context(|| format!("invalid plugin inheritance in {}", path.display()))?; + let inherit_user_plugins = inheritance + .inherited() + .with_context(|| format!("invalid plugin inheritance in {}", path.display()))?; if !inherit_user_plugins { if let Some(route) = &mut settings.route { route.span_plugins.clear(); @@ -663,6 +694,25 @@ mod tests { .span_plugins .is_empty() ); + std::fs::write( + &project, + r#"{"inherit_plugins":null,"inherit_user_plugins":true}"#, + ) + .unwrap(); + assert_eq!( + AgentSettings::load_hook_with_project(&user, Some(&project), None) + .unwrap() + .route + .unwrap() + .span_plugins, + [PathBuf::from("user.mjs")] + ); + std::fs::write( + &project, + r#"{"inherit_plugins":true,"inherit_user_plugins":null}"#, + ) + .unwrap(); + assert!(AgentSettings::load_hook_with_project(&user, Some(&project), None).is_err()); std::fs::write(&project, r#"{"inherit_plugins":false}"#).unwrap(); assert!( AgentSettings::load_hook_with_project(&user, Some(&project), None) diff --git a/bt-daemon/src/span_processor.rs b/bt-daemon/src/span_processor.rs index 7a3b858f..45cac754 100644 --- a/bt-daemon/src/span_processor.rs +++ b/bt-daemon/src/span_processor.rs @@ -1,8 +1,8 @@ //! Synchronous JavaScript span transforms. //! //! Session actors already execute on Tokio's worker pool. Each worker thread -//! lazily owns one QuickJS runtime and module cache, so JavaScript values never -//! cross threads and unrelated workers can transform spans concurrently. +//! caches a bounded number of isolated plugin runtimes. JavaScript values stay +//! on their worker thread, and unrelated workers can transform spans concurrently. use crate::translate::{SpanOp, SpanRow}; use rquickjs::{CatchResultExt, Context, Function, Module, Persistent, Runtime}; @@ -39,6 +39,17 @@ thread_local! { static ENGINES: RefCell> = RefCell::new(HashMap::new()); } +// Bound retained runtimes per worker even when a single route has a long chain. +const MAX_CACHED_ENGINES: usize = 4; + +fn limit_engines(engines: &mut HashMap) { + while engines.len() > MAX_CACHED_ENGINES { + if let Some(path) = engines.keys().next().cloned() { + engines.remove(&path); + } + } +} + #[derive(Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] enum Operation { @@ -123,7 +134,7 @@ impl Engine { fn load(&mut self, path: &Path) -> anyhow::Result>> { self.last_fingerprint = None; - let source = std::fs::read(path) + let source = crate::regular_file::read(path) .map_err(|error| anyhow::anyhow!("failed to read {}: {error}", path.display()))?; let fingerprint = PluginFingerprint { digest: Sha256::digest(&source).into(), @@ -342,87 +353,96 @@ fn process_inner( ); let mut failure = None; ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { - for plugin in plugins { - if !engines.contains_key(plugin) { - engines.insert(plugin.clone(), Engine::new()?); - } - let engine = engines - .get_mut(plugin) - .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; - if let Some(failed) = engine - .failed_plugins - .get(plugin) - .cloned() - .filter(|failed| use_failed_cache && !failed.timed_out) - { - if failed.fingerprint == plugin_fingerprint(plugin) { - failure = Some(PluginFailure { - path: plugin.clone(), - message: failed.message, - timed_out: failed.timed_out, - newly_seen: false, - }); - break; + // The current chain is the only one that needs cached runtimes. This + // retains isolation without keeping every previously visited project alive. + engines.retain(|path, _| plugins.contains(path)); + let result = (|| -> anyhow::Result<()> { + for plugin in plugins { + if !engines.contains_key(plugin) { + engines.insert(plugin.clone(), Engine::new()?); } - engine.failed_plugins.remove(plugin); - } - let candidate = engine.call(plugin, &row, operation, source, session_id); - let mut candidate = match candidate { - Ok(candidate) - if ( - candidate.span_id.as_str(), - candidate.root_span_id.as_str(), - &candidate.parent_span_ids, - ) == ( - original_ids.0.as_str(), - original_ids.1.as_str(), - &original_ids.2, - ) => + let engine = engines + .get_mut(plugin) + .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; + if let Some(failed) = engine + .failed_plugins + .get(plugin) + .cloned() + .filter(|failed| use_failed_cache && !failed.timed_out) { - candidate - } - Ok(_) => { - let message = "changed immutable span identity fields".to_owned(); - engine.failed_plugins.insert( - plugin.clone(), - failed_plugin(engine.last_fingerprint, &message, false), - ); - failure = Some(PluginFailure { - path: plugin.clone(), - message, - timed_out: false, - newly_seen: true, - }); - break; - } - Err(error) => { - if error.is::() { - return Err(error); + if failed.fingerprint == plugin_fingerprint(plugin) { + failure = Some(PluginFailure { + path: plugin.clone(), + message: failed.message, + timed_out: failed.timed_out, + newly_seen: false, + }); + break; } - let timed_out = error.downcast_ref::().is_some(); - let message = error.to_string(); - engine.failed_plugins.insert( - plugin.clone(), - failed_plugin(engine.last_fingerprint, &message, timed_out), - ); - failure = Some(PluginFailure { - path: plugin.clone(), - message, - timed_out, - newly_seen: true, - }); - break; + engine.failed_plugins.remove(plugin); } - }; - // Turn identity belongs to the translator, not the JSON transform. - candidate.is_turn = row.is_turn; - candidate.origin = row.origin.clone(); - candidate.turn_span_id = row.turn_span_id.clone(); - candidate.late_merge_key = row.late_merge_key.clone(); - candidate.late_merge_version = row.late_merge_version.clone(); - row = candidate; + let candidate = engine.call(plugin, &row, operation, source, session_id); + let mut candidate = match candidate { + Ok(candidate) + if ( + candidate.span_id.as_str(), + candidate.root_span_id.as_str(), + &candidate.parent_span_ids, + ) == ( + original_ids.0.as_str(), + original_ids.1.as_str(), + &original_ids.2, + ) => + { + candidate + } + Ok(_) => { + let message = "changed immutable span identity fields".to_owned(); + engine.failed_plugins.insert( + plugin.clone(), + failed_plugin(engine.last_fingerprint, &message, false), + ); + failure = Some(PluginFailure { + path: plugin.clone(), + message, + timed_out: false, + newly_seen: true, + }); + break; + } + Err(error) => { + if error.is::() { + return Err(error); + } + let timed_out = error.downcast_ref::().is_some(); + let message = error.to_string(); + engine.failed_plugins.insert( + plugin.clone(), + failed_plugin(engine.last_fingerprint, &message, timed_out), + ); + failure = Some(PluginFailure { + path: plugin.clone(), + message, + timed_out, + newly_seen: true, + }); + break; + } + }; + // Turn identity belongs to the translator, not the JSON transform. + candidate.is_turn = row.is_turn; + candidate.origin = row.origin.clone(); + candidate.turn_span_id = row.turn_span_id.clone(); + candidate.late_merge_key = row.late_merge_key.clone(); + candidate.late_merge_version = row.late_merge_version.clone(); + row = candidate; + } + Ok(()) + })(); + if failure.is_none() || result.is_err() { + limit_engines(engines); } - Ok(()) + result })?; Ok(ProcessResult { op: failure.is_none().then_some(match op { @@ -447,7 +467,7 @@ fn failed_plugin( fn plugin_fingerprint(path: &Path) -> Option { Some(PluginFingerprint { - digest: Sha256::digest(std::fs::read(path).ok()?).into(), + digest: Sha256::digest(crate::regular_file::read(path).ok()?).into(), }) } @@ -469,9 +489,9 @@ pub(crate) fn failed_digest(path: &Path) -> Option<[u8; 32]> { // Preserve the bytes actually loaded by predecessors, not a later filesystem // sample: an edit during a failing call must already qualify for recovery. pub(crate) fn chain_digests(paths: &[PathBuf], failed: &Path) -> Vec> { - ENGINES.with_borrow(|engines| { + ENGINES.with_borrow_mut(|engines| { let mut reached_failure = false; - paths + let result = paths .iter() .map(|path| { if path == failed { @@ -490,7 +510,9 @@ pub(crate) fn chain_digests(paths: &[PathBuf], failed: &Path) -> Vec Vec anyhow::Result<()> { ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { - for plugin in plugins { - if !engines.contains_key(plugin) { - engines.insert(plugin.clone(), Engine::new()?); + engines.retain(|path, _| plugins.contains(path)); + let result = (|| -> anyhow::Result<()> { + for plugin in plugins { + if !engines.contains_key(plugin) { + engines.insert(plugin.clone(), Engine::new()?); + } + engines + .get_mut(plugin) + .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))? + .load(plugin)?; } - engines - .get_mut(plugin) - .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))? - .load(plugin)?; - } - Ok(()) + Ok(()) + })(); + limit_engines(engines); + result }) } @@ -539,6 +566,82 @@ mod tests { } } + #[test] + fn long_plugin_chains_do_not_leave_unbounded_runtimes() { + let dir = tempfile::tempdir().unwrap(); + let paths: Vec<_> = (0..10) + .map(|i| dir.path().join(format!("{i}.mjs"))) + .collect(); + for path in &paths { + std::fs::write(path, "export default span => span").unwrap(); + } + assert!(process(&paths, &SpanOp::Insert(row()), "debug", "session") + .unwrap() + .failure + .is_none()); + ENGINES.with_borrow(|engines| assert!(engines.len() <= MAX_CACHED_ENGINES)); + } + + #[test] + fn failing_long_chain_preserves_digests_before_evicting_runtimes() { + let dir = tempfile::tempdir().unwrap(); + let paths: Vec<_> = (0..7) + .map(|i| dir.path().join(format!("{i}.mjs"))) + .collect(); + for path in &paths { + std::fs::write(path, "export default span => span").unwrap(); + } + let failed = paths.last().unwrap(); + std::fs::write( + failed, + "export default () => { throw new Error('failed'); }", + ) + .unwrap(); + assert!(process(&paths, &SpanOp::Insert(row()), "debug", "session") + .unwrap() + .failure + .is_some()); + assert_eq!(failed_digest(failed), file_digest(failed)); + assert_eq!( + chain_digests(&paths, failed), + paths + .iter() + .map(|path| file_digest(path)) + .collect::>() + ); + ENGINES.with_borrow(|engines| assert!(engines.len() <= MAX_CACHED_ENGINES)); + } + + #[test] + fn inactive_plugin_runtimes_are_released() { + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("a.mjs"); + let b = dir.path().join("b.mjs"); + let c = dir.path().join("c.mjs"); + for path in [&a, &b, &c] { + std::fs::write(path, "export default span => span").unwrap(); + } + process( + &[a.clone(), b.clone()], + &SpanOp::Insert(row()), + "debug", + "first", + ) + .unwrap(); + process( + std::slice::from_ref(&c), + &SpanOp::Insert(row()), + "debug", + "second", + ) + .unwrap(); + ENGINES.with_borrow(|engines| { + assert!(!engines.contains_key(&a)); + assert!(!engines.contains_key(&b)); + assert!(engines.contains_key(&c)); + }); + } + #[test] fn plugins_cannot_change_other_plugins_javascript_globals() { let dir = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index 14493690..c09c9fa4 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -14,28 +14,51 @@ pub(crate) fn path() -> anyhow::Result { #[cfg(windows)] { use std::os::windows::ffi::OsStringExt; - use windows_sys::Win32::System::Com::CoTaskMemFree; + use windows_sys::Win32::Foundation::RPC_E_CHANGED_MODE; + use windows_sys::Win32::System::Com::{ + CoInitializeEx, CoTaskMemFree, CoUninitialize, COINIT_MULTITHREADED, + }; use windows_sys::Win32::UI::Shell::{FOLDERID_ProgramData, SHGetKnownFolderPath}; + // COM initialization is thread-local; an existing apartment may use + // a different model, in which case it is already initialized. + let init = unsafe { CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED as u32) }; + anyhow::ensure!( + init >= 0 || init == RPC_E_CHANGED_MODE, + "cannot initialize COM (Windows error {init:#x})" + ); let mut raw = std::ptr::null_mut(); // Windows allocates the returned UTF-16 string with CoTaskMemAlloc. let status = unsafe { SHGetKnownFolderPath(&FOLDERID_ProgramData, 0, std::ptr::null_mut(), &mut raw) }; - anyhow::ensure!( - status >= 0 && !raw.is_null(), - "cannot resolve system tracing configuration directory (Windows error {status:#x})" - ); - let mut len = 0; + let result = if status >= 0 && !raw.is_null() { + let mut len = 0; + unsafe { + while *raw.add(len) != 0 { + len += 1; + } + Ok( + PathBuf::from(std::ffi::OsString::from_wide(std::slice::from_raw_parts( + raw, len, + ))) + .join("Braintrust") + .join("trace.json"), + ) + } + } else { + Err(anyhow::anyhow!( + "cannot resolve system tracing configuration directory (Windows error {status:#x})" + )) + }; unsafe { - while *raw.add(len) != 0 { - len += 1; + if !raw.is_null() { + CoTaskMemFree(raw.cast()); + } + if init >= 0 { + CoUninitialize(); } - let path = PathBuf::from(std::ffi::OsString::from_wide(std::slice::from_raw_parts( - raw, len, - ))); - CoTaskMemFree(raw.cast()); - Ok(path.join("Braintrust").join("trace.json")) } + result } #[cfg(not(windows))] { @@ -45,7 +68,7 @@ pub(crate) fn path() -> anyhow::Result { impl SystemTraceConfig { pub fn load(path: &Path) -> anyhow::Result { - let raw = match std::fs::read(path) { + let raw = match crate::regular_file::read(path) { Ok(raw) => raw, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { for entry in path.ancestors() { @@ -123,6 +146,63 @@ fn canonical_location(path: &Path) -> PathBuf { .unwrap_or_else(|| path.to_path_buf()) } +// Keep each link entry as well as its target: an intermediate symlink can be +// retargeted independently of the final file, including while it is missing. +fn policy_locations(path: &Path) -> anyhow::Result> { + let mut locations = Vec::new(); + let mut visited = std::collections::HashSet::new(); + let mut current = path.to_path_buf(); + loop { + anyhow::ensure!( + visited.len() < 40 && visited.insert(current.clone()), + "cyclic system tracing configuration symlink at {}", + current.display() + ); + let mut link = None; + for entry in current.ancestors().collect::>().into_iter().rev() { + match std::fs::symlink_metadata(entry) { + Ok(metadata) if metadata.file_type().is_symlink() => { + link = Some(entry.to_path_buf()); + break; + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => break, + Err(error) => { + return Err(error).with_context(|| { + format!("inspect system tracing configuration {}", entry.display()) + }) + } + } + } + let Some(link) = link else { + let entry = current + .parent() + .map(|parent| { + canonical_location(parent).join(current.file_name().unwrap_or_default()) + }) + .unwrap_or(current); + locations.push(entry); + return Ok(locations); + }; + let entry = link + .parent() + .map(|parent| canonical_location(parent).join(link.file_name().unwrap_or_default())) + .unwrap_or_else(|| link.clone()); + if !locations.contains(&entry) { + locations.push(entry); + } + let target = std::fs::read_link(&link).with_context(|| { + format!("read system tracing configuration link {}", link.display()) + })?; + let target = if target.is_absolute() { + target + } else { + link.parent().unwrap_or_else(|| Path::new(".")).join(target) + }; + current = target.join(current.strip_prefix(&link)?); + } +} + pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { use notify::{RecursiveMode, Watcher}; @@ -147,22 +227,17 @@ pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { // Watch existing ancestors individually so a newly created or replaced // configuration directory can be registered without a recursive watch. let mut watch_error = None; - let canonical_target = match std::fs::read_link(&path) { - Ok(target) if target.is_absolute() => canonical_location(&target), - Ok(target) => canonical_location( - &path.parent().unwrap_or_else(|| Path::new(".")).join(target), - ), - Err(_) => canonical_location(&path), + let locations = match policy_locations(&path) { + Ok(locations) => locations, + Err(error) => { + sender.send_replace(Policy::Invalid(format!("{error:#}"))); + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue 'restart; + } }; - let configured_target = path - .parent() - .map(|parent| { - canonical_location(parent).join(path.file_name().unwrap_or_default()) - }) - .unwrap_or_else(|| path.clone()); - if let Some(parent) = path.parent() { + if path.parent().is_some() { let mut directories = Vec::new(); - for location in [parent, canonical_target.parent().unwrap_or(parent)] { + for location in locations.iter().filter_map(|location| location.parent()) { for directory in location .ancestors() .filter(|directory| directory.is_dir()) @@ -246,8 +321,7 @@ pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { if !event.need_rescan() && matches!(event.kind, EventKind::Access(kind) if !matches!(kind, AccessKind::Close(AccessMode::Write))) { continue; } if event.need_rescan() || event.paths.is_empty() || event.paths.iter().any(|changed| { let entry = changed.parent().map(|parent| canonical_location(parent).join(changed.file_name().unwrap_or_default())).unwrap_or_else(|| changed.clone()); - let changed = canonical_location(changed); - canonical_target.starts_with(&changed) || configured_target.starts_with(&entry) + locations.iter().any(|location| location.starts_with(&entry)) }) { for changed in &event.paths { let mut index = 0; @@ -336,7 +410,11 @@ mod tests { std::fs::create_dir(&target_dir).unwrap(); let config = config_dir.join("trace.json"); let target = target_dir.join("policy.json"); - symlink(&target, &config).unwrap(); + let intermediate_dir = tmp.path().join("intermediate"); + std::fs::create_dir(&intermediate_dir).unwrap(); + let intermediate = intermediate_dir.join("link.json"); + symlink(&target, &intermediate).unwrap(); + symlink(&intermediate, &config).unwrap(); assert!(SystemTraceConfig::load(&config).is_err()); let mut policy = watch(config.clone()); async fn wait( @@ -379,6 +457,23 @@ mod tests { std::fs::create_dir(&other_dir).unwrap(); let other = other_dir.join("new.json"); std::fs::write(&other, r#"{"span_plugins":["new.mjs"]}"#).unwrap(); + let intermediate_replacement = intermediate_dir.join("replacement"); + symlink(&other, &intermediate_replacement).unwrap(); + std::fs::rename(&intermediate_replacement, &intermediate).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("new.mjs")]) + }) + .await; + std::fs::write(&other, r#"{"span_plugins":["intermediate.mjs"]}"#).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("intermediate.mjs")]) + }) + .await; + std::fs::write(&other, r#"{"span_plugins":["new.mjs"]}"#).unwrap(); + wait(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("new.mjs")]) + }) + .await; let replacement = config_dir.join("replacement"); symlink(&other, &replacement).unwrap(); std::fs::rename(&replacement, &config).unwrap(); @@ -393,6 +488,53 @@ mod tests { .await; } + #[cfg(unix)] + #[tokio::test] + async fn follows_retargeted_directory_symlinks() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let first = tmp.path().join("first"); + let second = tmp.path().join("second"); + std::fs::create_dir(&first).unwrap(); + std::fs::create_dir(&second).unwrap(); + std::fs::write( + first.join("trace.json"), + r#"{"span_plugins":["first.mjs"]}"#, + ) + .unwrap(); + std::fs::write( + second.join("trace.json"), + r#"{"span_plugins":["second.mjs"]}"#, + ) + .unwrap(); + let link = tmp.path().join("config"); + symlink(&first, &link).unwrap(); + let mut policy = watch(link.join("trace.json")); + async fn wait(policy: &mut tokio::sync::watch::Receiver, expected: Policy) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + if *policy.borrow_and_update() == expected { + return; + } + policy.changed().await.unwrap(); + } + }) + .await + .unwrap(); + } + wait(&mut policy, Policy::Valid(vec![link.join("first.mjs")])).await; + let replacement = tmp.path().join("replacement"); + symlink(&second, &replacement).unwrap(); + std::fs::rename(replacement, &link).unwrap(); + wait(&mut policy, Policy::Valid(vec![link.join("second.mjs")])).await; + std::fs::write( + second.join("trace.json"), + r#"{"span_plugins":["updated.mjs"]}"#, + ) + .unwrap(); + wait(&mut policy, Policy::Valid(vec![link.join("updated.mjs")])).await; + } + #[test] fn loads_relative_paths_and_rejects_invalid_policy() { let dir = tempfile::tempdir().unwrap(); From 7351146d2fbbf2c411e0afc734b67512a4705543 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 21:17:41 +0800 Subject: [PATCH 06/12] Preserve inheritance settings across versions --- bt-daemon/README.md | 11 +++++++---- bt-daemon/src/setup/mod.rs | 6 ++++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/bt-daemon/README.md b/bt-daemon/README.md index a5625557..f4cf5db7 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -95,7 +95,9 @@ bt trace install claude --scope project --plugin ./scripts/redact.mjs Use `--no-inherit-user-plugins` to omit the user-level plugins; use `--inherit-user-plugins` to restore the default. The project setting is `inherit_user_plugins`; the earlier `inherit_plugins` spelling remains supported. -If both are present, `inherit_user_plugins` takes precedence. The earlier `--no-inherit-plugins` and `--inherit-plugins` flags are also aliases. +If both are present, `inherit_user_plugins` takes precedence. Setup writes both +names so older installations honor the same choice. The earlier +`--no-inherit-plugins` and `--inherit-plugins` flags are also aliases. A project configuration can execute the JavaScript plugins it names when tracing runs, so review them before using tracing in a repository. @@ -151,9 +153,10 @@ and invocations in `/etc/braintrust/trace.json` (macOS and Linux) or Paths may be absolute or relative to this file. Global plugins run first, followed by route plugins; project and invocation options cannot remove them. Protect the configuration and plugin files with system permissions. Configuration -changes are loaded automatically. `bt trace doctor ` shows the configured -global plugins. An invalid or unreadable -configuration or a plugin failure holds delivery until it is fixed. +changes are loaded automatically; deliveries already in progress may finish +under the previous configuration. `bt trace doctor ` shows the configured +global plugins. An invalid or unreadable configuration or a plugin failure holds +delivery until it is fixed. An absent file leaves existing behavior unchanged. This protects delivery through Braintrust tracing, not against a user who can bypass or replace the software. Raw events and translated operations are stored locally before plugins run. diff --git a/bt-daemon/src/setup/mod.rs b/bt-daemon/src/setup/mod.rs index fade5278..6e289b7a 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -175,7 +175,8 @@ fn write_project_setup_at( } } if args.no_inherit_plugins || args.inherit_plugins { - settings.remove("inherit_plugins"); + // Keep older installations aligned during rollbacks or mixed-version use. + settings.insert("inherit_plugins".into(), Value::Bool(args.inherit_plugins)); settings.insert( "inherit_user_plugins".into(), Value::Bool(args.inherit_plugins), @@ -497,12 +498,13 @@ mod tests { serde_json::json!(["plugins/redact.mjs"]) ); assert_eq!(value["inherit_user_plugins"], false); - assert!(value.get("inherit_plugins").is_none()); + assert_eq!(value["inherit_plugins"], false); args.no_inherit_plugins = false; args.inherit_plugins = true; write_project_setup_at(&path, &args, &selection).unwrap(); let value: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!(value["inherit_user_plugins"], true); + assert_eq!(value["inherit_plugins"], true); args.plugin.clear(); args.plugin.push("bad.js".into()); assert!(write_project_setup_at(&path, &args, &selection).is_err()); From 08630a437e32d25476a006beb42516b903187eae Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 21:46:52 +0800 Subject: [PATCH 07/12] Fix chained symlink resolution on Linux --- bt-daemon/src/system_trace_config.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index c09c9fa4..0b5e4a93 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -199,7 +199,12 @@ fn policy_locations(path: &Path) -> anyhow::Result> { } else { link.parent().unwrap_or_else(|| Path::new(".")).join(target) }; - current = target.join(current.strip_prefix(&link)?); + let remainder = current.strip_prefix(&link)?; + current = if remainder.as_os_str().is_empty() { + target + } else { + target.join(remainder) + }; } } @@ -415,6 +420,11 @@ mod tests { let intermediate = intermediate_dir.join("link.json"); symlink(&target, &intermediate).unwrap(); symlink(&intermediate, &config).unwrap(); + let locations = policy_locations(&config).unwrap(); + assert!( + locations.contains(&canonical_location(&target)), + "missing final target must remain watched: {locations:?}" + ); assert!(SystemTraceConfig::load(&config).is_err()); let mut policy = watch(config.clone()); async fn wait( From 5076a78ae142376f9e0ffdcda4a5c975b4a9351f Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 21:53:35 +0800 Subject: [PATCH 08/12] Guard global policy changes during routing --- bt-daemon/src/pipeline/consumer.rs | 9 ++- bt-daemon/src/pipeline/routing.rs | 105 +++++++++++++++++++++++++++ bt-daemon/src/pipeline/submission.rs | 2 +- bt-daemon/src/system_trace_config.rs | 45 +++++++++++- 4 files changed, 158 insertions(+), 3 deletions(-) diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 39a331dd..394fb9f7 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -177,7 +177,9 @@ impl ConsumerOptions { } } -fn global_plugin_digests(policy: &crate::system_trace_config::Policy) -> Vec> { +pub(super) fn global_plugin_digests( + policy: &crate::system_trace_config::Policy, +) -> Vec> { match policy { crate::system_trace_config::Policy::Valid(plugins) => plugins .iter() @@ -410,6 +412,11 @@ impl Consumer { ) })?; routing.configure(¤t); + routing.guard_policy( + policy.clone(), + current_policy.clone(), + current_digests.clone(), + ); match routing.emit_shared(ops).await { Err(error) if error.is::() => { // Never resubmit after the signal, including when diff --git a/bt-daemon/src/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index a3e06b5c..f370c204 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -15,8 +15,23 @@ use tokio::sync::{mpsc, oneshot}; struct Request { config: SessionConfig, operation: Operation, + policy_guard: Option, reply: oneshot::Sender, } + +#[derive(Clone)] +struct PolicyGuard { + receiver: tokio::sync::watch::Receiver, + policy: crate::system_trace_config::Policy, + digests: Vec>, +} + +impl PolicyGuard { + fn changed(&self) -> bool { + *self.receiver.borrow() != self.policy + || super::consumer::global_plugin_digests(&self.policy) != self.digests + } +} struct Response { result: anyhow::Result, pending: bool, @@ -35,6 +50,7 @@ pub(crate) struct RoutingSink { tx: mpsc::Sender>, task: tokio::task::JoinHandle<()>, config: Option, + policy_guard: Option, pending: bool, permalink: Option, } @@ -57,6 +73,7 @@ impl RoutingSink { let request = delivery.value(); let (result, state) = match &request.operation { Operation::Emit(ops) => { + let was_stopped = stopped; let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); @@ -113,6 +130,37 @@ impl RoutingSink { } } super::prepare::unique_tags(&mut prepared); + if request + .policy_guard + .as_ref() + .is_some_and(PolicyGuard::changed) + { + stopped = was_stopped; + let request = match delivery.into_completed().await { + Ok(request) => request, + Err(failed) => { + *last_error.lock() = Some(format!( + "routing completion failed: {}", + failed.error + )); + continue; + } + }; + let state = submission.state(); + let _ = request.reply.send(Response { + result: Err(anyhow::Error::new(RouteFailure { + cause: anyhow::anyhow!( + "global tracing policy changed during processing" + ), + retry: RetryCondition::Transient, + emitted: 0, + report: false, + })), + pending: state.pending, + permalink: state.permalink, + }); + continue; + } let submit_input = SubmissionInput { config: request.config.clone(), operation: Operation::Emit(prepared), @@ -198,11 +246,25 @@ impl RoutingSink { tx, task, config: None, + policy_guard: None, pending: false, permalink: None, } } + pub fn guard_policy( + &mut self, + receiver: tokio::sync::watch::Receiver, + policy: crate::system_trace_config::Policy, + digests: Vec>, + ) { + self.policy_guard = Some(PolicyGuard { + receiver, + policy, + digests, + }); + } + pub async fn shutdown(self) { let Self { tx, mut task, .. } = self; drop(tx); @@ -226,6 +288,7 @@ impl RoutingSink { let delivery = Delivery::new(operation, Forward).map(|operation| Request { config, operation, + policy_guard: self.policy_guard.clone(), reply, }); // Retain ownership on a failed send; no upstream completion is implied. @@ -291,6 +354,48 @@ mod tests { } } + #[tokio::test] + async fn changed_global_plugin_is_not_submitted_to_sink() { + let tmp = tempfile::tempdir().unwrap(); + let plugin = tmp.path().join("global.mjs"); + std::fs::write(&plugin, "export default span => span;").unwrap(); + let policy = crate::system_trace_config::Policy::Valid(vec![plugin.clone()]); + let digests = super::super::consumer::global_plugin_digests(&policy); + let (_sender, receiver) = tokio::sync::watch::channel(policy.clone()); + let emitted = Arc::new(AtomicU64::new(0)); + let mut sink = RoutingSink::spawn( + Box::new(CountingSink(emitted.clone())), + "debug".into(), + "session".into(), + tmp.path().into(), + Arc::new(Mutex::new(None)), + ); + let config = SessionRoute { + span_plugins: vec![plugin.clone()], + ..Default::default() + } + .with_auth(BackendAuth { + token: "test".into(), + api_url: None, + app_url: None, + org_name: None, + org_id: None, + }); + sink.configure(&config); + sink.guard_policy(receiver, policy, digests); + std::fs::write( + &plugin, + "export default span => ({ ...span, name: 'new' });", + ) + .unwrap(); + assert!(sink + .emit(&[SpanOp::Insert(SpanRow::default())]) + .await + .is_err()); + assert_eq!(emitted.load(Ordering::SeqCst), 0); + sink.shutdown().await; + } + #[tokio::test] async fn stop_discards_prepared_batch_and_stays_latched_after_reconfiguration() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/submission.rs b/bt-daemon/src/pipeline/submission.rs index c106f58d..a5c8a0a8 100644 --- a/bt-daemon/src/pipeline/submission.rs +++ b/bt-daemon/src/pipeline/submission.rs @@ -97,7 +97,7 @@ impl Submission { Self { sink } } - fn state(&self) -> State { + pub(super) fn state(&self) -> State { State { pending: self.sink.has_pending_delivery(), permalink: self.sink.permalink(), diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index 0b5e4a93..c120f0b3 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -208,6 +208,11 @@ fn policy_locations(path: &Path) -> anyhow::Result> { } } +fn read_watched_policy(path: &Path, locations: &[PathBuf]) -> anyhow::Result> { + let policy = Policy::read(path); + Ok((policy_locations(path)? == locations).then_some(policy)) +} + pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { use notify::{RecursiveMode, Watcher}; @@ -291,9 +296,20 @@ pub(crate) fn watch(path: PathBuf) -> tokio::sync::watch::Receiver { Some("system tracing configuration has no parent directory".into()); } let failed = watch_error.is_some(); + // A symlink can be retargeted after resolving its locations but + // before installing the corresponding watches. Do not publish a + // policy read from an unwatched target. let next = match watch_error { Some(error) => Policy::Invalid(error), - None => Policy::read(&path), + None => match read_watched_policy(&path, &locations) { + Ok(Some(policy)) => policy, + Ok(None) => continue, + Err(error) => { + sender.send_replace(Policy::Invalid(format!("{error:#}"))); + tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } + continue 'restart; + } + }, }; sender.send_if_modified(|current| { if *current == next { @@ -364,6 +380,33 @@ pub(crate) fn fixed(plugins: Vec) -> tokio::sync::watch::Receiver Date: Tue, 1 Dec 2026 22:18:11 +0800 Subject: [PATCH 09/12] Preserve accepted deliveries across policy changes --- bt-daemon/src/pipeline/consumer.rs | 213 ++++++++++++++++++++++++++- bt-daemon/src/pipeline/routing.rs | 87 ++++++++++- bt-daemon/src/pipeline/submission.rs | 2 + bt-daemon/src/sink/braintrust.rs | 4 + bt-daemon/src/sink/mod.rs | 6 + 5 files changed, 302 insertions(+), 10 deletions(-) diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 394fb9f7..25186b00 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -21,6 +21,7 @@ use tokio::sync::{watch, Notify}; enum Work { Resubmit, + ReplayDeferred, Flush, Complete, } @@ -109,7 +110,7 @@ impl ConsumerOptions { failure.boundary = match work { Work::Complete => Boundary::Completion, Work::Flush => Boundary::Ledger, - Work::Resubmit => failure.boundary, + Work::Resubmit | Work::ReplayDeferred => failure.boundary, }; Box::new((failure, work)) } @@ -140,6 +141,12 @@ impl ConsumerOptions { work: Work, ) -> Result { match work { + Work::ReplayDeferred => { + if let Some(previous) = sink.take() { + previous.shutdown().await; + } + return Ok(false); + } Work::Resubmit => { // Dropping unresolved obligations asks their source to replay. // Recreate the consumed SDK batch too. @@ -235,6 +242,7 @@ impl Consumer { let mut recorded = None; let mut record_retry = 0; let mut previous_policy = None; + let mut deferred_replay: Option> = None; loop { let current_policy = policy.borrow_and_update().clone(); let current_digests = global_plugin_digests(¤t_policy); @@ -247,10 +255,23 @@ impl Consumer { .as_ref() .is_some_and(|held| matches!(held.1, Work::Complete)) { + let replaying = held + .as_ref() + .is_some_and(|held| matches!(held.1, Work::ReplayDeferred)); + let deferred = if held.is_none() && deferred_replay.is_none() { + sink.as_ref().and_then(RoutingSink::deferred_ops) + } else { + None + }; if let Some(previous) = sink.take() { previous.shutdown().await; } - pending.clear(); + if let Some(ops) = deferred { + deferred_replay = Some(ops); + } else if deferred_replay.is_none() || (held.is_some() && !replaying) { + pending.clear(); + deferred_replay = None; + } held = None; recorded = None; attempts = 0; @@ -284,6 +305,57 @@ impl Consumer { *error = held.as_ref().map(|held| held.0.message()); } } + if held.is_none() { + if let Some(ops) = deferred_replay.as_ref() { + let current = settings.borrow_and_update().clone(); + let result = async { + if sink.is_none() { + sink = Some(options.sink(¤t).await?); + } + let routing = sink + .as_mut() + .ok_or_else(|| anyhow::anyhow!("configured sink is missing"))?; + routing.configure(¤t); + routing.guard_policy( + policy.clone(), + current_policy.clone(), + current_digests.clone(), + ); + routing.emit_shared(ops).await?; + routing.flush().await?; + Ok::<(), anyhow::Error>(()) + } + .await; + if let Err(error) = result { + if error.is::() { + while let Err(error) = input.detach().await { + *options.error.lock() = Some(error.to_string()); + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + *options.error.lock() = None; + pending.clear(); + break; + } + let mut failure = options.routing(&error, ¤t, attempts); + failure.1 = Work::ReplayDeferred; + held = Some(failure); + continue; + } + deferred_replay = None; + *options.error.lock() = None; + *options.recovery.lock() = None; + recorded = None; + attempts = 0; + match options + .finish(&mut pending, &mut sink, ¤t, attempts, Work::Flush) + .await + { + Ok(_) => {} + Err(failure) => held = Some(failure), + } + continue; + } + } if let Some(waiting) = held.take() { let (mut failure, work) = *waiting; let mut reported = failure.clone(); @@ -1057,6 +1129,143 @@ mod tests { assert_eq!(record.accepted.load(Ordering::SeqCst), 1); consumer.shutdown().await; } + #[tokio::test] + async fn policy_change_does_not_reprocess_accepted_rows_behind_deferred_root() { + use serde_json::json; + use wiremock::{ + matchers::{method, path}, + Mock, MockServer, ResponseTemplate, + }; + let backend = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/version")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .mount(&backend) + .await; + Mock::given(method("POST")) + .and(path("/api/project/register")) + .respond_with( + ResponseTemplate::new(200).set_body_json(json!({"project":{"id":"proj-1"}})), + ) + .mount(&backend) + .await; + Mock::given(method("POST")) + .and(path("/logs3")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({}))) + .mount(&backend) + .await; + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + let route = SessionRoute::default(); + let root = SpanOp::Insert(SpanRow { + span_id: "root-a".into(), + root_span_id: "root-a".into(), + name: "root-a".into(), + metadata: Some(json!({"_bt_defer_root":true})), + ..Default::default() + }); + let accepted = SpanOp::Insert(SpanRow { + span_id: "accepted-b".into(), + root_span_id: "accepted-b".into(), + name: "accepted-b".into(), + ..Default::default() + }); + journal.translated(1, vec![root, accepted]).await.unwrap(); + let mut opts = options(tmp.path(), &route, Arc::new(Recording::default())); + let (policy, receiver) = + watch::channel(crate::system_trace_config::Policy::Valid(Vec::new())); + opts.system_policy = receiver; + opts.factory = Arc::new(crate::BraintrustSinkFactory::new( + crate::BraintrustSinkConfig { + api_url: Some(backend.uri()), + app_url: Some(backend.uri()), + }, + )); + let mut config = opts.config.borrow().clone(); + config.auth.api_url = Some(backend.uri()); + config.auth.app_url = Some(backend.uri()); + opts.config.send_replace(config); + let (consumer, progress, error) = + spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + tokio::time::timeout(std::time::Duration::from_secs(10), async { + loop { + if backend.received_requests().await.unwrap().iter().any(|r| { + r.url.path() == "/logs3" + && String::from_utf8_lossy(&r.body).contains("accepted-b") + }) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(progress.completed(), 0); + let plugin = tmp.path().join("new.mjs"); + std::fs::write( + &plugin, + "export default span => { throw new Error('temporary policy failure'); }", + ) + .unwrap(); + policy.send_replace(crate::system_trace_config::Policy::Valid(vec![plugin])); + wait_for(|| { + error + .lock() + .as_ref() + .is_some_and(|message| message.contains("temporary policy failure")) + }) + .await; + std::fs::write(tmp.path().join("new.mjs"), "export default span => { if (span.name === 'accepted-b') throw new Error('accepted row replayed'); return span.name === 'root-a' ? {...span, name: 'redacted-root'} : span; }").unwrap(); + wait_for(|| error.lock().is_none()).await; + journal + .translated( + 2, + vec![SpanOp::Insert(SpanRow { + span_id: "child-a".into(), + root_span_id: "root-a".into(), + parent_span_ids: vec!["root-a".into()], + name: "child-a".into(), + ..Default::default() + })], + ) + .await + .unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(10), + progress.through(3, &error), + ) + .await + .unwrap() + .unwrap(); + let rows: Vec = backend + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path() == "/logs3") + .flat_map(|r| { + serde_json::from_slice::(&r.body).unwrap()["rows"] + .as_array() + .cloned() + .unwrap_or_default() + }) + .collect(); + assert_eq!( + rows.iter() + .filter(|row| row["span_id"] == "accepted-b") + .count(), + 1 + ); + assert!(rows.iter().any(|row| row["span_id"] == "child-a")); + assert!(rows + .iter() + .any(|row| row["span_id"] == "root-a" + && row["span_attributes"]["name"] == "redacted-root")); + consumer.shutdown().await; + } + #[tokio::test] async fn policy_change_preserves_accepted_completion_receipts() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index f370c204..3e8389e5 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -35,6 +35,7 @@ impl PolicyGuard { struct Response { result: anyhow::Result, pending: bool, + pending_span_ids: Option>, permalink: Option, } @@ -52,6 +53,8 @@ pub(crate) struct RoutingSink { config: Option, policy_guard: Option, pending: bool, + pending_span_ids: Option>, + deferred: Vec, permalink: Option, } @@ -73,7 +76,6 @@ impl RoutingSink { let request = delivery.value(); let (result, state) = match &request.operation { Operation::Emit(ops) => { - let was_stopped = stopped; let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); @@ -130,12 +132,12 @@ impl RoutingSink { } } super::prepare::unique_tags(&mut prepared); - if request - .policy_guard - .as_ref() - .is_some_and(PolicyGuard::changed) + if !stopped + && request + .policy_guard + .as_ref() + .is_some_and(PolicyGuard::changed) { - stopped = was_stopped; let request = match delivery.into_completed().await { Ok(request) => request, Err(failed) => { @@ -157,6 +159,7 @@ impl RoutingSink { report: false, })), pending: state.pending, + pending_span_ids: state.pending_span_ids, permalink: state.permalink, }); continue; @@ -238,6 +241,7 @@ impl RoutingSink { let _ = request.reply.send(Response { result, pending: state.pending, + pending_span_ids: state.pending_span_ids, permalink: state.permalink, }); } @@ -248,6 +252,8 @@ impl RoutingSink { config: None, policy_guard: None, pending: false, + pending_span_ids: None, + deferred: Vec::new(), permalink: None, } } @@ -265,6 +271,14 @@ impl RoutingSink { }); } + /// Return the original operations that have not reached the sink yet. + /// Unknown sink state cannot safely distinguish accepted from deferred. + pub fn deferred_ops(&self) -> Option> { + self.pending_span_ids + .as_ref() + .map(|_| self.deferred.clone()) + } + pub async fn shutdown(self) { let Self { tx, mut task, .. } = self; drop(tx); @@ -300,6 +314,7 @@ impl RoutingSink { .await .map_err(|_| anyhow::anyhow!("routing actor dropped its reply"))?; self.pending = response.pending; + self.pending_span_ids = response.pending_span_ids; self.permalink = response.permalink; response.result } @@ -320,10 +335,23 @@ impl Sink for RoutingSink { .await } async fn emit_shared(&mut self, ops: &[super::live::SharedOp]) -> anyhow::Result { - self.request(Operation::Emit(ops.to_vec())).await + let count = self.request(Operation::Emit(ops.to_vec())).await?; + if self.pending_span_ids.is_some() { + self.deferred.extend_from_slice(ops); + } + Ok(count) } async fn flush(&mut self) -> anyhow::Result<()> { - self.request(Operation::Flush).await.map(|_| ()) + self.request(Operation::Flush).await?; + if let Some(ids) = &self.pending_span_ids { + self.deferred.retain(|op| { + let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op.as_ref(); + ids.contains(&row.span_id) + }); + } else if !self.pending { + self.deferred.clear(); + } + Ok(()) } fn has_pending_delivery(&self) -> bool { self.pending @@ -354,6 +382,49 @@ mod tests { } } + #[tokio::test] + async fn stop_signal_wins_over_changed_global_policy() { + let tmp = tempfile::tempdir().unwrap(); + let plugin = tmp.path().join("global.mjs"); + std::fs::write(&plugin, "export default span => span;").unwrap(); + let policy = crate::system_trace_config::Policy::Valid(vec![plugin.clone()]); + let digests = super::super::consumer::global_plugin_digests(&policy); + let (_sender, receiver) = tokio::sync::watch::channel(policy.clone()); + let emitted = Arc::new(AtomicU64::new(0)); + let mut sink = RoutingSink::spawn( + Box::new(CountingSink(emitted.clone())), + "debug".into(), + "session".into(), + tmp.path().into(), + Arc::new(Mutex::new(None)), + ); + let config = SessionRoute { + span_plugins: vec![plugin.clone()], + ..Default::default() + } + .with_auth(BackendAuth { + token: "test".into(), + api_url: None, + app_url: None, + org_name: None, + org_id: None, + }); + sink.configure(&config); + sink.guard_policy(receiver, policy, digests); + std::fs::write( + &plugin, + "export default () => { throw new StopTracingError(); }", + ) + .unwrap(); + assert!(sink + .emit(&[SpanOp::Insert(SpanRow::default())]) + .await + .unwrap_err() + .is::()); + assert_eq!(emitted.load(Ordering::SeqCst), 0); + sink.shutdown().await; + } + #[tokio::test] async fn changed_global_plugin_is_not_submitted_to_sink() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/submission.rs b/bt-daemon/src/pipeline/submission.rs index a5c8a0a8..a7c657e7 100644 --- a/bt-daemon/src/pipeline/submission.rs +++ b/bt-daemon/src/pipeline/submission.rs @@ -14,6 +14,7 @@ pub(crate) struct Input { pub(crate) struct State { pub pending: bool, + pub pending_span_ids: Option>, pub permalink: Option, } @@ -100,6 +101,7 @@ impl Submission { pub(super) fn state(&self) -> State { State { pending: self.sink.has_pending_delivery(), + pending_span_ids: self.sink.pending_delivery_span_ids(), permalink: self.sink.permalink(), } } diff --git a/bt-daemon/src/sink/braintrust.rs b/bt-daemon/src/sink/braintrust.rs index b5c01965..3bbc4541 100644 --- a/bt-daemon/src/sink/braintrust.rs +++ b/bt-daemon/src/sink/braintrust.rs @@ -518,6 +518,10 @@ impl Sink for BraintrustSink { !self.pending_roots.is_empty() } + fn pending_delivery_span_ids(&self) -> Option> { + Some(self.pending_roots.keys().cloned().collect()) + } + fn permalink(&self) -> Option { let creds = self.creds.as_ref()?; // Logs URLs address projects by name. Experiment and attached-parent diff --git a/bt-daemon/src/sink/mod.rs b/bt-daemon/src/sink/mod.rs index 0bf7cefd..47c28deb 100644 --- a/bt-daemon/src/sink/mod.rs +++ b/bt-daemon/src/sink/mod.rs @@ -57,6 +57,12 @@ pub trait Sink: Send { false } + /// Identifies deferred span IDs when the sink can distinguish them from + /// writes already accepted by its destination. `None` means unknown. + fn pending_delivery_span_ids(&self) -> Option> { + None + } + /// A user-facing trace permalink, once known. fn permalink(&self) -> Option { None From f73e622916c30f656b0b3af6bf1992369599ec4c Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 22:28:00 +0800 Subject: [PATCH 10/12] Handle shutdown and counts during deferred replay --- bt-daemon/src/pipeline/consumer.rs | 140 ++++++++++++++++++++++++++--- 1 file changed, 128 insertions(+), 12 deletions(-) diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 25186b00..9a620268 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -243,7 +243,7 @@ impl Consumer { let mut record_retry = 0; let mut previous_policy = None; let mut deferred_replay: Option> = None; - loop { + 'consumer: loop { let current_policy = policy.borrow_and_update().clone(); let current_digests = global_plugin_digests(¤t_policy); let current_revision = (current_policy.clone(), current_digests.clone()); @@ -308,7 +308,9 @@ impl Consumer { if held.is_none() { if let Some(ops) = deferred_replay.as_ref() { let current = settings.borrow_and_update().clone(); - let result = async { + let result = tokio::select! { + _ = stop.notified() => break, + result = async { if sink.is_none() { sink = Some(options.sink(¤t).await?); } @@ -321,16 +323,29 @@ impl Consumer { current_policy.clone(), current_digests.clone(), ); - routing.emit_shared(ops).await?; + let count = routing.emit_shared(ops).await?; + options.counters.spans_emitted.fetch_add(count, Ordering::Relaxed); routing.flush().await?; Ok::<(), anyhow::Error>(()) - } - .await; + } => result, + }; if let Err(error) = result { if error.is::() { - while let Err(error) = input.detach().await { - *options.error.lock() = Some(error.to_string()); - tokio::time::sleep(std::time::Duration::from_millis(250)).await; + loop { + let result = tokio::select! { + _ = stop.notified() => break 'consumer, + result = input.detach() => result, + }; + match result { + Ok(()) => break, + Err(error) => { + *options.error.lock() = Some(error.to_string()) + } + } + tokio::select! { + _ = stop.notified() => break 'consumer, + _ = tokio::time::sleep(std::time::Duration::from_millis(250)) => {} + } } *options.error.lock() = None; pending.clear(); @@ -346,10 +361,11 @@ impl Consumer { *options.recovery.lock() = None; recorded = None; attempts = 0; - match options - .finish(&mut pending, &mut sink, ¤t, attempts, Work::Flush) - .await - { + let finished = tokio::select! { + _ = stop.notified() => break, + result = options.finish(&mut pending, &mut sink, ¤t, attempts, Work::Flush) => result, + }; + match finished { Ok(_) => {} Err(failure) => held = Some(failure), } @@ -584,6 +600,56 @@ mod tests { defer_until: AtomicU64, } struct Factory(Arc); + + struct ReplayFactory { + creations: AtomicU64, + ready: Arc, + entered: Arc, + block: bool, + } + struct ReplaySink { + initial: bool, + ready: Arc, + entered: Arc, + block: bool, + } + impl SinkFactory for ReplayFactory { + fn create(&self, _: &str, _: &str) -> anyhow::Result> { + Ok(Box::new(ReplaySink { + initial: self.creations.fetch_add(1, Ordering::SeqCst) == 0, + ready: self.ready.clone(), + entered: self.entered.clone(), + block: self.block, + })) + } + } + #[async_trait::async_trait] + impl Sink for ReplaySink { + async fn emit(&mut self, _ops: &[SpanOp]) -> anyhow::Result { + Ok(u64::from(!self.initial)) + } + async fn flush(&mut self) -> anyhow::Result<()> { + if self.initial { + self.ready.notify_one(); + } else { + self.entered.notify_one(); + if self.block { + std::future::pending::<()>().await; + } + } + Ok(()) + } + fn has_pending_delivery(&self) -> bool { + self.initial + } + fn pending_delivery_span_ids(&self) -> Option> { + Some(if self.initial { + vec!["one".into()] + } else { + Vec::new() + }) + } + } struct CheckedSink { record: Arc, pending: u64, @@ -1105,6 +1171,56 @@ mod tests { consumer.shutdown().await; } + async fn setup_deferred_replay( + block: bool, + ) -> (tempfile::TempDir, Arc, Arc, Arc) { + let tmp = tempfile::tempdir().unwrap(); + let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) + .await + .unwrap(); + stored(&journal).await; + let route = SessionRoute::default(); + let mut opts = options(tmp.path(), &route, Arc::new(Recording::default())); + let (policy, receiver) = + watch::channel(crate::system_trace_config::Policy::Valid(Vec::new())); + opts.system_policy = receiver; + let ready = Arc::new(Notify::new()); + let entered = Arc::new(Notify::new()); + let counters = opts.counters.clone(); + opts.factory = Arc::new(ReplayFactory { + creations: AtomicU64::new(0), + ready: ready.clone(), + entered: entered.clone(), + block, + }); + let (consumer, _, _) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + tokio::time::timeout(std::time::Duration::from_secs(5), ready.notified()) + .await + .unwrap(); + let plugin = tmp.path().join("plugin.mjs"); + std::fs::write(&plugin, "export default span => span").unwrap(); + policy.send_replace(crate::system_trace_config::Policy::Valid(vec![plugin])); + tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + (tmp, consumer, entered, counters) + } + + #[tokio::test] + async fn shutdown_interrupts_a_stalled_deferred_replay() { + let (_tmp, consumer, _entered, _) = setup_deferred_replay(true).await; + tokio::time::timeout(std::time::Duration::from_secs(4), consumer.shutdown()) + .await + .expect("shutdown must not wait for the backend"); + } + + #[tokio::test] + async fn counts_rows_emitted_during_deferred_replay() { + let (_tmp, consumer, _entered, counters) = setup_deferred_replay(false).await; + wait_for(|| counters.spans_emitted.load(Ordering::SeqCst) == 1).await; + consumer.shutdown().await; + } + #[tokio::test] async fn head_write_recovery_retries_only_completion() { let tmp = tempfile::tempdir().unwrap(); From bd4faeffda530df5af2fe9cbdbfd3c4d330d2767 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 22:52:39 +0800 Subject: [PATCH 11/12] Simplify global tracing policy delivery and reload --- bt-daemon/src/pipeline/consumer.rs | 302 +++++++----------------- bt-daemon/src/pipeline/routing.rs | 88 ++----- bt-daemon/src/system_trace_config.rs | 329 +++++++++++---------------- 3 files changed, 237 insertions(+), 482 deletions(-) diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 9a620268..1f394a5e 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -141,19 +141,14 @@ impl ConsumerOptions { work: Work, ) -> Result { match work { - Work::ReplayDeferred => { + Work::Resubmit | Work::ReplayDeferred => { if let Some(previous) = sink.take() { previous.shutdown().await; } - return Ok(false); - } - Work::Resubmit => { - // Dropping unresolved obligations asks their source to replay. - // Recreate the consumed SDK batch too. - if let Some(previous) = sink.take() { - previous.shutdown().await; + // A full resubmission asks the source to replay abandoned receipts. + if matches!(work, Work::Resubmit) { + pending.clear(); } - pending.clear(); return Ok(false); } Work::Flush => { @@ -243,7 +238,7 @@ impl Consumer { let mut record_retry = 0; let mut previous_policy = None; let mut deferred_replay: Option> = None; - 'consumer: loop { + loop { let current_policy = policy.borrow_and_update().clone(); let current_digests = global_plugin_digests(¤t_policy); let current_revision = (current_policy.clone(), current_digests.clone()); @@ -305,73 +300,6 @@ impl Consumer { *error = held.as_ref().map(|held| held.0.message()); } } - if held.is_none() { - if let Some(ops) = deferred_replay.as_ref() { - let current = settings.borrow_and_update().clone(); - let result = tokio::select! { - _ = stop.notified() => break, - result = async { - if sink.is_none() { - sink = Some(options.sink(¤t).await?); - } - let routing = sink - .as_mut() - .ok_or_else(|| anyhow::anyhow!("configured sink is missing"))?; - routing.configure(¤t); - routing.guard_policy( - policy.clone(), - current_policy.clone(), - current_digests.clone(), - ); - let count = routing.emit_shared(ops).await?; - options.counters.spans_emitted.fetch_add(count, Ordering::Relaxed); - routing.flush().await?; - Ok::<(), anyhow::Error>(()) - } => result, - }; - if let Err(error) = result { - if error.is::() { - loop { - let result = tokio::select! { - _ = stop.notified() => break 'consumer, - result = input.detach() => result, - }; - match result { - Ok(()) => break, - Err(error) => { - *options.error.lock() = Some(error.to_string()) - } - } - tokio::select! { - _ = stop.notified() => break 'consumer, - _ = tokio::time::sleep(std::time::Duration::from_millis(250)) => {} - } - } - *options.error.lock() = None; - pending.clear(); - break; - } - let mut failure = options.routing(&error, ¤t, attempts); - failure.1 = Work::ReplayDeferred; - held = Some(failure); - continue; - } - deferred_replay = None; - *options.error.lock() = None; - *options.recovery.lock() = None; - recorded = None; - attempts = 0; - let finished = tokio::select! { - _ = stop.notified() => break, - result = options.finish(&mut pending, &mut sink, ¤t, attempts, Work::Flush) => result, - }; - match finished { - Ok(_) => {} - Err(failure) => held = Some(failure), - } - continue; - } - } if let Some(waiting) = held.take() { let (mut failure, work) = *waiting; let mut reported = failure.clone(); @@ -445,101 +373,99 @@ impl Consumer { } continue; } + let replaying = deferred_replay.is_some(); let attempt = async { - let received = tokio::select! { - result=input.receive()=>result, - result=settings.changed()=> { - return if result.is_err() { Ok(None) } else { Ok(Some(false)) }; - }, - result=policy.changed()=> { - return if result.is_err() { Ok(None) } else { Ok(Some(false)) }; - }, - }; - let delivery = received.map_err(|error| match error.downcast::() { - Ok(failure) => Box::new((failure, Work::Resubmit)), - Err(error) => options.storage(&error, attempts, Work::Resubmit), - })?; - let Some(delivery) = delivery else { - return Ok(None); - }; - let current_policy = policy.borrow().clone(); - if matches!( - current_policy, - crate::system_trace_config::Policy::Starting - | crate::system_trace_config::Policy::Invalid(_) - ) { - drop(delivery); - return Ok(Some(false)); - } - apply_policy(&config, &route_config, ¤t_policy); - let current = settings.borrow_and_update().clone(); - let creation = if sink.is_none() { - options - .sink(¤t) - .await - .map(|created| sink = Some(created)) - .map_err(|error| options.routing(&error, ¤t, attempts)) + let delivery = if replaying { + None } else { - Ok(()) + let received = tokio::select! { + result = input.receive() => result, + result = settings.changed() => return Ok(result.ok().map(|_| false)), + result = policy.changed() => return Ok(result.ok().map(|_| false)), + }; + match received.map_err(|error| match error.downcast::() { + Ok(failure) => Box::new((failure, Work::Resubmit)), + Err(error) => options.storage(&error, attempts, Work::Resubmit), + })? { + Some(delivery) => Some(delivery), + None => return Ok(None), + } }; if *policy.borrow() != current_policy || global_plugin_digests(¤t_policy) != current_digests { - drop(delivery); return Ok(Some(false)); } - let ops = delivery.value().as_slice(); - let mut stopped = false; + let current = settings.borrow_and_update().clone(); + let ops = delivery + .as_ref() + .map(Delivery::value) + .or(deferred_replay.as_ref()) + .map_or(&[][..], Vec::as_slice); let result = async { - creation?; - let routing = sink.as_mut().ok_or_else(|| { - options.storage( - &anyhow::anyhow!("configured sink is missing"), - attempts, - Work::Resubmit, - ) - })?; + if sink.is_none() { + sink = Some(options.sink(¤t).await?); + } + let routing = sink + .as_mut() + .ok_or_else(|| anyhow::anyhow!("configured sink is missing"))?; routing.configure(¤t); routing.guard_policy( policy.clone(), current_policy.clone(), - current_digests.clone(), + current_digests, ); - match routing.emit_shared(ops).await { - Err(error) if error.is::() => { - // Never resubmit after the signal, including when - // the terminal-state write temporarily fails. - while let Err(error) = input.detach().await { - *options.error.lock() = Some(error.to_string()); - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - } - *options.error.lock() = None; - stopped = true; - Ok(0) - } - result => { - result.map_err(|error| options.routing(&error, ¤t, attempts)) - } - } + routing.emit_shared(ops).await } .await; - if result.is_ok() { - options.counters.record(ops.iter().map(|op| op.as_ref())); - } - pending.push_back(delivery.map(|_| ())); - if stopped { + if result + .as_ref() + .is_err_and(|error| error.is::()) + { + // Never resubmit after the signal, including when + // the terminal-state write temporarily fails. + while let Err(error) = input.detach().await { + *options.error.lock() = Some(error.to_string()); + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + } + *options.error.lock() = None; pending.clear(); return Ok(None); } - let count = result?; + if let Some(delivery) = delivery { + if result.is_ok() { + options + .counters + .record(delivery.value().iter().map(|op| op.as_ref())); + } + pending.push_back(delivery.map(|_| ())); + } + let retry = |mut failure: Held| { + if replaying && matches!(failure.1, Work::Resubmit) { + failure.1 = Work::ReplayDeferred; + } + failure + }; + let count = result + .map_err(|error| retry(options.routing(&error, ¤t, attempts)))?; options .counters .spans_emitted .fetch_add(count, Ordering::Relaxed); - options + let finished = options .finish(&mut pending, &mut sink, ¤t, attempts, Work::Flush) - .await - .map(Some) + .await; + // A failed checkpoint can be retried without sending rows again. + if finished.as_ref().is_ok() + || finished + .as_ref() + .is_err_and(|failure| matches!(failure.1, Work::Complete)) + { + deferred_replay = None; + } + finished + .map(|completed| Some(completed || replaying)) + .map_err(retry) }; let result = tokio::select! { _=stop.notified()=>break, @@ -605,13 +531,11 @@ mod tests { creations: AtomicU64, ready: Arc, entered: Arc, - block: bool, } struct ReplaySink { initial: bool, ready: Arc, entered: Arc, - block: bool, } impl SinkFactory for ReplayFactory { fn create(&self, _: &str, _: &str) -> anyhow::Result> { @@ -619,7 +543,6 @@ mod tests { initial: self.creations.fetch_add(1, Ordering::SeqCst) == 0, ready: self.ready.clone(), entered: self.entered.clone(), - block: self.block, })) } } @@ -633,9 +556,7 @@ mod tests { self.ready.notify_one(); } else { self.entered.notify_one(); - if self.block { - std::future::pending::<()>().await; - } + std::future::pending::<()>().await; } Ok(()) } @@ -800,57 +721,13 @@ mod tests { consumer.shutdown().await; } - #[tokio::test] - async fn system_policy_reloads_and_invalid_edits_hold_delivery_until_repaired() { - let tmp = tempfile::tempdir().unwrap(); - let policy_path = tmp.path().join("trace.json"); - let plugin = tmp.path().join("redact.mjs"); - std::fs::write( - &plugin, - "export default span => ({...span, name: 'redacted'})", - ) - .unwrap(); - std::fs::write(&policy_path, r#"{"span_plugins":[]}"#).unwrap(); - let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) - .await - .unwrap(); - let route = SessionRoute::default(); - let record = Arc::new(Recording::default()); - let mut opts = options(tmp.path(), &route, record.clone()); - opts.system_policy = crate::system_trace_config::watch(policy_path.clone()); - let (consumer, progress, error) = - spawn(Cursor::open(&journal, &route).await.unwrap(), opts); - std::fs::write(&policy_path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); - wait_for(|| consumer.config.borrow().span_plugins == [plugin.clone()]).await; - std::fs::write(&policy_path, "{").unwrap(); - wait_for(|| { - error - .lock() - .as_ref() - .is_some_and(|e| e.contains("system tracing settings")) - }) - .await; - stored(&journal).await; - tokio::time::sleep(std::time::Duration::from_millis(350)).await; - assert_eq!(record.submitted.load(Ordering::SeqCst), 0); - std::fs::write(&policy_path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); - wait_for(|| error.lock().is_none()).await; - tokio::time::timeout( - std::time::Duration::from_secs(5), - progress.through(1, &error), - ) - .await - .unwrap() - .unwrap(); - assert_eq!(record.submitted.load(Ordering::SeqCst), 1); - consumer.shutdown().await; - } - #[tokio::test] async fn invalid_global_config_pauses_live_feed_and_replays_after_repair() { let tmp = tempfile::tempdir().unwrap(); let path = tmp.path().join("trace.json"); - std::fs::write(&path, "{").unwrap(); + std::fs::write(&path, "{}").unwrap(); + let plugin = tmp.path().join("redact.mjs"); + std::fs::write(&plugin, "export default span => span").unwrap(); let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await .unwrap(); @@ -860,6 +737,9 @@ mod tests { opts.system_policy = crate::system_trace_config::watch(path.clone()); let (consumer, progress, error) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); + std::fs::write(&path, r#"{"span_plugins":["redact.mjs"]}"#).unwrap(); + wait_for(|| consumer.config.borrow().span_plugins == [plugin.clone()]).await; + std::fs::write(&path, "{").unwrap(); wait_for(|| { error .lock() @@ -1171,9 +1051,8 @@ mod tests { consumer.shutdown().await; } - async fn setup_deferred_replay( - block: bool, - ) -> (tempfile::TempDir, Arc, Arc, Arc) { + #[tokio::test] + async fn deferred_replay_counts_rows_and_shuts_down_during_stalled_flush() { let tmp = tempfile::tempdir().unwrap(); let journal = SessionStorage::at(&tmp.path().join("spans.sqlite")) .await @@ -1191,7 +1070,6 @@ mod tests { creations: AtomicU64::new(0), ready: ready.clone(), entered: entered.clone(), - block, }); let (consumer, _, _) = spawn(Cursor::open(&journal, &route).await.unwrap(), opts); tokio::time::timeout(std::time::Duration::from_secs(5), ready.notified()) @@ -1203,24 +1081,12 @@ mod tests { tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified()) .await .unwrap(); - (tmp, consumer, entered, counters) - } - - #[tokio::test] - async fn shutdown_interrupts_a_stalled_deferred_replay() { - let (_tmp, consumer, _entered, _) = setup_deferred_replay(true).await; + assert_eq!(counters.spans_emitted.load(Ordering::SeqCst), 1); tokio::time::timeout(std::time::Duration::from_secs(4), consumer.shutdown()) .await .expect("shutdown must not wait for the backend"); } - #[tokio::test] - async fn counts_rows_emitted_during_deferred_replay() { - let (_tmp, consumer, _entered, counters) = setup_deferred_replay(false).await; - wait_for(|| counters.spans_emitted.load(Ordering::SeqCst) == 1).await; - consumer.shutdown().await; - } - #[tokio::test] async fn head_write_recovery_retries_only_completion() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index 3e8389e5..be412be3 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -75,7 +75,7 @@ impl RoutingSink { while let Ok(Some(delivery)) = InputPort::receive(&mut rx).await { let request = delivery.value(); let (result, state) = match &request.operation { - Operation::Emit(ops) => { + Operation::Emit(ops) => 'emit: { let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); @@ -138,19 +138,8 @@ impl RoutingSink { .as_ref() .is_some_and(PolicyGuard::changed) { - let request = match delivery.into_completed().await { - Ok(request) => request, - Err(failed) => { - *last_error.lock() = Some(format!( - "routing completion failed: {}", - failed.error - )); - continue; - } - }; - let state = submission.state(); - let _ = request.reply.send(Response { - result: Err(anyhow::Error::new(RouteFailure { + break 'emit ( + Err(anyhow::Error::new(RouteFailure { cause: anyhow::anyhow!( "global tracing policy changed during processing" ), @@ -158,11 +147,8 @@ impl RoutingSink { emitted: 0, report: false, })), - pending: state.pending, - pending_span_ids: state.pending_span_ids, - permalink: state.permalink, - }); - continue; + submission.state(), + ); } let submit_input = SubmissionInput { config: request.config.clone(), @@ -382,8 +368,7 @@ mod tests { } } - #[tokio::test] - async fn stop_signal_wins_over_changed_global_policy() { + async fn emit_with_changed_policy(replacement: &str) -> anyhow::Error { let tmp = tempfile::tempdir().unwrap(); let plugin = tmp.path().join("global.mjs"); std::fs::write(&plugin, "export default span => span;").unwrap(); @@ -411,60 +396,29 @@ mod tests { }); sink.configure(&config); sink.guard_policy(receiver, policy, digests); - std::fs::write( - &plugin, - "export default () => { throw new StopTracingError(); }", - ) - .unwrap(); - assert!(sink + std::fs::write(&plugin, replacement).unwrap(); + let error = sink .emit(&[SpanOp::Insert(SpanRow::default())]) .await - .unwrap_err() - .is::()); + .unwrap_err(); assert_eq!(emitted.load(Ordering::SeqCst), 0); sink.shutdown().await; + error + } + + #[tokio::test] + async fn stop_signal_wins_over_changed_global_policy() { + let error = + emit_with_changed_policy("export default () => { throw new StopTracingError(); }") + .await; + assert!(error.is::()); } #[tokio::test] async fn changed_global_plugin_is_not_submitted_to_sink() { - let tmp = tempfile::tempdir().unwrap(); - let plugin = tmp.path().join("global.mjs"); - std::fs::write(&plugin, "export default span => span;").unwrap(); - let policy = crate::system_trace_config::Policy::Valid(vec![plugin.clone()]); - let digests = super::super::consumer::global_plugin_digests(&policy); - let (_sender, receiver) = tokio::sync::watch::channel(policy.clone()); - let emitted = Arc::new(AtomicU64::new(0)); - let mut sink = RoutingSink::spawn( - Box::new(CountingSink(emitted.clone())), - "debug".into(), - "session".into(), - tmp.path().into(), - Arc::new(Mutex::new(None)), - ); - let config = SessionRoute { - span_plugins: vec![plugin.clone()], - ..Default::default() - } - .with_auth(BackendAuth { - token: "test".into(), - api_url: None, - app_url: None, - org_name: None, - org_id: None, - }); - sink.configure(&config); - sink.guard_policy(receiver, policy, digests); - std::fs::write( - &plugin, - "export default span => ({ ...span, name: 'new' });", - ) - .unwrap(); - assert!(sink - .emit(&[SpanOp::Insert(SpanRow::default())]) - .await - .is_err()); - assert_eq!(emitted.load(Ordering::SeqCst), 0); - sink.shutdown().await; + let error = + emit_with_changed_policy("export default span => ({ ...span, name: 'new' });").await; + assert!(error.to_string().contains("global tracing policy changed")); } #[tokio::test] diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index c120f0b3..d07691cc 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -214,160 +214,117 @@ fn read_watched_policy(path: &Path, locations: &[PathBuf]) -> anyhow::Result tokio::sync::watch::Receiver { - use notify::{RecursiveMode, Watcher}; - let (sender, receiver) = tokio::sync::watch::channel(Policy::Starting); tokio::spawn(async move { - 'restart: loop { - let (events_tx, mut events_rx) = tokio::sync::mpsc::unbounded_channel(); - let mut watcher = match notify::recommended_watcher(move |event| { - let _ = events_tx.send(event); - }) { - Ok(watcher) => watcher, - Err(error) => { - sender.send_replace(Policy::Invalid(format!( - "cannot watch system tracing configuration: {error}" - ))); - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue; - } - }; - let mut watched = Vec::::new(); - loop { - // Watch existing ancestors individually so a newly created or replaced - // configuration directory can be registered without a recursive watch. - let mut watch_error = None; - let locations = match policy_locations(&path) { - Ok(locations) => locations, - Err(error) => { - sender.send_replace(Policy::Invalid(format!("{error:#}"))); - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue 'restart; - } - }; - if path.parent().is_some() { - let mut directories = Vec::new(); - for location in locations.iter().filter_map(|location| location.parent()) { - for directory in location - .ancestors() - .filter(|directory| directory.is_dir()) - .take(2) - { - let directory = canonical_location(directory); - if !directories.contains(&directory) { - directories.push(directory); - } - } - } - if directories.is_empty() { - watch_error = Some(format!( - "cannot watch an existing parent of {}", - path.display() - )); - } - for directory in &directories { - if watched.contains(directory) { - continue; - } - match watcher.watch(directory, RecursiveMode::NonRecursive) { - Ok(()) => watched.push(directory.clone()), - Err(error) => { - watch_error = - Some(format!("cannot watch {}: {error}", directory.display())); - break; - } - } - } - if watch_error.is_none() { - let mut index = 0; - while index < watched.len() { - if directories.contains(&watched[index]) { - index += 1; - continue; - } - let removed = watched.remove(index); - if let Err(error) = watcher.unwatch(&removed) { - tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); - } - } - } - } else { - watch_error = - Some("system tracing configuration has no parent directory".into()); - } - let failed = watch_error.is_some(); - // A symlink can be retargeted after resolving its locations but - // before installing the corresponding watches. Do not publish a - // policy read from an unwatched target. - let next = match watch_error { - Some(error) => Policy::Invalid(error), - None => match read_watched_policy(&path, &locations) { - Ok(Some(policy)) => policy, - Ok(None) => continue, - Err(error) => { - sender.send_replace(Policy::Invalid(format!("{error:#}"))); - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue 'restart; - } - }, - }; - sender.send_if_modified(|current| { - if *current == next { - false - } else { - *current = next; - true - } - }); - if failed { - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue 'restart; - } - loop { - tokio::select! { - _ = sender.closed() => return, - event = events_rx.recv() => match event { - None => { - sender.send_replace(Policy::Invalid("system tracing configuration watch stopped".into())); - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue 'restart; - } - Some(Err(error)) => { - sender.send_replace(Policy::Invalid(format!("system tracing configuration watch failed: {error}"))); - tokio::select! { _ = sender.closed() => return, _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } - continue 'restart; - } - Some(Ok(event)) => { - use notify::event::{AccessKind, AccessMode, EventKind}; - if !event.need_rescan() && matches!(event.kind, EventKind::Access(kind) if !matches!(kind, AccessKind::Close(AccessMode::Write))) { continue; } - if event.need_rescan() || event.paths.is_empty() || event.paths.iter().any(|changed| { - let entry = changed.parent().map(|parent| canonical_location(parent).join(changed.file_name().unwrap_or_default())).unwrap_or_else(|| changed.clone()); - locations.iter().any(|location| location.starts_with(&entry)) - }) { - for changed in &event.paths { - let mut index = 0; - while index < watched.len() { - let canonical = canonical_location(&watched[index]); - if canonical == canonical_location(changed) { - let removed = watched.remove(index); - if let Err(error) = watcher.unwatch(&removed) { - tracing::debug!(path = %removed.display(), %error, "configuration watch already removed"); - } - } else { index += 1; } - } - } - break; - } - } - } - } - } + while let Err(error) = watch_policy(&path, &sender).await { + sender.send_replace(Policy::Invalid(format!("{error:#}"))); + tokio::select! { + _ = sender.closed() => break, + _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {} } } }); receiver } +async fn watch_policy( + path: &Path, + sender: &tokio::sync::watch::Sender, +) -> anyhow::Result<()> { + use notify::event::{AccessKind, AccessMode, EventKind}; + use notify::{RecursiveMode, Watcher}; + use std::collections::BTreeSet; + + let (events_tx, mut events) = tokio::sync::mpsc::unbounded_channel(); + let mut watcher = notify::recommended_watcher(move |event| { + let _ = events_tx.send(event); + }) + .context("cannot watch system tracing configuration")?; + let mut watched = BTreeSet::new(); + loop { + if sender.is_closed() { + return Ok(()); + } + let locations = policy_locations(path)?; + // Watch the nearest existing directory and its parent so directory + // creation and replacement both trigger registration of the new path. + let directories: BTreeSet<_> = locations + .iter() + .filter_map(|location| location.parent()) + .flat_map(|parent| parent.ancestors().filter(|dir| dir.is_dir()).take(2)) + .map(canonical_location) + .collect(); + anyhow::ensure!( + !directories.is_empty(), + "cannot watch an existing parent of {}", + path.display() + ); + for directory in directories.difference(&watched) { + watcher + .watch(directory, RecursiveMode::NonRecursive) + .with_context(|| format!("cannot watch {}", directory.display()))?; + } + for directory in watched.difference(&directories) { + if let Err(error) = watcher.unwatch(directory) { + tracing::debug!(path = %directory.display(), %error, "configuration watch already removed"); + } + } + watched = directories; + + // Symlink targets can change during registration. Only publish a + // policy after verifying that its target is covered by the watches. + let Some(next) = read_watched_policy(path, &locations)? else { + continue; + }; + sender.send_if_modified(|current| { + if *current == next { + return false; + } + *current = next; + true + }); + + loop { + let event = tokio::select! { + _ = sender.closed() => return Ok(()), + event = events.recv() => event.context("system tracing configuration watch stopped")? + .context("system tracing configuration watch failed")?, + }; + let rescan = event.need_rescan(); + if !rescan + && matches!(event.kind, EventKind::Access(kind) if kind != AccessKind::Close(AccessMode::Write)) + { + continue; + } + if !rescan + && !event.paths.is_empty() + && !event.paths.iter().any(|changed| { + let entry = changed + .parent() + .zip(changed.file_name()) + .map(|(parent, name)| canonical_location(parent).join(name)) + .unwrap_or_else(|| changed.clone()); + locations + .iter() + .any(|location| location.starts_with(entry.as_path())) + }) + { + continue; + } + watched.retain(|directory| { + if !event.paths.iter().any(|changed| canonical_location(changed) == canonical_location(directory)) { + return true; + } + if let Err(error) = watcher.unwatch(directory) { + tracing::debug!(path = %directory.display(), %error, "configuration watch already removed"); + } + false + }); + break; + } + } +} + #[cfg(test)] pub(crate) fn fixed(plugins: Vec) -> tokio::sync::watch::Receiver { let (sender, receiver) = tokio::sync::watch::channel(Policy::Valid(plugins)); @@ -381,6 +338,23 @@ pub(crate) fn fixed(plugins: Vec) -> tokio::sync::watch::Receiver, + predicate: impl Fn(&Policy) -> bool, + ) { + tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !predicate(&policy.borrow_and_update()) { + policy.changed().await.unwrap(); + } + }) + .await + .unwrap(); + } + + async fn wait_for(policy: &mut tokio::sync::watch::Receiver, expected: Policy) { + wait_until(policy, |current| *current == expected).await; + } + #[cfg(unix)] #[test] fn rejects_policy_read_after_symlink_retarget_during_watch_setup() { @@ -413,18 +387,6 @@ mod tests { let directory = tmp.path().join("system"); let path = directory.join("trace.json"); let mut policy = watch(path.clone()); - async fn wait_for(policy: &mut tokio::sync::watch::Receiver, expected: Policy) { - tokio::time::timeout(std::time::Duration::from_secs(10), async { - loop { - if *policy.borrow_and_update() == expected { - break; - } - policy.changed().await.unwrap(); - } - }) - .await - .unwrap(); - } wait_for(&mut policy, Policy::Valid(Vec::new())).await; std::fs::create_dir(&directory).unwrap(); let staged = directory.join("new.json"); @@ -470,38 +432,23 @@ mod tests { ); assert!(SystemTraceConfig::load(&config).is_err()); let mut policy = watch(config.clone()); - async fn wait( - policy: &mut tokio::sync::watch::Receiver, - predicate: impl Fn(&Policy) -> bool, - ) { - tokio::time::timeout(std::time::Duration::from_secs(10), async { - loop { - if predicate(&policy.borrow_and_update()) { - return; - } - policy.changed().await.unwrap(); - } - }) - .await - .unwrap(); - } - wait( + wait_until( &mut policy, |p| matches!(p, Policy::Invalid(message) if message.contains("broken")), ) .await; std::fs::write(&target, r#"{"span_plugins":["one.mjs"]}"#).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("one.mjs")]) }) .await; std::fs::write(&target, r#"{"span_plugins":["two.mjs"]}"#).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("two.mjs")]) }) .await; std::fs::remove_file(&target).unwrap(); - wait( + wait_until( &mut policy, |p| matches!(p, Policy::Invalid(message) if message.contains("broken")), ) @@ -513,29 +460,29 @@ mod tests { let intermediate_replacement = intermediate_dir.join("replacement"); symlink(&other, &intermediate_replacement).unwrap(); std::fs::rename(&intermediate_replacement, &intermediate).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("new.mjs")]) }) .await; std::fs::write(&other, r#"{"span_plugins":["intermediate.mjs"]}"#).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("intermediate.mjs")]) }) .await; std::fs::write(&other, r#"{"span_plugins":["new.mjs"]}"#).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("new.mjs")]) }) .await; let replacement = config_dir.join("replacement"); symlink(&other, &replacement).unwrap(); std::fs::rename(&replacement, &config).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("new.mjs")]) }) .await; std::fs::write(&other, r#"{"span_plugins":["newer.mjs"]}"#).unwrap(); - wait(&mut policy, |p| { + wait_until(&mut policy, |p| { *p == Policy::Valid(vec![config_dir.join("newer.mjs")]) }) .await; @@ -563,29 +510,17 @@ mod tests { let link = tmp.path().join("config"); symlink(&first, &link).unwrap(); let mut policy = watch(link.join("trace.json")); - async fn wait(policy: &mut tokio::sync::watch::Receiver, expected: Policy) { - tokio::time::timeout(std::time::Duration::from_secs(10), async { - loop { - if *policy.borrow_and_update() == expected { - return; - } - policy.changed().await.unwrap(); - } - }) - .await - .unwrap(); - } - wait(&mut policy, Policy::Valid(vec![link.join("first.mjs")])).await; + wait_for(&mut policy, Policy::Valid(vec![link.join("first.mjs")])).await; let replacement = tmp.path().join("replacement"); symlink(&second, &replacement).unwrap(); std::fs::rename(replacement, &link).unwrap(); - wait(&mut policy, Policy::Valid(vec![link.join("second.mjs")])).await; + wait_for(&mut policy, Policy::Valid(vec![link.join("second.mjs")])).await; std::fs::write( second.join("trace.json"), r#"{"span_plugins":["updated.mjs"]}"#, ) .unwrap(); - wait(&mut policy, Policy::Valid(vec![link.join("updated.mjs")])).await; + wait_for(&mut policy, Policy::Valid(vec![link.join("updated.mjs")])).await; } #[test] From b2e83981fc3e26784df8ad0dfe666d86266ce91f Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Tue, 1 Dec 2026 23:16:26 +0800 Subject: [PATCH 12/12] Bind routing requests to a policy revision --- bt-daemon/src/pipeline/consumer.rs | 74 ++++----- bt-daemon/src/pipeline/routing.rs | 227 ++++++++++++--------------- bt-daemon/src/pipeline/submission.rs | 1 + bt-daemon/src/system_trace_config.rs | 47 ++++++ 4 files changed, 175 insertions(+), 174 deletions(-) diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 1f394a5e..bdf3e71d 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -7,7 +7,7 @@ use super::{ }; use crate::{ dispatch::Counters, - sink::{Sink, SinkFactory}, + sink::SinkFactory, wire::{RecoveryInfo, SessionConfig, SessionRoute}, AuthProvider, AuthResolveReason, }; @@ -51,17 +51,16 @@ pub(crate) struct ConsumerOptions { } impl ConsumerOptions { - async fn sink(&self, config: &SessionConfig) -> anyhow::Result { + fn sink(&self) -> anyhow::Result { let inner = self.factory.create(&self.session_id, &self.source)?; - let mut sink = RoutingSink::spawn( + Ok(RoutingSink::spawn( inner, self.source.clone(), self.session_id.clone(), self.data_dir.clone(), self.error.clone(), - ); - sink.configure(config); - Ok(sink) + self.system_policy.clone(), + )) } async fn hold(&self, pending: &mut VecDeque>, failure: &mut Failure) -> bool { let result = match pending.front_mut() { @@ -159,7 +158,7 @@ impl ConsumerOptions { Work::Flush, ) })?; - sink.flush() + sink.flush(config) .await .map_err(|error| self.routing(&error, config, attempt))?; *self.permalink.lock() = sink.permalink(); @@ -179,27 +178,13 @@ impl ConsumerOptions { } } -pub(super) fn global_plugin_digests( - policy: &crate::system_trace_config::Policy, -) -> Vec> { - match policy { - crate::system_trace_config::Policy::Valid(plugins) => plugins - .iter() - .map(|path| crate::span_processor::file_digest(path)) - .collect(), - _ => Vec::new(), - } -} - fn apply_policy( config: &watch::Sender, route_config: &Mutex, policy: &crate::system_trace_config::Policy, ) { - if let crate::system_trace_config::Policy::Valid(plugins) = policy { - let route = route_config.lock(); - let mut effective = route.clone(); - effective.span_plugins.splice(0..0, plugins.iter().cloned()); + let route = route_config.lock(); + if let Some(effective) = policy.effective_config(&route) { config.send_if_modified(|current| { if serde_json::to_value(&*current).ok() == serde_json::to_value(&effective).ok() { false @@ -236,13 +221,13 @@ impl Consumer { let mut attempts = 0; let mut recorded = None; let mut record_retry = 0; - let mut previous_policy = None; + let mut previous_revision = None; let mut deferred_replay: Option> = None; loop { let current_policy = policy.borrow_and_update().clone(); - let current_digests = global_plugin_digests(¤t_policy); - let current_revision = (current_policy.clone(), current_digests.clone()); - if previous_policy + let current_revision = current_policy.revision(); + let current_policy = current_revision.policy(); + if previous_revision .as_ref() .is_some_and(|previous| previous != ¤t_revision) && !pending.is_empty() @@ -271,7 +256,7 @@ impl Consumer { recorded = None; attempts = 0; } - previous_policy = Some(current_revision); + previous_revision = Some(current_revision.clone()); if matches!( current_policy, crate::system_trace_config::Policy::Starting @@ -281,7 +266,7 @@ impl Consumer { .is_some_and(|held| matches!(held.1, Work::Complete)) { input.pause(); - if let crate::system_trace_config::Policy::Invalid(error) = ¤t_policy { + if let crate::system_trace_config::Policy::Invalid(error) = current_policy { *options.error.lock() = Some(format!("system tracing settings: {error}")); } tokio::select! { @@ -290,7 +275,7 @@ impl Consumer { } continue; } - apply_policy(&config, &route_config, ¤t_policy); + apply_policy(&config, &route_config, current_policy); { let mut error = options.error.lock(); if error @@ -319,9 +304,7 @@ impl Consumer { result=settings.changed()=>if result.is_err() { break; }, result=policy.changed()=>if result.is_err() { break; }, } - if *policy.borrow() != current_policy - || global_plugin_digests(¤t_policy) != current_digests - { + if !current_revision.is_current(&policy) { held = Some(Box::new((failure, work))); continue; } @@ -350,12 +333,12 @@ impl Consumer { ))); continue; } - if *policy.borrow() != current_policy { + if &*policy.borrow() != current_policy { held = Some(Box::new((failure, work))); continue; } route_config.lock().auth = current.auth.clone(); - apply_policy(&config, &route_config, ¤t_policy); + apply_policy(&config, &route_config, current_policy); current = config.borrow().clone(); } match options @@ -391,12 +374,14 @@ impl Consumer { None => return Ok(None), } }; - if *policy.borrow() != current_policy - || global_plugin_digests(¤t_policy) != current_digests - { + if !current_revision.is_current(&policy) { return Ok(Some(false)); } - let current = settings.borrow_and_update().clone(); + settings.mark_unchanged(); + let Some(current) = current_policy.effective_config(&route_config.lock()) + else { + return Ok(Some(false)); + }; let ops = delivery .as_ref() .map(Delivery::value) @@ -404,18 +389,12 @@ impl Consumer { .map_or(&[][..], Vec::as_slice); let result = async { if sink.is_none() { - sink = Some(options.sink(¤t).await?); + sink = Some(options.sink()?); } let routing = sink .as_mut() .ok_or_else(|| anyhow::anyhow!("configured sink is missing"))?; - routing.configure(¤t); - routing.guard_policy( - policy.clone(), - current_policy.clone(), - current_digests, - ); - routing.emit_shared(ops).await + routing.emit(¤t, current_revision.clone(), ops).await } .await; if result @@ -511,6 +490,7 @@ impl Consumer { mod tests { use super::*; use crate::{ + sink::Sink, translate::{SpanOp, SpanRow}, wire::BackendAuth, {collections::SessionStorage, pipeline::cursor::Cursor}, diff --git a/bt-daemon/src/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index be412be3..a9859c99 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -4,39 +4,33 @@ use super::plugins::{PluginOutcome, Plugins}; use super::prepare::Prepare; use super::recovery::{RetryCondition, RouteFailure}; use super::submission::{ - Input as SubmissionInput, Operation, Outcome as SubmissionOutcome, Submission, + Input as SubmissionInput, Operation, Outcome as SubmissionOutcome, State, Submission, }; use super::{Completion, Stage}; -use crate::{sink::Sink, translate::SpanOp, wire::SessionConfig}; +use crate::{ + sink::Sink, + system_trace_config::{Policy, PolicyRevision}, + translate::SpanOp, + wire::SessionConfig, +}; use parking_lot::Mutex; use std::{path::PathBuf, sync::Arc}; -use tokio::sync::{mpsc, oneshot}; +use tokio::sync::{mpsc, oneshot, watch}; + +enum RouteOperation { + Emit(Vec, PolicyRevision), + Flush, +} struct Request { config: SessionConfig, - operation: Operation, - policy_guard: Option, + operation: RouteOperation, reply: oneshot::Sender, } -#[derive(Clone)] -struct PolicyGuard { - receiver: tokio::sync::watch::Receiver, - policy: crate::system_trace_config::Policy, - digests: Vec>, -} - -impl PolicyGuard { - fn changed(&self) -> bool { - *self.receiver.borrow() != self.policy - || super::consumer::global_plugin_digests(&self.policy) != self.digests - } -} struct Response { result: anyhow::Result, - pending: bool, - pending_span_ids: Option>, - permalink: Option, + state: State, } struct Forward; @@ -50,12 +44,8 @@ impl Completion for Forward { pub(crate) struct RoutingSink { tx: mpsc::Sender>, task: tokio::task::JoinHandle<()>, - config: Option, - policy_guard: Option, - pending: bool, - pending_span_ids: Option>, + state: State, deferred: Vec, - permalink: Option, } impl RoutingSink { @@ -65,6 +55,7 @@ impl RoutingSink { session_id: String, data_dir: PathBuf, last_error: Arc>>, + policy: watch::Receiver, ) -> Self { let (tx, mut rx) = mpsc::channel::>(16); let task = tokio::spawn(async move { @@ -75,7 +66,7 @@ impl RoutingSink { while let Ok(Some(delivery)) = InputPort::receive(&mut rx).await { let request = delivery.value(); let (result, state) = match &request.operation { - Operation::Emit(ops) => 'emit: { + RouteOperation::Emit(ops, revision) => 'emit: { let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); @@ -132,12 +123,7 @@ impl RoutingSink { } } super::prepare::unique_tags(&mut prepared); - if !stopped - && request - .policy_guard - .as_ref() - .is_some_and(PolicyGuard::changed) - { + if !stopped && !revision.is_current(&policy) { break 'emit ( Err(anyhow::Error::new(RouteFailure { cause: anyhow::anyhow!( @@ -186,7 +172,7 @@ impl RoutingSink { (Ok(emitted), None) => (Ok(emitted), state), } } - Operation::Flush => { + RouteOperation::Flush => { let submit_input = SubmissionInput { config: request.config.clone(), operation: Operation::Flush, @@ -224,43 +210,22 @@ impl RoutingSink { continue; } }; - let _ = request.reply.send(Response { - result, - pending: state.pending, - pending_span_ids: state.pending_span_ids, - permalink: state.permalink, - }); + let _ = request.reply.send(Response { result, state }); } }); Self { tx, task, - config: None, - policy_guard: None, - pending: false, - pending_span_ids: None, + state: State::default(), deferred: Vec::new(), - permalink: None, } } - pub fn guard_policy( - &mut self, - receiver: tokio::sync::watch::Receiver, - policy: crate::system_trace_config::Policy, - digests: Vec>, - ) { - self.policy_guard = Some(PolicyGuard { - receiver, - policy, - digests, - }); - } - /// Return the original operations that have not reached the sink yet. /// Unknown sink state cannot safely distinguish accepted from deferred. pub fn deferred_ops(&self) -> Option> { - self.pending_span_ids + self.state + .pending_span_ids .as_ref() .map(|_| self.deferred.clone()) } @@ -279,18 +244,20 @@ impl RoutingSink { } } - async fn request(&mut self, operation: Operation) -> anyhow::Result { - let config = self - .config - .clone() - .ok_or_else(|| anyhow::anyhow!("route is not configured"))?; + async fn request( + &mut self, + config: &SessionConfig, + operation: RouteOperation, + ) -> anyhow::Result { let (reply, receive) = oneshot::channel(); - let delivery = Delivery::new(operation, Forward).map(|operation| Request { - config, - operation, - policy_guard: self.policy_guard.clone(), - reply, - }); + let delivery = Delivery::new( + Request { + config: config.clone(), + operation, + reply, + }, + Forward, + ); // Retain ownership on a failed send; no upstream completion is implied. if let Err(undelivered) = OutputPort::send(&mut self.tx, delivery).await { let _ = undelivered.value(); @@ -299,51 +266,41 @@ impl RoutingSink { let response = receive .await .map_err(|_| anyhow::anyhow!("routing actor dropped its reply"))?; - self.pending = response.pending; - self.pending_span_ids = response.pending_span_ids; - self.permalink = response.permalink; + self.state = response.state; response.result } -} -#[async_trait::async_trait] -impl Sink for RoutingSink { - fn configure(&mut self, config: &SessionConfig) { - self.config = Some(config.clone()); - } - async fn emit(&mut self, ops: &[SpanOp]) -> anyhow::Result { - self.emit_shared( - &ops.iter() - .cloned() - .map(super::live::SharedOp::new) - .collect::>(), - ) - .await - } - async fn emit_shared(&mut self, ops: &[super::live::SharedOp]) -> anyhow::Result { - let count = self.request(Operation::Emit(ops.to_vec())).await?; - if self.pending_span_ids.is_some() { + pub async fn emit( + &mut self, + config: &SessionConfig, + revision: PolicyRevision, + ops: &[super::live::SharedOp], + ) -> anyhow::Result { + let count = self + .request(config, RouteOperation::Emit(ops.to_vec(), revision)) + .await?; + if self.state.pending_span_ids.is_some() { self.deferred.extend_from_slice(ops); } Ok(count) } - async fn flush(&mut self) -> anyhow::Result<()> { - self.request(Operation::Flush).await?; - if let Some(ids) = &self.pending_span_ids { + pub async fn flush(&mut self, config: &SessionConfig) -> anyhow::Result<()> { + self.request(config, RouteOperation::Flush).await?; + if let Some(ids) = &self.state.pending_span_ids { self.deferred.retain(|op| { let (SpanOp::Insert(row) | SpanOp::Merge(row)) = op.as_ref(); ids.contains(&row.span_id) }); - } else if !self.pending { + } else if !self.state.pending { self.deferred.clear(); } Ok(()) } - fn has_pending_delivery(&self) -> bool { - self.pending + pub fn has_pending_delivery(&self) -> bool { + self.state.pending } - fn permalink(&self) -> Option { - self.permalink.clone() + pub fn permalink(&self) -> Option { + self.state.permalink.clone() } } @@ -373,8 +330,8 @@ mod tests { let plugin = tmp.path().join("global.mjs"); std::fs::write(&plugin, "export default span => span;").unwrap(); let policy = crate::system_trace_config::Policy::Valid(vec![plugin.clone()]); - let digests = super::super::consumer::global_plugin_digests(&policy); - let (_sender, receiver) = tokio::sync::watch::channel(policy.clone()); + let (_sender, receiver) = watch::channel(policy.clone()); + let revision = policy.revision(); let emitted = Arc::new(AtomicU64::new(0)); let mut sink = RoutingSink::spawn( Box::new(CountingSink(emitted.clone())), @@ -382,6 +339,7 @@ mod tests { "session".into(), tmp.path().into(), Arc::new(Mutex::new(None)), + receiver, ); let config = SessionRoute { span_plugins: vec![plugin.clone()], @@ -394,11 +352,15 @@ mod tests { org_name: None, org_id: None, }); - sink.configure(&config); - sink.guard_policy(receiver, policy, digests); std::fs::write(&plugin, replacement).unwrap(); let error = sink - .emit(&[SpanOp::Insert(SpanRow::default())]) + .emit( + &config, + revision, + &[super::super::live::SharedOp::new(SpanOp::Insert( + SpanRow::default(), + ))], + ) .await .unwrap_err(); assert_eq!(emitted.load(Ordering::SeqCst), 0); @@ -434,6 +396,7 @@ mod tests { "session".into(), tmp.path().into(), error.clone(), + crate::system_trace_config::fixed(Vec::new()), ); let mut config = SessionRoute { span_plugins: vec![plugin], @@ -446,22 +409,25 @@ mod tests { org_name: None, org_id: None, }); - sink.configure(&config); + let revision = Policy::Valid(Vec::new()).revision(); let op = |name: &str| { - SpanOp::Insert(SpanRow { + super::super::live::SharedOp::new(SpanOp::Insert(SpanRow { name: name.into(), ..Default::default() - }) + })) }; assert!(sink - .emit(&[op("allowed"), op("private"), op("later")]) + .emit( + &config, + revision.clone(), + &[op("allowed"), op("private"), op("later")] + ) .await .unwrap_err() .is::()); config.span_plugins.clear(); - sink.configure(&config); assert!(sink - .emit(&[op("future")]) + .emit(&config, revision.clone(), &[op("future")]) .await .unwrap_err() .is::()); @@ -495,6 +461,7 @@ mod tests { "owned".into(), tmp.path().into(), Arc::new(Mutex::new(None)), + crate::system_trace_config::fixed(Vec::new()), ); sink.shutdown().await; assert!(dropped.load(Ordering::SeqCst)); @@ -513,33 +480,39 @@ mod tests { "partial".into(), tmp.path().into(), error.clone(), + crate::system_trace_config::fixed(Vec::new()), ); - sink.configure( - &SessionRoute { - span_plugins: vec![plugin], - ..SessionRoute::default() - } - .with_auth(BackendAuth { - token: "test".into(), - api_url: None, - app_url: None, - org_name: None, - org_id: None, - }), - ); + let config = SessionRoute { + span_plugins: vec![plugin], + ..SessionRoute::default() + } + .with_auth(BackendAuth { + token: "test".into(), + api_url: None, + app_url: None, + org_name: None, + org_id: None, + }); + let revision = Policy::Valid(Vec::new()).revision(); let op = |name: &str| { - SpanOp::Insert(SpanRow { + super::super::live::SharedOp::new(SpanOp::Insert(SpanRow { span_id: name.into(), name: name.into(), ..SpanRow::default() - }) + })) }; - let failure = sink.emit(&[op("accept"), op("reject")]).await.unwrap_err(); + let failure = sink + .emit(&config, revision.clone(), &[op("accept"), op("reject")]) + .await + .unwrap_err(); let first = failure.downcast_ref::().unwrap(); assert_eq!(first.emitted, 1); assert!(first.report); assert_eq!(emitted.load(Ordering::Relaxed), 1); - let failure = sink.emit(&[op("accept")]).await.unwrap_err(); + let failure = sink + .emit(&config, revision.clone(), &[op("accept")]) + .await + .unwrap_err(); let cached = failure.downcast_ref::().unwrap(); assert_eq!(cached.emitted, 0); assert!( diff --git a/bt-daemon/src/pipeline/submission.rs b/bt-daemon/src/pipeline/submission.rs index a7c657e7..b0c3e139 100644 --- a/bt-daemon/src/pipeline/submission.rs +++ b/bt-daemon/src/pipeline/submission.rs @@ -12,6 +12,7 @@ pub(crate) struct Input { pub operation: Operation, } +#[derive(Default)] pub(crate) struct State { pub pending: bool, pub pending_span_ids: Option>, diff --git a/bt-daemon/src/system_trace_config.rs b/bt-daemon/src/system_trace_config.rs index d07691cc..a78e77a8 100644 --- a/bt-daemon/src/system_trace_config.rs +++ b/bt-daemon/src/system_trace_config.rs @@ -126,7 +126,54 @@ pub(crate) enum Policy { Invalid(String), } +#[derive(Clone, PartialEq, Eq)] +pub(crate) struct PolicyRevision { + policy: Policy, + digests: Vec>, +} + +impl PolicyRevision { + pub fn policy(&self) -> &Policy { + &self.policy + } + + pub fn is_current(&self, policy: &tokio::sync::watch::Receiver) -> bool { + // Release the watch lock before reading plugin files. + let same_policy = *policy.borrow() == self.policy; + same_policy && self.policy.plugin_digests() == self.digests + } +} + impl Policy { + pub fn revision(self) -> PolicyRevision { + PolicyRevision { + digests: self.plugin_digests(), + policy: self, + } + } + + fn plugin_digests(&self) -> Vec> { + match self { + Self::Valid(plugins) => plugins + .iter() + .map(|path| crate::span_processor::file_digest(path)) + .collect(), + _ => Vec::new(), + } + } + + pub fn effective_config( + &self, + route: &crate::wire::SessionConfig, + ) -> Option { + let Self::Valid(plugins) = self else { + return None; + }; + let mut effective = route.clone(); + effective.span_plugins.splice(0..0, plugins.iter().cloned()); + Some(effective) + } + fn read(path: &Path) -> Self { match SystemTraceConfig::load(path) { Ok(config) => Self::Valid(config.span_plugins),