Skip to content
Merged
50 changes: 33 additions & 17 deletions bt-daemon/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ pub(crate) struct DaemonClient {
host: HostInfo,
no_spawn: bool,
conn: Option<Conn>,
upgrade_after_capture: bool,
}

impl DaemonClient {
Expand All @@ -276,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<bool> {
async fn open(
&mut self,
init: &serde_json::Value,
retrying: bool,
capture: bool,
) -> anyhow::Result<bool> {
const MAX_HANDOVER_ATTEMPTS: usize = 3;
let mut handover_attempts = 0;
loop {
Expand All @@ -301,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",
Expand All @@ -326,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<tokio::time::Instant> = 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;
}
Expand All @@ -346,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) => {
Expand All @@ -360,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;
}
}
Expand All @@ -386,7 +402,7 @@ impl DaemonClient {
"pid": std::process::id()
}
});
self.open(&init, false).await?;
self.open(&init, false, false).await?;
}
let conn = self
.conn
Expand Down
224 changes: 224 additions & 0 deletions bt-daemon/src/pipeline/translation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ struct Producer {
state: State,
publication: Option<Publication>,
phase: Boundary,
buffered: Vec<SpanOp>,
buffered_events: usize,
defer_commit: bool,
}

impl Producer {
Expand Down Expand Up @@ -269,6 +272,9 @@ impl Producer {
state,
publication: None,
phase: Boundary::Journal,
buffered: Vec::new(),
buffered_events: 0,
defer_commit: false,
})
}

Expand Down Expand Up @@ -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?);
Expand Down Expand Up @@ -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?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the fetched control when a batch flush fails

When replaying a persisted backlog, next_input() has already advanced the journal reader past the control before this flush runs. If publish() encounters a transient storage failure, recovery retries the saved publication for the preceding batch and then calls advance() without resetting the reader or retaining entry. The control is consequently skipped, and a later commit can delete it without applying it. In particular, skipping a Reset makes subsequent events use stale translator state. Retain the fetched control across the failed flush, or rewind the reader to the successfully committed prefix before resuming.

Useful? React with 👍 / 👎.

}
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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -994,6 +1044,145 @@ pub(crate) mod tests {
}
}

pub(crate) fn sdk897_backlog_events(
root: &std::path::Path,
turns: usize,
body_bytes: usize,
) -> (Vec<crate::wire::Envelope>, usize) {
use crate::wire::Envelope;
use serde_json::json;
let transcript = root.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();
(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::<usize>().ok())
.unwrap_or(300);
let body_bytes = std::env::var("SDK897_BODY_BYTES")
.ok()
.and_then(|s| s.parse::<usize>().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)
.chain(std::iter::once(turns))
.collect::<std::collections::BTreeSet<_>>()
{
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());
}
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={} remaining_event_bytes={} db_bytes={db_bytes} wal_bytes={wal_bytes}",
completed * 2,
continuation.len(),
replay_time.as_millis(),
mean_save_us,
status.event_tail.saturating_sub(status.translated_through),
);
}
if let Ok(budget) = std::env::var("SDK897_MAX_REPLAY_MS") {
let budget = budget
.parse::<u128>()
.expect("SDK897_MAX_REPLAY_MS must be an integer");
assert!(
replay_time.as_millis() <= budget,
"replay exceeded {budget} ms"
);
}
f.source.shutdown().await;
if std::env::var_os("SDK897_KEEP_DATA").is_some() {
println!("retained_data_dir={}", f._dir.keep().display());
}
}

#[test]
fn every_agent_resumes_from_saved_state_at_every_native_boundary() {
let registry = crate::translate::Registry::default_agents();
Expand Down Expand Up @@ -1103,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;
Expand Down
Loading
Loading