From 05ab61c56f7495ec5e5b711be34831744c7e0ec8 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Fri, 20 Nov 2026 19:43:49 +0800 Subject: [PATCH 1/8] Add replay performance diagnostics --- bt-daemon/src/pipeline/translation.rs | 105 ++++++++++++++++++++++++++ bt-daemon/src/server/maintenance.rs | 69 +++++++++++++++++ 2 files changed, 174 insertions(+) diff --git a/bt-daemon/src/pipeline/translation.rs b/bt-daemon/src/pipeline/translation.rs index 8a12f03a..eff44fb8 100644 --- a/bt-daemon/src/pipeline/translation.rs +++ b/bt-daemon/src/pipeline/translation.rs @@ -994,6 +994,111 @@ pub(crate) mod tests { } } + /// Run explicitly with `cargo test --lib sdk897_claude_backlog -- --ignored --nocapture`. + /// This diagnostic preloads a real SQLite event backlog and translates it + /// through the production Claude translator and checkpoint transaction. + #[tokio::test] + #[ignore = "manual replay performance diagnostic"] + async fn sdk897_claude_backlog() { + use crate::wire::Envelope; + use serde_json::json; + use std::time::{Duration, Instant}; + + let turns = std::env::var("SDK897_TURNS") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(300); + let body_bytes = std::env::var("SDK897_BODY_BYTES") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(2048); + let interval = (turns / 3).max(1); + assert!(turns > 0, "SDK897_TURNS must be positive"); + let f = SourceFixture::new("claude-code").await; + let transcript = f.options.data_dir.join("claude-replay.jsonl"); + let mut contents = Vec::new(); + let mut events = Vec::new(); + for turn in 0..turns { + for (kind, record, hook) in [ + ( + "user", + json!({"type":"user","uuid":format!("u-{turn}"),"timestamp":"2026-01-01T00:00:00Z","message":{"role":"user","content":format!("turn {turn} {}", "x".repeat(body_bytes))}}), + "UserPromptSubmit", + ), + ( + "assistant", + json!({"type":"assistant","uuid":format!("a-{turn}"),"timestamp":"2026-01-01T00:00:01Z","message":{"id":format!("m-{turn}"),"model":"claude-test","role":"assistant","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}}), + "Stop", + ), + ] { + contents.extend_from_slice(record.to_string().as_bytes()); + contents.push(b'\n'); + let mut payload = json!({"transcript_path": transcript, "_bt_claude_transcript_mirrors": {transcript.to_string_lossy().to_string(): {"mirror": transcript,"through": contents.len()}}}); + if kind == "user" { + payload["prompt"] = json!(format!("turn {turn}")); + } + events.push(Envelope { + source: "claude-code".into(), + session_id: "checkpoint".into(), + event: hook.into(), + ts_ms: 1_767_225_600_000 + turn as i64 * 2000, + payload, + source_version: None, + plugin_version: None, + managed_run_id: None, + capture: None, + route: None, + config: None, + }); + } + } + std::fs::write(&transcript, &contents).unwrap(); + let mut boundaries = Vec::new(); + for event in &events { + boundaries.push(f.write(event, false).await); + } + assert_eq!(f.db().count(Table::Events), (turns * 2) as u64); + let mut replay_time = Duration::ZERO; + for completed in (interval..=turns) + .step_by(interval) + .chain(std::iter::once(turns)) + .collect::>() + { + let start = Instant::now(); + f.process(boundaries[completed * 2 - 1]).await; + replay_time += start.elapsed(); + let continuation = f.options.storage.continuation().await.unwrap().unwrap(); + let saved: Continuation = serde_json::from_slice(&continuation).unwrap(); + let mut translator = f + .options + .registry + .create_checked_with_session_namespace("claude-code", &f.options.namespace) + .unwrap(); + translator.restore_state(&saved.native).unwrap(); + let serial_start = Instant::now(); + for _ in 0..10 { + std::hint::black_box(translator.save_state().unwrap()); + } + println!( + "turns={completed} events={} continuation_bytes={} replay_ms={} mean_save_us={}", + completed * 2, + continuation.len(), + replay_time.as_millis(), + serial_start.elapsed().as_micros() / 10 + ); + } + if let Ok(budget) = std::env::var("SDK897_MAX_REPLAY_MS") { + let budget = budget + .parse::() + .expect("SDK897_MAX_REPLAY_MS must be an integer"); + assert!( + replay_time.as_millis() <= budget, + "replay exceeded {budget} ms" + ); + } + f.source.shutdown().await; + } + #[test] fn every_agent_resumes_from_saved_state_at_every_native_boundary() { let registry = crate::translate::Registry::default_agents(); diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index b6e22ec4..e0a72cdf 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -447,6 +447,75 @@ mod tests { ) } + /// Run with `cargo test --lib sdk897_control_plane -- --ignored --nocapture`. + /// Holding the recovery gate makes the control RPC behavior deterministic. + #[tokio::test] + #[ignore = "manual recovery responsiveness diagnostic"] + async fn sdk897_control_plane() { + let mut timely = Vec::new(); + for method_name in [ + crate::wire::method::STATUS_GET, + crate::wire::method::DAEMON_SHUTDOWN, + ] { + let tmp = tempfile::tempdir().unwrap(); + let (daemon, ready) = paused_ingress(tmp.path()); + let request = crate::wire::Request::new( + crate::wire::RequestId::Int(1), + method_name, + serde_json::json!({}), + ); + let mut client = None; + let response = tokio::time::timeout( + Duration::from_millis(250), + super::super::rpc::handle_request(&daemon, request, &mut client), + ) + .await; + let returned = response.is_ok_and(|response| response.error.is_none()); + println!("{method_name}: returned_before_recovery={returned}"); + timely.push(returned); + ready.send(()).unwrap(); + drain_all(&daemon).await; + } + #[cfg(unix)] + { + let tmp = tempfile::tempdir().unwrap(); + let (daemon, ready) = paused_ingress(tmp.path()); + let socket = tmp.path().join("daemon.sock"); + let listener = tokio::net::UnixListener::bind(&socket).unwrap(); + let server_daemon = daemon.clone(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let _ = super::super::rpc::serve_connection(server_daemon, stream).await; + }); + let host = crate::HostInfo { + serve_argv: Vec::new(), + version: "newer-test-version".into(), + }; + let capture = event("handover", SessionRoute::default()); + let result = tokio::time::timeout( + Duration::from_millis(250), + crate::forward_envelope(&capture, &socket, &host, false), + ) + .await; + assert!( + !matches!(result, Ok(Ok(()))), + "an unacknowledged event must not be reported as captured" + ); + let returned = result.is_ok(); + println!("hook.handover: returned_before_recovery={returned}"); + timely.push(returned); + ready.send(()).unwrap(); + server.await.unwrap(); + drain_all(&daemon).await; + } + if std::env::var_os("SDK897_EXPECT_RESPONSIVE").is_some() { + assert!( + timely.into_iter().all(|returned| returned), + "control RPC blocked behind recovery" + ); + } + } + #[tokio::test] async fn concurrent_recovery_and_dispatch_share_one_source_producer() { let f = crate::pipeline::translation::tests::SourceFixture::new("debug").await; From 2c61a2d1cd45cebb15a70edfab31d50ed899fb45 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Fri, 20 Nov 2026 20:47:47 +0800 Subject: [PATCH 2/8] Measure large backlog and daemon recovery --- bt-daemon/src/pipeline/translation.rs | 78 ++++++++++++++++++------- bt-daemon/src/server/maintenance.rs | 83 +++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 22 deletions(-) diff --git a/bt-daemon/src/pipeline/translation.rs b/bt-daemon/src/pipeline/translation.rs index eff44fb8..0dfb5807 100644 --- a/bt-daemon/src/pipeline/translation.rs +++ b/bt-daemon/src/pipeline/translation.rs @@ -994,28 +994,14 @@ pub(crate) mod tests { } } - /// Run explicitly with `cargo test --lib sdk897_claude_backlog -- --ignored --nocapture`. - /// This diagnostic preloads a real SQLite event backlog and translates it - /// through the production Claude translator and checkpoint transaction. - #[tokio::test] - #[ignore = "manual replay performance diagnostic"] - async fn sdk897_claude_backlog() { + pub(crate) fn sdk897_backlog_events( + root: &std::path::Path, + turns: usize, + body_bytes: usize, + ) -> (Vec, usize) { use crate::wire::Envelope; use serde_json::json; - use std::time::{Duration, Instant}; - - let turns = std::env::var("SDK897_TURNS") - .ok() - .and_then(|s| s.parse::().ok()) - .unwrap_or(300); - let body_bytes = std::env::var("SDK897_BODY_BYTES") - .ok() - .and_then(|s| s.parse::().ok()) - .unwrap_or(2048); - let interval = (turns / 3).max(1); - assert!(turns > 0, "SDK897_TURNS must be positive"); - let f = SourceFixture::new("claude-code").await; - let transcript = f.options.data_dir.join("claude-replay.jsonl"); + let transcript = root.join("claude-replay.jsonl"); let mut contents = Vec::new(); let mut events = Vec::new(); for turn in 0..turns { @@ -1053,11 +1039,52 @@ pub(crate) mod tests { } } std::fs::write(&transcript, &contents).unwrap(); + (events, contents.len()) + } + + /// Run explicitly with `cargo test --lib sdk897_claude_backlog -- --ignored --nocapture`. + /// This diagnostic preloads a real SQLite event backlog and translates it + /// through the production Claude translator and checkpoint transaction. + #[tokio::test] + #[ignore = "manual replay performance diagnostic"] + async fn sdk897_claude_backlog() { + use std::time::{Duration, Instant}; + + let turns = std::env::var("SDK897_TURNS") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(300); + let body_bytes = std::env::var("SDK897_BODY_BYTES") + .ok() + .and_then(|s| s.parse::().ok()) + .unwrap_or(2048); + let interval = (turns / 3).max(1); + assert!(turns > 0, "SDK897_TURNS must be positive"); + let f = SourceFixture::new("claude-code").await; + let (events, transcript_bytes) = + sdk897_backlog_events(&f.options.data_dir, turns, body_bytes); let mut boundaries = Vec::new(); for event in &events { boundaries.push(f.write(event, false).await); } assert_eq!(f.db().count(Table::Events), (turns * 2) as u64); + let db_path = crate::collections::inspect::session_path( + &f.options.data_dir, + &f.options.source, + &f.options.session_id, + ); + let storage_bytes = || { + let db = std::fs::metadata(&db_path).map(|m| m.len()).unwrap_or(0); + let wal_path = format!("{}-wal", db_path.display()); + let wal = std::fs::metadata(wal_path).map(|m| m.len()).unwrap_or(0); + (db, wal) + }; + let (db_bytes, wal_bytes) = storage_bytes(); + println!( + "preloaded_events={} transcript_bytes={} db_bytes={db_bytes} wal_bytes={wal_bytes}", + events.len(), + transcript_bytes + ); let mut replay_time = Duration::ZERO; for completed in (interval..=turns) .step_by(interval) @@ -1079,12 +1106,16 @@ pub(crate) mod tests { for _ in 0..10 { std::hint::black_box(translator.save_state().unwrap()); } + let mean_save_us = serial_start.elapsed().as_micros() / 10; + let (db_bytes, wal_bytes) = storage_bytes(); + let status = f.options.storage.status().await.unwrap(); println!( - "turns={completed} events={} continuation_bytes={} replay_ms={} mean_save_us={}", + "turns={completed} events={} continuation_bytes={} replay_ms={} mean_save_us={} remaining_event_bytes={} db_bytes={db_bytes} wal_bytes={wal_bytes}", completed * 2, continuation.len(), replay_time.as_millis(), - serial_start.elapsed().as_micros() / 10 + mean_save_us, + status.event_tail.saturating_sub(status.translated_through), ); } if let Ok(budget) = std::env::var("SDK897_MAX_REPLAY_MS") { @@ -1097,6 +1128,9 @@ pub(crate) mod tests { ); } f.source.shutdown().await; + if std::env::var_os("SDK897_KEEP_DATA").is_some() { + println!("retained_data_dir={}", f._dir.keep().display()); + } } #[test] diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index e0a72cdf..801b5613 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -447,6 +447,89 @@ mod tests { ) } + /// Exercise startup with a persisted Claude backlog and live control RPCs. + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "manual recovery responsiveness diagnostic"] + async fn sdk897_actual_recovery() { + let tmp = tempfile::tempdir().unwrap(); + let turns = std::env::var("SDK897_TURNS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(1200); + let (events, transcript_bytes) = + crate::pipeline::translation::tests::sdk897_backlog_events(tmp.path(), turns, 2048); + let storage = + crate::collections::SessionStorage::open(tmp.path(), "claude-code", "checkpoint") + .await + .unwrap(); + let route = SessionRoute { + destination: Some(crate::wire::TraceDestination::ProjectLogs { + project_id: Some("project".into()), + project_name: None, + }), + ..Default::default() + }; + for mut event in events { + event.route = Some(route.clone()); + storage.append(&event, None).await.unwrap().unwrap(); + } + let initial = storage.status().await.unwrap(); + assert!(initial.event_tail > initial.translated_through); + let socket = tmp.path().join("daemon.sock"); + let args = crate::args::ServeArgs { + socket: Some(socket.clone()), + data_dir: Some(tmp.path().into()), + idle_timeout_secs: 0, + session_idle_timeout_secs: 0, + retention: None, + }; + let mut options = debug_serve_options("test", tmp.path()); + options.auth_provider = Some(Arc::new(TestAuth)); + let started = Instant::now(); + let server = tokio::spawn(super::super::run_serve(args, options)); + tokio::time::timeout(Duration::from_secs(20), async { + while !socket.exists() { + tokio::task::yield_now().await; + } + while storage.status().await.unwrap().translated_through == initial.translated_through { + tokio::task::yield_now().await; + } + }) + .await + .expect("recovery did not start"); + let before = storage.status().await.unwrap(); + let status = tokio::time::timeout( + Duration::from_secs(2), + crate::run_status(crate::args::StatusArgs { + socket: Some(socket.clone()), + session_id: None, + }), + ) + .await; + let after = storage.status().await.unwrap(); + println!("actual_recovery turns={turns} transcript_bytes={transcript_bytes} event_tail={} before={} after={} status_returned={} elapsed_ms={}", initial.event_tail, before.translated_through, after.translated_through, status.is_ok(), started.elapsed().as_millis()); + if status.is_err() { + assert!( + after.translated_through > before.translated_through, + "recovery made no progress during status request" + ); + } + let shutdown = + tokio::time::timeout(Duration::from_secs(2), crate::shutdown_daemon(&socket)).await; + println!( + "shutdown_returned={} elapsed_ms={}", + shutdown.is_ok(), + started.elapsed().as_millis() + ); + let result = tokio::time::timeout(Duration::from_secs(300), server) + .await + .expect("daemon did not finish") + .unwrap(); + result.unwrap(); + println!("daemon_finished_ms={}", started.elapsed().as_millis()); + } + /// Run with `cargo test --lib sdk897_control_plane -- --ignored --nocapture`. /// Holding the recovery gate makes the control RPC behavior deterministic. #[tokio::test] From 3e78e221cf21c21e93ecf6da398c20f01bda000a Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 00:27:51 +0800 Subject: [PATCH 3/8] Keep daemon controls responsive during recovery --- bt-daemon/src/client.rs | 7 ++++++- bt-daemon/src/server/rpc.rs | 2 -- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/bt-daemon/src/client.rs b/bt-daemon/src/client.rs index 5386befe..866258f2 100644 --- a/bt-daemon/src/client.rs +++ b/bt-daemon/src/client.rs @@ -256,7 +256,12 @@ pub async fn forward_envelope( host: &HostInfo, no_spawn: bool, ) -> anyhow::Result<()> { - DaemonClient::new(socket, host, no_spawn).log(env).await + tokio::time::timeout( + std::time::Duration::from_secs(5), + DaemonClient::new(socket, host, no_spawn).log(env), + ) + .await + .map_err(|_| anyhow::anyhow!("daemon did not accept the event within 5 seconds"))? } /// One reusable connection to a current daemon. It starts the daemon or hands diff --git a/bt-daemon/src/server/rpc.rs b/bt-daemon/src/server/rpc.rs index bc87080f..e87843e7 100644 --- a/bt-daemon/src/server/rpc.rs +++ b/bt-daemon/src/server/rpc.rs @@ -316,7 +316,6 @@ pub(super) async fn handle_request( } method::STATUS_GET => { let p = parse!(StatusParams); - daemon.settle_ingress().await; Response::serialized(id, daemon.status(p)) } method::AUTH_DIAGNOSE => { @@ -327,7 +326,6 @@ pub(super) async fn handle_request( if !client_may_shutdown(client.as_ref(), &daemon.version) { return Response::serialized(id, ShutdownResult { ok: false }); } - drain_all(daemon).await; Response::serialized(id, ShutdownResult { ok: true }) } other => Response::err( From 4fdee2b703c5d162b0e324abbdcdddabf109f763 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 00:52:15 +0800 Subject: [PATCH 4/8] Batch replay checkpoints and capture before daemon handover --- bt-daemon/src/client.rs | 57 ++++++++++-------- bt-daemon/src/pipeline/translation.rs | 85 +++++++++++++++++++++++++++ bt-daemon/src/server/maintenance.rs | 11 +++- bt-daemon/src/trace_runtime.rs | 3 + 4 files changed, 131 insertions(+), 25 deletions(-) diff --git a/bt-daemon/src/client.rs b/bt-daemon/src/client.rs index 866258f2..07146769 100644 --- a/bt-daemon/src/client.rs +++ b/bt-daemon/src/client.rs @@ -256,12 +256,7 @@ pub async fn forward_envelope( host: &HostInfo, no_spawn: bool, ) -> anyhow::Result<()> { - tokio::time::timeout( - std::time::Duration::from_secs(5), - DaemonClient::new(socket, host, no_spawn).log(env), - ) - .await - .map_err(|_| anyhow::anyhow!("daemon did not accept the event within 5 seconds"))? + DaemonClient::new(socket, host, no_spawn).log(env).await } /// One reusable connection to a current daemon. It starts the daemon or hands @@ -272,6 +267,7 @@ pub(crate) struct DaemonClient { host: HostInfo, no_spawn: bool, conn: Option, + upgrade_after_capture: bool, } impl DaemonClient { @@ -281,12 +277,18 @@ impl DaemonClient { host: host.clone(), no_spawn, conn: None, + upgrade_after_capture: false, } } /// Connect and initialize. `Ok(false)` is a transient failure to retry /// while a replacement daemon takes over. - async fn open(&mut self, init: &serde_json::Value, retrying: bool) -> anyhow::Result { + async fn open( + &mut self, + init: &serde_json::Value, + retrying: bool, + capture: bool, + ) -> anyhow::Result { const MAX_HANDOVER_ATTEMPTS: usize = 3; let mut handover_attempts = 0; loop { @@ -306,6 +308,14 @@ impl DaemonClient { self.conn = Some(conn); return Ok(true); } + // Capture with the running daemon before requesting handover. Its + // event.log acknowledgement is the durable boundary; an upgrade + // must never delay or abandon an event that has not reached it. + if capture && !self.no_spawn { + self.upgrade_after_capture = true; + self.conn = Some(conn); + return Ok(true); + } if self.no_spawn { anyhow::bail!( "daemon version {} is older than client {} and --no-spawn is set", @@ -331,16 +341,10 @@ impl DaemonClient { /// Capture one event. Returns once the daemon has durably accepted it. pub(crate) async fn log(&mut self, env: &Envelope) -> anyhow::Result<()> { let init = initialize_params(env, &self.host.version); - let mut retry_deadline: Option = None; + let mut retrying = false; loop { - if retry_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) { - anyhow::bail!( - "replacement daemon did not accept the event at {}", - self.socket.display() - ); - } let reused = self.conn.is_some(); - if !reused && !self.open(&init, retry_deadline.is_some()).await? { + if !reused && !self.open(&init, retrying, true).await? { tokio::time::sleep(std::time::Duration::from_millis(20)).await; continue; } @@ -351,11 +355,9 @@ impl DaemonClient { Ok(result) => result, // A reused connection may belong to a daemon that has since // exited; reconnect once before treating this as a failure. - Err(_) if reused || retry_deadline.is_some() => { + Err(_) if reused || retrying => { self.conn = None; - retry_deadline.get_or_insert_with(|| { - tokio::time::Instant::now() + std::time::Duration::from_secs(5) - }); + retrying = true; continue; } Err(error) => { @@ -365,13 +367,22 @@ impl DaemonClient { }; let result: wire::EventLogResult = serde_json::from_value(result)?; if result.accepted { + if self.upgrade_after_capture { + // This timeout only bounds maintenance after durable capture. + // Failure leaves the accepted event with the old daemon. + let _ = tokio::time::timeout( + Duration::from_millis(250), + conn.request(method::DAEMON_SHUTDOWN, serde_json::json!({})), + ) + .await; + self.upgrade_after_capture = false; + self.conn = None; + } return Ok(()); } // A quiescing daemon is handing over; capture with its replacement. self.conn = None; - retry_deadline.get_or_insert_with(|| { - tokio::time::Instant::now() + std::time::Duration::from_secs(5) - }); + retrying = true; tokio::time::sleep(std::time::Duration::from_millis(20)).await; } } @@ -391,7 +402,7 @@ impl DaemonClient { "pid": std::process::id() } }); - self.open(&init, false).await?; + self.open(&init, false, false).await?; } let conn = self .conn diff --git a/bt-daemon/src/pipeline/translation.rs b/bt-daemon/src/pipeline/translation.rs index 0dfb5807..ccd1d375 100644 --- a/bt-daemon/src/pipeline/translation.rs +++ b/bt-daemon/src/pipeline/translation.rs @@ -232,6 +232,9 @@ struct Producer { state: State, publication: Option, phase: Boundary, + buffered: Vec, + buffered_events: usize, + defer_commit: bool, } impl Producer { @@ -269,6 +272,9 @@ impl Producer { state, publication: None, phase: Boundary::Journal, + buffered: Vec::new(), + buffered_events: 0, + defer_commit: false, }) } @@ -528,6 +534,8 @@ impl Producer { if self.translator.is_some() { return Ok(()); } + self.buffered.clear(); + self.buffered_events = 0; let continuation = self.options.storage.continuation().await?; self.committed = self.options.storage.status().await?.translated_through; self.roots = Roots::restore(self.options.storage.root_candidates().await?); @@ -615,7 +623,25 @@ impl Producer { } self.phase = Boundary::Journal; while let Some(entry) = self.next_input(through).await? { + // A control must observe a fully committed prefix, especially Retire, + // whose continuation intentionally precedes terminal updates. + if matches!(&entry.event, SourceEvent::Control(_)) && self.buffered_events > 0 { + self.defer_commit = false; + self.publication = Some(Publication { + input: self.position, + observation: true, + capture: self.capture.clone(), + ops: None, + built: Vec::new(), + complete: true, + continuation: None, + }); + self.publish().await?; + } let input = entry.position.through; + self.defer_commit = matches!(&entry.event, SourceEvent::Event(_)) + && input < through + && self.buffered_events < 15; let observation = !matches!(&entry.event,SourceEvent::Control(control) if matches!(control.kind,ControlKind::Retire)); let mut continuation = None; let (first, capture) = match entry.event { @@ -700,6 +726,19 @@ impl Producer { self.phase = Boundary::Journal; self.position = input; } + if self.buffered_events > 0 { + self.defer_commit = false; + self.publication = Some(Publication { + input: self.position, + observation: true, + capture: self.capture.clone(), + ops: None, + built: Vec::new(), + complete: true, + continuation: None, + }); + self.publish().await?; + } if self.position < through { // Every stored record through `through` is consumed. The rest of // the range is what a legacy journal reserved without importing a @@ -783,6 +822,17 @@ impl Producer { pending.complete = pending.ops.is_none(); } if publish { + if self.defer_commit { + self.buffered.append(&mut pending.built); + self.buffered_events += 1; + self.position = pending.input; + return Ok(()); + } + if self.buffered_events > 0 { + self.buffered.append(&mut pending.built); + pending.built = std::mem::take(&mut self.buffered); + self.buffered_events = 0; + } self.phase = Boundary::Journal; let state = match &pending.continuation { Some(state) => state.clone(), @@ -1242,6 +1292,41 @@ pub(crate) mod tests { assert_eq!(covered, Registry::default_agents().sources()); } + #[tokio::test] + async fn failed_batch_retains_inputs_and_restart_replays_without_duplicates() { + let mut f = SourceFixture::new("claude-code").await; + let (events, _) = sdk897_backlog_events(&f.options.data_dir, 16, 128); + let mut tail = 0; + for event in &events { + tail = f.write(event, false).await; + } + let db = f.db(); + db.inject(Fault::Handoff).unwrap(); + f.source.advance(tail).await.unwrap(); + assert!(f.source.barrier().await.is_err()); + assert_eq!(db.count(Table::Events), 32); + assert_eq!(db.count(Table::Ops), 0); + assert!(f.options.storage.continuation().await.unwrap().is_none()); + f.source.shutdown().await; + db.clear(Fault::Handoff).unwrap(); + f.reopen().await; + f.source.advance(tail).await.unwrap(); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while f.source.barrier().await.is_err() { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(db.count(Table::Events), 0); + let rows = db.op_records(); + assert!(!rows.is_empty()); + f.reopen().await; + f.process(tail).await; + assert_eq!(db.op_records(), rows); + f.source.shutdown().await; + } + #[tokio::test] async fn a_failed_checkpoint_publishes_nothing_and_retries_the_whole_handoff() { let mut f = SourceFixture::new("debug").await; diff --git a/bt-daemon/src/server/maintenance.rs b/bt-daemon/src/server/maintenance.rs index 801b5613..9165e787 100644 --- a/bt-daemon/src/server/maintenance.rs +++ b/bt-daemon/src/server/maintenance.rs @@ -581,8 +581,15 @@ mod tests { ) .await; assert!( - !matches!(result, Ok(Ok(()))), - "an unacknowledged event must not be reported as captured" + matches!(result, Ok(Ok(()))), + "hook must capture before handover" + ); + let storage = crate::collections::SessionStorage::open(tmp.path(), "debug", "handover") + .await + .unwrap(); + assert!( + storage.status().await.unwrap().event_tail > 0, + "capture must be durable before recovery finishes" ); let returned = result.is_ok(); println!("hook.handover: returned_before_recovery={returned}"); diff --git a/bt-daemon/src/trace_runtime.rs b/bt-daemon/src/trace_runtime.rs index f5709781..a1a35d02 100644 --- a/bt-daemon/src/trace_runtime.rs +++ b/bt-daemon/src/trace_runtime.rs @@ -1451,6 +1451,9 @@ mod tests { crate::forward_envelope(&env, &self.socket, &host, true) .await .unwrap(); + // Status is a nonblocking snapshot. Wait explicitly when a test + // needs the result of processing a just-captured event. + let _ = crate::flush_session(session_id, &self.socket, 100).await; } async fn stop(self) { From 8d0102e8ea1028896a0a9ca10f1b5af47ed249c2 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 01:14:14 +0800 Subject: [PATCH 5/8] Wait for routed session snapshots in distributed tracing tests --- bt-daemon/tests/distributed_tracing.rs | 52 +++++++++++++++++++++----- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/bt-daemon/tests/distributed_tracing.rs b/bt-daemon/tests/distributed_tracing.rs index 752f24d4..ea4721da 100644 --- a/bt-daemon/tests/distributed_tracing.rs +++ b/bt-daemon/tests/distributed_tracing.rs @@ -2280,13 +2280,29 @@ async fn truncated_first_child_capture_stays_standalone_despite_later_evidence() .truncate(1); child_events[0].capture.as_mut().unwrap().truncated = true; forward(child_events.remove(0), &socket, &host).await; - let status = run_status(StatusArgs { - socket: Some(socket.clone()), - session_id: Some("partial-child".into()), + // Status is a passive snapshot; capture acknowledgement does not wait + // for routing. Observe the eventual session without forcing a flush. + let status = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let status = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: Some("partial-child".into()), + }) + .await + .unwrap() + .unwrap(); + if status + .sessions + .iter() + .any(|s| s.session_id == "partial-child") + { + break status; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) .await - .unwrap() - .unwrap(); + .expect("captured session must become visible"); let accepted = status .sessions .iter() @@ -2555,13 +2571,29 @@ async fn unconfirmed_child_is_visible_and_delivered_without_more_events() { prompt.capture = child_events[0].capture.clone(); forward(child_events.remove(0), &socket, &host).await; forward(prompt, &socket, &host).await; - let status = run_status(StatusArgs { - socket: Some(socket.clone()), - session_id: Some("bounded-child".into()), + // Status is a passive snapshot; capture acknowledgement does not wait + // for routing. Observe the eventual session without forcing a flush. + let status = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let status = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: Some("bounded-child".into()), + }) + .await + .unwrap() + .unwrap(); + if status + .sessions + .iter() + .any(|s| s.session_id == "bounded-child") + { + break status; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) .await - .unwrap() - .unwrap(); + .expect("captured session must become visible"); let child = status .sessions .iter() From 417fae30a254149e1bb3e6801c9a4c55560c8dbb Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 01:21:26 +0800 Subject: [PATCH 6/8] Keep handover endpoint available while draining captured events --- bt-daemon/src/server/rpc.rs | 10 +++- bt-daemon/tests/pipeline.rs | 104 +++++++++++++++++++++++++++--------- 2 files changed, 88 insertions(+), 26 deletions(-) diff --git a/bt-daemon/src/server/rpc.rs b/bt-daemon/src/server/rpc.rs index e87843e7..a6ccdb55 100644 --- a/bt-daemon/src/server/rpc.rs +++ b/bt-daemon/src/server/rpc.rs @@ -145,7 +145,15 @@ pub(super) async fn serve_connection( } .await; if shutdown_after_response { - daemon.trigger_shutdown(); + // Keep accepting connections during the drain so late hooks + // receive a handover response and retry with the replacement. + // The shutdown acknowledgement itself must not wait for it. + daemon.begin_quiesce(); + let draining = daemon.clone(); + tokio::spawn(async move { + drain_all(&draining).await; + draining.trigger_shutdown(); + }); } write_result?; if stop_after_response { diff --git a/bt-daemon/tests/pipeline.rs b/bt-daemon/tests/pipeline.rs index 84f6f231..e43b694d 100644 --- a/bt-daemon/tests/pipeline.rs +++ b/bt-daemon/tests/pipeline.rs @@ -1187,18 +1187,37 @@ async fn auth_resolution_failure_is_reported_without_exposing_credentials() { ) .await .unwrap(); - let status = run_status(StatusArgs { - socket: Some(socket.clone()), - session_id: Some("login-needed".into()), + // Status observes asynchronous processing without forcing a drain. + let status = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let status = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: Some("login-needed".into()), + }) + .await + .unwrap() + .unwrap(); + if status.sessions.iter().any(|s| { + s.last_error + .as_deref() + .is_some_and(|error| error.contains("select a profile explicitly")) + }) { + break status; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) .await - .unwrap() - .unwrap(); + .expect("expected session state did not become visible"); let status_error = status.sessions[0].last_error.as_deref().unwrap(); assert!(status_error.contains("select a profile explicitly")); assert!(!status_error.contains("secret-")); assert!( - !journal_store::pending(&data_dir, "debug", "login-needed").is_empty(), + !journal_store::pending(&data_dir, "debug", "login-needed").is_empty() + || Inspector::session(&data_dir, "debug", "login-needed") + .unwrap() + .count(Table::Ops) + > 0, "capture must remain durable even when background auth fails" ); { @@ -1744,13 +1763,24 @@ async fn status_reports_sessions_and_filters_by_session_id() { .await .unwrap(); - let all = run_status(StatusArgs { - socket: Some(socket.clone()), - session_id: None, + // Status observes asynchronous processing without forcing a drain. + let all = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let all = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: None, + }) + .await + .unwrap() + .unwrap(); + if all.sessions.len() == 2 { + break all; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) .await - .unwrap() - .unwrap(); + .expect("expected session state did not become visible"); assert_eq!(all.daemon_version, "test"); assert_eq!(all.sessions.len(), 2); @@ -1846,7 +1876,7 @@ async fn daemon_version_handover_only_moves_forward() { } #[tokio::test] -async fn shutdown_drains_then_retries_late_capture_on_replacement() { +async fn shutdown_acknowledges_then_drains_and_retries_late_capture_on_replacement() { let gate = Arc::new(tokio::sync::Notify::new()); let emitted = Arc::new(std::sync::atomic::AtomicU64::new(0)); let (data_dir, socket, handle, _tmp) = start_gated_daemon(gate.clone(), emitted.clone()).await; @@ -1876,13 +1906,18 @@ async fn shutdown_drains_then_retries_late_capture_on_replacement() { }) .await .expect("daemon did not begin shutdown"); + tokio::time::timeout(Duration::from_secs(1), shutdown_task) + .await + .expect("shutdown acknowledgement waited for the sink") + .unwrap() + .unwrap(); assert!( - !shutdown_task.is_finished(), - "shutdown returned before the sink drained" + !handle.is_finished(), + "daemon exited before its sink drained" ); let late_socket = socket.clone(); - let late_event = tokio::spawn(async move { + let mut late_event = tokio::spawn(async move { forward_envelope( &envelope("drained-shutdown", "PostToolUse", 2), &late_socket, @@ -1892,13 +1927,21 @@ async fn shutdown_drains_then_retries_late_capture_on_replacement() { .await }); - shutdown_task.abort(); - let _ = shutdown_task.await; + assert!( + tokio::time::timeout(Duration::from_millis(50), &mut late_event) + .await + .is_err(), + "late capture must remain pending while the sink blocks handover" + ); gate.notify_one(); tokio::time::timeout(Duration::from_secs(5), handle) .await - .expect("daemon stayed alive after the shutdown client disconnected") + .expect("daemon stayed alive after its sink was released") .unwrap(); + assert!( + emitted.load(std::sync::atomic::Ordering::Relaxed) > 0, + "shutdown must deliver captured output before the daemon exits" + ); let replacement = start_daemon_at(data_dir.clone(), socket.clone()).await; late_event.await.unwrap().unwrap(); shutdown(&socket).await; @@ -4680,15 +4723,26 @@ async fn managed_run_flush_shares_one_budget_and_returns_pending_counts() { .await .unwrap(); } - // Journal acknowledgement precedes actor creation. Observe the ingress - // barrier before measuring finalize's budget, so initialization is excluded. - let status = run_status(StatusArgs { - socket: Some(socket.clone()), - session_id: None, + // Journal acknowledgement precedes actor creation. Wait until all actors + // are visible before measuring finalize's budget, excluding initialization. + let status = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let status = run_status(StatusArgs { + socket: Some(socket.clone()), + session_id: None, + }) + .await + .unwrap() + .unwrap(); + + if status.sessions.len() == 3 { + break status; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } }) .await - .unwrap() - .unwrap(); + .expect("managed sessions did not become visible"); assert_eq!(status.sessions.len(), 3); // All three sinks remain blocked. The server must answer with diagnostics // within its shared budget, before the client's outer deadline expires. From 39d353762e3feca8a918ac142e34931e3458da94 Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 01:33:22 +0800 Subject: [PATCH 7/8] Observe completed routing and durable pending snapshots in tests --- bt-daemon/tests/distributed_tracing.rs | 65 ++++++++++++++------------ 1 file changed, 36 insertions(+), 29 deletions(-) diff --git a/bt-daemon/tests/distributed_tracing.rs b/bt-daemon/tests/distributed_tracing.rs index ea4721da..359d889f 100644 --- a/bt-daemon/tests/distributed_tracing.rs +++ b/bt-daemon/tests/distributed_tracing.rs @@ -2281,7 +2281,8 @@ async fn truncated_first_child_capture_stays_standalone_despite_later_evidence() child_events[0].capture.as_mut().unwrap().truncated = true; forward(child_events.remove(0), &socket, &host).await; // Status is a passive snapshot; capture acknowledgement does not wait - // for routing. Observe the eventual session without forcing a flush. + // for routing. Wait past the resolved-but-not-dispatched snapshot without + // forcing a flush; other errors still reach the assertion below. let status = tokio::time::timeout(Duration::from_secs(5), async { loop { let status = run_status(StatusArgs { @@ -2291,11 +2292,11 @@ async fn truncated_first_child_capture_stays_standalone_despite_later_evidence() .await .unwrap() .unwrap(); - if status - .sessions - .iter() - .any(|s| s.session_id == "partial-child") - { + if status.sessions.iter().any(|s| { + s.session_id == "partial-child" + && s.last_error.as_deref() + != Some("correlation resolved; journaled events awaiting delivery") + }) { break status; } tokio::time::sleep(Duration::from_millis(10)).await; @@ -2310,7 +2311,7 @@ async fn truncated_first_child_capture_stays_standalone_despite_later_evidence() .expect("incomplete first capture must be accepted immediately"); assert!( accepted.last_error.is_none(), - "incomplete evidence must not defer delivery" + "incomplete evidence must not defer delivery: {accepted:?}" ); forward_all(&mut child_events, &socket, &host).await; forward( @@ -3142,29 +3143,35 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() } async fn stored_pending_child(data_dir: &Path, session: &str) -> (PathBuf, serde_json::Value) { - let mut entries = tokio::fs::read_dir(data_dir.join("correlation")) - .await - .unwrap(); - while let Some(entry) = entries.next_entry().await.unwrap() { - if entry - .path() - .extension() - .and_then(|extension| extension.to_str()) - != Some("json") - { - continue; - } - let state: serde_json::Value = - serde_json::from_slice(&tokio::fs::read(entry.path()).await.unwrap()).unwrap(); - if state["events"].as_array().is_some_and(|events| { - events - .iter() - .any(|event| event["env"]["session_id"] == session) - }) { - return (entry.path(), state); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let mut entries = tokio::fs::read_dir(data_dir.join("correlation")) + .await + .unwrap(); + while let Some(entry) = entries.next_entry().await.unwrap() { + if entry + .path() + .extension() + .and_then(|extension| extension.to_str()) + != Some("json") + { + continue; + } + let state: serde_json::Value = + serde_json::from_slice(&tokio::fs::read(entry.path()).await.unwrap()).unwrap(); + if state["events"].as_array().is_some_and(|events| { + events + .iter() + .any(|event| event["env"]["session_id"] == session) + }) { + return (entry.path(), state); + } + } + tokio::time::sleep(Duration::from_millis(10)).await; } - } - panic!("no persisted pending event for {session}"); + }) + .await + .unwrap_or_else(|_| panic!("no persisted pending event for {session}")) } fn test_host() -> HostInfo { From 8aad6906485271fa58a6c5c106be641c04d20e6b Mon Sep 17 00:00:00 2001 From: Stephen Belanger Date: Sat, 21 Nov 2026 01:45:31 +0800 Subject: [PATCH 8/8] Restore restart test snapshots into a fresh data directory --- bt-daemon/tests/distributed_tracing.rs | 54 ++++++++++++++++---------- 1 file changed, 33 insertions(+), 21 deletions(-) diff --git a/bt-daemon/tests/distributed_tracing.rs b/bt-daemon/tests/distributed_tracing.rs index 359d889f..3721c5c6 100644 --- a/bt-daemon/tests/distributed_tracing.rs +++ b/bt-daemon/tests/distributed_tracing.rs @@ -2991,37 +2991,49 @@ async fn pending_restart_preserves_current_candidates_and_decided_legacy_links() let saved_database = std::fs::read(&backup).unwrap(); shutdown_daemon(&socket).await.unwrap(); daemon.await.unwrap(); - // Restore the accepted-but-undelivered checkpoint, as after an abrupt - // process exit. Shutdown itself is covered separately above. + // Restore the crash image into a new directory. Windows cannot unlink + // SQLite files while an exiting task still owns a connection. Backup + // the other databases through SQLite, preserving their committed WAL. + let restored_dir = tmp.path().join("restored-data"); + let mut dirs = vec![(data_dir.clone(), restored_dir.clone())]; + let child_database = journal_store::path(&data_dir, "claude-code", "bounded-child"); + while let Some((from, to)) = dirs.pop() { + tokio::fs::create_dir_all(&to).await.unwrap(); + let mut entries = tokio::fs::read_dir(&from).await.unwrap(); + while let Some(entry) = entries.next_entry().await.unwrap() { + let source = entry.path(); + let target = to.join(entry.file_name()); + if entry.file_type().await.unwrap().is_dir() { + dirs.push((source, target)); + } else if source.extension().is_some_and(|ext| ext == "sqlite") { + if source != child_database { + bt_daemon::storage_inspect::Inspector::open(&source) + .unwrap() + .backup(&target) + .unwrap(); + } + } else if !source.to_string_lossy().ends_with("-wal") + && !source.to_string_lossy().ends_with("-shm") + { + tokio::fs::copy(&source, &target).await.unwrap(); + } + } + } + let path = restored_dir.join(path.strip_prefix(&data_dir).unwrap()); + let journal_path = restored_dir.join(journal_path.strip_prefix(&data_dir).unwrap()); + let data_dir = restored_dir; tokio::fs::create_dir_all(journal_path.parent().unwrap()) .await .unwrap(); - tokio::fs::write(&journal_path, journal).await.unwrap(); - // This crash fixture rolls back source persistence as well as delivery. - let id = journal_path - .file_stem() - .unwrap() - .to_str() - .unwrap() - .rsplit("--") - .next() - .unwrap(); - for suffix in [".sqlite", ".sqlite-wal", ".sqlite-shm"] { - let path = data_dir.join("pipeline").join(format!("{id}{suffix}")); - if path.exists() { - tokio::fs::remove_file(path).await.unwrap(); - } - } if format == "current" { - // A current-version crash preserves the SQLite collection and its - // exact IDs, rather than manufacturing a legacy NDJSON replacement. - tokio::fs::remove_file(&journal_path).await.unwrap(); tokio::fs::write( journal_store::path(&data_dir, "claude-code", "bounded-child"), saved_database, ) .await .unwrap(); + } else { + tokio::fs::write(&journal_path, journal).await.unwrap(); } let mut legacy_route = original_route.clone(); legacy_route.destination = Some(external_parent());