A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[factory] daemon: delete a dead-worker RLM child without a worker handshake (#3632)
Sebastian Müllerd356a1c69b6f
diff --git a/crates/pa-daemon/src/supervisor.rs b/crates/pa-daemon/src/supervisor.rsindex c4200d1ee7..6614642f05 100644--- a/crates/pa-daemon/src/supervisor.rs+++ b/crates/pa-daemon/src/supervisor.rs@@ -24,6 +24,8 @@ use launch_budget::WORKER_AUTH_FLOOR_MS;use signals_shutdown::daemon_closing_shutdown_event;mod supervision;+#[cfg(all(test, unix))]+mod dead_child_delete_tests;#[cfg(test)]mod handshake_tests;#[cfg(test)]diff --git a/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rs b/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rsnew file mode 100644index 0000000000..c009542928--- /dev/null+++ b/crates/pa-daemon/src/supervisor/dead_child_delete_tests.rs@@ -0,0 +1,283 @@+//! The delete of an RLM child whose worker process is gone: the resident+//! delete completes without a worker handshake, and a retry after the+//! ledger boundary already stands succeeds only once the worker is gone.++use super::*;++struct Fixture {+ _dir: tempfile::TempDir,+ supervisor: Arc<Supervisor>,+ child_file: String,+ ledger: Arc<crate::rlm_ledger::RlmSpawnLedger>,+}++async fn fixture() -> Fixture {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ let sessions_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ let child_file = sessions_dir.join("child-dead.jsonl");+ std::fs::write(+ &child_file,+ "{\"type\":\"session\",\"version\":3,\"id\":\"child-dead\",\"timestamp\":\"t\",\"cwd\":\"/c\"}\n",+ )+ .unwrap();+ let parent_file = sessions_dir.join("parent.jsonl");+ std::fs::write(&parent_file, "{\"type\":\"session\",\"id\":\"p\"}\n").unwrap();+ let ledger = supervisor+ .rlm_spawn_ledger_for(None)+ .await+ .expect("the spawn ledger resolves");+ let child_file = child_file.to_string_lossy().into_owned();+ ledger+ .append_spawn(&crate::rlm_ledger::RlmSpawnInput {+ child_id: "sub-dead".to_string(),+ parent: parent_file.to_string_lossy().into_owned(),+ child: child_file.clone(),+ depth: 1,+ name: "dead-worker".to_string(),+ })+ .expect("the spawn edge appends");+ Fixture {+ _dir: dir,+ supervisor,+ child_file,+ ledger,+ }+}++/// The child worker's descriptor, persisted under the supervisor's descriptor dir.+fn child_descriptor(+ supervisor: &Supervisor,+ child_file: &str,+ pid: u32,+ start_id: Option<&str>,+) -> (DaemonWorkerDescriptor, std::path::PathBuf) {+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({+ "version": 2,+ "workerId": "w-child",+ "pid": pid,+ "processStartId": start_id,+ "socketPath": "/tmp/none.sock",+ "recoveryJournalPath": "/tmp/none.jsonl",+ "supervisorSocketPath": supervisor.options.socket_path.to_string_lossy(),+ "authenticationToken": "token",+ "rootActiveSessionId": "w-child",+ "sessionFile": child_file,+ "createdAt": "t",+ "updatedAt": "t",+ "lifecycle": "ready",+ "createCommand": { "rlmDepth": 1, "rlmChildId": "sub-dead" },+ "consecutiveFailures": 0,+ }))+ .expect("descriptor");+ let path = supervisor.descriptor_dir.join("w-child.json");+ crate::descriptor::persist_worker(&path, &descriptor).expect("descriptor persists");+ (descriptor, path)+}++/// A pid that provably belonged to a process which has exited and been reaped.+fn reaped_pid() -> (u32, Option<String>) {+ let mut child = std::process::Command::new("true")+ .spawn()+ .expect("spawn true");+ let pid = child.id();+ let start_id = crate::lease::get_process_start_id(pid);+ child.wait().expect("reap true");+ (pid, start_id)+}++async fn route_delete(supervisor: &Arc<Supervisor>) -> Value {+ let (targeted_tx, _targeted_rx) = tokio::sync::mpsc::channel::<Arc<Value>>(16);+ let attached = subscribers::ClientSubscriptions::new("c".to_string(), targeted_tx);+ let command: DaemonCommand = serde_json::from_value(json!({+ "type": "kill",+ "activeSessionId": "w-child",+ "rlmLedgerDelete": "user",+ "rlmChildId": "sub-dead",+ }))+ .expect("command");+ let (lines, _) = supervisor+ .route_client_command(+ &command,+ "c",+ &attached,+ "k-1".to_string(),+ "kill".to_string(),+ None,+ )+ .await;+ lines.into_iter().next().expect("one response line")+}++/// A reaped worker awaiting its relaunch can never answer the kill: the delete+/// succeeds from the ledger boundary alone instead of answering the route's+/// not-connected failure after the stop already ran.+#[tokio::test]+async fn a_delete_of_a_dead_workers_child_completes_without_a_handshake() {+ let Fixture {+ _dir,+ supervisor,+ child_file,+ ledger,+ } = fixture().await;+ let (pid, start_id) = reaped_pid();+ let (descriptor, descriptor_path) =+ child_descriptor(&supervisor, &child_file, pid, start_id.as_deref());+ let resident = ResidentWorker::new("w-child".to_string(), descriptor, descriptor_path.clone());+ resident.note_session_ready();+ supervisor.registry.insert(Arc::clone(&resident)).await;++ let response = route_delete(&supervisor).await;++ assert_eq!(response["success"], json!(true), "{response}");+ assert!(supervisor.registry.get("w-child").await.is_none());+ assert!(+ !descriptor_path.exists(),+ "the dead worker's descriptor retires"+ );+ assert!(ledger.live_edges().expect("edges").is_empty());+}++/// Liveness, not route state, gates the short-circuit: a live worker still+/// receives the kill.+#[tokio::test]+async fn a_delete_of_a_live_workers_child_still_routes_the_kill() {+ let Fixture {+ _dir,+ supervisor,+ child_file,+ ..+ } = fixture().await;+ let mut sleeper = std::process::Command::new("sleep")+ .arg("60")+ .spawn()+ .expect("spawn sleep");+ let pid = sleeper.id();+ let (descriptor, descriptor_path) = child_descriptor(+ &supervisor,+ &child_file,+ pid,+ crate::lease::get_process_start_id(pid).as_deref(),+ );+ let resident = ResidentWorker::new("w-child".to_string(), descriptor, descriptor_path);+ let (cmd_tx, mut cmd_rx) = mpsc::channel::<WorkerRequest>(4);+ *resident.cmd_tx.lock().await = Some(cmd_tx);+ let pump_resident = Arc::clone(&resident);+ let pump = tokio::spawn(async move {+ let mut seen = Vec::new();+ while let Some(request) = cmd_rx.recv().await {+ seen.push(request.command_type.clone());+ if let Some(reply) = pump_resident+ .pending+ .lock()+ .await+ .remove(&request.request_id)+ {+ let _ = reply.send(WorkerReply::Typed(crate::protocol::response_success(+ None,+ &request.command_type,+ None,+ )));+ }+ if request.command_type == "shutdown" {+ break;+ }+ }+ seen+ });+ resident.note_connection_live();+ resident.note_session_ready();+ supervisor.registry.insert(Arc::clone(&resident)).await;++ let response = route_delete(&supervisor).await;++ let _ = sleeper.kill();+ let _ = sleeper.wait();+ assert_eq!(response["success"], json!(true), "{response}");+ let seen = pump.await.expect("pump");+ assert_eq!(seen.first().map(String::as_str), Some("kill"), "{seen:?}");+}++/// A retry after the boundary already stands is idempotent once the worker is+/// gone, and refused while its process still runs.+#[tokio::test]+async fn a_retried_delete_after_the_tombstone_is_gated_on_the_worker_process() {+ let Fixture {+ _dir,+ supervisor,+ child_file,+ ledger,+ } = fixture().await;+ ledger+ .append_delete(+ "sub-dead",+ &child_file,+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ .expect("the first attempt's tombstone");+ let retry = || {+ supervisor.tombstone_saved_rlm_child(+ "w-child",+ Some("sub-dead"),+ crate::rlm_ledger::RlmLedgerDeleteReason::User,+ )+ };++ // The first attempt stopped after the tombstone, before archiving or+ // sweeping artifacts. A successful retry must finish that cleanup.+ let artifacts = crate::scheduled_jobs::session_artifact_dir(+ std::path::Path::new(&child_file),+ "child-dead",+ )+ .expect("artifact directory");+ std::fs::create_dir_all(&artifacts).unwrap();+ std::fs::write(+ artifacts.join("unfinished.txt"),+ "left by interrupted delete",+ )+ .unwrap();+ let (pid, start_id) = reaped_pid();+ child_descriptor(&supervisor, &child_file, pid, start_id.as_deref());+ retry()+ .await+ .expect("a dead worker no longer blocks the delete");+ assert!(!artifacts.exists(), "the retry finishes the artifact sweep");+ assert_eq!(+ crate::session_store::read_session_info(std::path::Path::new(&child_file))+ .expect("session metadata")+ .state+ .as_deref(),+ Some("archived"),+ "the retry archives the stopped session"+ );++ let mut sleeper = std::process::Command::new("sleep")+ .arg("60")+ .spawn()+ .expect("spawn sleep");+ let live_pid = sleeper.id();+ child_descriptor(+ &supervisor,+ &child_file,+ live_pid,+ crate::lease::get_process_start_id(live_pid).as_deref(),+ );+ let ledger_before = std::fs::read(ledger.ledger_path()).unwrap();+ let refused = retry().await;+ let _ = sleeper.kill();+ let _ = sleeper.wait();+ let error = format!(+ "{:#}",+ refused.expect_err("a live worker refuses the delete")+ );+ assert!(error.contains(&format!("(pid {live_pid})")), "{error}");+ assert_eq!(std::fs::read(ledger.ledger_path()).unwrap(), ledger_before);+}diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rsindex 5c9cf7174e..b1302935e7 100644--- a/crates/pa-daemon/src/supervisor/routing.rs+++ b/crates/pa-daemon/src/supervisor/routing.rs@@ -548,6 +548,24 @@ impl Supervisor {false,);}+ // A dead worker can never answer the kill: a routed kill would fail (not+ // connected) after the stop already ran. The tombstone stands, so the stop+ // completes without a handshake and the delete succeeds.+ let (pid, start_id) = {+ let descriptor = resident.descriptor.lock().await;+ (descriptor.pid, descriptor.process_start_id.clone())+ };+ if super::worker_lifecycle::worker_process_gone(pid, start_id).await {+ self.finish_plain_kill_stop(&resident, rest).await;+ return (+ vec![response_line(&response_success(+ Some(&command_id),+ &type_name,+ None,+ ))],+ false,+ );+ }}}if let DaemonCommand::Attach {@@ -1033,46 +1051,53 @@ impl Supervisor {let edges = ledger.live_edges().with_context(|| "read the spawn ledger edges".to_string())?;- // `rlmChildId` is the durable key; the selector is the child's LIVE id, NOT- // the file stem. Order: (1a) edge matching BOTH the stem and the id; (1b)- // the LAST live edge carrying the id; (2) the stem-matching edge.- let mut resolved: Option<(String, String)> = None;- if let Some(id) = child_id {- for edge in &edges {- let stem = std::path::Path::new(&edge.child)- .file_stem()- .map(|name| name.to_string_lossy().to_string())- .unwrap_or_default();- if stem == selector && edge.child_id == id {- resolved = Some((edge.child_id.clone(), edge.child.clone()));- break;- }- }- if resolved.is_none() {- for edge in &edges {- if edge.child_id == id {- resolved = Some((edge.child_id.clone(), edge.child.clone()));- }- }- }+ let (child_id, session_file) = if let Some(resolved) =+ resolve_ledger_child(&edges, selector, child_id)+ {+ ledger+ .append_delete(&resolved.0, &resolved.1, reason)+ .with_context(|| format!("tombstone RLM subagent {}", resolved.0))?;+ resolved} else {- for edge in &edges {- let stem = std::path::Path::new(&edge.child)- .file_stem()- .map(|name| name.to_string_lossy().to_string())- .unwrap_or_default();- if stem == selector {- resolved = Some((edge.child_id.clone(), edge.child.clone()));- break;+ // A retry after the boundary already stands: an earlier attempt tombstoned the+ // edge and ran its finalize, so only a still-running worker blocks the delete.+ let tombstoned: Vec<_> = ledger+ .edges(true)+ .with_context(|| "read the spawn ledger edges".to_string())?+ .into_iter()+ .filter(|edge| edge.deleted.is_some())+ .collect();+ let Some((deleted_child_id, session_file)) =+ resolve_ledger_child(&tombstoned, selector, child_id)+ else {+ anyhow::bail!("stopped RLM subagent \"{selector}\" is not in the spawn ledger");+ };+ let canonical =+ crate::lease::canonical_session_path(std::path::Path::new(&session_file));+ for (_, descriptor) in+ crate::descriptor::load_descriptors(&self.descriptor_dir, &self.options.socket_path)+ {+ let same_session = descriptor.session_file.as_deref().is_some_and(|file| {+ crate::lease::canonical_session_path(std::path::Path::new(file)) == canonical+ });+ if same_session+ && !super::worker_lifecycle::worker_process_gone(+ descriptor.pid,+ descriptor.process_start_id.clone(),+ )+ .await+ {+ anyhow::bail!(+ "deleted RLM subagent \"{selector}\": worker {} (pid {}) is still running; delete refused until it exits",+ descriptor.worker_id,+ descriptor.pid+ );}}- }- let Some((child_id, session_file)) = resolved else {- anyhow::bail!("stopped RLM subagent \"{selector}\" is not in the spawn ledger");+ // The first attempt may have stopped after appending its tombstone.+ // Reuse the same finalization without writing a second boundary.+ (deleted_child_id, session_file)};- ledger- .append_delete(&child_id, &session_file, reason)- .with_context(|| format!("tombstone RLM subagent {child_id}"))?;// The stopped child's teardown mirrors the resident delete's end state: the usage// capture, archived state, and artifact sweep land as a live child's kill leaves them.let sessions_dir = crate::paths::sessions_dir(&self.options.agent_dir)@@ -1125,6 +1150,29 @@ impl Supervisor {}}+/// The ledger edge a delete addresses, as `(child_id, child_file)`. `rlmChildId` is the durable+/// key; the selector is the child's LIVE id, NOT the file stem. Order: (1a) edge matching BOTH+/// the stem and the id; (1b) the LAST edge carrying the id; (2) the stem-matching edge.+fn resolve_ledger_child(+ edges: &[crate::rlm_ledger::RlmLedgerEdge],+ selector: &str,+ child_id: Option<&str>,+) -> Option<(String, String)> {+ let stem_matches = |edge: &crate::rlm_ledger::RlmLedgerEdge| {+ std::path::Path::new(&edge.child)+ .file_stem()+ .is_some_and(|name| name.to_string_lossy() == selector)+ };+ let found = match child_id {+ Some(id) => edges+ .iter()+ .find(|edge| stem_matches(edge) && edge.child_id == id)+ .or_else(|| edges.iter().rev().find(|edge| edge.child_id == id)),+ None => edges.iter().find(|edge| stem_matches(edge)),+ };+ found.map(|edge| (edge.child_id.clone(), edge.child.clone()))+}+/// The client response line for one relayed worker payload: the worker's/// own `response_line` bytes with the client's command id spliced in front.pub(crate) fn spliced_client_line(command_id: &str, worker_payload: &[u8]) -> Vec<u8> {diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex 4b281a27d4..b35286d9a3 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -908,6 +908,27 @@ pub(super) fn recovery_journal_owner_is_gone(}}+/// Whether a worker process is provably gone (the journal-owner rule: dead, or its pid now+/// belongs to another process). Pid 0 records no identity and is never proof.+pub(super) async fn worker_process_gone(pid: u64, start_id: Option<String>) -> bool {+ let Ok(pid) = u32::try_from(pid) else {+ return false;+ };+ if pid == 0 {+ return false;+ }+ // On macOS the start-id probe shells out to `ps`: keep it off the executor.+ tokio::task::spawn_blocking(move || {+ recovery_journal_owner_is_gone(+ crate::lease::is_process_alive(pid).ok(),+ start_id.as_deref(),+ crate::lease::get_process_start_id(pid).as_deref(),+ )+ })+ .await+ .unwrap_or(false)+}+/// Probe a worker socket until it accepts connections or the connect budget runs out; the/// error names the worker so a stuck launch reports which session never came up.pub(super) async fn probe_worker_socket(diff --git a/scripts/review_dead_child_delete_parity.py b/scripts/review_dead_child_delete_parity.pynew file mode 100644index 0000000000..35abd9e2e9--- /dev/null+++ b/scripts/review_dead_child_delete_parity.py@@ -0,0 +1,170 @@+#!/usr/bin/env python3+"""Hosted real TS/Rust RLM child deletion baseline and Rust idempotent retry.++A real kernel admits a child whose model request is held. The ordinary daemon+kill command is accepted by both implementations. Rust closes its separate+child worker and removes its projection. TS hosts the child in its parent worker+and its plain kill leaves the spawn edge live; its immediate projection is+retained in the receipt without claiming delete parity. Rust recognizes rlmLedgerDelete and persists+its edge boundary; pinned TS ignores that Rust-native marker (raw ledger+absence is retained as an explicit difference). The new dead-PID and+interrupted-cleanup branches are separately exercised by hosted Unix supervisor+regressions; this fixture does not manufacture a process death or claim parity+for historical TS retry errors.+"""+import argparse+import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import threading+import time++from review_ledger_liveness_parity import Provider, PARENT, NAME+from review_agent_bounce_parity import Client+from review_draft_disconnect_parity import digest, env_for, TS_ARCHIVE_SHA256+from review_goal_fixture_lifecycle import OwnedProcesses, TAG, finish, verify_worker, process_identity+++def delete_contract(rows, child_id):+ deletes = [row for row in rows if row.get('op') == 'delete' and row.get('childId') == child_id]+ assert deletes, 'the actual child deletion did not persist its boundary'+ assert all(row.get('reason') == 'user' for row in deletes), deletes+ return deletes+++def observe(binary, kind, root, observed):+ env = env_for(root, kind)+ env[TAG] = str(root)+ library = Path(os.environ['PI_PACKAGE_DIR']) / 'skills'+ env['PYTHONPATH'] = os.pathsep.join(str(p) for p in library.glob('*/src') if p.is_dir())+ provider = Provider()+ threading.Thread(target=provider.serve_forever, daemon=True).start()+ (root / 'agent/models.json').write_text(json.dumps({'providers': {'parity-local': {+ 'api': 'openai-completions', 'apiKey': 'fixture-only',+ 'baseUrl': f'http://127.0.0.1:{provider.server_port}/v1', 'models': [{+ 'id': 'parity-1', 'name': 'Parity 1', 'reasoning': False,+ 'contextWindow': 128000, 'maxTokens': 4096}]}}}))+ (root / 'agent/settings.json').write_text(json.dumps({'prewarmPythonKernel': False,+ 'defaultProvider': 'parity-local', 'defaultModel': 'parity-1'}))+ path = root / 'd.sock'+ scope = OwnedProcesses(binary, root, path)+ daemon = control = None+ log = open(root / 'daemon.log', 'wb')+ try:+ command = [str(binary), '--mode', 'daemon', '--daemon-socket', str(path)]+ daemon = subprocess.Popen(command, cwd=root, env=env, stdout=log,+ stderr=subprocess.STDOUT, start_new_session=True)+ scope.register(daemon, command)+ control = Client(path, daemon)+ created = control.call('create', config={'cwd': str(root), 'agentDir': str(root / 'agent'),+ 'provider': 'parity-local', 'model': 'parity-1', 'telemetryDisabled': True})+ active = created.get('activeSessionId') or created.get('id')+ assert active, created+ control.call('attach', activeSessionId=active)+ control.call('prompt', activeSessionId=active, message=PARENT)+ child_id = provider.ready()['child_id']+ listed = control.call('list', all=True)+ rows = [r for r in listed['sessions'] if r.get('rlmChildId') == child_id]+ assert len(rows) == 1 and rows[0].get('sessionName') == NAME, rows+ row = rows[0]+ child_active = row.get('activeSessionId') or row.get('id')+ assert child_active and row.get('parentActiveSessionId') == active, row+ observed['child_before'] = row+ descriptors = [json.loads(p.read_text()) for p in (root / 'agent/daemon-workers').rglob('*.json')]+ worker_root = child_active if kind == 'rust' else active+ child_descriptors = [d for d in descriptors if d.get('rootActiveSessionId') == worker_root]+ assert len(child_descriptors) == 1, child_descriptors+ pid, identity = verify_worker(child_descriptors[0], worker_root, binary, path)+ if kind == 'ts':+ assert row['workerPid'] == pid, 'TS child is not in the verified parent worker'+ observed['worker_layout'] = 'separate child worker' if kind == 'rust' else 'shared parent worker'+ scope.discover()+ observed['child_process_identity'] = {'pid': pid, 'start_id': identity}+ payload = {'activeSessionId': child_active, 'rlmLedgerDelete': 'user', 'rlmChildId': child_id}+ observed['delete_response'] = control.call('kill', **payload)+ after_list = control.call('list', all=True)+ observed['sessions_after'] = after_list+ if kind == 'rust':+ assert not any(r.get('activeSessionId') == child_active for r in after_list['sessions']), after_list+ observed['child_session_closed'] = True+ deadline = time.monotonic() + 15+ while True:+ try:+ current, state = process_identity(pid)+ stopped = current != identity or state == 'Z'+ except FileNotFoundError:+ stopped = True+ if stopped:+ break+ assert time.monotonic() < deadline, 'actual child worker did not exit after kill'+ threading.Event().wait(0.025)+ observed['child_worker_stopped'] = True+ else:+ observed['ts_child_projection_after_raw_kill'] = [r for r in after_list['sessions']+ if r.get('rlmChildId') == child_id]+ current, state = process_identity(pid)+ assert current == identity and state != 'Z', 'TS unexpectedly lost the shared parent worker'+ observed['shared_parent_worker_alive'] = True+ def ledger():+ return [json.loads(line) for p in (root / 'agent/rlm-ledger').glob('*.jsonl')+ for line in p.read_text().splitlines()]+ observed['ledger_after'] = ledger()+ if kind == 'ts':+ assert not [r for r in observed['ledger_after']+ if r.get('op') == 'delete' and r.get('childId') == child_id], observed['ledger_after']+ observed['intentional_difference'] = 'TS does not recognize the Rust-native rlmLedgerDelete kill marker'+ else:+ boundary = delete_contract(observed['ledger_after'], child_id)+ assert len(boundary) == 1, 'expected exactly one original deletion boundary'+ observed['retry_response'] = control.call('kill', **payload)+ observed['ledger_after_retry'] = ledger()+ # No second deletion boundary; usage amendments, if any, retain+ # their actual rows and are not normalized out of this count.+ after = delete_contract(observed['ledger_after_retry'], child_id)+ assert after == boundary, 'idempotent retry changed the original boundary'+ observed['behavior_verified'] = True+ finally:+ observed['wire'] = list(control.wire) if control else []+ observed['provider_requests'] = provider.requests+ provider.release.set()+ finish(scope, control, daemon, observed)+ log.close()+ observed['daemon_log'] = (root / 'daemon.log').read_text(errors='replace')[-10000:]+ provider.shutdown()+ provider.server_close()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ result = {'verified': False, 'scope': __doc__, 'runs': {}, 'not_verified': [+ 'dead PID and interrupted cleanup (hosted Unix supervisor tests)',+ 'parent kernel registry removal', 'TS repeated-delete behavior', 'TUI']}+ try:+ assert sys.platform == 'linux'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256+ result['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-ddelete-', dir='/tmp') as folder:+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ observed = result['runs'][kind] = {'binary_sha256': digest(binary)}+ try:+ observe(binary, kind, Path(folder) / kind, observed)+ except Exception as error:+ observed['error'] = str(error)+ assert all(r.get('behavior_verified') and r.get('cleanup_verified') and 'error' not in r+ for r in result['runs'].values()), 'actual delete verification failed'+ result['verified'] = True+ except Exception as error:+ result['error'] = str(error)+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(result, ensure_ascii=False, indent=2))+ return 0 if result['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/test_review_dead_child_delete_parity.py b/scripts/test_review_dead_child_delete_parity.pynew file mode 100644index 0000000000..881378ca2f--- /dev/null+++ b/scripts/test_review_dead_child_delete_parity.py@@ -0,0 +1,16 @@+import unittest+from review_dead_child_delete_parity import delete_contract+++class DeleteReceiptGuards(unittest.TestCase):+ def test_requires_exact_child_delete_boundary(self):+ valid = {'op': 'delete', 'childId': 'child', 'reason': 'user'}+ self.assertEqual(delete_contract([valid], 'child'), [valid])+ for rows in [[], [{**valid, 'childId': 'other'}], [{**valid, 'op': 'spawn'}],+ [{**valid, 'reason': 'unknown'}]]:+ with self.assertRaises(AssertionError):+ delete_contract(rows, 'child')+++if __name__ == '__main__':+ unittest.main()