Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion bt-daemon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Expand Down
1 change: 1 addition & 0 deletions bt-daemon/src/command_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
87 changes: 87 additions & 0 deletions bt-daemon/src/pipeline/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ impl ConsumerOptions {
Ok(sink)
}
async fn hold(&self, pending: &mut VecDeque<Delivery<()>>, 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.
Expand Down Expand Up @@ -287,6 +292,13 @@ impl Consumer {
)
})?;
routing.configure(&current);
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::<crate::span_processor::StopTracing>() => {
// Never resubmit after the signal, including when
Expand All @@ -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)
}
Expand Down Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions bt-daemon/src/pipeline/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
10 changes: 9 additions & 1 deletion bt-daemon/src/pipeline/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub(crate) struct Plugins {
paths: Vec<PathBuf>,
pub source: String,
pub session_id: String,
pub recovering_plugin_hold: bool,
blocked: Option<(Vec<PathBuf>, PluginRejected)>,
}

Expand All @@ -40,6 +41,7 @@ impl Plugins {
Self {
paths: Vec::new(),
source: source.into(),
recovering_plugin_hold: false,
session_id: session_id.into(),
blocked: None,
}
Expand Down Expand Up @@ -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);
Expand Down
7 changes: 7 additions & 0 deletions bt-daemon/src/pipeline/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 9 additions & 0 deletions bt-daemon/src/pipeline/routing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use tokio::sync::{mpsc, oneshot};
struct Request {
config: SessionConfig,
operation: Operation,
recovering_plugin_hold: bool,
reply: oneshot::Sender<Response>,
}
struct Response {
Expand All @@ -37,6 +38,7 @@ pub(crate) struct RoutingSink {
config: Option<SessionConfig>,
pending: bool,
permalink: Option<String>,
recovering_plugin_hold: bool,
}

impl RoutingSink {
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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 {
Expand Down
39 changes: 37 additions & 2 deletions bt-daemon/src/span_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,14 @@ struct PluginContext<'a> {
source: &'a str,
session_id: &'a str,
env: &'a BTreeMap<String, String>,
recovering_plugin_hold: bool,
}

struct Engine {
modules: HashMap<PathBuf, CachedModule>,
failed_plugins: HashMap<PathBuf, FailedPlugin>,
env: BTreeMap<String, String>,
recovering_plugin_hold: bool,
last_fingerprint: Option<PluginFingerprint>,
context: Context,
started: Instant,
Expand Down Expand Up @@ -112,6 +114,7 @@ impl Engine {
modules: HashMap::new(),
failed_plugins: HashMap::new(),
env: environment(),
recovering_plugin_hold: false,
last_fingerprint: None,
context,
started,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -306,23 +310,32 @@ pub fn process(
source: &str,
session_id: &str,
) -> anyhow::Result<ProcessResult> {
process_inner(plugins, op, source, session_id, true)
process_inner(plugins, op, source, session_id, false, true)
}

pub(crate) fn process_isolated(
plugins: &[PathBuf],
op: &SpanOp,
source: &str,
session_id: &str,
recovering_plugin_hold: bool,
) -> anyhow::Result<ProcessResult> {
process_inner(plugins, op, source, session_id, false)
process_inner(
plugins,
op,
source,
session_id,
recovering_plugin_hold,
false,
)
}

fn process_inner(
plugins: &[PathBuf],
op: &SpanOp,
source: &str,
session_id: &str,
recovering_plugin_hold: bool,
use_failed_cache: bool,
) -> anyhow::Result<ProcessResult> {
if plugins.is_empty() {
Expand All @@ -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
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 2 additions & 0 deletions bt-daemon/src/wire/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down