A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
monitor replacement worker lifetimes (#3488)
Sebastian Müllerf9938131edfe
diff --git a/.changes/replacement-worker-monitoring.md b/.changes/replacement-worker-monitoring.mdnew file mode 100644index 0000000000..fa560cb13a--- /dev/null+++ b/.changes/replacement-worker-monitoring.md@@ -0,0 +1 @@+- Replacement session workers stay supervised after re-registration, and failed worker relaunches after an abandoned update resume crash recovery instead of leaving the session unsupervised.diff --git a/crates/pa-daemon/src/registry.rs b/crates/pa-daemon/src/registry.rsindex 9bee2c82d0..c18b2104d4 100644--- a/crates/pa-daemon/src/registry.rs+++ b/crates/pa-daemon/src/registry.rs@@ -108,6 +108,10 @@ pub(crate) struct ResidentWorker {/// Unix-millis spawn time of the current child (0 for an adopted pid): only a lifetime past the/// stable window earns a counter reset (spawn-dies-fast churn accumulates).pub(crate) spawned_at_ms: AtomicU64,+ /// The resident's monitor generation: the latest `spawn_monitor` claim.+ /// A watch whose generation was superseded returns at the exit check+ /// instead of running crash bookkeeping over the new owner's process.+ pub(crate) monitor_epoch: AtomicU64,/// The worker advertised `direct_peer_transport` in its `worker_auth` response.pub(crate) peer_transport_capable: AtomicBool,/// The last-good heartbeats catalog answer, tagged with its generation: served when the worker@@ -173,6 +177,7 @@ impl ResidentWorker {intentional_stop: AtomicBool::new(false),consecutive_failures: AtomicU32::new(0),spawned_at_ms: AtomicU64::new(0),+ monitor_epoch: AtomicU64::new(0),peer_transport_capable: AtomicBool::new(false),heartbeat_snapshot: Mutex::new(None),cron_snapshot: Mutex::new(None),diff --git a/crates/pa-daemon/src/supervisor/adoption.rs b/crates/pa-daemon/src/supervisor/adoption.rsindex ec1eb132a9..4a5f4eedcd 100644--- a/crates/pa-daemon/src/supervisor/adoption.rs+++ b/crates/pa-daemon/src/supervisor/adoption.rs@@ -400,10 +400,16 @@ impl Supervisor {};// Serialize against descriptor adoption for the same worker.let guard = self.registry.adoption_guard(active_session_id).await;- let resident = match self.registry.get(active_session_id).await {- Some(resident) => resident,+ let (resident, re_arm_monitor) = match self.registry.get(active_session_id).await {+ Some(resident) => {+ // The monitor ownership reads before this registration's+ // descriptor update overwrites the pid: a registrant naming+ // a different process than the watched one takes the resident.+ let pid_changed = resident.descriptor.lock().await.pid != *pid;+ (resident, pid_changed)+ }None => match self.adopt_registered_worker(®istration, token).await {- Ok(resident) => resident,+ Ok(resident) => (resident, false),Err(error) => {let message = format!("{error:#}");// The definitive unknown-worker refusal is observable (log + telemetry)@@ -476,6 +482,13 @@ impl Supervisor {};durable_session_id};+ // 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);+ }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).// The settle lands after the registration is recorded, so a woken waiter'sdiff --git a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs b/crates/pa-daemon/src/supervisor/spawn_record_tests.rsindex d2b312c022..c0ede373cc 100644--- a/crates/pa-daemon/src/supervisor/spawn_record_tests.rs+++ b/crates/pa-daemon/src/supervisor/spawn_record_tests.rs@@ -181,6 +181,57 @@ async fn a_relaunch_spawn_record_serves_the_durable_persist() {assert!(persisted.pid > 0, "the spawned pid rides the record");}+/// A spawn record that cannot land (the descriptor path is occupied) must+/// fail the launch and kill the spawned child: a lost record is how a+/// successor boot adopts a stale or recycled pid as a live worker. On the+/// unfixed tree the persist failure is discarded and the launch only fails+/// later, at the connect probe, with no spawn record behind it.+#[tokio::test]+async fn a_spawn_record_persist_failure_kills_the_child_and_fails_the_launch() {+ let (supervisor, dir) = spawn_record_witness("persistfail");+ let descriptor_path = dir.join("w-persistfail.json");+ // The spawn record's destination is occupied: the atomic persist fails.+ std::fs::create_dir(&descriptor_path).unwrap();+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({+ "version": 2,+ "workerId": "w-persistfail",+ "pid": 0,+ "socketPath": dir.join("w-persistfail.sock").to_string_lossy(),+ "recoveryJournalPath": "/tmp/w-persistfail.recovery.jsonl",+ "supervisorSocketPath": "/tmp/none.sock",+ "authenticationToken": "spawnrec-token",+ "rootActiveSessionId": "w-persistfail",+ "createdAt": "2026-10-01T00:00:00Z",+ "updatedAt": "2026-10-01T00:00:00Z",+ "lifecycle": "ready",+ "createCommand": {},+ "consecutiveFailures": 0,+ }))+ .expect("descriptor");+ let resident = ResidentWorker::new(+ "w-persistfail".to_string(),+ descriptor,+ descriptor_path.clone(),+ );+ supervisor.registry.insert(Arc::clone(&resident)).await;+ let outcome = supervisor.relaunch_worker(&resident).await;+ let error = format!(+ "{:#}",+ outcome.expect_err("the launch fails at the spawn record")+ );+ assert!(+ error.contains("persist spawned worker identity"),+ "the launch owns the spawn-record failure: {error}"+ );+ // The spawned child is dead: the descriptor named it before the persist.+ let pid = resident.descriptor.lock().await.pid;+ assert!(pid > 0, "the child's pid was recorded before the persist");+ assert!(+ !crate::lease::is_process_alive(pid as u32).unwrap_or(true),+ "the failed-launch child is killed"+ );+}+/// A fresh create's spawn record keeps the unsynced TS `persistWorker`/// shape (TS's `writeFileAtomicSync` fsync is opt-in and the descriptor/// family never requests it); the create-completion persistdiff --git a/crates/pa-daemon/src/supervisor/supervision.rs b/crates/pa-daemon/src/supervisor/supervision.rsindex 949e160531..f689fc33ea 100644--- a/crates/pa-daemon/src/supervisor/supervision.rs+++ b/crates/pa-daemon/src/supervisor/supervision.rs@@ -73,16 +73,30 @@ impl Supervisor {pid: u64,) {let supervisor = Arc::clone(self);- tokio::spawn(async move {- supervisor.watch_worker(resident, child, pid).await;- });+ tokio::spawn(supervisor.watch_worker(resident, child, pid));}- pub(super) async fn watch_worker(+ /// Watch one process lifetime for the resident. The generation claim is+ /// synchronous, so the newest arm owns the resident before its task is+ /// even polled: a watch whose generation a later arm superseded returns+ /// at the exit check instead of running crash bookkeeping over the new+ /// owner's process.+ pub(super) fn watch_worker(+ self: Arc<Self>,+ resident: Arc<ResidentWorker>,+ child: Option<Child>,+ adopted_pid: u64,+ ) -> 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)+ }++ async fn watch_worker_owned(self: Arc<Self>,resident: Arc<ResidentWorker>,mut child: Option<Child>,mut adopted_pid: u64,+ monitor_epoch: u64,) {loop {if let Some(mut child) = child.take() {@@ -118,14 +132,20 @@ impl Supervisor {tokio::time::sleep(ADOPTED_EXIT_FALLBACK_POLL).await;}}- // A relaunch elsewhere (update abandon, retry) took over the- // resident with a new process.- if self.is_stopping(&resident)- || resident.descriptor.lock().await.pid != adopted_pid- {+ // Manual retry still replaces the descriptor's pid without+ // arming a monitor. Preserve that handoff fence alongside+ // generation ownership so the predecessor's exit cannot+ // enter crash recovery over the retry's replacement.+ if resident.descriptor.lock().await.pid != adopted_pid {return;}}+ // The exit is the watched process's, not the resident's: a later+ // monitor arm (a registration re-arm, an update abandon) owns the+ // resident now.+ if self.superseded(&resident, monitor_epoch) {+ return;+ }self.note_daemon_event("worker_exited", Some("crash"));// A hard-killed parent bypasses every worker-side close (#246): close the// resident RLM children here, before the restart, so a relaunched parent@@ -190,6 +210,13 @@ impl Supervisor {resident.worker_id));tokio::time::sleep(Duration::from_millis(backoff_ms)).await;+ // The backoff can span a registration re-arm or an update+ // commit's abandon: both claim the resident while this watch+ // slept, and a superseded watch must not relaunch a second+ // worker next to the new owner's.+ if self.superseded(&resident, monitor_epoch) {+ return;+ }match self.relaunch_worker(&resident).await {Ok(new_child) => {// No counter reset on a successful relaunch: a spawn that dies fast must@@ -221,6 +248,13 @@ impl Supervisor {|| resident.intentional_stop.load(Ordering::SeqCst)}+ /// Whether this watch no longer owns the resident's process: the stop+ /// flag is read before the generation, so an update abandon's clear and+ /// bump can never both slip past the same check.+ fn superseded(&self, resident: &Arc<ResidentWorker>, monitor_epoch: u64) -> bool {+ self.is_stopping(resident) || resident.monitor_epoch.load(Ordering::SeqCst) != monitor_epoch+ }+/// Whether the supervisor is tearing down (long-lived daemon tasks/// poll this instead of holding their own shutdown wiring).pub(crate) fn is_shutting_down(&self) -> bool {@@ -455,7 +489,7 @@ impl Supervisor {if std::env::var("PA_DAEMON_DEBUG").is_ok() {eprintln!("[supervisor] spawned worker pid {:?}", child.id());}- {+ let spawn_record = {let mut descriptor = resident.descriptor.lock().await;// Capture the child's start identity alongside its pid (TS `getProcessStartId`// at spawn): the holder checks need it to recognize a recycled pid.@@ -476,7 +510,15 @@ impl Supervisor {// lose the descriptor's whole payload — the recovery journal// pointer and the durable create command the next boot's// revival replays.- let _ = persist_worker_at(&resident.descriptor_path, &descriptor, spawn_record_sync);+ persist_worker_at(&resident.descriptor_path, &descriptor, spawn_record_sync)+ };+ // Fail closed: a spawn record that could not land would leave the+ // successor boot adopting this pid as live (or a recycled pid as the+ // worker), so the launch is rolled back instead of left unrecorded.+ if let Err(error) = spawn_record {+ let mut child = child;+ let _ = child.kill().await;+ return Err(error).context("persist spawned worker identity");}// A worker that never comes up inside the connect budget is killed here, so adiff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex a45dff7e3d..f4e0170634 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -266,9 +266,9 @@ async fn an_adopted_watch_hands_off_at_exit_without_a_timer() {);}{- // A relaunch elsewhere took the resident: the pid no longer names- // the watched process, so the watch hands off instead of running- // the crash arm over the replacement.+ // An explicit new monitor (an update abandon's relaunch) took the+ // resident. The old watch returns at the exit instead of running+ // the crash arm over the new owner's process.let mut worker = std::process::Command::new("sleep").arg("600").spawn()@@ -284,7 +284,7 @@ async fn an_adopted_watch_hands_off_at_exit_without_a_timer() {futures::poll!(watch.as_mut()).is_pending(),"a live adopted worker keeps the watch parked");- resident.descriptor.lock().await.pid = u64::from(std::process::id());+ supervisor.spawn_monitor(Arc::clone(&resident), None, u64::from(std::process::id()));worker.kill().expect("kill sleep");worker.wait().expect("reap sleep");watch.await;@@ -296,6 +296,57 @@ async fn an_adopted_watch_hands_off_at_exit_without_a_timer() {}}+/// Manual retry can replace the descriptor's pid without arming a monitor.+/// The adopted predecessor must still hand off, even with an unchanged epoch.+#[cfg(any(target_os = "linux", target_os = "macos"))]+#[tokio::test(start_paused = true)]+async fn a_pid_only_replacement_keeps_the_adopted_predecessor_out_of_crash_recovery() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ // A missed handoff must not spawn the test executable as a worker.+ std::fs::write(agent_dir.join("logs"), "not a directory").unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ let mut predecessor = tokio::process::Command::new("sleep")+ .arg("600")+ .kill_on_drop(true)+ .spawn()+ .expect("spawn isolated predecessor");+ let mut replacement = tokio::process::Command::new("sleep")+ .arg("600")+ .kill_on_drop(true)+ .spawn()+ .expect("spawn isolated replacement");+ let predecessor_pid = predecessor.id().unwrap();+ let resident = adopted_watch_resident(dir.path(), predecessor_pid);+ supervisor.registry.insert(Arc::clone(&resident)).await;+ let mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(+ Arc::clone(&resident),+ None,+ u64::from(predecessor_pid)+ ));+ assert!(futures::poll!(watch.as_mut()).is_pending());+ let epoch = resident.monitor_epoch.load(Ordering::SeqCst);+ resident.descriptor.lock().await.pid = u64::from(replacement.id().unwrap());+ assert_eq!(resident.monitor_epoch.load(Ordering::SeqCst), epoch);+ // Reap both test-owned processes before checking the watch's result.+ predecessor.kill().await.expect("reap isolated predecessor");+ replacement.kill().await.expect("reap isolated replacement");+ watch.await;+ assert_eq!(resident.consecutive_failures.load(Ordering::SeqCst), 0);+ assert_eq!(+ resident.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Ready+ );+ assert!(supervisor.registry.get("w-adopted-watch").await.is_some());+}+/// The watched adopted worker's resident, with the descriptor carrying the/// watched pid (the post-exit ownership check compares against it).#[cfg(any(target_os = "linux", target_os = "macos"))]@@ -323,6 +374,360 @@ fn adopted_watch_resident(dir: &std::path::Path, pid: u32) -> Arc<ResidentWorker)}+/// The red-first headline: a replacement registration for a resident the+/// supervisor watches over an adopted pid must transfer the watch to the+/// registrant's process. On the unfixed tree the predecessor's exit+/// returned the watch (the pid no longer matched) and the replacement's+/// death went unobserved: no give-up, no cleanup, a dead resident still+/// in the registry.+#[cfg(any(target_os = "linux", target_os = "macos"))] // the kernel-watch arms+#[tokio::test]+async fn a_registered_replacement_pid_is_monitored_after_the_predecessor_exits() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ let mut predecessor = std::process::Command::new("sleep")+ .arg("600")+ .spawn()+ .expect("spawn the predecessor");+ let mut replacement = std::process::Command::new("sleep")+ .arg("600")+ .spawn()+ .expect("spawn the replacement");+ let resident = adopted_watch_resident(dir.path(), predecessor.id());+ // 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+ .consecutive_failures+ .store(MAX_CONSECUTIVE_FAILURES, Ordering::SeqCst);+ supervisor.registry.insert(Arc::clone(&resident)).await;+ let mut old_watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(+ Arc::clone(&resident),+ None,+ u64::from(predecessor.id())+ ));+ assert!(+ futures::poll!(old_watch.as_mut()).is_pending(),+ "a live adopted worker keeps the watch parked"+ );+ // The replacement registers: a new process for the same resident.+ let command = DaemonCommand::WorkerRegister {+ id: None,+ active_session_id: "w-adopted-watch".into(),+ session_id: None,+ socket_path: dir+ .path()+ .join("replacement.sock")+ .to_string_lossy()+ .to_string(),+ worker_instance_id: "replacement-instance".into(),+ token: "token".into(),+ pid: u64::from(replacement.id()),+ rest: Map::default(),+ };+ let registered = supervisor+ .handle_worker_register("register-1", "worker_register", &command)+ .await;+ assert!(+ registered.success,+ "the replacement registers: {registered:?}"+ );+ // The predecessor's exit retires the old watch without crash bookkeeping.+ predecessor.kill().expect("kill the predecessor");+ predecessor.wait().expect("reap the predecessor");+ tokio::time::timeout(Duration::from_secs(2), old_watch)+ .await+ .expect("the old watch returns at the predecessor's exit");+ assert_eq!(+ resident.consecutive_failures.load(Ordering::SeqCst),+ MAX_CONSECUTIVE_FAILURES+ );+ assert_eq!(+ resident.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Ready+ );+ // The replacement's death is supervised: the give-up runs at the cap.+ replacement.kill().expect("kill the replacement");+ replacement.wait().expect("reap the replacement");+ tokio::time::timeout(Duration::from_secs(5), async {+ while supervisor.registry.get("w-adopted-watch").await.is_some() {+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ })+ .await+ .expect("the replacement's death reaches the give-up");+ assert_eq!(+ resident.consecutive_failures.load(Ordering::SeqCst),+ MAX_CONSECUTIVE_FAILURES + 1+ );+ assert_eq!(+ resident.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Failed+ );+}++/// A second explicit monitor arm retires the old watch at the exit: the+/// superseded generation must not run crash bookkeeping over the resident+/// the new arm owns. On the unfixed tree the unchanged pid falls through+/// to the crash arm and the death counts a failure.+#[cfg(any(target_os = "linux", target_os = "macos"))] // the kernel-watch arms+#[tokio::test]+async fn a_superseded_watch_leaves_the_failure_count_to_the_new_monitor() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ let mut worker = std::process::Command::new("sleep")+ .arg("600")+ .spawn()+ .expect("spawn sleep");+ let resident = adopted_watch_resident(dir.path(), worker.id());+ // The cap is armed: an unsupervised crash arm would give up at once.+ resident+ .consecutive_failures+ .store(MAX_CONSECUTIVE_FAILURES, Ordering::SeqCst);+ supervisor.registry.insert(Arc::clone(&resident)).await;+ let mut watch = std::pin::pin!(Arc::clone(&supervisor).watch_worker(+ Arc::clone(&resident),+ None,+ u64::from(worker.id())+ ));+ 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()));+ 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_eq!(+ resident.consecutive_failures.load(Ordering::SeqCst),+ MAX_CONSECUTIVE_FAILURES,+ "the superseded watch must not count the exit as a failure"+ );+ assert_eq!(+ resident.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Ready+ );+ assert!(+ supervisor.registry.get("w-adopted-watch").await.is_some(),+ "the resident stays owned by the new generation"+ );+}++/// A watch parked in the crash backoff must not relaunch over the resident+/// when another arm claimed it during the sleep: the generation moved on+/// while this watch was backed off.+#[cfg(any(target_os = "linux", target_os = "macos"))] // the kernel-watch arms+#[tokio::test(start_paused = true)]+async fn a_superseded_watch_in_backoff_does_not_relaunch_over_the_new_owner() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ // An unsupervised relaunch would fail deterministically here: a file+ // stands where the logs dir would go.+ std::fs::write(agent_dir.join("logs"), "not a directory").unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ let mut worker = std::process::Command::new("sleep")+ .arg("600")+ .spawn()+ .expect("spawn sleep");+ let resident = adopted_watch_resident(dir.path(), worker.id());+ supervisor.registry.insert(Arc::clone(&resident)).await;+ // A spawned watch, like production's spawn_monitor arms it: the parked+ // task registers a real waker with the kernel exit watch.+ let mut watch = tokio::spawn(Arc::clone(&supervisor).watch_worker(+ Arc::clone(&resident),+ None,+ u64::from(worker.id()),+ ));+ tokio::task::yield_now().await;+ assert!(+ futures::poll!(&mut watch).is_pending(),+ "a live adopted worker keeps the watch parked"+ );+ worker.kill().expect("kill sleep");+ worker.wait().expect("reap sleep");+ // The crash arm counts its failure, then parks in its backoff: the+ // millisecond poll parks the runtime long enough to deliver the exit+ // event while the paused clock stays deep inside the backoff window.+ tokio::time::timeout(Duration::from_secs(5), async {+ while resident.consecutive_failures.load(Ordering::SeqCst) == 0 {+ tokio::time::sleep(Duration::from_millis(1)).await;+ }+ })+ .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()));+ tokio::time::timeout(Duration::from_secs(5), watch)+ .await+ .expect("the superseded watch returns after the backoff")+ .expect("the watch task completes");+ assert_eq!(+ resident.consecutive_failures.load(Ordering::SeqCst),+ 1,+ "no relaunch arm ran over the new owner"+ );+ assert_eq!(+ resident.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Ready+ );+ assert!(+ supervisor.registry.get("w-adopted-watch").await.is_some(),+ "the resident stays owned by the new generation"+ );+}++/// The abandon-update resident: the commit's stop acked and exited, with+/// the give-up budget at the cap so a supervised failure settles at once.+fn abandon_update_resident(dir: &std::path::Path, worker_id: &str) -> Arc<ResidentWorker> {+ let descriptor: DaemonWorkerDescriptor = serde_json::from_value(serde_json::json!({+ "version": 2,+ "workerId": worker_id,+ "pid": 0,+ "socketPath": "/tmp/none.sock",+ "recoveryJournalPath": dir.join(format!("{worker_id}.recovery.jsonl")).to_string_lossy(),+ "supervisorSocketPath": "/tmp/none.sock",+ "authenticationToken": "token",+ "rootActiveSessionId": worker_id,+ "createdAt": "t",+ "updatedAt": "t",+ "lifecycle": "ready",+ "createCommand": {},+ "consecutiveFailures": 0,+ }))+ .expect("descriptor");+ let resident = ResidentWorker::new(+ worker_id.to_string(),+ descriptor,+ dir.join(format!("{worker_id}.descriptor.json")),+ );+ resident+ .consecutive_failures+ .store(MAX_CONSECUTIVE_FAILURES, Ordering::SeqCst);+ resident+}++/// The update commit's abandon (a stop refusal in the budget) re-opens+/// supervision for the worker that already stopped: when the relaunch+/// fails, the resident is handed back to the crash path instead of+/// staying unsupervised in the registry. On the unfixed tree the failed+/// relaunch is only logged.+#[tokio::test(start_paused = true)]+async fn an_abandoned_updates_failed_relaunch_arms_supervision_again() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ // The abandon's relaunch fails deterministically: a file stands where+ // the logs dir would go.+ std::fs::write(agent_dir.join("logs"), "not a directory").unwrap();+ let supervisor = Arc::new(+ Supervisor::new(SupervisorOptions {+ socket_path: dir.path().join("daemon.sock"),+ agent_dir,+ })+ .expect("supervisor"),+ );+ // The stopped worker acks the graceful stop (pid 0 is already gone for+ // the exit wait); the refuser never answers inside the budget.+ let stopped = abandon_update_resident(dir.path(), "w-abandon-stopped");+ let (stopped_tx, mut stopped_rx) = mpsc::channel::<WorkerRequest>(1);+ *stopped.cmd_tx.lock().await = Some(stopped_tx);+ let pump_resident = Arc::clone(&stopped);+ tokio::spawn(async move {+ let request = stopped_rx.recv().await.expect("the stop routes a shutdown");+ let reply = pump_resident+ .pending+ .lock()+ .await+ .remove(&request.request_id)+ .expect("the routed shutdown holds a reply slot");+ let _ = reply.send(WorkerReply::Typed(crate::protocol::response_success(+ None, "shutdown", None,+ )));+ });+ supervisor.registry.insert(Arc::clone(&stopped)).await;+ stopped.note_connection_live();+ let refused = abandon_update_resident(dir.path(), "w-abandon-refused");+ let (refused_tx, mut refused_rx) = mpsc::channel::<WorkerRequest>(1);+ *refused.cmd_tx.lock().await = Some(refused_tx);+ tokio::spawn(async move {+ // The refuser never answers: the shutdown request runs out of budget.+ let _ = refused_rx.recv().await;+ });+ supervisor.registry.insert(Arc::clone(&refused)).await;+ refused.note_connection_live();++ // Reach the committed stop window without the prepare machinery's+ // snapshot phase: the update state machine is driven directly.+ let update_id = UpdateId::from("u-abandon".to_string());+ let budget = UpdateTimeoutBudget::from_env();+ supervisor+ .update_prepare+ .begin(update_id.clone(), util::now_ms(), &budget);+ supervisor.update_prepare.drain_complete(&update_id);+ supervisor+ .update_prepare+ .snapshot_written(&update_id, util::now_ms(), &budget);+ supervisor.update_prepare.prepare_acked(&update_id);+ let command = DaemonCommand::CommitUpdateRestart {+ id: None,+ update_id: Some("u-abandon".to_string()),+ rest: Map::default(),+ };+ let (lines, ok) = supervisor+ .handle_commit_update_restart("commit-1", "commit_update_restart", &command)+ .await;+ assert!(!ok, "the refusal abandons the update: {lines:?}");++ // The stopped worker's failed relaunch re-arms supervision: the give-up+ // (the resident's budget was at the cap) removes the resident instead+ // of leaving the dead channel in the registry.+ tokio::time::timeout(Duration::from_secs(5), async {+ while supervisor.registry.get("w-abandon-stopped").await.is_some() {+ tokio::time::sleep(Duration::from_millis(5)).await;+ }+ })+ .await+ .expect("the abandoned relaunch's failure reaches the give-up");+ assert_eq!(+ stopped.descriptor.lock().await.lifecycle,+ DaemonWorkerLifecycle::Failed+ );+ assert_eq!(+ stopped.consecutive_failures.load(Ordering::SeqCst),+ MAX_CONSECUTIVE_FAILURES + 1+ );+ // The refuser's session is untouched: it keeps running.+ assert!(+ supervisor.registry.get("w-abandon-refused").await.is_some(),+ "the refusal keeps its session running"+ );+}+/// The saved-session surfaces (the `list --all` summary row and the/// `list_saved_sessions` catalog row) carry the persisted thinking/// level: the agents-view Model column renders "model:level" fordiff --git a/crates/pa-daemon/src/supervisor/update_restart.rs b/crates/pa-daemon/src/supervisor/update_restart.rsindex 5da09c02a6..af736695b4 100644--- a/crates/pa-daemon/src/supervisor/update_restart.rs+++ b/crates/pa-daemon/src/supervisor/update_restart.rs@@ -347,6 +347,13 @@ impl Supervisor {for (resident, (_, verdict)) in residents.iter().zip(&verdicts) {match verdict {WorkerStopVerdict::Stopped => {+ // The old monitor may only now observe its+ // child's exit. Retire that watch before+ // reopening supervision: the bump lands+ // before the stop flag is cleared, so a+ // watch woken at the exit reads either the+ // intentional stop or the new generation.+ resident.monitor_epoch.fetch_add(1, Ordering::SeqCst);resident.intentional_stop.store(false, Ordering::SeqCst);match self.relaunch_worker(resident).await {Ok(child) => {@@ -358,6 +365,14 @@ impl Supervisor {"worker {} abandon relaunch failed: {error:#}",resident.worker_id));+ // The old watch already returned on the+ // intentional stop: hand the resident's+ // remaining failure budget to the crash+ // 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);+ }}}}