Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

perf: write current session sidecars at every worker exit (#3614)

Sebastian Müller823904967e91
diff --git a/crates/pa-cli/tests/continue_guard_e2e.rs b/crates/pa-cli/tests/continue_guard_e2e.rs
index 8b1c3ab4ac..774259209c 100644
--- a/crates/pa-cli/tests/continue_guard_e2e.rs
+++ b/crates/pa-cli/tests/continue_guard_e2e.rs
@@ -187,6 +187,9 @@ fn print_continue_refuses_an_active_daemon_session() {
.expect("sessions")
.flatten()
.map(|entry| entry.path())
+ // The ended print session also persists its info sidecar beside the
+ // file; only the session files count here.
+ .filter(|path| path.extension().and_then(|e| e.to_str()) == Some("jsonl"))
.collect();
assert_eq!(session_files.len(), 1, "one persisted session");
let session_path = session_files[0].clone();
diff --git a/crates/pa-daemon/src/lease.rs b/crates/pa-daemon/src/lease.rs
index e6a3684b1c..874ddfac74 100644
--- a/crates/pa-daemon/src/lease.rs
+++ b/crates/pa-daemon/src/lease.rs
@@ -330,6 +330,20 @@ pub struct SessionLease {
}
impl SessionLease {
+ /// Write both sidecars while the lease is still held: the window
+ /// snapshot (current by construction) and the info sidecar, whose scan
+ /// state this folds current — rows appended since the last read (the
+ /// close's own final rows) fold here instead of at the next open.
+ /// Best-effort like the window flush: only the lease holder writes,
+ /// and a failed write costs the next open its warm resume, nothing
+ /// more. `release` runs this before the reclaim; the orphan exit,
+ /// which keeps its lease through process death, runs it alone.
+ pub(crate) fn write_sidecars(&self) {
+ let _ = pa_core::session::window::flush_cache(&self.opened_path);
+ let _ = crate::session_store::read_session_info(&self.opened_path);
+ crate::session_store::persist_info_sidecar(&self.opened_path);
+ }
+
pub fn release(&self) {
if self
.released
@@ -352,12 +366,7 @@ impl SessionLease {
{
std::thread::yield_now();
}
- let _ = pa_core::session::window::flush_cache(&self.opened_path);
- // The usage-scan sidecar persists beside the window snapshot, in
- // the same lease-keyed, best-effort shape: only the lease holder
- // writes, and a failed write costs the next open its warm resume,
- // nothing more.
- crate::session_store::persist_info_sidecar(&self.opened_path);
+ self.write_sidecars();
let _ = with_lease_guard(&self.directory, GuardWait::Fast, || {
if let Ok(Some(owner)) = read_owner(&self.directory) {
if owner.token == self.token {
diff --git a/crates/pa-daemon/src/session_store_info_tests.rs b/crates/pa-daemon/src/session_store_info_tests.rs
index 4bbf6b9079..d056246cab 100644
--- a/crates/pa-daemon/src/session_store_info_tests.rs
+++ b/crates/pa-daemon/src/session_store_info_tests.rs
@@ -1210,3 +1210,26 @@ fn borrowed_metadata_reads_match_full_parse_across_shape_matrix() {
fs::remove_dir_all(dir).unwrap();
}
+
+/// The single-writer premise: a fold by a process that does not hold the
+/// file's lease (the daemon catalog's cold read) never persists a sidecar.
+#[test]
+fn a_non_holder_fold_writes_no_sidecar() {
+ let dir = test_dir();
+ let path = dir.join("unleased.jsonl");
+ append_rows(
+ &path,
+ &[
+ json!({"type":"session","id":"sc","timestamp":"2026-09-23T00:00:00.000Z","cwd":"/test"}),
+ json!({"type":"message","id":"u1","timestamp":"2026-09-23T00:00:00.000Z",
+ "message":{"role":"user","content":"hi","timestamp":1_790_110_000_000_u64}}),
+ ],
+ );
+ let info = read_session_info(&path).unwrap();
+ assert_eq!(info.message_count, 1);
+ assert!(
+ !path.with_extension("info-cache.json").exists(),
+ "only the lease holder's release writes a sidecar"
+ );
+ fs::remove_dir_all(dir).unwrap();
+}
diff --git a/crates/pa-daemon/src/supervisor_lost.rs b/crates/pa-daemon/src/supervisor_lost.rs
index 6822256f4d..87f7ea8af1 100644
--- a/crates/pa-daemon/src/supervisor_lost.rs
+++ b/crates/pa-daemon/src/supervisor_lost.rs
@@ -106,6 +106,20 @@ async fn exit_orphaned(worker: &Worker, absent_since: tokio::time::Instant) {
agent_engine.dispose_kernel().await;
}
let _ = worker.record_recovery(false, "shutdown");
+ // The lease is retained through exit, but the sidecars still get the
+ // holder's current state before the process dies; a drain writer
+ // racing the fold leaves a valid warm tail (the load re-checks the
+ // generation and prefix).
+ let lease = worker
+ .core
+ .lock()
+ .unwrap()
+ .store
+ .as_ref()
+ .and_then(|store| store.lease.clone());
+ if let Some(lease) = lease {
+ lease.write_sidecars();
+ }
// Retain the lease through process exit: kernel disposal has a bounded
// host-request drain, so writers may survive until the process dies.
// The dead-owner sweep or the next acquire reclaims its directory.
diff --git a/crates/pa-daemon/src/worker/tests.rs b/crates/pa-daemon/src/worker/tests.rs
index 8f74d8a56e..b09353c6af 100644
--- a/crates/pa-daemon/src/worker/tests.rs
+++ b/crates/pa-daemon/src/worker/tests.rs
@@ -110,6 +110,7 @@ mod connection_state_tests;
mod goal_tests;
mod kill_broadcast_tests;
mod queue_tests;
+mod sidecar_exit_tests;
mod summary_tests;
mod warning_marker_tests;
mod windowed_attach_tests;
diff --git a/crates/pa-daemon/src/worker/tests/sidecar_exit_tests.rs b/crates/pa-daemon/src/worker/tests/sidecar_exit_tests.rs
new file mode 100644
index 0000000000..f32c815e6c
--- /dev/null
+++ b/crates/pa-daemon/src/worker/tests/sidecar_exit_tests.rs
@@ -0,0 +1,123 @@
+#![cfg(unix)]
+//! The session-end sidecar pins: a worker that ends a session leaves a
+//! current info sidecar — the next process that reads the file folds zero bytes.
+use super::*;
+use std::path::{Path, PathBuf};
+
+/// The sidecar must certify the file's final generation and have consumed
+/// it whole: `generation.len == file len && offset == file len`.
+fn assert_sidecar_current(label: &str, session_file: &Path) {
+ let file_len = std::fs::metadata(session_file).expect("session file").len();
+ let sidecar = session_file.with_extension("info-cache.json");
+ let bytes =
+ std::fs::read(&sidecar).unwrap_or_else(|error| panic!("{label}: no sidecar: {error}"));
+ let value: Value = serde_json::from_slice(&bytes).expect("the sidecar is JSON");
+ let len = value["state"]["generation"]["len"]
+ .as_u64()
+ .expect("gen len");
+ let offset = value["state"]["offset"].as_u64().expect("offset");
+ assert_eq!(
+ (len, offset),
+ (file_len, file_len),
+ "{label}: the sidecar must be current to the file's final bytes"
+ );
+}
+
+fn faux_worker(dir: &Path, reply: &str) -> std::sync::Arc<Worker> {
+ let config = WorkerConfig {
+ socket_path: dir.join("worker.sock"),
+ supervisor_socket_path: std::path::PathBuf::new(),
+ token: "token".to_string(),
+ worker_instance_id: String::new(),
+ active_session_id: "sidecar-exit-session".to_string(),
+ agent_dir: dir.join("agent"),
+ recovery_journal_path: dir.join("recovery.jsonl"),
+ telemetry_disabled: None,
+ script: Some(json!({ "engine": "faux", "responses": [reply] })),
+ };
+ std::sync::Arc::new(Worker::new(config, None))
+}
+
+async fn create_and_prompt(worker: &Worker, create: &Value, message: &str) -> PathBuf {
+ let created = worker.dispatch("create", create).await;
+ assert!(created.success, "create failed: {created:?}");
+ let session_file = created.data.expect("summary")["sessionFile"]
+ .as_str()
+ .expect("session file")
+ .to_string();
+ let prompted = worker
+ .dispatch(
+ "prompt_and_wait",
+ &json!({"activeSessionId": "sidecar-exit-session", "message": message}),
+ )
+ .await;
+ assert!(prompted.success, "the prompt failed: {prompted:?}");
+ PathBuf::from(session_file)
+}
+
+async fn kill(worker: &Worker) {
+ let killed = worker.dispatch("kill", &json!({})).await;
+ assert!(killed.success, "kill failed: {killed:?}");
+}
+
+/// A worker whose turn settled: the fresh arm never folds, so the sidecar
+/// is current only if the END wrote it — not a warm tail of the kill's own
+/// archived row.
+#[cfg(unix)]
+#[allow(clippy::await_holding_lock)] // the faux registry is process-global: the guard must span the async flow
+#[tokio::test]
+async fn an_ended_worker_session_leaves_a_current_info_sidecar() {
+ let _faux = crate::agent_engine::tests::FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let dir = std::env::temp_dir().join(format!("pa-sidecar-exit-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let worker = faux_worker(&dir, "sidecar reply");
+ let session_file = create_and_prompt(
+ &worker,
+ &json!({
+ "cwd": dir.to_string_lossy(),
+ "sessionDir": dir.join("sessions").to_string_lossy(),
+ }),
+ "sidecar question",
+ )
+ .await;
+ // The scan prime the roster pushes make in production (the push queue
+ // is off in this fixture; the orphan-exit e2e covers the push path).
+ let _ = crate::session_store::read_session_info(&session_file);
+ kill(&worker).await;
+ assert_sidecar_current("fresh + turn + kill", &session_file);
+}
+
+/// The bump-day shape: a reopened session over a dead-version sidecar ends
+/// with a sidecar at the served version, current to the file's final bytes.
+#[cfg(unix)]
+#[allow(clippy::await_holding_lock)] // the faux registry is process-global: the guard must span the async flow
+#[tokio::test]
+async fn a_reopened_session_ends_with_a_current_info_sidecar() {
+ let _faux = crate::agent_engine::tests::FAUX_TEST_LOCK
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let dir = std::env::temp_dir().join(format!("pa-sidecar-reopen-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let create = json!({
+ "cwd": dir.to_string_lossy(),
+ "sessionPath": dir.join("sessions").join("reopen.jsonl").to_string_lossy(),
+ });
+ let first = faux_worker(&dir, "first reply");
+ let session_file = create_and_prompt(&first, &create, "first question").await;
+ let _ = crate::session_store::read_session_info(&session_file);
+ kill(&first).await;
+ // The dead-version sidecar a newer build must not serve.
+ let sidecar = session_file.with_extension("info-cache.json");
+ let mut value: Value =
+ serde_json::from_slice(&std::fs::read(&sidecar).expect("the first kill wrote a sidecar"))
+ .expect("the sidecar is JSON");
+ value["version"] = json!(1);
+ std::fs::write(&sidecar, serde_json::to_vec(&value).unwrap()).unwrap();
+
+ let second = faux_worker(&dir, "second reply");
+ create_and_prompt(&second, &create, "second question").await;
+ kill(&second).await;
+ assert_sidecar_current("reopen + turn + kill", &session_file);
+}
diff --git a/crates/pa-daemon/tests/worker_orphan_exit_e2e.rs b/crates/pa-daemon/tests/worker_orphan_exit_e2e.rs
index deb5bc1306..147d85e663 100644
--- a/crates/pa-daemon/tests/worker_orphan_exit_e2e.rs
+++ b/crates/pa-daemon/tests/worker_orphan_exit_e2e.rs
@@ -25,16 +25,18 @@ impl Drop for WorkerGuard {
/// with the lost-exit window at zero (exit at the first availability check
/// that cannot connect).
fn spawn_worker(dir: &Path, supervisor_socket: &Path) -> WorkerGuard {
- spawn_worker_with_window(dir, supervisor_socket, "0")
+ spawn_worker_with_window(dir, supervisor_socket, "0", None)
}
fn spawn_worker_with_window(
dir: &Path,
supervisor_socket: &Path,
lost_exit_ms: &str,
+ script: Option<&Path>,
) -> WorkerGuard {
std::fs::create_dir_all(dir.join("agent")).expect("agent dir");
- let child = Command::new(env!("CARGO_BIN_EXE_pa-daemon"))
+ let mut command = Command::new(env!("CARGO_BIN_EXE_pa-daemon"));
+ command
.arg("worker")
.env(pa_daemon::worker::WORKER_ROLE_ENV, "1")
.env(
@@ -61,7 +63,11 @@ fn spawn_worker_with_window(
.env(
pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,
lost_exit_ms,
- )
+ );
+ if let Some(script) = script {
+ command.env(pa_daemon::worker::WORKER_SCRIPT_ENV, script);
+ }
+ let child = command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -229,7 +235,7 @@ fn the_orphan_exit_preserves_the_session_and_allows_dead_owner_lease_reclaim() {
let dir = tempfile::tempdir().expect("temp dir");
let canonical_dir = std::fs::canonicalize(dir.path()).expect("canonical dir");
let supervisor_socket = dir.path().join("never-bound-supervisor.sock");
- let mut worker = spawn_worker_with_window(dir.path(), &supervisor_socket, "4000");
+ let mut worker = spawn_worker_with_window(dir.path(), &supervisor_socket, "4000", None);
let worker_socket = dir.path().join("worker.sock");
wait_worker_socket(&worker_socket);
let session_file = canonical_dir.join("orphan-lease-session.jsonl");
@@ -286,7 +292,7 @@ fn an_orphaned_worker_waits_for_a_running_user_bash() {
let dir = tempfile::tempdir().expect("temp dir");
let canonical_dir = std::fs::canonicalize(dir.path()).expect("canonical dir");
let supervisor_socket = dir.path().join("never-bound-supervisor.sock");
- let mut worker = spawn_worker_with_window(dir.path(), &supervisor_socket, "4000");
+ let mut worker = spawn_worker_with_window(dir.path(), &supervisor_socket, "4000", None);
let worker_socket = dir.path().join("worker.sock");
wait_worker_socket(&worker_socket);
let session_file = canonical_dir.join("orphan-bash-session.jsonl");
@@ -330,3 +336,60 @@ fn an_orphaned_worker_waits_for_a_running_user_bash() {
})]
);
}
+
+/// The orphan exit retains its lease through process death, but it still
+/// writes the sidecars while it holds them: a session whose turn settled
+/// leaves a current info sidecar (`generation.len == offset == file len`),
+/// so the next daemon boot folds zero bytes instead of the transcript.
+#[test]
+fn the_orphan_exit_writes_a_current_info_sidecar() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let canonical_dir = std::fs::canonicalize(dir.path()).expect("canonical dir");
+ let script = dir.path().join("faux-script.json");
+ std::fs::write(
+ &script,
+ r#"{"engine":"faux","responses":["orphan sidecar reply"]}"#,
+ )
+ .expect("script file");
+ let supervisor_socket = dir.path().join("never-bound-supervisor.sock");
+ let mut worker =
+ spawn_worker_with_window(dir.path(), &supervisor_socket, "4000", Some(&script));
+ let worker_socket = dir.path().join("worker.sock");
+ wait_worker_socket(&worker_socket);
+ let session_file = canonical_dir.join("orphan-sidecar-session.jsonl");
+ let mut client = WorkerClient::connect(&worker_socket, "orphan-e2e-bootstrap-token");
+ let created = client.request(
+ "create",
+ &serde_json::json!({ "sessionPath": session_file.to_string_lossy() }),
+ );
+ assert_eq!(created["success"], true, "create failed: {created}");
+ let prompted = client.request(
+ "prompt_and_wait",
+ &serde_json::json!({
+ "activeSessionId": "orphan-e2e-session",
+ "message": "orphan sidecar question",
+ }),
+ );
+ assert_eq!(prompted["success"], true, "prompt failed: {prompted}");
+ drop(client);
+
+ assert!(
+ wait_exit(&mut worker.child, Duration::from_secs(40)),
+ "the orphaned worker exited on the supervisor-lost window"
+ );
+ let file_len = std::fs::metadata(&session_file)
+ .expect("session file")
+ .len();
+ let sidecar = std::fs::read(session_file.with_extension("info-cache.json"))
+ .expect("the orphan exit wrote its info sidecar");
+ let value: serde_json::Value = serde_json::from_slice(&sidecar).expect("sidecar json");
+ let len = value["state"]["generation"]["len"]
+ .as_u64()
+ .expect("gen len");
+ let offset = value["state"]["offset"].as_u64().expect("offset");
+ assert_eq!(
+ (len, offset),
+ (file_len, file_len),
+ "the orphan exit's sidecar must be current"
+ );
+}
diff --git a/scripts/review_ledger_liveness_parity.py b/scripts/review_ledger_liveness_parity.py
index f9493e6a76..0275187a72 100644
--- a/scripts/review_ledger_liveness_parity.py
+++ b/scripts/review_ledger_liveness_parity.py
@@ -3,8 +3,9 @@
A real parent kernel admits a child with rlm.spawn. The synthetic provider holds
that child's turn while both daemons answer repeated list/roster reads. This is
-live-family baseline parity, not a TS proof of external symlink retargeting or
-passivation/registration timing; those boundaries are recorded as out of scope.
+live-family baseline parity plus real disk relocation/deletion and catalog wake
+restore observations. Historical flat-path tombstone rows are explicit fixture
+inputs. Symlink retargeting and registration timing remain out of scope.
"""
import argparse
import http.server
@@ -25,6 +26,7 @@ from review_restore_notice_parity import texts
PARENT = 'Create the ledger liveness fixture child.'
CHILD = 'LEDGER_LIVENESS_CHILD_HOLD'
NAME = 'ledger-fixture-child'
+BILLING = 'LEDGER_CACHE_BILLING_TURN'
MARKER = 'LEDGER_LIVENESS_ADMITTED='
CODE = """import json
ledger_handle = await rlm.spawn('LEDGER_LIVENESS_CHILD_HOLD', name='ledger-fixture-child')
@@ -95,6 +97,8 @@ class Provider(http.server.ThreadingHTTPServer):
self.probe = None
self.parent_calls = 0
self.child_arrived = False
+ self.billing_calls = 0
+ self.restore_release = threading.Event()
def ready(self):
with self.arrived:
@@ -114,7 +118,11 @@ class Handler(http.server.BaseHTTPRequestHandler):
is_child = any(CHILD in text for text in user_texts)
with self.server.arrived:
self.server.requests.append(body)
- if is_child:
+ billing = any(BILLING in text for text in user_texts)
+ if billing:
+ self.server.billing_calls += 1
+ delta, finish = {'content': 'Billing fixture completed.'}, 'stop'
+ elif is_child:
self.server.child_arrived = True
delta, finish = {'content': 'Child fixture released.'}, 'stop'
else:
@@ -132,11 +140,16 @@ class Handler(http.server.BaseHTTPRequestHandler):
self.server.probe = admitted_probe(body)
delta, finish = {'content': 'Parent fixture completed.'}, 'stop'
self.server.arrived.notify_all()
- if is_child:
+ if billing and self.server.billing_calls > 1:
+ # The restored session's new delivery remains in flight while
+ # its catalog own-usage is compared with the original captured usage.
+ self.server.restore_release.wait(LIMIT * 4)
+ elif is_child:
self.server.release.wait(LIMIT * 4)
def chunk(delta, reason=None):
return {'id': 'ledger-fixture', 'object': 'chat.completion.chunk', 'created': 1,
- 'model': 'parity-1', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}]}
+ 'model': 'parity-1', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': reason}],
+ 'usage': {'prompt_tokens': 8, 'completion_tokens': 3, 'total_tokens': 11} if reason else None}
wire = ''.join('data: ' + json.dumps(row) + '\n\n' for row in (
chunk({'role': 'assistant', **delta}), chunk({}, finish))) + 'data: [DONE]\n\n'
encoded = wire.encode()
@@ -163,7 +176,136 @@ def family_contract(rows, child_id, parent_active):
'parent': '<resident-parent>', 'transcript_exists': True}
-def run_case(binary, kind, root, observed):
+def catalog_row(view, path):
+ rows = [row for row in view['sessions'] if Path(row['path']).resolve() == path.resolve()]
+ assert len(rows) == 1, 'expected exactly one actual catalog path: ' + repr(rows)
+ return rows[0]
+
+
+def archive_restore_unsupported(response, session_id):
+ return (response.get('type') == 'response' and response.get('command') == 'send_message'
+ and response.get('success') is False
+ and response.get('error') == 'Unknown active session: ' + session_id)
+
+
+def cache_boundaries(client, config, root, created, child, ledger_path, provider, kind, observed,
+ require_current_sidecar):
+ parent_file = Path(created['sessionFile'])
+ child_file = Path(child['sessionFile'])
+ child_active = child.get('activeSessionId') or child.get('id')
+ assert child_active, child
+ headers = [json.loads(line) for line in child_file.read_text().splitlines()
+ if line.strip() and json.loads(line).get('type') == 'session']
+ assert len(headers) == 1 and headers[0].get('id'), headers
+ child_session_id = headers[0]['id']
+ provider.release.set()
+ client.call('wait_for_idle', activeSessionId=child_active)
+ client.call('wait_for_idle', activeSessionId=created.get('activeSessionId') or created['id'])
+ client.call('kill', activeSessionId=child_active)
+ sidecar = child_file.with_suffix('.info-cache.json')
+ if kind == 'rust':
+ observed['lease_exit_sidecar'] = {'path': str(sidecar), 'exists': sidecar.is_file()}
+ if sidecar.is_file():
+ data = json.loads(sidecar.read_text())
+ generation = data['state']['generation']['len']
+ offset = data['state']['offset']
+ length = child_file.stat().st_size
+ observed['lease_exit_sidecar'].update(version=data['version'], generation=generation,
+ offset=offset, transcript_bytes=length, current=(generation == offset == length))
+ if require_current_sidecar:
+ assert observed['lease_exit_sidecar'].get('current'), 'ended child sidecar is not current'
+ before = ledger_path.read_bytes()
+ trace = observed['cache_boundaries'] = {'artifact_reads': [], 'setup':
+ 'actual spawned child transcript moved only after worker kill; historical flat-path tombstone fixture below'}
+ relocated = root / 'agent/session-artifacts/ledger-moved/first' / child_file.name
+ relocated.parent.mkdir(parents=True)
+ child_file.rename(relocated)
+ first = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ trace['artifact_reads'].append(first)
+ first_matches = [row for row in first['sessions'] if Path(row['path']).resolve() == relocated.resolve()]
+ assert len(first_matches) <= 1, first_matches
+ trace['first_relocated_child_present'] = len(first_matches) == 1
+ if kind == 'rust':
+ assert catalog_row(first, relocated)['id'] == child_session_id
+ moved_again = root / 'agent/session-artifacts/ledger-moved/second' / child_file.name
+ moved_again.parent.mkdir(parents=True)
+ relocated.rename(moved_again)
+ second = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ trace['artifact_reads'].append(second)
+ recovered = [row for row in second['sessions'] if Path(row['path']).resolve() == moved_again.resolve()]
+ removed = root / ('removed-' + child_file.name)
+ moved_again.rename(removed)
+ third = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ trace['artifact_reads'].append(third)
+ stale = [row for row in third['sessions'] if row['id'] == child_session_id]
+ trace['artifact_contract'] = {'relocation_recovered': len(recovered) == 1, 'removed_child_absent': not stale}
+ if kind == 'rust':
+ assert trace['artifact_contract'] == {'relocation_recovered': True, 'removed_child_absent': True}, trace
+ assert ledger_path.read_bytes() == before, 'artifact mutations unexpectedly changed ledger'
+ # Restore the actual transcript so normal cleanup retains the original fixture layout.
+ removed.rename(child_file)
+
+ billing = client.call('create', name='ledger-billing-child', config=config)
+ billing_active = billing.get('activeSessionId') or billing.get('id')
+ billing_file = Path(billing['sessionFile'])
+ client.call('prompt_and_wait', activeSessionId=billing_active, message=BILLING)
+ client.call('kill', activeSessionId=billing_active)
+ own_view = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ own = catalog_row(own_view, billing_file)
+ usage = own.get('usage')
+ assert usage and usage['inputTokens'] > 0 and usage['outputTokens'] > 0, own
+ # Controlled, valid historic ledger input: unlike the initial admission this
+ # edge is seeded by the fixture, never claimed to be an actual rlm.spawn.
+ records = [
+ {'v': 1, 'op': 'spawn', 'at': '2026-01-01T00:00:00Z', 'childId': 'fixture-flat-child',
+ 'parent': str(parent_file), 'child': str(billing_file), 'depth': 1, 'name': 'billing-child'},
+ {'v': 1, 'op': 'delete', 'at': '2026-01-01T00:00:01Z', 'childId': 'fixture-flat-child',
+ 'child': str(billing_file), 'reason': 'user', 'usage': usage}]
+ with ledger_path.open('a') as output:
+ for record in records:
+ output.write(json.dumps(record) + '\n')
+ trace['seeded_historical_records'] = records
+ archive = root / 'agent/sessions-archive' / billing_file.name
+ archive.parent.mkdir(parents=True, exist_ok=True)
+ billing_file.rename(archive)
+ unchanged = ledger_path.read_bytes()
+ warm = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ trace['bucket_warm'] = warm
+ parent_before = catalog_row(warm, parent_file)
+ trace['warm_bucket_matches_actual_usage'] = parent_before.get('deletedDescendantUsage') == usage
+ if kind == 'rust':
+ assert trace['warm_bucket_matches_actual_usage'], parent_before
+ try:
+ wake = client.call('send_message', targetActiveSessionId=own['id'], message='Restore the billing fixture.')
+ except AssertionError:
+ response = client.wire[-1]
+ if kind != 'ts' or not archive_restore_unsupported(response, own['id']):
+ raise
+ # The pinned binary has now actually refused this archived selector.
+ # Retain the refusal; never simulate a restore or call it parity.
+ trace['actual_restore_wake'] = {'supported': False, 'response': response}
+ assert archive.is_file() and not billing_file.exists(), 'refused wake partially restored the file'
+ assert ledger_path.read_bytes() == unchanged, 'refused wake changed the ledger'
+ trace['bucket_contract'] = {'actual_archive_restore_supported': False,
+ 'restored_child_has_own_usage': None, 'parent_bucket_withdrawn': None}
+ trace['ledger_unchanged_across_boundary_operations'] = True
+ return {'artifact': trace['artifact_contract'], 'bucket': trace['bucket_contract']}
+ trace['actual_restore_wake'] = {'supported': True, 'receipt': wake}
+ assert billing_file.is_file() and not archive.exists(), 'actual catalog wake did not restore transcript'
+ restored = client.call('list_saved_sessions', cwd=str(root), scope='all')
+ trace['bucket_after_actual_restore'] = restored
+ parent_after = catalog_row(restored, parent_file)
+ restored_child = catalog_row(restored, billing_file)
+ trace['bucket_contract'] = {'restored_child_has_own_usage': restored_child.get('usage') == usage,
+ 'parent_bucket_withdrawn': 'deletedDescendantUsage' not in parent_after}
+ if kind == 'rust':
+ assert trace['bucket_contract'] == {'restored_child_has_own_usage': True, 'parent_bucket_withdrawn': True}, trace
+ assert ledger_path.read_bytes() == unchanged, 'actual restore unexpectedly appended ledger'
+ trace['ledger_unchanged_across_boundary_operations'] = True
+ return {'artifact': trace['artifact_contract'], 'bucket': trace['bucket_contract']}
+
+
+def run_case(binary, kind, root, observed, require_current_sidecar=False):
env = env_for(root, kind)
library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'
env['PYTHONPATH'] = os.pathsep.join(sorted(str(path) for path in library.glob('*/src') if path.is_dir()))
@@ -218,12 +360,16 @@ def run_case(binary, kind, root, observed):
listed = [row for row in observed['lists'][0]['sessions'] if row.get('rlmChildId') == child_id]
assert Path(spawns[0]['child']).resolve() == Path(listed[0]['sessionFile']).resolve(), spawns
assert Path(spawns[0]['child']).is_file(), spawns
+ assert len(ledgers) == 1, ledgers
+ cache_boundaries(client, config, root, created, listed[0], ledgers[0], provider, kind, observed,
+ require_current_sidecar)
return {'list': contracts, 'roster': roster_contract,
'durable_spawn': {'name': NAME, 'depth': 1, 'count': 1,
'parent_matches_created_session': True, 'child_transcript_exists': True}}
finally:
observed['owned_before_shutdown'] = owned_processes(root)
provider.release.set()
+ provider.restore_release.set()
if process and process.poll() is None and client:
try:
client.call('shutdown', force=True)
@@ -247,7 +393,7 @@ def run_case(binary, kind, root, observed):
confirm_cleanup(root, observed)
-def main():
+def main(require_current_sidecar=False):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--receipt', type=Path, required=True)
args = parser.parse_args()
@@ -264,12 +410,21 @@ def main():
binary = Path(os.environ['PA_' + kind.upper() + '_BINARY']).resolve()
observed = result['runs'][kind] = {'binary_sha256': digest(binary)}
try:
- observed['contract'] = run_case(binary, kind, Path(temporary) / kind, observed)
+ observed['contract'] = run_case(binary, kind, Path(temporary) / kind, observed, require_current_sidecar)
except Exception as error:
observed['error'] = str(error)
errors = {kind: run['error'] for kind, run in result['runs'].items() if 'error' in run}
assert not errors, errors
assert result['runs']['ts']['contract'] == result['runs']['rust']['contract'], 'family contract mismatch'
+ result['cache_boundary_observations'] = {kind: {key: run['cache_boundaries'][key] for key in
+ ('artifact_contract', 'bucket_contract')} for kind, run in result['runs'].items()}
+ result['cache_boundary_scope'] = ('Rust regression invariants required; actual TS observations retained. '
+ 'Pinned TS omitted relocated passive children, did not expose the warmed deleted-spend bucket, and '
+ 'refused the archived selector with Unknown active session in actual hosted reads. These are '
+ 'explicit baseline limitations; no full cache-boundary parity is claimed.')
+ result['cache_boundary_comparison'] = ('identical' if result['cache_boundary_observations']['ts'] ==
+ result['cache_boundary_observations']['rust'] else 'actual TS/Rust difference; raw reads retained')
+ result['require_current_rust_lease_exit_sidecar'] = require_current_sidecar
result['verified'] = True
except Exception as error:
result['error'] = str(error)
diff --git a/scripts/review_sidecar_exit_parity.py b/scripts/review_sidecar_exit_parity.py
new file mode 100644
index 0000000000..4787fa1e09
--- /dev/null
+++ b/scripts/review_sidecar_exit_parity.py
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+"""Compare actual TS/Rust lifecycle/catalog values and require Rust exit-sidecar currency.
+
+The Rust-only v2 info sidecar must certify the final ended child transcript.
+The imported verifier retains actual TS catalog and cache-boundary observations;
+TS has no Rust sidecar-format requirement.
+"""
+import sys
+from review_ledger_liveness_parity import main
+
+if __name__ == '__main__':
+ sys.exit(main(require_current_sidecar=True))
diff --git a/scripts/test_review_ledger_liveness_parity.py b/scripts/test_review_ledger_liveness_parity.py
index 268a7abc23..a1a7b6395c 100644
--- a/scripts/test_review_ledger_liveness_parity.py
+++ b/scripts/test_review_ledger_liveness_parity.py
@@ -5,10 +5,30 @@ from unittest.mock import patch
from pathlib import Path
import unittest
-from review_ledger_liveness_parity import NAME, MARKER, admitted_probe, confirm_cleanup, family_contract
+from review_ledger_liveness_parity import NAME, MARKER, admitted_probe, archive_restore_unsupported, catalog_row, confirm_cleanup, family_contract
class FamilyReceiptTests(unittest.TestCase):
+ def test_only_exact_actual_archive_refusal_is_classified_unsupported(self):
+ row = {'type': 'response', 'command': 'send_message', 'success': False,
+ 'error': 'Unknown active session: saved-id'}
+ self.assertTrue(archive_restore_unsupported(row, 'saved-id'))
+ for changed in ({'success': True}, {'error': 'Request timed out'},
+ {'error': 'Unknown active session: different-id'}, {'command': 'kill'}):
+ self.assertFalse(archive_restore_unsupported({**row, **changed}, 'saved-id'))
+
+ def test_duplicate_catalog_paths_fail(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / 'child.jsonl'
+ row = {'path': str(path), 'id': 'child'}
+ with self.assertRaises(AssertionError):
+ catalog_row({'sessions': [row, row]}, path)
+
+ def test_catalog_selection_does_not_accept_a_matching_id_at_an_unrelated_path(self):
+ row = {'path': '/unrelated/child.jsonl', 'id': 'child'}
+ with self.assertRaises(AssertionError):
+ catalog_row({'sessions': [row]}, Path('/fixture/child.jsonl'))
+
def test_duplicate_current_probes_fail(self):
text = MARKER + '{"child_id":"child"}'
with self.assertRaises(AssertionError):