A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
whole-worker idle passivation reaches resident roots (#3209)
Sebastian Müller72b71224f368
diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rsindex e66a786126..aec8de6887 100644--- a/crates/pa-daemon/src/supervisor/tests.rs+++ b/crates/pa-daemon/src/supervisor/tests.rs@@ -962,10 +962,12 @@ async fn idle_passivation_requires_the_worker_token() {}#[tokio::test]-async fn idle_passivation_refuses_a_root_worker() {- // The parent-owned gate: only a child worker (rlmDepth > 0 in the- // create command) may ask; a root worker's lease is client-owned- // policy and the ask is refused.+async fn idle_passivation_refuses_client_owned_and_in_memory_workers() {+ // The refusal gate (TS `canEvictWorker`'s `hasOwnerClient` arm,+ // widened): a client-owned worker never passivates itself, and an+ // in-memory (noSession) root has no file to wake from. An unowned+ // sessioned root passes this gate (the e2e drives the pass side+ // end to end).let dir = tempfile::TempDir::new().unwrap();let agent_dir = dir.path().join("agent");std::fs::create_dir_all(&agent_dir).unwrap();@@ -978,17 +980,17 @@ async fn idle_passivation_refuses_a_root_worker() {);let descriptor = pa_types::daemon::DaemonWorkerDescriptor {version: 1,- worker_id: "w-root".to_string(),+ worker_id: "w-owned".to_string(),pid: 4242,process_start_id: None,socket_path: "/tmp/none.sock".to_string(),recovery_journal_path: "/tmp/none.jsonl".to_string(),orphan_process_journal_path: None,supervisor_socket_path: "/tmp/none.sock".to_string(),- authentication_token: "root-token".to_string(),+ authentication_token: "owned-token".to_string(),worker_instance_id: None,- root_active_session_id: "w-root".to_string(),- owner_client_id: None,+ root_active_session_id: "w-owned".to_string(),+ owner_client_id: Some("client-1".to_string()),root_session_id: Some("root-1".to_string()),session_file: None,session_dir: None,@@ -1008,10 +1010,18 @@ async fn idle_passivation_refuses_a_root_worker() {last_error: None,rest: Map::default(),};- let resident = ResidentWorker::new("w-root".to_string(), descriptor, dir.path().join("w.d"));+ let in_memory = {+ let mut descriptor = descriptor.clone();+ descriptor.worker_id = "w-mem".to_string();+ descriptor.authentication_token = "mem-token".to_string();+ descriptor.owner_client_id = None;+ descriptor.create_command.no_session = Some(true);+ descriptor+ };+ let resident = ResidentWorker::new("w-owned".to_string(), descriptor, dir.path().join("w.d"));supervisor.registry.insert(resident).await;let response = supervisor- .handle_worker_idle_passivation("c1", "worker_idle_passivation", "root-token", Some(1))+ .handle_worker_idle_passivation("c1", "worker_idle_passivation", "owned-token", Some(1)).await;assert!(!response.success);assert!(@@ -1019,81 +1029,22 @@ async fn idle_passivation_refuses_a_root_worker() {.error.as_deref().unwrap_or("")- .contains("child-worker policy"),- "the root worker's ask is refused: {response:?}"- );-}--#[tokio::test]-async fn idle_passivation_accepts_a_parent_owned_revived_child() {- // The parent-owned gate's pass side (Macroscope's/Bugbot's revival- // identity finding): a worker relaunched by a WAKE whose create's- // rest carries the child's rlmDepth passes the gate - the revived- // child stays passivation-eligible (its park window arms on the- // persisted header depth; the fence reads the create identity).- 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: agent_dir.clone(),- })- .expect("supervisor"),+ .contains("client-owned or in-memory (noSession) worker"),+ "the client-owned worker's ask is refused: {response:?}");- let descriptor = pa_types::daemon::DaemonWorkerDescriptor {- version: 1,- worker_id: "w-child".to_string(),- pid: 4245,- process_start_id: None,- socket_path: "/tmp/none.sock".to_string(),- recovery_journal_path: "/tmp/none.jsonl".to_string(),- orphan_process_journal_path: None,- supervisor_socket_path: "/tmp/none.sock".to_string(),- authentication_token: "child-token".to_string(),- worker_instance_id: None,- root_active_session_id: "w-child".to_string(),- owner_client_id: None,- root_session_id: Some("kid".to_string()),- session_file: None,- session_dir: None,- telemetry_disabled: None,- created_at: "t".to_string(),- updated_at: "t".to_string(),- lifecycle: DaemonWorkerLifecycle::Ready,- create_command: pa_types::daemon::DurableDaemonCreateCommand {- session_path: None,- no_session: None,- rest: Map::from_iter([- ("rlmDepth".to_string(), json!(1)),- ("rlmChildId".to_string(), json!("sub-kid")),- ]),- },- consecutive_failures: 0,- stop_requested_at: None,- archive_on_stop: None,- last_failure_at: None,- last_error: None,- rest: Map::default(),- };- let resident = ResidentWorker::new("w-child".to_string(), descriptor, agent_dir);- supervisor- .registry- .insert(std::sync::Arc::clone(&resident))- .await;+ let resident = ResidentWorker::new("w-mem".to_string(), in_memory, dir.path().join("w-mem.d"));+ supervisor.registry.insert(resident).await;let response = supervisor- .handle_worker_idle_passivation("c1", "worker_idle_passivation", "child-token", Some(1))+ .handle_worker_idle_passivation("c2", "worker_idle_passivation", "mem-token", Some(1)).await;- // The gate passes: the answer is NOT the child-worker-policy refusal- // (the stop path itself answers with its own outcome - the gate is- // what this test pins).+ assert!(!response.success);assert!(- !response+ response.error.as_deref().unwrap_or("")- .contains("child-worker policy"),- "the parent-owned revived child's ask must pass the gate: {response:?}"+ .contains("client-owned or in-memory (noSession) worker"),+ "the in-memory worker's ask is refused: {response:?}");}diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rsindex e9c62c5030..151e82c448 100644--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs@@ -618,18 +618,21 @@ impl Supervisor {}/// The worker-driven idle passivation (TS's `idleEvictionMinutes`- /// tier, whole-worker): a parent-owned child worker whose park arm- /// proved the idle state and crossed the threshold asks for its own- /// graceful stop over the supervisor link. The supervisor verifies- /// the worker token, re-verifies the parent-owned descriptor (a root- /// worker can never ask its way out), and re-reads the setting — the- /// supervisor's own fresh-snapshot fence: a setting flipped to- /// `"off"` (or past the threshold) between the worker's ask and the- /// stop cancels the passivation. The stop itself is the existing- /// graceful path (`stop_worker`: durable tombstone, routed shutdown,- /// process-retirement wait, registry removal, roster passivation),- /// so a passivated child's row stays visible and family-addressable- /// and its next prompt wakes a fresh worker over the session file.+ /// tier, whole-worker): an unowned worker whose park arm proved the+ /// idle state and crossed the threshold asks for its own graceful+ /// stop over the supervisor link — TS `canEvictWorker` reaches roots+ /// and children alike. The supervisor verifies the worker token,+ /// refuses a client-owned or noSession descriptor (TS+ /// `hasOwnerClient`: the owner's disconnect cleanup owns that stop;+ /// an in-memory session has no file to wake from), and re-reads the+ /// setting — the supervisor's own fresh-snapshot fence: a setting+ /// flipped to `"off"` (or past the threshold) between the worker's+ /// ask and the stop cancels the passivation. The stop itself is the+ /// existing graceful path (`stop_worker`: durable tombstone, routed+ /// shutdown, process-retirement wait, registry removal, roster+ /// passivation), so the passivated worker's row stays visible and+ /// its next prompt (or an attach by durable id) wakes a fresh worker+ /// over the session file.pub(crate) async fn handle_worker_idle_passivation(self: &Arc<Self>,command_id: &str,@@ -645,25 +648,21 @@ impl Supervisor {None,);};- // The parent-owned gate: only a child worker (rlmDepth > 0) may- // ask; a root worker's resident lease is client-owned policy.- let parent_owned = {+ // Rust clients create noSession roots unowned (`lifecycle: None`);+ // TS makes them client-owned, so its `hasOwnerClient` refuses them.+ // An in-memory session has no file to wake from.+ {let descriptor = resident.descriptor.lock().await;- descriptor- .create_command- .rest- .get("rlmDepth")- .and_then(serde_json::Value::as_u64)- .unwrap_or(0)- > 0- };- if !parent_owned {- return response_failure(- Some(command_id),- type_name,- "Idle passivation is a child-worker policy; the root worker stays resident",- None,- );+ if descriptor.owner_client_id.is_some()+ || descriptor.create_command.no_session == Some(true)+ {+ return response_failure(+ Some(command_id),+ type_name,+ "Idle passivation is refused for a client-owned or in-memory (noSession) worker",+ None,+ );+ }}// The supervisor-side settings re-read (the fence): the same// `idleEvictionMinutes` surface the worker read.diff --git a/crates/pa-daemon/src/worker/turn.rs b/crates/pa-daemon/src/worker/turn.rsindex 476e58eca0..b4badb6121 100644--- a/crates/pa-daemon/src/worker/turn.rs+++ b/crates/pa-daemon/src/worker/turn.rs@@ -183,7 +183,7 @@ impl TurnRunner {// The whole-worker idle passivation (TS's// `idleEvictionMinutes` tier, worker-driven): the same park// state the kernel release proved, plus the idle clock. The- // window arms only for parent-owned children under a live+ // window arms for any idle unattached session under a live// threshold; the select's notified arm is the wake path — a// queued delivery wins the race and the next park re-arms.match self.idle_passivation_window() {@@ -226,24 +226,25 @@ impl TurnRunner {}}- /// The idle-eviction window for a parent-owned child (TS's- /// `idleEvictionMinutes` consumer, worker-side): `Some(remaining)`- /// when the park state holds (parent-owned, unattached, not- /// compacting, not shutting down, no live background bash, no- /// queued input in the lanes — TS `isSessionActive`'s- /// pending-prompt-admissions arm) and the setting is a live- /// threshold; `None` otherwise (roots, attached children, `"off"`,- /// and any state the engine gates would reject stay parked without- /// a timer). The engine gate- /// (`SessionEngine::can_passivate_worker`) is re-checked at the- /// fire inside [`Self::maybe_request_idle_passivation`] — the+ /// The idle-eviction window for an unowned session (TS's+ /// `idleEvictionMinutes` consumer, worker-side; TS `canEvictWorker`+ /// reaches roots and children alike): `Some(remaining)` when the+ /// park state holds (unattached, not compacting, not shutting down,+ /// no live background bash, no queued input in the lanes — TS+ /// `isSessionActive`'s pending-prompt-admissions arm) and the+ /// setting is a live threshold; `None` otherwise (attached+ /// sessions, `"off"`, and any state the engine gates would reject+ /// stay parked without a timer). The client-owned and noSession+ /// refusals are supervisor-side (the descriptor's `ownerClientId`+ /// and `noSession`). The engine gate+ /// (`SessionEngine::can_passivate_worker`) is re-checked at the fire+ /// inside [`Self::maybe_request_idle_passivation`] — the/// fresh-snapshot fence — so this window only decides whether to/// arm.pub(super) fn idle_passivation_window(&self) -> Option<std::time::Duration> {- let (rlm_depth, attached, compacting, shutdown, queued, last_activity, cwd) = {+ let (attached, compacting, shutdown, queued, last_activity, cwd) = {let core = self.core.lock().unwrap();(- core.rlm_depth,core.attached_client_ids.is_empty(),core.compacting,core.shutdown_requested,@@ -269,7 +270,7 @@ impl TurnRunner {core.cwd.clone(),)};- if rlm_depth == 0 || !attached || compacting || shutdown || queued {+ if !attached || compacting || shutdown || queued {return None;}// A live background bash handle keeps the worker resident (the@@ -301,10 +302,9 @@ impl TurnRunner {/// next park re-arms, exactly like the kernel release's best-effort/// arm.pub(super) async fn maybe_request_idle_passivation(&self) {- let (rlm_depth, attached, compacting, shutdown, queued, last_activity, cwd) = {+ let (attached, compacting, shutdown, queued, last_activity, cwd) = {let core = self.core.lock().unwrap();(- core.rlm_depth,core.attached_client_ids.is_empty(),core.compacting,core.shutdown_requested,@@ -325,7 +325,7 @@ impl TurnRunner {// The fresh-snapshot fence: the wake that raced the timer must// find the worker resident, so any state change since the window// armed cancels the passivation.- if rlm_depth == 0 || !attached || compacting || shutdown || queued {+ if !attached || compacting || shutdown || queued {return;}if self.user_bash.is_running() {diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/park.rs b/crates/pa-daemon/src/worker/turn_stream_tests/park.rsindex 4a63979ac0..88cc4debee 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/park.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/park.rs@@ -303,7 +303,7 @@ fn passivation_settings(dir: &std::path::Path, value: &serde_json::Value) {}#[tokio::test]-async fn idle_passivation_window_arms_only_for_idle_parent_owned_children() {+async fn idle_passivation_window_arms_only_for_idle_unattached_sessions() {let dir = tempfile::TempDir::new().unwrap();let agent_dir = dir.path().join("agent");passivation_settings(&agent_dir, &serde_json::json!(1));@@ -312,18 +312,15 @@ async fn idle_passivation_window_arms_only_for_idle_parent_owned_children() {// The shared PassivationContext with a live settings dir.runner.passivation.agent_dir = agent_dir.clone();- // A root session (rlm_depth 0): no window.- assert!(runner.idle_passivation_window().is_none());-- // A parent-owned child under a live threshold: the window arms.+ // An idle root session under a live threshold: the window arms (TS+ // `canEvictWorker` reaches roots; the depth fence is gone).{let mut core = runner.core.lock().unwrap();- core.rlm_depth = 1;core.cwd = dir.path().to_string_lossy().to_string();core.last_activity_ms = crate::util::now_ms();}let window = runner.idle_passivation_window();- assert!(window.is_some(), "a parent-owned idle child must arm");+ assert!(window.is_some(), "an unattached idle root must arm");// A 1-minute threshold from now: the remaining window is under a// minute (the clock already ran during the test).assert!(diff --git a/crates/pa-daemon/tests/idle_passivation_e2e.rs b/crates/pa-daemon/tests/idle_passivation_e2e.rsindex 7b30c99ae6..7ec5a1b0d8 100644--- a/crates/pa-daemon/tests/idle_passivation_e2e.rs+++ b/crates/pa-daemon/tests/idle_passivation_e2e.rs@@ -154,6 +154,24 @@ fn worker_token(agent_dir: &Path, active_session_id: &str) -> Option<String> {None}+/// The worker's pid from its persisted descriptor (the process the+/// passivation must retire).+fn worker_pid(agent_dir: &Path, active_session_id: &str) -> Option<u64> {+ let instances = std::fs::read_dir(agent_dir.join("daemon-workers")).ok()?;+ for instance in instances.flatten() {+ let descriptor_path = instance.path().join(format!("{active_session_id}.json"));+ let Ok(content) = std::fs::read_to_string(&descriptor_path) else {+ continue;+ };+ if let Ok(descriptor) = serde_json::from_str::<Value>(&content) {+ if let Some(pid) = descriptor.get("pid").and_then(Value::as_u64) {+ return Some(pid);+ }+ }+ }+ None+}+fn write_faux_script(dir: &Path, name: &str, responses: &Value) -> PathBuf {let path = dir.join(format!("{name}.json"));std::fs::write(@@ -298,25 +316,8 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_prompt() {};let child_token =worker_token(&agent_dir, &child_active_session_id).expect("the child worker's token");- let child_pid = {- let instances = std::fs::read_dir(agent_dir.join("daemon-workers")).expect("workers");- let mut pid = None;- for instance in instances.flatten() {- let descriptor_path = instance- .path()- .join(format!("{child_active_session_id}.json"));- let Ok(content) = std::fs::read_to_string(&descriptor_path) else {- continue;- };- if let Ok(descriptor) = serde_json::from_str::<Value>(&content) {- if let Some(found) = descriptor.get("pid").and_then(Value::as_u64) {- pid = Some(found);- break;- }- }- }- pid.expect("the child worker's pid")- };+ let child_pid =+ worker_pid(&agent_dir, &child_active_session_id).expect("the child worker's pid");assert!(std::path::Path::new(&format!("/proc/{child_pid}")).exists());let child_alive = || std::path::Path::new(&format!("/proc/{child_pid}")).exists();@@ -474,3 +475,122 @@ async fn a_settled_child_passivates_stays_listable_and_revives_by_prompt() {"the revival prompt never landed in the child's session file ({child_file:?}, response: {revived})");}++/// An idle unowned ROOT passivates through the same worker-driven ask+/// (TS `canEvictWorker` reaches roots and children alike) and resumes+/// by its durable session id: the attach wakes a fresh worker over the+/// saved file and the snapshot carries the pre-passivation transcript.+#[tokio::test]+async fn an_idle_root_passivates_and_resumes_by_its_durable_id_with_its_transcript() {+ let Some(kernel_python) = kernel_python() else {+ eprintln!("kernel python unavailable; skipping the root passivation e2e");+ return;+ };+ let dir = tempfile::TempDir::new().expect("temp dir");+ let socket = dir.path().join("daemon.sock");+ let agent_dir = dir.path().join("agent");+ let sessions_dir = agent_dir.join("sessions");+ std::fs::create_dir_all(&sessions_dir).expect("sessions dir");+ std::fs::write(+ agent_dir.join("settings.json"),+ json!({ "idleEvictionMinutes": 1 }).to_string(),+ )+ .expect("write settings");+ let root_script = write_faux_script(dir.path(), "root", &json!([{ "text": "root turn done" }]));++ let _daemon = spawn_supervisor(&socket, &agent_dir, &kernel_python);+ wait_socket_ready(&socket);+ let (mut client, hello) = Client::connect(&socket);+ assert_eq!(hello["type"], "daemon_hello");++ client.send_command(+ "create-root",+ &json!({+ "type": "create",+ "name": "root",+ "config": {+ "cwd": dir.path().to_string_lossy(),+ "sessionDir": sessions_dir.to_string_lossy(),+ "script": root_script.to_string_lossy(),+ },+ }),+ );+ let created = client.read_response("create-root");+ assert_eq!(created["success"], true, "create root failed: {created}");+ let root_active_session_id = created["data"]["activeSessionId"]+ .as_str()+ .or_else(|| created["data"]["id"].as_str())+ .expect("root active session id")+ .to_string();+ let root_session_id = created["data"]["sessionId"]+ .as_str()+ .expect("root durable session id")+ .to_string();++ client.send_command(+ "first-turn",+ &json!({+ "type": "prompt_and_wait",+ "activeSessionId": root_active_session_id,+ "message": "first turn",+ }),+ );+ let first = client.read_response("first-turn");+ assert_eq!(first["success"], true, "the first turn failed: {first}");++ let root_token =+ worker_token(&agent_dir, &root_active_session_id).expect("the root worker's token");+ let root_pid = worker_pid(&agent_dir, &root_active_session_id).expect("the root worker's pid");+ assert!(std::path::Path::new(&format!("/proc/{root_pid}")).exists());++ // THE PASSIVATION ASK for a ROOT: the supervisor's handler accepts an+ // unowned worker regardless of depth (without the fix this answers+ // the child-worker-policy refusal).+ client.send_command(+ "passivate-root",+ &json!({+ "type": "worker_idle_passivation",+ "workerToken": root_token,+ "idleMinutes": 1,+ }),+ );+ let passivated = client.read_response("passivate-root");+ assert_eq!(+ passivated["success"], true,+ "the root's idle passivation must succeed: {passivated}"+ );++ // The root worker's process is gone (the whole-worker stop).+ let deadline = Instant::now() + Duration::from_secs(60);+ while std::path::Path::new(&format!("/proc/{root_pid}")).exists() {+ assert!(+ Instant::now() < deadline,+ "the root worker process survived the passivation"+ );+ tokio::time::sleep(Duration::from_millis(100)).await;+ }++ // THE RESUME: a fresh client attaches by the DURABLE session id (the+ // TUI reattach selector); the route's wake arm resolves the saved+ // session, launches a fresh worker over the file, and the snapshot+ // carries the pre-passivation transcript.+ let (mut fresh, _hello) = Client::connect(&socket);+ fresh.send_command(+ "re-attach",+ &json!({ "type": "attach", "activeSessionId": root_session_id }),+ );+ let attached = fresh.read_response("re-attach");+ assert_eq!(+ attached["success"], true,+ "the attach by the durable id must wake the passivated root: {attached}"+ );+ let messages = attached["data"]["snapshot"]["messages"].to_string();+ assert!(+ messages.contains("first turn"),+ "the snapshot must carry the first turn's user prompt: {messages}"+ );+ assert!(+ messages.contains("root turn done"),+ "the snapshot must carry the first turn's reply: {messages}"+ );+}