A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(kernel): reap orphaned bash groups after worker loss (#3530)
Sebastian Müllerc537f7e5ebde
diff --git a/Cargo.lock b/Cargo.lockindex 48245f29a6..a8a8f9f814 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1562,6 +1562,7 @@ dependencies = ["anyhow","filetime","futures",+ "nix","pa-agent","pa-ai","pa-core",diff --git a/crates/pa-core/src/kernel/orphan_journal.rs b/crates/pa-core/src/kernel/orphan_journal.rsindex 809e68cc97..1bb6b25ccc 100644--- a/crates/pa-core/src/kernel/orphan_journal.rs+++ b/crates/pa-core/src/kernel/orphan_journal.rs@@ -110,7 +110,8 @@ fn civil_from_unix(secs: i64) -> (i64, u32, u32, u32, u32, u32) {(year, m, d, hh, mm, ss)}-/// Read the still-active orphan processes recorded by this host process.+/// Read the still-active orphan processes a journal recorded for one owner+/// pid — the host reads its own pid; the supervisor reads a dead worker's.////// # Errors///@@ -119,8 +120,10 @@ fn civil_from_unix(secs: i64) -> (i64, u32, u32, u32, u32, u32) {/// # Panics////// The `pid` unwrap is unreachable behind the validity filter.-pub fn read_active_orphan_processes(path: &Path) -> anyhow::Result<Vec<ActiveOrphanProcess>> {- let owner_pid = i64::from(std::process::id());+pub fn read_active_orphan_processes(+ path: &Path,+ owner_pid: i64,+) -> anyhow::Result<Vec<ActiveOrphanProcess>> {let contents = match std::fs::read_to_string(path) {Ok(c) => c,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),@@ -191,7 +194,7 @@ pub fn reap_kernel_orphan_processes(kernel_pid: i32) {if kernel_pid <= 0 {return;}- let Ok(orphans) = read_active_orphan_processes(&path) else {+ let Ok(orphans) = read_active_orphan_processes(&path, i64::from(std::process::id())) else {return;};for orphan in orphans {@@ -207,6 +210,36 @@ pub fn reap_kernel_orphan_processes(kernel_pid: i32) {}}+/// Kill the still-active `bash()` process groups a dead worker's kernels+/// journaled, then clear the journal (TS `recoverUncertainWorkerOperations`'+/// orphan sweep, owner-scoped to the worker's own pid). The journal is+/// kept only when a kill failed and every record carried an identity, so+/// the next recovery pass can safely retry.+pub fn reap_worker_orphan_processes(path: &Path, worker_pid: i32) {+ if worker_pid <= 0 {+ return;+ }+ let Ok(orphans) = read_active_orphan_processes(path, i64::from(worker_pid)) else {+ return;+ };+ let mut reap_failed = false;+ let mut retry_is_safe = true;+ for orphan in orphans {+ if orphan.process_start_id.is_none() {+ retry_is_safe = false;+ }+ if !should_reap(&orphan) {+ continue;+ }+ if !kill_orphan_process(orphan.pid) {+ reap_failed = true;+ }+ }+ if !reap_failed || !retry_is_safe {+ let _ = std::fs::remove_file(path);+ }+}+#[cfg(test)]mod tests {use super::*;@@ -225,4 +258,52 @@ mod tests {assert_eq!(civil_from_unix(0), (1970, 1, 1, 0, 0, 0));assert_eq!(civil_from_unix(1_700_000_000), (2023, 11, 14, 22, 13, 20));}++ /// The worker reap's journal-clearing rule for the records a live-reap+ /// e2e cannot stage: a dead pid journaled identity-free (the kill is+ /// attempted; whether it fails or hits a reused pid, a blind retry is+ /// unsafe, so the journal is spent) and the same pid journaled with a+ /// stale identity (the start-id check never reaps a reused pid).+ #[test]+ fn worker_reap_spends_stale_and_identity_free_records() {+ let dir = tempfile::tempdir().expect("temp dir");+ let path = dir.path().join("w.orphans.jsonl");+ let owner = i64::from(std::process::id());+ let mut child = std::process::Command::new("sleep")+ .arg("0")+ .spawn()+ .expect("spawn short-lived child");+ let dead_pid = child.id() as i32;+ let _ = child.wait();+ let identity_free = json!({+ "version": 1,+ "pid": dead_pid,+ "ownerPid": owner,+ "active": true,+ "recordedAt": iso8601_now(),+ });+ let stale_identity = json!({+ "version": 1,+ "pid": dead_pid,+ "ownerPid": owner,+ "active": true,+ "processStartId": "proc:1",+ "recordedAt": iso8601_now(),+ });+ for record in [identity_free, stale_identity] {+ // Separate sweeps: the reader retains only the latest row per pid.+ std::fs::write(&path, format!("{record}\n")).expect("write journal");+ let active = read_active_orphan_processes(&path, owner).expect("read journal");+ assert_eq!(active.len(), 1);+ assert_eq!(+ active[0].process_start_id.as_deref(),+ record["processStartId"].as_str()+ );+ reap_worker_orphan_processes(&path, owner as i32);+ assert!(+ !path.exists(),+ "the journal is spent, not kept for a blind retry"+ );+ }+ }}diff --git a/crates/pa-daemon/Cargo.toml b/crates/pa-daemon/Cargo.tomlindex edec141847..3f8a059e82 100644--- a/crates/pa-daemon/Cargo.toml+++ b/crates/pa-daemon/Cargo.toml@@ -24,6 +24,8 @@ uuid = { version = "1", features = ["v4", "v7"] }[dev-dependencies]filetime = "0.2"tempfile = "3"+# The orphan-journal e2e signals and probes process groups directly.+nix = { version = "0.29", features = ["signal", "process"] }socket2 = "0.6"# The supervisor property suite draws sibling rosters for the live# rename ladder; the plain std features are enough (no fork/timeout).diff --git a/crates/pa-daemon/src/descriptor.rs b/crates/pa-daemon/src/descriptor.rsindex 5761a1d65c..4f94686ba1 100644--- a/crates/pa-daemon/src/descriptor.rs+++ b/crates/pa-daemon/src/descriptor.rs@@ -100,6 +100,12 @@ pub fn worker_launch_env(if let Some(script) = script {env.insert(crate::worker::WORKER_SCRIPT_ENV.to_string(), script);}+ if let Some(orphan_journal_path) = &descriptor.orphan_process_journal_path {+ env.insert(+ pa_core::kernel::orphan_journal::ORPHAN_PROCESS_JOURNAL_ENV.to_string(),+ orphan_journal_path.clone(),+ );+ }if let Some(dir) = &descriptor.session_dir {env.insert(crate::paths::SESSION_DIR_ENV.to_string(), dir.clone());}@@ -409,17 +415,31 @@ pub fn load_descriptors(let Ok(content) = std::fs::read_to_string(&path) else {continue;};- let Ok(descriptor) = serde_json::from_str::<WorkerDescriptor>(&content) else {+ let Ok(mut descriptor) = serde_json::from_str::<WorkerDescriptor>(&content) else {continue;};if validate_descriptor(&descriptor, supervisor_socket_path).is_err() {continue;}+ backfill_orphan_journal_path(dir, &mut descriptor);loaded.push((path, descriptor));}loaded}+/// Wire the orphan-process journal path on a pre-upgrade descriptor (TS+/// `??=` at boot load): the path is derived, never chosen, so a missing+/// field heals itself on the first load that uses the descriptor.+pub fn backfill_orphan_journal_path(dir: &Path, descriptor: &mut WorkerDescriptor) {+ if descriptor.orphan_process_journal_path.is_none() {+ descriptor.orphan_process_journal_path = Some(+ crate::journal::orphan_journal_path(dir, &descriptor.worker_id)+ .to_string_lossy()+ .to_string(),+ );+ }+}+/// Read persisted supervisor config when it belongs to this socket.#[must_use]pub fn load_supervisor_config(diff --git a/crates/pa-daemon/src/journal.rs b/crates/pa-daemon/src/journal.rsindex d081ec9732..4423c942e7 100644--- a/crates/pa-daemon/src/journal.rs+++ b/crates/pa-daemon/src/journal.rs@@ -11,6 +11,16 @@ use std::path::Path;pub(crate) const RECOVERY_JOURNAL_SUFFIX: &str = ".recovery.jsonl";+/// The worker's orphan-process journal file suffix (TS+/// `${workerId}.orphans.jsonl`, beside the recovery journal).+pub(crate) const ORPHAN_JOURNAL_SUFFIX: &str = ".orphans.jsonl";++/// The worker's orphan-process journal path under its descriptor dir.+#[must_use]+pub(crate) fn orphan_journal_path(descriptor_dir: &Path, worker_id: &str) -> std::path::PathBuf {+ descriptor_dir.join(format!("{worker_id}{ORPHAN_JOURNAL_SUFFIX}"))+}+pub(crate) fn append_record(path: &Path, record: &Value) -> Result<()> {if let Some(parent) = path.parent() {fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;diff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rsindex 4a5f4eedcd..cfa8bfd8cf 100644--- a/crates/pa-daemon/src/supervisor/adoption.rs+++ b/crates/pa-daemon/src/supervisor/adoption.rs@@ -173,6 +173,27 @@ impl Supervisor {self.spawn_roster_boot_seed();}+ /// Positive owner-death evidence for the recorded pid (the inverse of+ /// the tombstone's [`recorded_process_alive`]): the process is+ /// provably gone, or the pid provably names a different process now.+ /// An unobservable pid proves nothing and answers `false`.+ async fn recorded_worker_is_gone(&self, resident: &Arc<ResidentWorker>) -> bool {+ let (pid, expected) = {+ let descriptor = resident.descriptor.lock().await;+ (descriptor.pid, descriptor.process_start_id.clone())+ };+ let Ok(pid) = u32::try_from(pid) else {+ return false;+ };+ tokio::task::spawn_blocking(move || {+ let alive = crate::lease::is_process_alive(pid).ok();+ let observed = crate::lease::get_process_start_id(pid);+ !recorded_process_alive(alive, expected.as_deref(), observed.as_deref())+ })+ .await+ .unwrap_or(false)+ }+/// Adopt one persisted worker descriptor. Serialized against worker/// self-registration by the per-worker adoption gate: whichever path/// arrives first builds the roster entry; the other finds it present.@@ -228,6 +249,7 @@ impl Supervisor {let alive = (descriptor.stop_requested_at.is_none() || recorded_process_alive)&& socket::can_connect(&socket_path, Duration::from_millis(500)).await;let pid = descriptor.pid;+ let orphan_generation = super::supervision::OrphanGeneration::from_descriptor(&descriptor);let journal_path = PathBuf::from(&descriptor.recovery_journal_path);let resident = ResidentWorker::new(worker_id.clone(), descriptor, path);// The durable pending FIRST: a failed identity persist left a side record carrying the@@ -268,6 +290,14 @@ impl Supervisor {}(adopted, None)} else {+ // An unconnectable socket proves nothing about the process: a+ // live-but-slow worker still owns its journaled `bash()` groups,+ // so the boot reap needs the same positive owner-death evidence+ // the tombstone probes use (TS `recoverWorker` runs its orphan+ // sweep only once the recorded process identity is gone).+ if self.recorded_worker_is_gone(&resident).await {+ self.reap_dead_worker_orphans(&resident).await;+ }let interrupted =crate::journal::WorkerRecoveryJournal::read_interrupted(&journal_path);let kept = match &boot {@@ -324,9 +354,10 @@ impl Supervisor {Arc::clone(&resident),Some(child),u64::from(child_pid),+ None,);}- None => self.spawn_monitor(Arc::clone(&resident), None, pid),+ None => self.spawn_monitor(Arc::clone(&resident), None, pid, orphan_generation),}// The adopted worker joins the roster from its live state.self.refresh_roster_entry(&resident).await;@@ -428,11 +459,17 @@ impl Supervisor {// The registration's durable id is optional on the wire: a re-registering worker// that does not report it still owns its persisted descriptor. Both reads share// this one lock acquisition — a second one let the create path race into a stall.- let durable_session_id = {+ let (durable_session_id, orphan_generation) = {let mut descriptor = resident.descriptor.lock().await;if token.as_str() != descriptor.authentication_token {return fail("Session worker authentication failed");}+ // A registrant must not inherit the predecessor's journal merely+ // because registration updates its pid. Spawn publishes the path+ // and pid together; only that already-matching pair is cleanup evidence.+ let orphan_generation =+ super::supervision::OrphanGeneration::from_descriptor(&descriptor)+ .filter(|generation| u64::from(generation.pid) == *pid);let previous_worker_instance_id = descriptor.worker_instance_id.clone();// A REPLACEMENT registration flips the roster's stale-delta slot to the replacement// BEFORE it is exposed anywhere: a predecessor's pull or frame still in flight must@@ -442,6 +479,20 @@ impl Supervisor {let mut roster = self.roster.lock().unwrap();roster.note_worker_generation(&resident.worker_id, &replacement);}+ if descriptor.pid != *pid {+ // The old monitor retains the predecessor's cleanup identity.+ // The registrant's path is unknown: reserve an unused generation+ // path so boot backfill cannot restore the predecessor's legacy+ // path. This does not claim the live registrant writes this file.+ descriptor.orphan_process_journal_path = Some(+ crate::journal::orphan_journal_path(+ &self.descriptor_dir,+ &format!("{}-{}", descriptor.worker_id, uuid::Uuid::new_v4()),+ )+ .to_string_lossy()+ .into_owned(),+ );+ }descriptor.pid = *pid;// Refresh the identity from the live registrant: a recycled pid must not keep// the old holder's identity; an unobservable start id keeps the previous value.@@ -480,14 +531,14 @@ impl Supervisor {.and_then(|file| Path::new(file).file_stem()).map(|stem| stem.to_string_lossy().to_string()),};- durable_session_id+ (durable_session_id, orphan_generation)};// A pre-existing resident whose registrant named a different process// (boot adoption can watch a stale on-disk pid): arm the monitor for// the registrant. The generation claim retires the stale watch at its// exit check.if re_arm_monitor {- self.spawn_monitor(Arc::clone(&resident), None, *pid);+ self.spawn_monitor(Arc::clone(&resident), None, *pid, orphan_generation);}let record = self.registry.record_registration(registration).await;// A restore pass that owns this session's roster row can settle it now (spec §10.4).@@ -566,13 +617,18 @@ impl Supervisor {));}};- let descriptor: crate::descriptor::WorkerDescriptor = serde_json::from_str(&content)+ let mut descriptor: crate::descriptor::WorkerDescriptor = serde_json::from_str(&content).with_context(|| format!("invalid descriptor {}", descriptor_path.display()))?;crate::descriptor::validate_descriptor(&descriptor, &self.options.socket_path)?;if token != descriptor.authentication_token.as_str() {return Err(anyhow!("Session worker authentication failed"));}+ // The same boot-load backfill: a pre-upgrade descriptor wires its+ // orphan journal here too, so a relaunch of this worker journals.+ crate::descriptor::backfill_orphan_journal_path(&self.descriptor_dir, &mut descriptor);let worker_id = descriptor.worker_id.clone();+ let orphan_generation = super::supervision::OrphanGeneration::from_descriptor(&descriptor)+ .filter(|generation| u64::from(generation.pid) == registration.pid);let resident = ResidentWorker::new(registration.active_session_id.clone(),descriptor,@@ -593,6 +649,17 @@ impl Supervisor {{let mut descriptor = resident.descriptor.lock().await;if descriptor.pid != registration.pid {+ // A tombstoned registrant also has an unknown journal path.+ // Reserve an unused generation instead of None, which boot+ // backfill could bind to the predecessor's legacy journal.+ descriptor.orphan_process_journal_path = Some(+ crate::journal::orphan_journal_path(+ &self.descriptor_dir,+ &format!("{}-{}", descriptor.worker_id, uuid::Uuid::new_v4()),+ )+ .to_string_lossy()+ .into_owned(),+ );descriptor.pid = registration.pid;}if let Some(start_id) = crate::lease::get_process_start_id(registration.pid as u32)@@ -626,7 +693,12 @@ impl Supervisor {// client commands may reach it immediately.resident.note_session_ready();self.registry.insert(Arc::clone(&resident)).await;- self.spawn_monitor(Arc::clone(&resident), None, registration.pid);+ self.spawn_monitor(+ Arc::clone(&resident),+ None,+ registration.pid,+ orphan_generation,+ );self.log_line(&format!("adopted session worker {worker_id} via self-registration"));diff --git a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs b/crates/pa-daemon/src/supervisor/spawn_record_tests.rsindex c0ede373cc..8dccf3fd57 100644--- a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs+++ b/crates/pa-daemon/src/supervisor/spawn_record_tests.rs@@ -179,6 +179,42 @@ async fn a_relaunch_spawn_record_serves_the_durable_persist() {.expect("parse the spawn record");assert_eq!(persisted.lifecycle, DaemonWorkerLifecycle::Starting);assert!(persisted.pid > 0, "the spawned pid rides the record");++ let first_path = persisted+ .orphan_process_journal_path+ .expect("first journal");+ std::fs::write(&first_path, "").expect("old generation journal");+ assert!(supervisor.relaunch_worker(&resident).await.is_err());+ let replacement: DaemonWorkerDescriptor =+ serde_json::from_slice(&std::fs::read(&descriptor_path).expect("replacement spawn record"))+ .expect("parse replacement");+ let replacement_path = replacement+ .orphan_process_journal_path+ .as_ref()+ .expect("replacement journal");+ assert_ne!(&first_path, replacement_path, "each spawn owns its journal");+ let launch_env = crate::descriptor::worker_launch_env(+ &supervisor.options.agent_dir,+ &supervisor.options.socket_path.to_string_lossy(),+ "replacement-nonce",+ &replacement,+ );+ assert_eq!(+ launch_env.get(pa_core::kernel::orphan_journal::ORPHAN_PROCESS_JOURNAL_ENV),+ Some(replacement_path),+ "the persisted replacement path is the worker launch environment",+ );+ let retained = b"replacement-owned journal records\n";+ std::fs::write(replacement_path, retained).expect("replacement journal");+ pa_core::kernel::orphan_journal::reap_worker_orphan_processes(+ Path::new(&first_path),+ i32::try_from(persisted.pid).expect("worker pid"),+ );+ assert!(+ !Path::new(&first_path).exists(),+ "the old journal was swept"+ );+ assert_eq!(std::fs::read(replacement_path).unwrap(), retained);}/// A spawn record that cannot land (the descriptor path is occupied) mustdiff --git a/crates/pa-daemon/src/supervisor/supervision.rs b/crates/pa-daemon/src/supervisor/supervision.rsindex 1f8c2c2556..fefc811a99 100644--- a/crates/pa-daemon/src/supervisor/supervision.rs+++ b/crates/pa-daemon/src/supervisor/supervision.rs@@ -12,6 +12,58 @@ use super::{use crate::lease::is_process_alive;use crate::registry::WorkerRelay;+/// The immutable cleanup identity of one worker process lifetime.+#[derive(Clone, Debug)]+pub(super) struct OrphanGeneration {+ pub(super) pid: u32,+ pub(super) path: String,+}++impl OrphanGeneration {+ pub(super) fn from_descriptor(+ descriptor: &crate::descriptor::WorkerDescriptor,+ ) -> Option<Self> {+ Some(Self {+ pid: u32::try_from(descriptor.pid).ok()?,+ path: descriptor.orphan_process_journal_path.clone()?,+ })+ }++ /// The caller has observed this generation exit; no resident lookup or+ /// fallible liveness recheck may substitute a different process here.+ async fn reap(&self) {+ let generation = self.clone();+ let _ = tokio::task::spawn_blocking(move || {+ if let Ok(pid) = i32::try_from(generation.pid) {+ pa_core::kernel::orphan_journal::reap_worker_orphan_processes(+ std::path::Path::new(&generation.path),+ pid,+ );+ }+ })+ .await;+ }+}++/// A child and its cleanup identity must survive descriptor replacements together.+#[derive(Debug)]+pub(crate) struct SpawnedWorker {+ child: Child,+ orphan_generation: OrphanGeneration,+}++impl SpawnedWorker {+ pub(crate) fn id(&self) -> Option<u32> {+ self.child.id()+ }++ pub(crate) async fn kill(&mut self) -> std::io::Result<()> {+ self.child.kill().await?;+ self.orphan_generation.reap().await;+ Ok(())+ }+}+pub(super) const MAX_CONSECUTIVE_FAILURES: u32 = 5;/// A crash-path child that lived at least this long proved health: its death resets/// the failure count instead of accumulating toward the give-up cap.@@ -69,11 +121,12 @@ impl Supervisor {pub(super) fn spawn_monitor(self: &Arc<Self>,resident: Arc<ResidentWorker>,- child: Option<Child>,+ child: Option<SpawnedWorker>,pid: u64,+ orphan_generation: Option<OrphanGeneration>,) {let supervisor = Arc::clone(self);- tokio::spawn(supervisor.watch_worker(resident, child, pid));+ tokio::spawn(supervisor.watch_worker(resident, child, pid, orphan_generation));}/// Watch one process lifetime for the resident. The generation claim is@@ -84,23 +137,34 @@ impl Supervisor {pub(super) fn watch_worker(self: Arc<Self>,resident: Arc<ResidentWorker>,- child: Option<Child>,+ child: Option<SpawnedWorker>,adopted_pid: u64,+ orphan_generation: Option<OrphanGeneration>,) -> impl std::future::Future<Output = ()> {let monitor_epoch = resident.monitor_epoch.fetch_add(1, Ordering::SeqCst) + 1;- self.watch_worker_owned(resident, child, adopted_pid, monitor_epoch)+ self.watch_worker_owned(+ resident,+ child,+ adopted_pid,+ monitor_epoch,+ orphan_generation,+ )}async fn watch_worker_owned(self: Arc<Self>,resident: Arc<ResidentWorker>,- mut child: Option<Child>,+ mut child: Option<SpawnedWorker>,mut adopted_pid: u64,monitor_epoch: u64,+ mut orphan_generation: Option<OrphanGeneration>,) {loop {if let Some(mut child) = child.take() {- let status = child.wait().await;+ let status = child.child.wait().await;+ if status.is_ok() {+ child.orphan_generation.reap().await;+ }if resident.intentional_stop.load(Ordering::SeqCst)|| self.shutting_down.load(Ordering::SeqCst){@@ -118,19 +182,26 @@ impl Supervisor {// to watch, and a watch on pid 0 would report a phantom// exit; fall straight to the failure/backoff/relaunch arm// instead.- if let Err(error) =- pa_core::platform::process::wait_for_exit(adopted_pid as u32).await+ let exited = match pa_core::platform::process::wait_for_exit(adopted_pid as u32)+ .await{- // The slow fallback, only where the kernel exit watch- // cannot register.- self.log_line(&format!(- "session worker {}: kernel exit watch unavailable ({error}); polling liveness every {}s",- resident.worker_id,- ADOPTED_EXIT_FALLBACK_POLL.as_secs()- ));- while matches!(is_process_alive(adopted_pid as u32), Ok(true)) {- tokio::time::sleep(ADOPTED_EXIT_FALLBACK_POLL).await;+ Ok(()) => true,+ Err(error) => {+ self.log_line(&format!(+ "session worker {}: kernel exit watch unavailable ({error}); polling liveness every {}s",+ resident.worker_id, ADOPTED_EXIT_FALLBACK_POLL.as_secs()+ ));+ loop {+ match is_process_alive(adopted_pid as u32) {+ Ok(false) => break true,+ Ok(true) => tokio::time::sleep(ADOPTED_EXIT_FALLBACK_POLL).await,+ Err(_) => break false,+ }+ }}+ };+ if let Some(generation) = orphan_generation.take().filter(|_| exited) {+ generation.reap().await;}// Manual retry still replaces the descriptor's pid without// arming a monitor. Preserve that handoff fence alongside@@ -278,7 +349,7 @@ impl Supervisor {pub(crate) async fn relaunch_worker(self: &Arc<Self>,resident: &Arc<ResidentWorker>,- ) -> Result<Child> {+ ) -> Result<SpawnedWorker> {if self.is_stopping(resident) {return Err(anyhow!("supervisor is shutting down"));}@@ -447,11 +518,20 @@ impl Supervisor {resident: &Arc<ResidentWorker>,connect_deadline: tokio::time::Instant,spawn_record_sync: TempSync,- ) -> Result<Child> {+ ) -> Result<SpawnedWorker> {// One env definition for spawn and for the update roster's `launch_env` row// (spec §8: "env snapshot to respawn the worker identically").- let (worker_socket, cwd, launch_env) = {- let descriptor = resident.descriptor.lock().await;+ let (worker_socket, cwd, launch_env, orphan_path) = {+ let mut descriptor = resident.descriptor.lock().await.clone();+ // Each process lifetime owns a different file. An old owner's+ // in-flight reap must never clear a replacement's journal.+ let orphan_path = crate::journal::orphan_journal_path(+ &self.descriptor_dir,+ &format!("{}-{}", resident.worker_id, uuid::Uuid::new_v4()),+ )+ .to_string_lossy()+ .into_owned();+ descriptor.orphan_process_journal_path = Some(orphan_path.clone());(PathBuf::from(&descriptor.socket_path),descriptor@@ -467,6 +547,7 @@ impl Supervisor {&uuid::Uuid::new_v4().to_string(),&descriptor,),+ orphan_path,)};@@ -492,6 +573,13 @@ impl Supervisor {let child = command.spawn().with_context(|| format!("spawn session worker {}", resident.worker_id))?;+ let child = SpawnedWorker {+ orphan_generation: OrphanGeneration {+ pid: child.id().unwrap_or(0),+ path: orphan_path.clone(),+ },+ child,+ };let now_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as u64);@@ -506,6 +594,9 @@ impl Supervisor {let child_pid = child.id().unwrap_or(0);descriptor.pid = u64::from(child_pid);descriptor.process_start_id = crate::protocol::process_start_id(child_pid);+ // Publish the path with its owner identity, never against the+ // previous generation's pid before the spawn succeeds.+ descriptor.orphan_process_journal_path = Some(orphan_path);descriptor.lifecycle = DaemonWorkerLifecycle::Starting;// The spawn record's durability is per launch class// (`spawn_record_sync`): a fresh create rides the TSdiff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex f4e0170634..fe8f5edc91 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -143,7 +143,7 @@ async fn a_failed_relaunch_accumulates_to_the_give_up_cap() {supervisor.registry.insert(Arc::clone(&resident)).await;tokio::time::timeout(Duration::from_secs(60),- Arc::clone(&supervisor).watch_worker(Arc::clone(&resident), None, 0),+ Arc::clone(&supervisor).watch_worker(Arc::clone(&resident), None, 0, None),).await.expect("the watch loop gives up instead of spinning");@@ -200,7 +200,7 @@ async fn a_stop_during_the_storm_leaves_the_terminal_state_to_the_stop() {supervisor.registry.insert(Arc::clone(&resident)).await;tokio::time::timeout(Duration::from_secs(60),- Arc::clone(&supervisor).watch_worker(Arc::clone(&resident), None, 0),+ Arc::clone(&supervisor).watch_worker(Arc::clone(&resident), None, 0, None),).await.expect("the give-up arm returns instead of spinning");@@ -249,7 +249,8 @@ async fn an_adopted_watch_hands_off_at_exit_without_a_timer() {let mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(Arc::clone(&resident),None,- u64::from(worker.id())+ u64::from(worker.id()),+ None));assert!(futures::poll!(watch.as_mut()).is_pending(),@@ -278,13 +279,19 @@ async fn an_adopted_watch_hands_off_at_exit_without_a_timer() {let mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(Arc::clone(&resident),None,- u64::from(worker.id())+ u64::from(worker.id()),+ None));assert!(futures::poll!(watch.as_mut()).is_pending(),"a live adopted worker keeps the watch parked");- supervisor.spawn_monitor(Arc::clone(&resident), None, u64::from(std::process::id()));+ supervisor.spawn_monitor(+ Arc::clone(&resident),+ None,+ u64::from(std::process::id()),+ None,+ );worker.kill().expect("kill sleep");worker.wait().expect("reap sleep");watch.await;@@ -329,7 +336,8 @@ async fn a_pid_only_replacement_keeps_the_adopted_predecessor_out_of_crash_recovlet mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(Arc::clone(&resident),None,- u64::from(predecessor_pid)+ u64::from(predecessor_pid),+ None));assert!(futures::poll!(watch.as_mut()).is_pending());let epoch = resident.monitor_epoch.load(Ordering::SeqCst);@@ -402,6 +410,11 @@ async fn a_registered_replacement_pid_is_monitored_after_the_predecessor_exits().spawn().expect("spawn the replacement");let resident = adopted_watch_resident(dir.path(), predecessor.id());+ let predecessor_journal = dir.path().join("predecessor.orphans.jsonl");+ let retained = b"";+ std::fs::write(&predecessor_journal, retained).unwrap();+ resident.descriptor.lock().await.orphan_process_journal_path =+ Some(predecessor_journal.to_string_lossy().into_owned());// The give-up budget is at the cap: a supervised death must reach the// give-up at once, so the predecessor's unbookkept exit is observable.resident@@ -411,7 +424,8 @@ async fn a_registered_replacement_pid_is_monitored_after_the_predecessor_exits()let mut old_watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(Arc::clone(&resident),None,- u64::from(predecessor.id())+ u64::from(predecessor.id()),+ None));assert!(futures::poll!(old_watch.as_mut()).is_pending(),@@ -439,6 +453,21 @@ async fn a_registered_replacement_pid_is_monitored_after_the_predecessor_exits()registered.success,"the replacement registers: {registered:?}");+ let mut registered_descriptor = resident.descriptor.lock().await.clone();+ let unknown_journal = registered_descriptor+ .orphan_process_journal_path+ .clone()+ .expect("unknown generation reserves an unused path");+ assert_ne!(Path::new(&unknown_journal), predecessor_journal);+ assert!(!Path::new(&unknown_journal).exists());+ crate::descriptor::backfill_orphan_journal_path(+ &supervisor.descriptor_dir,+ &mut registered_descriptor,+ );+ assert_eq!(+ registered_descriptor.orphan_process_journal_path.as_deref(),+ Some(unknown_journal.as_str())+ );// The predecessor's exit retires the old watch without crash bookkeeping.predecessor.kill().expect("kill the predecessor");predecessor.wait().expect("reap the predecessor");@@ -463,6 +492,18 @@ async fn a_registered_replacement_pid_is_monitored_after_the_predecessor_exits()}).await.expect("the replacement's death reaches the give-up");+ assert_eq!(+ std::fs::read(&predecessor_journal).unwrap(),+ retained,+ "a mismatched registration must not reap the predecessor's journal",+ );+ let mut reloaded: crate::descriptor::WorkerDescriptor =+ serde_json::from_slice(&std::fs::read(&resident.descriptor_path).unwrap()).unwrap();+ crate::descriptor::backfill_orphan_journal_path(&supervisor.descriptor_dir, &mut reloaded);+ assert_eq!(+ reloaded.orphan_process_journal_path.as_deref(),+ Some(unknown_journal.as_str())+ );assert_eq!(resident.consecutive_failures.load(Ordering::SeqCst),MAX_CONSECUTIVE_FAILURES + 1@@ -495,6 +536,14 @@ async fn a_superseded_watch_leaves_the_failure_count_to_the_new_monitor() {.spawn().expect("spawn sleep");let resident = adopted_watch_resident(dir.path(), worker.id());+ let old_journal = dir.path().join("old.orphans.jsonl");+ let new_journal = dir.path().join("new.orphans.jsonl");+ std::fs::write(&old_journal, "").unwrap();+ std::fs::write(&new_journal, "replacement records").unwrap();+ let generation = super::supervision::OrphanGeneration {+ pid: worker.id(),+ path: old_journal.to_string_lossy().into_owned(),+ };// The cap is armed: an unsupervised crash arm would give up at once.resident.consecutive_failures@@ -503,19 +552,32 @@ async fn a_superseded_watch_leaves_the_failure_count_to_the_new_monitor() {let mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(Arc::clone(&resident),None,- u64::from(worker.id())+ u64::from(worker.id()),+ Some(generation)));assert!(futures::poll!(watch.as_mut()).is_pending(),"a live adopted worker keeps the watch parked");- // The descriptor keeps the watched pid: only the generation moved on.- supervisor.spawn_monitor(Arc::clone(&resident), None, u64::from(std::process::id()));+ // A new generation owns a distinct journal before the old exit arrives.+ resident.descriptor.lock().await.orphan_process_journal_path =+ Some(new_journal.to_string_lossy().into_owned());+ supervisor.spawn_monitor(+ Arc::clone(&resident),+ None,+ u64::from(std::process::id()),+ None,+ );worker.kill().expect("kill sleep");worker.wait().expect("reap sleep");tokio::time::timeout(Duration::from_secs(2), watch).await.expect("the superseded watch returns at the exit");+ assert!(+ !old_journal.exists(),+ "the superseded monitor still reaps its generation"+ );+ assert_eq!(std::fs::read(&new_journal).unwrap(), b"replacement records");assert_eq!(resident.consecutive_failures.load(Ordering::SeqCst),MAX_CONSECUTIVE_FAILURES,@@ -562,6 +624,7 @@ async fn a_superseded_watch_in_backoff_does_not_relaunch_over_the_new_owner() {Arc::clone(&resident),None,u64::from(worker.id()),+ None,));tokio::task::yield_now().await;assert!(@@ -581,7 +644,12 @@ async fn a_superseded_watch_in_backoff_does_not_relaunch_over_the_new_owner() {.await.expect("the crash arm counts the exit before its backoff");// Another arm claims the resident while the watch is backed off.- supervisor.spawn_monitor(Arc::clone(&resident), None, u64::from(std::process::id()));+ supervisor.spawn_monitor(+ Arc::clone(&resident),+ None,+ u64::from(std::process::id()),+ None,+ );tokio::time::timeout(Duration::from_secs(5), watch).await.expect("the superseded watch returns after the backoff")diff --git a/crates/pa-daemon/src/supervisor/update_restart.rs b/crates/pa-daemon/src/supervisor/update_restart.rsindex af736695b4..96d6a8ed9e 100644--- a/crates/pa-daemon/src/supervisor/update_restart.rs+++ b/crates/pa-daemon/src/supervisor/update_restart.rs@@ -358,7 +358,12 @@ impl Supervisor {match self.relaunch_worker(resident).await {Ok(child) => {resident.consecutive_failures.store(0, Ordering::SeqCst);- self.spawn_monitor(Arc::clone(resident), Some(child), 0);+ self.spawn_monitor(+ Arc::clone(resident),+ Some(child),+ 0,+ None,+ );}Err(error) => {self.log_line(&format!(@@ -371,7 +376,7 @@ impl Supervisor {// path instead of leaving it unsupervised.if !self.is_stopping(resident) {resident.spawned_at_ms.store(0, Ordering::SeqCst);- self.spawn_monitor(Arc::clone(resident), None, 0);+ self.spawn_monitor(Arc::clone(resident), None, 0, None);}}}diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex 3da13b383b..fe1bf06bfa 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -279,7 +279,11 @@ impl Supervisor {process_start_id: None,socket_path: worker_socket.to_string_lossy().to_string(),recovery_journal_path: recovery_journal_path.to_string_lossy().to_string(),- orphan_process_journal_path: None,+ orphan_process_journal_path: Some(+ crate::journal::orphan_journal_path(&self.descriptor_dir, &worker_id)+ .to_string_lossy()+ .to_string(),+ ),supervisor_socket_path: self.options.socket_path.to_string_lossy().to_string(),authentication_token: uuid::Uuid::new_v4().to_string(),worker_instance_id: Some(uuid::Uuid::new_v4().to_string()),@@ -461,7 +465,7 @@ impl Supervisor {// now be routed to this worker — nothing overtakes the session's create.resident.note_session_ready();let pid = child.id().unwrap_or(0);- self.spawn_monitor(Arc::clone(&resident), Some(child), u64::from(pid));+ self.spawn_monitor(Arc::clone(&resident), Some(child), u64::from(pid), None);Ok((resident, create_summary))}@@ -776,6 +780,10 @@ impl Supervisor {));}_ => {+ // The worker is provably gone, so its kernels can no longer+ // run their teardown reap: kill the `bash()` groups they+ // journaled before the descriptor dies with its files.+ self.reap_dead_worker_orphans(resident).await;// Metadata retirement historically treats failed liveness probes// as gone. Journal deletion needs positive owner-death evidence:// an unobservable process may still be writing durable work.@@ -790,9 +798,53 @@ impl Supervisor {// The identity-pending side record dies with the descriptor it shadows// (an orphaned pending would shadow the next identity).let _ = crate::descriptor::clear_identity_pending(&resident.descriptor_path);+ // The reaper alone owns orphan-journal removal. A read or+ // identity-verified kill failure must preserve its retry records.}}}++ /// Kill the `bash()` process groups a provably-dead worker's kernels+ /// journaled (TS `recoverUncertainWorkerOperations`' orphan sweep):+ /// a worker killed without its shutdown hook leaves them behind, and+ /// only the supervisor still knows the journal's path.+ pub(super) async fn reap_dead_worker_orphans(self: &Arc<Self>, resident: &Arc<ResidentWorker>) {+ // Capture one generation: a concurrent retry or registration may+ // replace the descriptor while the blocking identity probe runs.+ let (pid, start_id, orphan_path) = {+ let descriptor = resident.descriptor.lock().await;+ (+ descriptor.pid,+ descriptor.process_start_id.clone(),+ descriptor.orphan_process_journal_path.clone(),+ )+ };+ let Some(orphan_path) = orphan_path else {+ return;+ };+ let Ok(worker_pid) = i32::try_from(pid) else {+ return;+ };+ // The reap is blocking file I/O and kill signals (and on macOS a+ // `ps` probe): keep it off the async executor, as the adoption+ // identity probes do.+ let _ = tokio::task::spawn_blocking(move || {+ // Stop escalation and adopted-process watch failures do not+ // prove death. The proof and reap must use the same owner pid.+ if !recovery_journal_owner_is_gone(+ crate::lease::is_process_alive(worker_pid as u32).ok(),+ start_id.as_deref(),+ crate::lease::get_process_start_id(worker_pid as u32).as_deref(),+ ) {+ return;+ }+ pa_core::kernel::orphan_journal::reap_worker_orphan_processes(+ Path::new(&orphan_path),+ worker_pid,+ );+ })+ .await;+ }}/// A dead process or a verified replacement identity proves the old writer@@ -1002,7 +1054,12 @@ mod tests {std::fs::write(&unknown_journal, retained).expect("unknown journal");std::fs::write(descriptor_dir.join("w-unknown.json"), "not json").expect("unverifiable descriptor");+ // A failed journal read must survive descriptor retirement for retry.+ let orphan_path = descriptor_dir.join("w-gone.orphans.jsonl");+ let unreadable = [0xff, 0xfe];+ std::fs::write(&orphan_path, unreadable).expect("orphan journal");let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({+ "orphanProcessJournalPath": orphan_path.to_string_lossy(),"version": 2,"workerId": "w-gone","pid": pid,@@ -1030,7 +1087,39 @@ mod tests {"the journal dies with the descriptor");assert!(!descriptor_path.exists());+ assert_eq!(std::fs::read(orphan_path).unwrap(), unreadable);assert_eq!(std::fs::read(unowned_journal).unwrap(), retained);assert_eq!(std::fs::read(unknown_journal).unwrap(), retained);}+ #[tokio::test]+ async fn a_live_worker_keeps_its_orphan_journal() {+ let dir = tempfile::tempdir().expect("temp dir");+ let supervisor = supervisor_in(dir.path());+ let orphan_path = supervisor.descriptor_dir.join("w-live.orphans.jsonl");+ std::fs::write(&orphan_path, "").expect("orphan journal");+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(json!({+ "version": 2,+ "workerId": "w-live",+ "pid": std::process::id(),+ "socketPath": "/tmp/w-live.sock",+ "recoveryJournalPath": "/tmp/w-live.recovery.jsonl",+ "orphanProcessJournalPath": orphan_path.to_string_lossy(),+ "supervisorSocketPath": supervisor.options.socket_path.to_string_lossy(),+ "authenticationToken": "token",+ "rootActiveSessionId": "w-live",+ "createdAt": "2026-10-07T00:00:00Z",+ "updatedAt": "2026-10-07T00:00:00Z",+ "lifecycle": "ready",+ "createCommand": {},+ "consecutiveFailures": 0,+ }))+ .expect("descriptor");+ let resident = ResidentWorker::new(+ "w-live".to_string(),+ descriptor,+ supervisor.descriptor_dir.join("w-live.json"),+ );+ supervisor.reap_dead_worker_orphans(&resident).await;+ assert_eq!(std::fs::read(orphan_path).unwrap(), b"");+ }}diff --git a/crates/pa-daemon/tests/orphan_journal_e2e.rs b/crates/pa-daemon/tests/orphan_journal_e2e.rsnew file mode 100644index 0000000000..d9ed0e2201--- /dev/null+++ b/crates/pa-daemon/tests/orphan_journal_e2e.rs@@ -0,0 +1,530 @@+//! Orphan-process journal e2e: a kernel (or its worker) dying without a+//! shutdown hook must not leak the `bash()` process groups it journaled+//! — the worker-side kernel-teardown reap and the supervisor-side worker+//! death reap each answer one half of that contract.+// 64-bit-only targets; the narrowing casts sit at bounded OS boundaries.+#![allow(+ clippy::cast_possible_truncation,+ clippy::cast_possible_wrap,+ clippy::cast_sign_loss,+ clippy::cast_precision_loss+)]+// Fn length is a style gate, not correctness.+#![allow(clippy::too_many_lines)]+#![cfg(unix)]++use std::fmt::Write as _;+use std::io::{BufRead, BufReader, Read, Write};+use std::net::{TcpListener, TcpStream};+use std::os::unix::net::UnixStream;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::{Duration, Instant};++use nix::sys::signal::{kill as signal_pid, Signal};+use nix::unistd::Pid;+use serde_json::{json, Value};++struct Daemon {+ child: Child,+ socket: PathBuf,+}++impl Drop for Daemon {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++/// The kernel Python with prime-agent-runtime installed; `PA_E2E_KERNEL_PYTHON` overrides.+fn kernel_python() -> Option<PathBuf> {+ if let Some(explicit) = std::env::var_os("PA_E2E_KERNEL_PYTHON") {+ let explicit = PathBuf::from(explicit);+ assert!(+ explicit.exists(),+ "PA_E2E_KERNEL_PYTHON {} not found",+ explicit.display()+ );+ return Some(explicit);+ }+ let candidate = PathBuf::from(std::env::var("HOME").map_or_else(+ |_| "/home/ubuntu/.prime/agent/kernel-venv/bin/python".to_string(),+ |home| format!("{home}/.prime/agent/kernel-venv/bin/python"),+ ));+ if candidate.exists() {+ return Some(candidate);+ }+ eprintln!(+ "kernel python {} not found; skipping orphan journal e2e",+ candidate.display()+ );+ None+}++// Ownership transfers to Daemon, whose Drop kills and waits for the child.+#[allow(clippy::zombie_processes)]+fn spawn_daemon(socket: &Path, agent_dir: &Path, kernel_python: Option<&Path>) -> Daemon {+ std::fs::create_dir_all(agent_dir).expect("agent dir");+ let mut command = Command::new(env!("CARGO_BIN_EXE_pa-daemon"));+ command+ .arg("supervisor")+ .arg("--socket")+ .arg(socket)+ .arg("--agent-dir")+ .arg(agent_dir)+ .env_remove("PRIME_API_KEY")+ .env("PRIME_AGENT_CODING_AGENT_DIR", agent_dir)+ .env(+ pa_daemon::worker::WORKER_SUPERVISOR_LOST_EXIT_MS_ENV,+ "20000",+ );+ if let Some(kernel_python) = kernel_python {+ command.env("PRIME_AGENT_KERNEL_PYTHON", kernel_python);+ }+ let child = command+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("spawn pa-daemon supervisor");+ let deadline = Instant::now() + Duration::from_secs(15);+ while Instant::now() < deadline {+ if socket.exists() {+ return Daemon {+ child,+ socket: socket.to_path_buf(),+ };+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ panic!("supervisor socket never appeared");+}++/// The orphaning cell: a released `bash("sleep 600")` handle whose process+/// group outlives the turn, plus the ids the test needs to kill and probe.+fn orphaning_cell() -> String {+ // The e2e kernel namespace does not preload `os`, so the cell imports+ // it before printing the ids the test kills and probes by.+ let code = "h = bash(\"sleep 600\")\nimport os\nprint(f'ORPHAN_PGID={h.pid} KERNEL_PID={os.getpid()}')";+ serde_json::to_string(&json!({ "code": code })).expect("serialize cell")+}++/// The sequential mock: one SSE answer per request in order.+fn spawn_mock(next: &'static AtomicUsize) -> PathBuf {+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock");+ let url = format!(+ "http://127.0.0.1:{}/v1",+ listener.local_addr().unwrap().port()+ );+ std::thread::spawn(move || {+ for stream in listener.incoming() {+ let Ok(stream) = stream else { continue };+ std::thread::spawn(move || {+ let _ = serve(stream, next);+ });+ }+ });+ PathBuf::from(url)+}++fn chunk(delta: &Value, finish_reason: Option<&str>) -> String {+ json!({+ "id": "chatcmpl-orphan",+ "object": "chat.completion.chunk",+ "created": 1_750_000_000,+ "model": "mock-1",+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],+ })+ .to_string()+}++fn serve(mut stream: TcpStream, next: &AtomicUsize) -> std::io::Result<()> {+ let mut reader = BufReader::new(stream.try_clone()?);+ let mut content_length = 0usize;+ loop {+ let mut line = String::new();+ if reader.read_line(&mut line)? == 0 {+ return Ok(());+ }+ if line == "\r\n" {+ break;+ }+ let lower = line.to_ascii_lowercase();+ if let Some(value) = lower.strip_prefix("content-length:") {+ content_length = value.trim().parse().unwrap_or_default();+ }+ }+ let mut body = vec![0u8; content_length];+ if content_length > 0 {+ reader.read_exact(&mut body)?;+ }+ // The scripted sequence: request 1 answers the python_repl tool call that+ // starts the orphaning sleep, request 2 settles the turn.+ let request = next.fetch_add(1, Ordering::SeqCst);+ let mut payload = String::new();+ let data = match request {+ 0 => [+ chunk(+ &json!({+ "role": "assistant",+ "content": "",+ "tool_calls": [{+ "index": 0,+ "id": "call-orphan-1",+ "type": "function",+ "function": {+ "name": "python_repl",+ "arguments": orphaning_cell(),+ }+ }]+ }),+ None,+ ),+ chunk(&json!({}), Some("tool_calls")),+ ],+ 1 => [+ chunk(+ &json!({"role": "assistant", "content": "the orphan sleeps"}),+ None,+ ),+ chunk(&json!({}), Some("stop")),+ ],+ _ => [+ chunk(+ &json!({"role": "assistant", "content": "nothing to do"}),+ None,+ ),+ chunk(&json!({}), Some("stop")),+ ],+ };+ for data in data {+ write!(payload, "data: {data}\n\n").expect("write to String");+ }+ payload.push_str("data: [DONE]\n\n");+ stream.write_all(+ format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n{payload}"+ )+ .as_bytes(),+ )+}++struct Client {+ reader: BufReader<UnixStream>,+ writer: UnixStream,+}++impl Client {+ fn connect(socket: &Path) -> Client {+ let stream = UnixStream::connect(socket).expect("connect");+ let writer = stream.try_clone().expect("clone");+ let mut client = Client {+ reader: BufReader::new(stream),+ writer,+ };+ let hello = client.read_line();+ assert_eq!(hello["type"], "daemon_hello");+ client+ }++ fn read_line(&mut self) -> Value {+ let mut line = String::new();+ let deadline = Instant::now() + Duration::from_secs(120);+ self.reader+ .get_mut()+ .set_read_timeout(Some(Duration::from_millis(100)))+ .expect("timeout");+ loop {+ match self.reader.read_line(&mut line) {+ Ok(0) => panic!("supervisor closed the connection"),+ Ok(_) if line.trim().is_empty() => line.clear(),+ Ok(_) => return serde_json::from_str(line.trim()).expect("parse line"),+ Err(error) => {+ assert!(+ Instant::now() < deadline,+ "timed out waiting for supervisor line: {error}"+ );+ }+ }+ }+ }++ fn request(&mut self, id: &str, command: &Value) -> Value {+ let envelope = json!({+ "type": "command",+ "id": id,+ "protocol": { "name": "prime-agent.daemon", "version": 7 },+ "command": command,+ });+ let mut line = serde_json::to_string(&envelope).expect("serialize");+ line.push('\n');+ self.writer+ .write_all(line.as_bytes())+ .unwrap_or_else(|error| panic!("write command {id}: {error}"));+ let deadline = Instant::now() + Duration::from_secs(120);+ loop {+ assert!(Instant::now() < deadline, "no response for id {id}");+ let line = self.read_line();+ if line.get("id").and_then(Value::as_str) == Some(id) {+ return line;+ }+ }+ }++ fn messages(&mut self, active_session_id: &str) -> String {+ let response = self.request(+ "gm",+ &json!({ "type": "get_messages", "activeSessionId": active_session_id }),+ );+ assert_eq!(response["success"], true, "get_messages failed: {response}");+ serde_json::to_string(&response["data"]).expect("messages json")+ }+}++fn wait_until<T>(deadline: Duration, mut probe: impl FnMut() -> Option<T>) -> T {+ let deadline = Instant::now() + deadline;+ loop {+ if let Some(value) = probe() {+ return value;+ }+ assert!(Instant::now() < deadline, "condition never became true");+ std::thread::sleep(Duration::from_millis(100));+ }+}++fn create_session(client: &mut Client, id: &str, dir: &Path, agent_dir: &Path) -> String {+ let sessions = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions).expect("sessions dir");+ let created = client.request(+ id,+ &json!({+ "type": "create",+ "name": "orphan-lane",+ "config": {+ "cwd": dir.to_string_lossy(),+ "sessionDir": sessions.to_string_lossy(),+ "provider": "prime-inference",+ "model": "mock-1",+ },+ }),+ );+ assert_eq!(created["success"], true, "create failed: {created}");+ created["data"]["id"]+ .as_str()+ .or_else(|| created["data"]["activeSessionId"].as_str())+ .expect("active session id")+ .to_string()+}++/// The session's own ids for the killing and probing: the bash process+/// group and the kernel pid the orphaning cell printed, parsed from the+/// tool result the turn settled with. The cell's code echoes through the+/// tool-call arguments too (`ORPHAN_PGID={h.pid}` there), so the parse+/// scans every marker occurrence for the first one followed by digits —+/// only the executed result prints them.+fn orphan_ids(client: &mut Client, active_session_id: &str) -> (i32, i32) {+ wait_until(Duration::from_secs(30), || {+ let messages = client.messages(active_session_id);+ let pgid = number_after(&messages, "ORPHAN_PGID=")?;+ let kernel_pid = number_after(&messages, "KERNEL_PID=")?;+ Some((pgid, kernel_pid))+ })+}++fn number_after(text: &str, marker: &str) -> Option<i32> {+ text.split(marker).skip(1).find_map(|rest| {+ let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();+ digits.parse::<i32>().ok().filter(|pid| *pid > 0)+ })+}++/// The persisted worker descriptor's pid for this session: the pid the+/// supervisor reaps by when the worker itself dies.+fn worker_pid(agent_dir: &Path, active_session_id: &str) -> i32 {+ wait_until(Duration::from_secs(30), || {+ let workers_dir = agent_dir.join("daemon-workers");+ let Ok(entries) = std::fs::read_dir(&workers_dir) else {+ return None;+ };+ for dir in entries.flatten() {+ let Ok(files) = std::fs::read_dir(dir.path()) else {+ continue;+ };+ for file in files.flatten() {+ let path = file.path();+ if path.extension().and_then(|e| e.to_str()) != Some("json") {+ continue;+ }+ let Ok(content) = std::fs::read_to_string(&path) else {+ continue;+ };+ let Ok(descriptor) = serde_json::from_str::<Value>(&content) else {+ continue;+ };+ if descriptor["workerId"].as_str() != Some(active_session_id) {+ continue;+ }+ let pid = descriptor["pid"].as_i64().unwrap_or(0);+ if pid > 0 {+ return Some(pid as i32);+ }+ }+ }+ None+ })+}++fn group_alive(pgid: i32) -> bool {+ // The whole process group: signaling the negative pgid answers ESRCH+ // only when every process the group named is gone.+ signal_pid(Pid::from_raw(-pgid), None).is_ok()+}++/// Wait out the one liveness signal the feature produces: the group's+/// death. The message names the kill that failed to reap it, so a red+/// run says exactly which half of the contract leaked.+fn expect_group_dead(pgid: i32, cause: &str) {+ let deadline = Instant::now() + Duration::from_secs(30);+ while group_alive(pgid) {+ assert!(+ Instant::now() < deadline,+ "the journaled bash group (pgid {pgid}) survived {cause}: the reap never ran"+ );+ std::thread::sleep(Duration::from_millis(100));+ }+}++/// A red run must not leak `sleep 600` past the test: the group dies with+/// the guard whether or not the assertions passed.+struct GroupGuard(i32);++impl Drop for GroupGuard {+ fn drop(&mut self) {+ let _ = signal_pid(Pid::from_raw(-self.0), Signal::SIGKILL);+ }+}++/// The shared opening: a live session whose kernel runs a released+/// `bash("sleep 600")` group, with the daemon, client, and ids in hand.+struct OrphanedSession {+ daemon: Daemon,+ active_session_id: String,+ pgid: i32,+ kernel_pid: i32,+ worker_pid: i32,+}++fn session_with_orphan(+ mock_next: &'static AtomicUsize,+ root: &Path,+ socket_file: &str,+) -> OrphanedSession {+ let Some(kernel_python) = kernel_python() else {+ panic!("the orphan journal e2e requires a live kernel python");+ };+ let agent_dir = root.join("agent");+ std::fs::create_dir_all(&agent_dir).expect("agent dir");+ let socket = agent_dir.join(socket_file);+ let url = spawn_mock(mock_next);+ std::fs::write(+ agent_dir.join("models.json"),+ json!({+ "providers": {+ "prime-inference": {+ "api": "openai-completions",+ "baseUrl": url.to_string_lossy(),+ "apiKey": "sk-orphan",+ "models": [+ {+ "id": "mock-1",+ "name": "Mock 1",+ "api": "openai-completions",+ "contextWindow": 128_000,+ "maxTokens": 4096+ }+ ]+ }+ }+ })+ .to_string(),+ )+ .expect("write models.json");+ let daemon = spawn_daemon(&socket, &agent_dir, Some(&kernel_python));+ let mut client = Client::connect(&socket);+ let active_session_id = create_session(&mut client, "c1", root, &agent_dir);+ let started = client.request(+ "p1",+ &json!({+ "type": "prompt_and_wait",+ "activeSessionId": active_session_id,+ "message": "start the orphan and stop",+ }),+ );+ assert_eq!(started["success"], true, "first turn failed: {started}");+ let (pgid, kernel_pid) = orphan_ids(&mut client, &active_session_id);+ let worker_pid = worker_pid(&agent_dir, &active_session_id);+ assert!(+ group_alive(pgid),+ "the orphaning sleep died before the kill: pgid {pgid}"+ );+ OrphanedSession {+ daemon,+ active_session_id,+ pgid,+ kernel_pid,+ worker_pid,+ }+}++/// T1: a kernel killed without its shutdown hook must not leak the+/// `bash()` groups it journaled — the worker's teardown reaps them.+#[test]+fn a_killed_kernel_reaps_its_journaled_bash_groups() {+ static NEXT: AtomicUsize = AtomicUsize::new(0);+ if kernel_python().is_none() {+ return;+ }+ let root = tempfile::TempDir::new().expect("temp dir");+ let session = session_with_orphan(&NEXT, root.path(), "t1.sock");+ let _guard = GroupGuard(session.pgid);++ signal_pid(Pid::from_raw(session.kernel_pid), Signal::SIGKILL).expect("kill the kernel pid");+ // Event-driven: the reap lands when the worker notices the dead+ // kernel and tears it down — never a sleep-based wait.+ expect_group_dead(session.pgid, "the kernel kill");++ // Teardown: stop the session through the live supervisor so the+ // worker (and its kernel) do not leak past the test.+ let mut client = Client::connect(&session.daemon.socket);+ client.request(+ "k1",+ &json!({ "type": "kill", "activeSessionId": session.active_session_id }),+ );+}++/// T2: the stopped worker cannot run its own teardown reap when the+/// kernel and worker die — only the supervisor can, from the journal the+/// dead worker's kernel wrote.+#[test]+fn a_dead_worker_reaps_its_journaled_bash_groups_from_the_supervisor() {+ static NEXT: AtomicUsize = AtomicUsize::new(0);+ if kernel_python().is_none() {+ return;+ }+ let root = tempfile::TempDir::new().expect("temp dir");+ let session = session_with_orphan(&NEXT, root.path(), "t2.sock");+ let _guard = GroupGuard(session.pgid);++ // SIGSTOP first: the worker must not run its kernel-teardown reap when+ // the kernel dies. SIGKILL cannot be caught, so the worker dies without+ // ever observing either death.+ signal_pid(Pid::from_raw(session.worker_pid), Signal::SIGSTOP).expect("stop the worker pid");+ signal_pid(Pid::from_raw(session.kernel_pid), Signal::SIGKILL).expect("kill the kernel pid");+ signal_pid(Pid::from_raw(session.worker_pid), Signal::SIGKILL)+ .expect("kill the stopped worker");+ // The supervisor's crash monitor owns the only reap: the group dies+ // when it fires, not on any timeout of ours.+ expect_group_dead(session.pgid, "the worker kill");+}