From 3e2680361686aebbd0244a6327e21c396963869b Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Wed, 2 Dec 2026 00:43:56 +0800 Subject: [PATCH] Recover trace delivery when pinned credentials are restored --- bt-daemon/src/collections/span_ops.rs | 35 +++++- bt-daemon/src/pipeline/consumer.rs | 11 +- bt-daemon/src/pipeline/cursor.rs | 12 ++- bt-daemon/src/pipeline/recovery.rs | 12 +++ bt-daemon/src/server/auth.rs | 28 +++-- bt-daemon/src/server/ingress.rs | 11 +- bt-daemon/src/server/sessions.rs | 3 +- bt-daemon/tests/pipeline.rs | 148 ++++++++++++++++++++++++++ 8 files changed, 233 insertions(+), 27 deletions(-) diff --git a/bt-daemon/src/collections/span_ops.rs b/bt-daemon/src/collections/span_ops.rs index aef9175e..e921137d 100644 --- a/bt-daemon/src/collections/span_ops.rs +++ b/bt-daemon/src/collections/span_ops.rs @@ -8,7 +8,7 @@ use crate::{ attachments::Attachment, pipeline::live::{Multiplexer, Receiver, Record, SharedOp, BYTE_BUDGET, WINDOW}, translate::{OriginSnapshot, SinkFields, SpanOp, SpanRow, SpanType}, - wire::{SessionConfig, SessionRoute}, + wire::{BackendAuth, SessionConfig, SessionRoute}, }; use rusqlite::{params, Connection, OptionalExtension}; use serde::{Deserialize, Serialize}; @@ -590,13 +590,38 @@ impl SessionStorage { .await } + fn binding(auth: &BackendAuth) -> anyhow::Result { + Ok(serde_json::to_string(&serde_json::json!({ + "api_url": auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"), + "org_id": auth.org_id, + "org_name": auth.org_name, + }))?) + } + + /// Validate refreshed credentials without creating or changing a binding. + pub async fn check_binding(&self, route: &str, auth: &BackendAuth) -> anyhow::Result { + let route = route.to_owned(); + let binding = Self::binding(auth)?; + self.run(move |db| { + let previous: Option = db + .query_row("SELECT binding FROM heads WHERE route=?", [route], |row| { + row.get(0) + }) + .optional()? + .flatten(); + if let Some(previous) = previous { + anyhow::ensure!(previous == binding, BindingChanged); + return Ok(true); + } + Ok(false) + }) + .await + } + /// Tokens can change; a durable head's backend and organization cannot. pub async fn bind(&self, route: &str, config: &SessionConfig) -> anyhow::Result<()> { let route = route.to_owned(); - let binding = serde_json::to_string(&serde_json::json!({ - "api_url": config.auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"), - "org_id":config.auth.org_id,"org_name":config.auth.org_name, - }))?; + let binding = Self::binding(&config.auth)?; self.write(move |tx| { let previous: Option = tx.one("SELECT binding FROM heads WHERE route=?", [&route])?; diff --git a/bt-daemon/src/pipeline/consumer.rs b/bt-daemon/src/pipeline/consumer.rs index c4b801c1..5fdf9e84 100644 --- a/bt-daemon/src/pipeline/consumer.rs +++ b/bt-daemon/src/pipeline/consumer.rs @@ -89,14 +89,6 @@ impl ConsumerOptions { route.auth.profile_id.is_none() || route.auth.profile_id == lease.selection.profile_id, "credential refresh changed the pinned profile" ); - anyhow::ensure!( - config.auth.org_id.is_none() || config.auth.org_id == lease.auth.org_id, - "credential refresh changed the pinned organization" - ); - anyhow::ensure!( - config.auth.api_url.is_none() || config.auth.api_url == lease.auth.api_url, - "credential refresh changed the pinned backend" - ); config.auth = lease.auth; Ok(()) } @@ -233,7 +225,8 @@ impl Consumer { if matches!(failure.boundary, Boundary::Credentials) { if let Err(error) = options.credentials(&mut current).await { held = Some(Box::new(( - Failure::credentials(error.to_string(), attempts), + Failure::credentials(error.to_string(), attempts) + .at(failure.position), work, ))); continue; diff --git a/bt-daemon/src/pipeline/cursor.rs b/bt-daemon/src/pipeline/cursor.rs index 4eeb83e2..5390590d 100644 --- a/bt-daemon/src/pipeline/cursor.rs +++ b/bt-daemon/src/pipeline/cursor.rs @@ -32,7 +32,8 @@ pub(crate) async fn reconfigure_held( failure.condition, super::recovery::Condition::Configuration { .. } | super::recovery::Condition::Plugin { .. } - ) || !held.route.same_destination(&route) + ) || failure.is_legacy_binding_mismatch() + || !held.route.same_destination(&route) { return None; } @@ -359,11 +360,13 @@ impl Cursor { None => return Err(error.into()), }, }; + // Older daemons persisted binding mismatches as settings holds. + // Recheck the binding below even if no settings changed. if matches!(failure.boundary, Boundary::Completion) && self.completed >= failure.through.unwrap_or(failure.position) { self.session.set_failure(&self.route, None).await?; - } else { + } else if !failure.is_legacy_binding_mismatch() { *self.error.lock() = Some(failure.message()); *self.recovery.lock() = Some(failure.info(false)); if matches!( @@ -386,7 +389,10 @@ impl Cursor { if let Err(error) = self.session.bind(&self.route, config).await { if error.downcast_ref::().is_some() { let failure = - Failure::legacy(error.to_string(), self.completed + 1, config); + Failure::credentials(error.to_string(), 0).at(self.completed + 1); + tracing::warn!( + "trace delivery paused; restore the selected credentials for the original backend and organization" + ); self.session .set_failure(&self.route, Some(serde_json::to_string(&failure)?)) .await?; diff --git a/bt-daemon/src/pipeline/recovery.rs b/bt-daemon/src/pipeline/recovery.rs index c1a6f1f8..856c5601 100644 --- a/bt-daemon/src/pipeline/recovery.rs +++ b/bt-daemon/src/pipeline/recovery.rs @@ -239,6 +239,18 @@ impl Failure { } failure } + pub fn is_legacy_binding_mismatch(&self) -> bool { + self.boundary == Boundary::Sink + && matches!( + self.condition, + Condition::Configuration { + recheck_ms: None, + .. + } + ) + && self.reason == crate::collections::BindingChanged.to_string() + } + pub fn legacy(reason: String, position: u64, config: &SessionConfig) -> Self { Self { boundary: Boundary::Sink, diff --git a/bt-daemon/src/server/auth.rs b/bt-daemon/src/server/auth.rs index 5b9a1748..4346f756 100644 --- a/bt-daemon/src/server/auth.rs +++ b/bt-daemon/src/server/auth.rs @@ -38,6 +38,7 @@ pub(crate) async fn resolve_route_auth( struct RouteAuthProvider { provider: Arc, key: DeliveryKey, + storage: Option, states: Arc>>, } #[async_trait::async_trait] @@ -48,6 +49,10 @@ impl AuthProvider for RouteAuthProvider { reason: AuthResolveReason, ) -> anyhow::Result { let lease = self.provider.resolve(selection, reason).await?; + let durably_bound = match &self.storage { + Some(storage) => storage.check_binding(&self.key.route, &lease.auth).await?, + None => false, + }; let mut states = self.states.lock().await; if let Some(state) = states.get_mut(&self.key) { anyhow::ensure!( @@ -55,9 +60,10 @@ impl AuthProvider for RouteAuthProvider { "credential refresh changed the pinned auth selection" ); anyhow::ensure!( - lease.auth.api_url == state.lease.auth.api_url - && lease.auth.org_id == state.lease.auth.org_id - && lease.auth.org_name == state.lease.auth.org_name, + durably_bound + || (lease.auth.api_url == state.lease.auth.api_url + && lease.auth.org_id == state.lease.auth.org_id + && lease.auth.org_name == state.lease.auth.org_name), "credential refresh changed the pinned backend or organization" ); state.lease = lease.clone(); @@ -67,11 +73,16 @@ impl AuthProvider for RouteAuthProvider { } impl Daemon { - pub(super) fn route_auth_provider(&self, key: &DeliveryKey) -> Option> { + pub(super) fn route_auth_provider( + &self, + key: &DeliveryKey, + storage: Option, + ) -> Option> { self.auth_provider.as_ref().map(|provider| { Arc::new(RouteAuthProvider { provider: provider.clone(), key: key.clone(), + storage, states: self.session_auth.clone(), }) as Arc }) @@ -119,7 +130,7 @@ impl Daemon { }; let provider = self - .route_auth_provider(&key) + .route_auth_provider(&key, None) .ok_or_else(|| anyhow::anyhow!("daemon host has no Braintrust auth provider"))?; let lease = resolve_route_auth( provider.as_ref(), @@ -220,15 +231,16 @@ impl Daemon { &self, key: &DeliveryKey, ) -> anyhow::Result<()> { - let Some(provider) = self.route_auth_provider(key) else { - return Ok(()); - }; let Some(state) = self.session_auth.lock().await.get(key).cloned() else { return Ok(()); }; if !lease_is_expiring(&state.lease) { return Ok(()); } + let storage = self.storage_for(&key.source, &key.session_id).await?; + let Some(provider) = self.route_auth_provider(key, Some(storage)) else { + return Ok(()); + }; let selection = state.lease.selection.clone(); let lease = provider .resolve(&selection, AuthResolveReason::Expiring) diff --git a/bt-daemon/src/server/ingress.rs b/bt-daemon/src/server/ingress.rs index 381507f4..bc43abb2 100644 --- a/bt-daemon/src/server/ingress.rs +++ b/bt-daemon/src/server/ingress.rs @@ -271,7 +271,7 @@ pub(super) async fn accept_resolved_event( let session_lock = daemon.dispatch_lock(&source, &session_id); let _session_guard = session_lock.lock().await; - let result = async { + let result: Result<_, Failure> = async { let delivery_key = daemon .configure_event(&mut env) .await @@ -313,6 +313,15 @@ pub(super) async fn accept_resolved_event( } tracing::debug!(source, event, session_id, "event accepted") } + Err(error) if error.boundary == crate::pipeline::recovery::Boundary::Credentials => { + if attempt == 0 { + tracing::warn!( + source, + session_id, + "trace delivery paused; captures are queued locally. Run `bt trace status` for credential recovery instructions" + ); + } + } Err(error) => tracing::warn!(source, event, session_id, %error, "event rejected"), } if result.is_ok() && schedule_flush { diff --git a/bt-daemon/src/server/sessions.rs b/bt-daemon/src/server/sessions.rs index 38321b35..980dbc05 100644 --- a/bt-daemon/src/server/sessions.rs +++ b/bt-daemon/src/server/sessions.rs @@ -116,6 +116,7 @@ impl Daemon { translation.advance(replay_through).await?; let _ = translation.barrier().await; let input = translation.subscribe(&route).await?; + let storage = self.storage_for(&env.source, &env.session_id).await?; let mut map = self.sessions.lock(); if let Some(s) = map.get(key) { return Ok(s.clone()); @@ -126,7 +127,7 @@ impl Daemon { translation, input, route: route.clone(), - auth_provider: self.route_auth_provider(key), + auth_provider: self.route_auth_provider(key, Some(storage)), session_id: env.session_id.clone(), source: env.source.clone(), bt_version: self.version.clone(), diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index ad01c778..77a57d32 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -4885,3 +4885,151 @@ async fn managed_run_flush_shares_one_budget_and_returns_pending_counts() { assert!(result.pending > 0); handle.abort(); } + +#[tokio::test] +async fn durable_binding_holds_until_original_credentials_return() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct ChangingAuth { + destination: AtomicUsize, + retries: AtomicUsize, + } + + #[async_trait] + impl AuthProvider for ChangingAuth { + async fn resolve( + &self, + selection: &AuthSelection, + reason: AuthResolveReason, + ) -> anyhow::Result { + let destination = self.destination.load(Ordering::SeqCst); + if reason == AuthResolveReason::Unauthorized { + self.retries.fetch_add(1, Ordering::SeqCst); + } + Ok(AuthLease { + selection: selection.clone(), + auth: BackendAuth { + token: "test-replacement-token".into(), + api_url: Some(if destination == 0 { + "https://other.example.test".into() + } else { + "https://original.example.test".into() + }), + org_id: Some(if destination == 1 { + "test-other-org".into() + } else { + "test-org".into() + }), + ..Default::default() + }, + expires_at_ms: None, + }) + } + } + + for legacy in [false, true] { + let tmp = tempfile::tempdir().unwrap(); + let data = tmp.path().join("data"); + let socket = test_endpoint(tmp.path()); + let event = envelope("binding-recovery", "SessionStart", 1); + let route = event.route.as_ref().unwrap(); + seed_dormant_route(&data, &event.source, &event.session_id, route); + let db_path = + bt_daemon::storage_inspect::session_path(&data, &event.source, &event.session_id); + let failure = legacy.then(|| serde_json::json!({ + "boundary": "sink", + "position": 1, + "through": null, + "reason": "credential resolution changed the durable head's pinned backend or organization", + "attempt": 0, + "condition": {"when": "configuration", "signature": "old", "recheck_ms": null}, + }).to_string()); + rusqlite::Connection::open(&db_path) + .unwrap() + .execute( + "UPDATE heads SET binding=?, failure=? WHERE route=?", + rusqlite::params![ + serde_json::json!({ + "api_url": "https://original.example.test", + "org_id": "test-org", + "org_name": null, + }) + .to_string(), + failure, + serde_json::to_string(route).unwrap(), + ], + ) + .unwrap(); + let auth = Arc::new(ChangingAuth { + destination: AtomicUsize::new(0), + retries: AtomicUsize::new(0), + }); + let mut options = debug_serve_options("test", &data); + options.auth_provider = Some(auth.clone()); + let args = ServeArgs { + socket: Some(socket.clone()), + data_dir: Some(data.clone()), + idle_timeout_secs: 0, + session_idle_timeout_secs: 0, + retention: None, + }; + let handle = tokio::spawn(async move { run_serve(args, options).await.unwrap() }); + wait_for(&socket).await; + forward_envelope(&event, &socket, &dummy_host(), false) + .await + .unwrap(); + let output = data.join("spans/binding-recovery.ndjson"); + for (destination, retries) in [(0, 1), (1, 2)] { + auth.destination.store(destination, Ordering::SeqCst); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + let status = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: Some(event.session_id.clone()), + }) + .await + .unwrap() + .unwrap(); + if auth.retries.load(Ordering::SeqCst) >= retries + && status.sessions.iter().any(|session| { + session.recovery.as_ref().is_some_and(|recovery| { + recovery.stage == "credentials" + && recovery.attempt >= retries as u32 + && !recovery.eligible + }) + }) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("held head must attempt credential resolution"); + assert!( + !output.exists(), + "wrong destination must never reach the sink" + ); + } + + auth.destination.store(2, Ordering::SeqCst); + tokio::time::timeout(Duration::from_secs(8), async { + loop { + if std::fs::read_to_string(&output).is_ok_and(|rows| rows.lines().count() >= 2) { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("restored credentials must drain the original event"); + assert!( + flush_session(&event.session_id, &socket, 5000) + .await + .unwrap() + .flushed + ); + shutdown(&socket).await; + handle.await.unwrap(); + } +}