diff --git a/bt-daemon/README.md b/bt-daemon/README.md index f58e1eca..754ae95e 100644 --- a/bt-daemon/README.md +++ b/bt-daemon/README.md @@ -96,7 +96,7 @@ list and use only the `--plugin` flags passed to their command. 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 -`{ operation, source, session_id, env }`, and must return a JSON-compatible span +`{ operation, source, session_id, env, recovering_plugin_hold }`, and must return a JSON-compatible span object. Span, root, and parent identities cannot be changed: ```js @@ -202,6 +202,17 @@ export default function guard(span) { } ``` +`context.recovering_plugin_hold` is a boolean indicating that the current +batch is being retried after a durable plugin failure, including timeouts. +It is false for ordinary delivery and remains true until the held work is +resolved. Older runtimes omit this field. To migrate a privacy filter without +releasing previously held operations, deploy a runtime supporting this field +first, then update the filter to throw `StopTracingError` immediately when it +is true, before evaluating any relaxed rules. Keep the old strict rules when +the field is absent. This conservatively discards every previously held route, +including holds caused by unrelated plugin errors or timeouts; it does not +retract already delivered spans or erase native transcripts. + Plugin failures are deduplicated in the daemon's private local state, including the raw QuickJS exception and stack. Inspect them with: diff --git a/bt-daemon/src/command_output.rs b/bt-daemon/src/command_output.rs index 58d28ced..3b4bd7f1 100644 --- a/bt-daemon/src/command_output.rs +++ b/bt-daemon/src/command_output.rs @@ -572,6 +572,7 @@ mod tests { route: None, recovery: Some(crate::wire::RecoveryInfo { stage: "plugin".into(), + recovering_plugin_hold: true, position: 1, reason: "deadline".into(), retry: "bounded retry".into(), diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index 0ce9c785..ffa04091 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -60,6 +60,11 @@ impl ConsumerOptions { Ok(sink) } async fn hold(&self, pending: &mut VecDeque>, failure: &mut Failure) -> bool { + failure.recovering_plugin_hold |= self + .recovery + .lock() + .as_ref() + .is_some_and(|recovery| recovery.recovering_plugin_hold); let result = match pending.front_mut() { Some(delivery) => delivery.failed(failure).await, None => Ok(()), // Input errors are reported by the source itself. @@ -287,6 +292,13 @@ impl Consumer { ) })?; routing.configure(¤t); + routing.set_recovering_plugin_hold( + options + .recovery + .lock() + .as_ref() + .is_some_and(|recovery| recovery.recovering_plugin_hold), + ); match routing.emit_shared(ops).await { Err(error) if error.is::() => { // Never resubmit after the signal, including when @@ -296,6 +308,7 @@ impl Consumer { tokio::time::sleep(std::time::Duration::from_millis(250)).await; } *options.error.lock() = None; + *options.recovery.lock() = None; stopped = true; Ok(0) } @@ -794,6 +807,80 @@ mod tests { healthy.shutdown().await; } + #[tokio::test] + async fn prior_plugin_hold_is_visible_on_restart_and_can_be_discarded() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("spans.sqlite"); + let plugin = tmp.path().join("guard.mjs"); + std::fs::write(&plugin, "export default () => { throw new Error('held'); }").unwrap(); + let journal = SpanJournal::open(&path).await.unwrap(); + let route = SessionRoute { + span_plugins: vec![plugin.clone()], + ..Default::default() + }; + let healthy_route = SessionRoute::default(); + let stopped_cursor = journal.subscribe(&route, 0).await.unwrap(); + journal.subscribe(&healthy_route, 0).await.unwrap(); + stored(&journal).await; + let record = Arc::new(Recording::default()); + let (consumer, _, error) = + spawn(stopped_cursor, options(tmp.path(), &route, record.clone())); + wait_for(|| error.lock().is_some()).await; + consumer.shutdown().await; + journal.close().await.unwrap(); + + std::fs::write(&plugin, "export default (span, context) => { if (context.recovering_plugin_hold) throw new StopTracingError(); return span; }").unwrap(); + let journal = SpanJournal::open(&path).await.unwrap(); + let opts = options(tmp.path(), &route, record.clone()); + let recovery = opts.recovery.clone(); + let (consumer, progress, _) = spawn(journal.subscribe(&route, 0).await.unwrap(), opts); + let healthy_record = Arc::new(Recording::default()); + let (healthy, healthy_progress, _) = spawn( + journal.subscribe(&healthy_route, 0).await.unwrap(), + options(tmp.path(), &healthy_route, healthy_record.clone()), + ); + wait_for(|| progress.completed() == i64::MAX as u64 && healthy_progress.completed() == 1) + .await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 0); + assert_eq!(healthy_record.accepted.load(Ordering::SeqCst), 1); + assert!(recovery.lock().is_none()); + journal.begin(11, true).await.unwrap(); + journal + .append( + 11, + &[SpanOp::Insert(SpanRow { + span_id: "later".into(), + root_span_id: "later".into(), + name: "later".into(), + end_ms: Some(2), + ..Default::default() + })], + ) + .await + .unwrap(); + journal.commit(11).await.unwrap(); + wait_for(|| healthy_progress.completed() == 2).await; + assert_eq!(record.submitted.load(Ordering::SeqCst), 0); + assert_eq!(healthy_record.accepted.load(Ordering::SeqCst), 2); + assert_eq!(progress.pending(), 0); + consumer.shutdown().await; + healthy.shutdown().await; + std::fs::write(&plugin, "export default span => span").unwrap(); + let opts = options(tmp.path(), &route, record.clone()); + let mut input = journal + .subscribe(&route, 0) + .await + .unwrap() + .into_input( + opts.config.subscribe(), + "test".into(), + opts.error, + opts.recovery, + ) + .input; + assert!(input.receive().await.unwrap().is_none()); + } + #[tokio::test] async fn unauthorized_delivery_refreshes_credentials_at_the_same_head() { let tmp = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/pipeline/journal.rs b/bt-daemon/src/pipeline/journal.rs index 4e8cf3a8..ae018444 100644 --- a/bt-daemon/src/pipeline/journal.rs +++ b/bt-daemon/src/pipeline/journal.rs @@ -2241,6 +2241,7 @@ mod tests { let cursor = journal.subscribe(&original, 0).await.unwrap(); let failure = Failure { boundary: Boundary::Sink, + recovering_plugin_hold: false, position: 1, through: None, reason: "rejected row".into(), diff --git a/bt-daemon/src/pipeline/plugins.rs b/bt-daemon/src/pipeline/plugins.rs index 2b75de8d..00e6201e 100644 --- a/bt-daemon/src/pipeline/plugins.rs +++ b/bt-daemon/src/pipeline/plugins.rs @@ -14,6 +14,7 @@ pub(crate) struct Plugins { paths: Vec, pub source: String, pub session_id: String, + pub recovering_plugin_hold: bool, blocked: Option<(Vec, PluginRejected)>, } @@ -40,6 +41,7 @@ impl Plugins { Self { paths: Vec::new(), source: source.into(), + recovering_plugin_hold: false, session_id: session_id.into(), blocked: None, } @@ -80,7 +82,13 @@ impl Stage for Plugins { } } self.blocked = None; - match span_processor::process_isolated(&self.paths, input, &self.source, &self.session_id) { + match span_processor::process_isolated( + &self.paths, + input, + &self.source, + &self.session_id, + self.recovering_plugin_hold, + ) { Ok(result) => match (result.op, result.failure) { (_, Some(failure)) => { let digest = span_processor::failed_digest(&failure.path); diff --git a/bt-daemon/src/pipeline/recovery.rs b/bt-daemon/src/pipeline/recovery.rs index b7111574..12fa5c8c 100644 --- a/bt-daemon/src/pipeline/recovery.rs +++ b/bt-daemon/src/pipeline/recovery.rs @@ -111,6 +111,8 @@ impl std::error::Error for RouteFailure { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub(crate) struct Failure { pub boundary: Boundary, + #[serde(default)] + pub recovering_plugin_hold: bool, pub position: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub through: Option, @@ -161,6 +163,7 @@ impl Failure { let delay = 250i64.saturating_mul(1i64 << attempt.min(8)).min(30_000); Self { boundary, + recovering_plugin_hold: false, position, through: None, reason, @@ -173,6 +176,7 @@ impl Failure { pub fn revision(boundary: Boundary, position: u64, reason: String, version: &str) -> Self { Self { boundary, + recovering_plugin_hold: false, position, through: None, reason, @@ -242,6 +246,7 @@ impl Failure { pub fn legacy(reason: String, position: u64, config: &SessionConfig) -> Self { Self { boundary: Boundary::Sink, + recovering_plugin_hold: false, position, through: None, reason, @@ -289,6 +294,8 @@ impl Failure { }; RecoveryInfo { stage: self.boundary.to_string(), + recovering_plugin_hold: self.recovering_plugin_hold + || self.boundary == Boundary::Plugin, position: self.position, reason: self.reason.clone(), retry, diff --git a/bt-daemon/src/pipeline/routing.rs b/bt-daemon/src/pipeline/routing.rs index a3e06b5c..64ba344b 100644 --- a/bt-daemon/src/pipeline/routing.rs +++ b/bt-daemon/src/pipeline/routing.rs @@ -15,6 +15,7 @@ use tokio::sync::{mpsc, oneshot}; struct Request { config: SessionConfig, operation: Operation, + recovering_plugin_hold: bool, reply: oneshot::Sender, } struct Response { @@ -37,6 +38,7 @@ pub(crate) struct RoutingSink { config: Option, pending: bool, permalink: Option, + recovering_plugin_hold: bool, } impl RoutingSink { @@ -60,6 +62,7 @@ impl RoutingSink { let mut ops = ops.clone(); prepare.apply_shared(&mut ops, &request.config); plugins.configure(&request.config.span_plugins); + plugins.recovering_plugin_hold = request.recovering_plugin_hold; let mut prepared = Vec::with_capacity(ops.len()); let mut failure = None; let mut report = false; @@ -199,10 +202,15 @@ impl RoutingSink { task, config: None, pending: false, + recovering_plugin_hold: false, permalink: None, } } + pub fn set_recovering_plugin_hold(&mut self, recovering: bool) { + self.recovering_plugin_hold = recovering; + } + pub async fn shutdown(self) { let Self { tx, mut task, .. } = self; drop(tx); @@ -227,6 +235,7 @@ impl RoutingSink { config, operation, reply, + recovering_plugin_hold: self.recovering_plugin_hold, }); // Retain ownership on a failed send; no upstream completion is implied. if let Err(undelivered) = OutputPort::send(&mut self.tx, delivery).await { diff --git a/bt-daemon/src/span_processor.rs b/bt-daemon/src/span_processor.rs index 2a60369a..bdbc20b8 100644 --- a/bt-daemon/src/span_processor.rs +++ b/bt-daemon/src/span_processor.rs @@ -52,12 +52,14 @@ struct PluginContext<'a> { source: &'a str, session_id: &'a str, env: &'a BTreeMap, + recovering_plugin_hold: bool, } struct Engine { modules: HashMap, failed_plugins: HashMap, env: BTreeMap, + recovering_plugin_hold: bool, last_fingerprint: Option, context: Context, started: Instant, @@ -112,6 +114,7 @@ impl Engine { modules: HashMap::new(), failed_plugins: HashMap::new(), env: environment(), + recovering_plugin_hold: false, last_fingerprint: None, context, started, @@ -208,6 +211,7 @@ impl Engine { source, session_id, env: &self.env, + recovering_plugin_hold: self.recovering_plugin_hold, }; self.arm_deadline(budget); let started = Instant::now(); @@ -306,7 +310,7 @@ pub fn process( source: &str, session_id: &str, ) -> anyhow::Result { - process_inner(plugins, op, source, session_id, true) + process_inner(plugins, op, source, session_id, false, true) } pub(crate) fn process_isolated( @@ -314,8 +318,16 @@ pub(crate) fn process_isolated( op: &SpanOp, source: &str, session_id: &str, + recovering_plugin_hold: bool, ) -> anyhow::Result { - process_inner(plugins, op, source, session_id, false) + process_inner( + plugins, + op, + source, + session_id, + recovering_plugin_hold, + false, + ) } fn process_inner( @@ -323,6 +335,7 @@ fn process_inner( op: &SpanOp, source: &str, session_id: &str, + recovering_plugin_hold: bool, use_failed_cache: bool, ) -> anyhow::Result { if plugins.is_empty() { @@ -348,6 +361,7 @@ fn process_inner( let engine = slot .as_mut() .ok_or_else(|| anyhow::anyhow!("span processor engine was not initialized"))?; + engine.recovering_plugin_hold = recovering_plugin_hold; for plugin in plugins { if let Some(failed) = engine .failed_plugins @@ -564,6 +578,27 @@ mod tests { ); } + #[test] + fn recovery_context_is_explicit_for_each_call() { + let dir = tempfile::tempdir().unwrap(); + let plugin = dir.path().join("guard.mjs"); + std::fs::write(&plugin, "export default (span, context) => ({...span, name: String(context.recovering_plugin_hold)})").unwrap(); + for held in [true, false] { + let result = process_isolated( + std::slice::from_ref(&plugin), + &SpanOp::Insert(row()), + "debug", + "session", + held, + ) + .unwrap(); + let Some(SpanOp::Insert(span)) = result.op else { + panic!("expected insert"); + }; + assert_eq!(span.name, held.to_string()); + } + } + #[test] fn composes_plugins_and_exposes_context_env() { let dir = tempfile::tempdir().unwrap(); diff --git a/bt-daemon/src/wire/methods.rs b/bt-daemon/src/wire/methods.rs index 0f331753..dc25059f 100644 --- a/bt-daemon/src/wire/methods.rs +++ b/bt-daemon/src/wire/methods.rs @@ -132,6 +132,8 @@ pub struct RecoveryInfo { #[serde(default)] pub attempt: u32, pub stage: String, + #[serde(default)] + pub recovering_plugin_hold: bool, pub position: u64, pub reason: String, pub retry: String,