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 56f728d7..198d868d 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" @@ -59,8 +60,11 @@ 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"] } +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..f4cf5db7 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -92,12 +92,17 @@ 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. 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. -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,13 +138,37 @@ 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. +### Global span plugins + +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): + +```json +{ + "span_plugins": ["/opt/company/braintrust/redact.mjs"] +} +``` + +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; 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. + ### JavaScript span plugins `--plugin PATH` registers a synchronous ES module that transforms each 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 @@ -200,10 +229,10 @@ 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. +# sanitize-history.mjs runs after any global plugins for this import. bt trace import codex SESSION_ID --plugin ./sanitize-history.mjs ``` @@ -221,8 +250,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 4ac51171..f6c9ec6e 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 global_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: {}\nGlobal span plugins (configured): {}", + self.system_settings_path.display(), + match &self.global_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..ba81ecf1 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"), + global_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..cfbdd32b 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 system_policy: tokio::sync::watch::Receiver, 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, + system_policy: options.system_policy, config, route: options.route, counters: counters.clone(), diff --git a/bt-daemon/src/lib.rs b/bt-daemon/src/lib.rs index 10d080ae..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; @@ -40,6 +41,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..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, }; @@ -21,6 +21,7 @@ use tokio::sync::{watch, Notify}; enum Work { Resubmit, + ReplayDeferred, Flush, Complete, } @@ -30,12 +31,15 @@ pub(crate) struct Consumer { task: Mutex>>, config: watch::Sender, stop: Arc, + 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 system_policy: watch::Receiver, pub route: SessionRoute, pub config: watch::Sender, pub counters: Arc, @@ -47,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() { @@ -106,7 +109,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)) } @@ -137,13 +140,14 @@ impl ConsumerOptions { work: Work, ) -> Result { match work { - Work::Resubmit => { - // Dropping unresolved obligations asks their source to replay. - // Recreate the consumed SDK batch too. + Work::Resubmit | Work::ReplayDeferred => { if let Some(previous) = sink.take() { previous.shutdown().await; } - pending.clear(); + // A full resubmission asks the source to replay abandoned receipts. + if matches!(work, Work::Resubmit) { + pending.clear(); + } return Ok(false); } Work::Flush => { @@ -154,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(); @@ -174,27 +178,113 @@ impl ConsumerOptions { } } +fn apply_policy( + config: &watch::Sender, + route_config: &Mutex, + policy: &crate::system_trace_config::Policy, +) { + 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 + } else { + *current = effective; + true + } + }); + } +} + impl Consumer { pub fn spawn( mut input: Box>>, options: ConsumerOptions, ) -> Arc { let config = options.config.clone(); + 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(), + system_policy: options.system_policy.clone(), + 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_revision = None; + let mut deferred_replay: Option> = None; loop { + let current_policy = policy.borrow_and_update().clone(); + 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() + && !held + .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; + } + 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; + } + previous_revision = Some(current_revision.clone()); + if matches!( + 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) = current_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, current_policy); + { + let mut error = options.error.lock(); + if error + .as_ref() + .is_some_and(|message| message.starts_with("system tracing settings:")) + { + *error = held.as_ref().map(|held| held.0.message()); + } + } if let Some(waiting) = held.take() { let (mut failure, work) = *waiting; let mut reported = failure.clone(); @@ -212,6 +302,11 @@ 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; }, + } + if !current_revision.is_current(&policy) { + held = Some(Box::new((failure, work))); + continue; } let mut current = settings.borrow_and_update().clone(); if recorded.as_ref() != Some(&reported) @@ -238,7 +333,13 @@ impl Consumer { ))); continue; } - config.send_replace(current.clone()); + if &*policy.borrow() != current_policy { + held = Some(Box::new((failure, work))); + continue; + } + route_config.lock().auth = current.auth.clone(); + apply_policy(&config, &route_config, current_policy); + current = config.borrow().clone(); } match options .finish(&mut pending, &mut sink, ¤t, attempts, work) @@ -255,73 +356,95 @@ 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)) }; - }, + let delivery = if replaying { + None + } else { + 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), + } }; - 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); + if !current_revision.is_current(&policy) { + return Ok(Some(false)); + } + settings.mark_unchanged(); + let Some(current) = current_policy.effective_config(&route_config.lock()) + else { + return Ok(Some(false)); }; - let current = settings.borrow_and_update().clone(); - let ops = delivery.value().as_slice(); - let mut stopped = false; + let ops = delivery + .as_ref() + .map(Delivery::value) + .or(deferred_replay.as_ref()) + .map_or(&[][..], Vec::as_slice); let result = async { if sink.is_none() { - sink = - Some(options.sink(¤t).await.map_err(|error| { - options.routing(&error, ¤t, attempts) - })?); - } - let routing = sink.as_mut().ok_or_else(|| { - options.storage( - &anyhow::anyhow!("configured sink is missing"), - attempts, - Work::Resubmit, - ) - })?; - routing.configure(¤t); - 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)) - } + sink = Some(options.sink()?); } + let routing = sink + .as_mut() + .ok_or_else(|| anyhow::anyhow!("configured sink is missing"))?; + routing.emit(¤t, current_revision.clone(), 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, @@ -347,13 +470,12 @@ impl Consumer { handle } pub fn configure(&self, config: SessionConfig) { - self.config.send_if_modified(|current| { - if serde_json::to_value(&*current).ok() == serde_json::to_value(&config).ok() { - return false; - } - *current = config; - true - }); + *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(); @@ -368,6 +490,7 @@ impl Consumer { mod tests { use super::*; use crate::{ + sink::Sink, translate::{SpanOp, SpanRow}, wire::BackendAuth, {collections::SessionStorage, pipeline::cursor::Cursor}, @@ -383,6 +506,51 @@ mod tests { defer_until: AtomicU64, } struct Factory(Arc); + + struct ReplayFactory { + creations: AtomicU64, + ready: Arc, + entered: Arc, + } + struct ReplaySink { + initial: bool, + ready: Arc, + entered: Arc, + } + 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(), + })) + } + } + #[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(); + 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, @@ -438,6 +606,7 @@ mod tests { session_id: "test".into(), version: "test".into(), data_dir: dir.into(), + system_policy: crate::system_trace_config::fixed(Vec::new()), route: route.clone(), config: watch::channel(route.with_auth(BackendAuth { token: "never-persist-this".into(), @@ -500,6 +669,220 @@ 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.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; + 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 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 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(); + 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); + 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() + .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(); @@ -648,6 +1031,42 @@ mod tests { consumer.shutdown().await; } + #[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 + .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(), + }); + 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(); + 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 head_write_recovery_retries_only_completion() { let tmp = tempfile::tempdir().unwrap(); @@ -672,6 +1091,177 @@ 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(); + 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(); @@ -736,6 +1326,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.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; + 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.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(), + 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/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/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index a3e06b5c..a9859c99 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -4,23 +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, + operation: RouteOperation, reply: oneshot::Sender, } + struct Response { result: anyhow::Result, - pending: bool, - permalink: Option, + state: State, } struct Forward; @@ -34,9 +44,8 @@ impl Completion for Forward { pub(crate) struct RoutingSink { tx: mpsc::Sender>, task: tokio::task::JoinHandle<()>, - config: Option, - pending: bool, - permalink: Option, + state: State, + deferred: Vec, } impl RoutingSink { @@ -46,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 { @@ -56,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) => { + RouteOperation::Emit(ops, revision) => 'emit: { let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); @@ -113,6 +123,19 @@ impl RoutingSink { } } super::prepare::unique_tags(&mut prepared); + if !stopped && !revision.is_current(&policy) { + break 'emit ( + Err(anyhow::Error::new(RouteFailure { + cause: anyhow::anyhow!( + "global tracing policy changed during processing" + ), + retry: RetryCondition::Transient, + emitted: 0, + report: false, + })), + submission.state(), + ); + } let submit_input = SubmissionInput { config: request.config.clone(), operation: Operation::Emit(prepared), @@ -149,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, @@ -187,22 +210,26 @@ impl RoutingSink { continue; } }; - let _ = request.reply.send(Response { - result, - pending: state.pending, - permalink: state.permalink, - }); + let _ = request.reply.send(Response { result, state }); } }); Self { tx, task, - config: None, - pending: false, - permalink: None, + state: State::default(), + deferred: Vec::new(), } } + /// 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.state + .pending_span_ids + .as_ref() + .map(|_| self.deferred.clone()) + } + pub async fn shutdown(self) { let Self { tx, mut task, .. } = self; drop(tx); @@ -217,17 +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, - 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(); @@ -236,37 +266,41 @@ impl RoutingSink { let response = receive .await .map_err(|_| anyhow::anyhow!("routing actor dropped its reply"))?; - self.pending = response.pending; - 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 { - self.request(Operation::Emit(ops.to_vec())).await + 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.map(|_| ()) + 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.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() } } @@ -291,6 +325,64 @@ mod tests { } } + 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(); + let policy = crate::system_trace_config::Policy::Valid(vec![plugin.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())), + "debug".into(), + "session".into(), + tmp.path().into(), + Arc::new(Mutex::new(None)), + receiver, + ); + 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, + }); + std::fs::write(&plugin, replacement).unwrap(); + let error = sink + .emit( + &config, + revision, + &[super::super::live::SharedOp::new(SpanOp::Insert( + SpanRow::default(), + ))], + ) + .await + .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 error = + emit_with_changed_policy("export default span => ({ ...span, name: 'new' });").await; + assert!(error.to_string().contains("global tracing policy changed")); + } + #[tokio::test] async fn stop_discards_prepared_batch_and_stays_latched_after_reconfiguration() { let tmp = tempfile::tempdir().unwrap(); @@ -304,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], @@ -316,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::()); @@ -365,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)); @@ -383,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 c106f58d..b0c3e139 100644 --- a/bt-daemon/src/pipeline/submission.rs +++ b/bt-daemon/src/pipeline/submission.rs @@ -12,8 +12,10 @@ pub(crate) struct Input { pub operation: Operation, } +#[derive(Default)] pub(crate) struct State { pub pending: bool, + pub pending_span_ids: Option>, pub permalink: Option, } @@ -97,9 +99,10 @@ impl Submission { Self { sink } } - fn state(&self) -> State { + 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/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/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 5b56bf94..f2ab900a 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, + crate::system_trace_config::fixed(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, + crate::system_trace_config::fixed(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..339ca4a5 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, + system_policy: tokio::sync::watch::Receiver, translators: Arc, sink_factory: Arc, auth_provider: Option>, @@ -155,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) + Self::new_with_startup( + opts, + data_dir, + None, + maintenance::RETENTION, + crate::system_trace_config::fixed(Vec::new()), + ) } fn new_with_startup( @@ -163,6 +170,7 @@ impl Daemon { data_dir: PathBuf, startup: Option>, retention: Duration, + 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()); @@ -170,6 +178,7 @@ impl Daemon { version: opts.version, data_dir, retention, + system_policy, translators: opts.translators, sink_factory: opts.sink_factory, auth_provider: opts.auth_provider, @@ -244,6 +253,16 @@ 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_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)?; @@ -272,7 +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); + 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/server/sessions.rs b/bt-daemon/src/server/sessions.rs index 38321b35..1d3065f0 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(), + system_policy: self.system_policy.clone(), }, self.sink_factory.clone(), ); diff --git a/bt-daemon/src/settings.rs b/bt-daemon/src/settings.rs index 8954ce06..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,16 +154,12 @@ impl AgentSettings { } else { Self::default() }; - let inherit_plugins = object - .get("inherit_plugins") - .map(|value| { - value.as_bool().ok_or_else(|| { - anyhow::anyhow!("inherit_plugins in {} must be a boolean", path.display()) - }) - }) - .transpose()? - .unwrap_or(true); - if !inherit_plugins { + 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(); } @@ -624,6 +659,60 @@ 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":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/setup/mod.rs b/bt-daemon/src/setup/mod.rs index 43cd3175..6e289b7a 100644 --- a/bt-daemon/src/setup/mod.rs +++ b/bt-daemon/src/setup/mod.rs @@ -174,11 +174,13 @@ 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 { + // 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), + ); } if !plugins.is_empty() { let route = settings @@ -485,6 +487,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,11 +497,13 @@ mod tests { value["route"]["span_plugins"], serde_json::json!(["plugins/redact.mjs"]) ); + assert_eq!(value["inherit_user_plugins"], false); 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()); 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 diff --git a/bt-daemon/src/span_processor.rs b/bt-daemon/src/span_processor.rs index 2a60369a..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}; @@ -36,7 +36,18 @@ struct PluginTimeout { } thread_local! { - static ENGINE: RefCell> = const { RefCell::new(None) }; + 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)] @@ -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(), @@ -341,88 +352,97 @@ 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"))?; - for plugin in plugins { - 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; + ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { + // 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(), }) } @@ -456,9 +476,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,45 +489,52 @@ 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_mut(|engines| { let mut reached_failure = false; - paths + let result = 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 { file_digest(path) } }) - .collect() + .collect(); + limit_engines(engines); + result }) } /// Compile each module and verify that it default-exports a function. Explicit /// CLI commands call this before persisting or launching with a plugin chain. pub fn validate(plugins: &[PathBuf]) -> 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"))?; - for plugin in plugins { - engine.load(plugin)?; - } - Ok(()) + ENGINES.with_borrow_mut(|engines| -> anyhow::Result<()> { + 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)?; + } + Ok(()) + })(); + limit_engines(engines); + result }) } @@ -539,6 +566,105 @@ 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(); + 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 new file mode 100644 index 00000000..a78e77a8 --- /dev/null +++ b/bt-daemon/src/system_trace_config.rs @@ -0,0 +1,589 @@ +//! 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::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) + }; + 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 { + if !raw.is_null() { + CoTaskMemFree(raw.cast()); + } + if init >= 0 { + CoUninitialize(); + } + } + result + } + #[cfg(not(windows))] + { + Ok(PathBuf::from("/etc/braintrust/trace.json")) + } +} + +impl SystemTraceConfig { + pub fn load(path: &Path) -> anyhow::Result { + 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() { + 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(|| { + 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 global plugin path in {}", path.display()); + } + if plugin.is_relative() { + *plugin = directory.join(&*plugin); + } + } + Ok(config) + } +} + +/// 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), +} + +#[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), + Err(error) => Self::Invalid(format!("{error:#}")), + } + } +} + +// 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()) +} + +// 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) + }; + let remainder = current.strip_prefix(&link)?; + current = if remainder.as_os_str().is_empty() { + target + } else { + target.join(remainder) + }; + } +} + +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 { + let (sender, receiver) = tokio::sync::watch::channel(Policy::Starting); + tokio::spawn(async move { + 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)); + tokio::spawn(async move { + sender.closed().await; + }); + receiver +} + +#[cfg(test)] +mod tests { + use super::*; + + async fn wait_until( + policy: &mut 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() { + 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"), "{}").unwrap(); + std::fs::write(second.join("trace.json"), "{}").unwrap(); + let link = tmp.path().join("config"); + symlink(&first, &link).unwrap(); + let path = link.join("trace.json"); + let old_locations = policy_locations(&path).unwrap(); + let replacement = tmp.path().join("replacement"); + symlink(&second, &replacement).unwrap(); + std::fs::rename(replacement, &link).unwrap(); + + assert_eq!(read_watched_policy(&path, &old_locations).unwrap(), None); + let current_locations = policy_locations(&path).unwrap(); + assert_eq!( + read_watched_policy(&path, ¤t_locations).unwrap(), + Some(Policy::Valid(Vec::new())) + ); + } + #[tokio::test] + async fn watches_new_directories_and_atomic_file_replacements() { + let tmp = tempfile::tempdir().unwrap(); + let directory = tmp.path().join("system"); + let path = directory.join("trace.json"); + let mut policy = watch(path.clone()); + 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; + } + + #[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"); + 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(); + 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()); + 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_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_until(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("two.mjs")]) + }) + .await; + std::fs::remove_file(&target).unwrap(); + wait_until( + &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 intermediate_replacement = intermediate_dir.join("replacement"); + symlink(&other, &intermediate_replacement).unwrap(); + std::fs::rename(&intermediate_replacement, &intermediate).unwrap(); + 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_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_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_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_until(&mut policy, |p| { + *p == Policy::Valid(vec![config_dir.join("newer.mjs")]) + }) + .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")); + 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_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_for(&mut policy, Policy::Valid(vec![link.join("updated.mjs")])).await; + } + + #[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_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 d54137a5..f7ae4961 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 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)) + { + 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(), + 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(