Skip to content

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

Rust

rlm: admit a spawned child only after its task prompt lands (#3708)

Sebastian Müllerdd384e3a2b3f
diff --git a/crates/pa-daemon/src/rlm_children/host.rs b/crates/pa-daemon/src/rlm_children/host.rs
index cbaef9a905..25f526984b 100644
--- a/crates/pa-daemon/src/rlm_children/host.rs
+++ b/crates/pa-daemon/src/rlm_children/host.rs
@@ -250,7 +250,6 @@ impl RlmSubagentHost for SupervisorChildSessions {
if watcher_record.lock().await.closed_by_parent {
return;
}
- watcher_record.lock().await.prompt_admitted = true;
if let Err(error) = watcher_this
.prompt_child(
&child_active_session_id,
@@ -286,15 +285,14 @@ impl RlmSubagentHost for SupervisorChildSessions {
.kill_child(&child_active_session_id, ChildCloseReason::Killed)
.await;
watcher_this
- .settle_failed(
- &watcher_record,
- format!("{retry_error:#}"),
- super::lifecycle::FailedArm::Prompt,
- )
+ .settle_failed(&watcher_record, format!("{retry_error:#}"))
.await;
return;
}
}
+ // The worker accepted the task: from here an idle read is a
+ // finished run, never the pre-prompt idle worker.
+ watcher_record.lock().await.prompt_admitted = true;
watcher_this.watch_child_settle(&watcher_record).await;
});
Ok(RlmSpawnHandle {
diff --git a/crates/pa-daemon/src/rlm_children/lifecycle.rs b/crates/pa-daemon/src/rlm_children/lifecycle.rs
index 662ba82933..7e4a953f0a 100644
--- a/crates/pa-daemon/src/rlm_children/lifecycle.rs
+++ b/crates/pa-daemon/src/rlm_children/lifecycle.rs
@@ -566,11 +566,7 @@ impl SupervisorChildSessionsInner {
// holds; capture them before the terminal notice.
self.emit_final_child_usage(record).await;
if self
- .settle_failed(
- record,
- "Child worker unreachable".to_string(),
- FailedArm::Unreachable,
- )
+ .settle_failed(record, "Child worker unreachable".to_string())
.await
{
return;
@@ -662,24 +658,16 @@ impl SupervisorChildSessionsInner {
/// settles `error` with its failure text and the parent receives the
/// `rlm_child_failure` row — whether or not the child replied — then
/// the settle funnel fires like TS's `finally` resume. Exactly-once:
- /// the claim is split by arm. The unreachable arm keeps
- /// `should_mark_unreachable_error` — an already-settled child keeps
- /// its verdict (#3104's passivation semantics: a verdict a reader's
- /// refresh lands inside the give-up keeps standing, and the claim
- /// reports the loss so the watcher runs that verdict's settle tail).
- /// The prompt arm bails only on a REAL terminal verdict:
- /// a task turn that provably never started cannot have genuinely
- /// completed, so a `done` visible inside the prompt-failure window is
- /// `refresh_record`'s admission-window misread of an alive-but-idle
- /// worker, not a settle verdict — the failure row must still land
- /// (and, since #3171, the run must still mark settled, or the
- /// quiescence barrier parks forever). Returns whether this call
- /// claimed the settle.
+ /// a child that already holds a verdict keeps it
+ /// (`should_mark_error`; #3104's passivation semantics: a verdict a
+ /// reader's refresh lands inside the unreachable give-up keeps
+ /// standing, and the claim reports the loss so the watcher runs that
+ /// verdict's settle tail). Returns whether this call claimed the
+ /// settle.
pub(super) async fn settle_failed(
&self,
record: &Arc<Mutex<ChildRecord>>,
error: String,
- arm: FailedArm,
) -> bool {
// The exit capture (the M4 seam): a child that dies without
// reporting still said something — the live worker's last
@@ -725,15 +713,7 @@ impl SupervisorChildSessionsInner {
};
let message = {
let mut record = record.lock().await;
- let keep_verdict = match arm {
- FailedArm::Unreachable => !should_mark_unreachable_error(&record),
- FailedArm::Prompt => {
- record.closed_by_parent
- || record.notice_delivered
- || matches!(record.settled_status, Some("error" | "cancelled"))
- }
- };
- if keep_verdict {
+ if !should_mark_error(&record) {
return false;
}
record.settled_status = Some("error");
@@ -810,24 +790,14 @@ impl SupervisorChildSessionsInner {
}
}
-/// Which failure arm is claiming the settle: the two arms bail on
-/// different evidence (see `settle_failed`).
-pub(super) enum FailedArm {
- /// The task-prompt admission failed and its retry failed.
- Prompt,
- /// The unreachable-poller's give-up (`WATCH_MAX_UNREACHABLE_POLLS`
- /// consecutive dead polls).
- Unreachable,
-}
-
-/// Whether a child may still settle as an error (the unreachable
-/// give-up's claim): a parent-closed child, a noticed child, or an
+/// Whether a child may still settle as an error (the failed task prompt's
+/// or the unreachable give-up's claim): a parent-closed child, a noticed child, or an
/// ALREADY-SETTLED child keeps its POSITIVE verdict — its worker leaving
/// afterward (the idle passivation's graceful stop, a crash after
/// settle, or a give-up) is residency churn, not a settle verdict
/// change. The settle state is durable and the passive roster row
/// stays the representation.
-pub(super) fn should_mark_unreachable_error(state: &ChildRecord) -> bool {
+pub(super) fn should_mark_error(state: &ChildRecord) -> bool {
!(state.closed_by_parent || state.notice_delivered || state.settled_status.is_some())
}
diff --git a/crates/pa-daemon/src/rlm_children/watch_tests.rs b/crates/pa-daemon/src/rlm_children/watch_tests.rs
index 188f5fdddc..f1275e8530 100644
--- a/crates/pa-daemon/src/rlm_children/watch_tests.rs
+++ b/crates/pa-daemon/src/rlm_children/watch_tests.rs
@@ -162,7 +162,17 @@ async fn spawn_fake_supervisor(
"sessionName": "f20-worker",
})),
),
- "prompt" => response_success(Some(&id), command_type, None),
+ "prompt" => {
+ if let Some(gate) = child_subagents
+ .prompt_gate
+ .as_ref()
+ .filter(|gate| gate.armed.swap(false, Ordering::SeqCst))
+ {
+ gate.copied.notify_one();
+ gate.release.notified().await;
+ }
+ response_success(Some(&id), command_type, None)
+ }
"wait_for_idle" => {
tokio::time::sleep(std::time::Duration::from_millis(idle_delay_ms))
.await;
@@ -297,6 +307,8 @@ struct FakeChildSubagents {
answer_reads: AtomicU32,
live_state: std::sync::Mutex<Option<Value>>,
peer_gate: Option<Arc<FakePeerGate>>,
+ /// Holds the task `prompt` in flight: the worker has not accepted it yet.
+ prompt_gate: Option<Arc<FakePeerGate>>,
}
#[derive(Default)]
@@ -730,6 +742,58 @@ async fn a_settled_child_without_a_reply_delivers_the_terminal_notice() {
assert!(extra.is_err(), "no second notice may arrive");
}
+/// A `collect` that lands while the task prompt is still in flight reads
+/// the child's pre-prompt idle worker: the child is still running, never a
+/// `done` settle with no answer (the factory settled its verifier before
+/// the verifier's turn ran).
+#[tokio::test]
+async fn a_collect_while_the_task_prompt_is_in_flight_does_not_settle_the_child() {
+ let (follow_up_tx, mut follow_up_rx) = mpsc::unbounded_channel();
+ let gate = Arc::new(FakePeerGate {
+ armed: AtomicBool::new(true),
+ ..FakePeerGate::default()
+ });
+ let (sessions, _kill_rx) = sessions_with_fake_child_subagents(
+ follow_up_tx,
+ 0,
+ FakeKill::Success,
+ FakeChild::Healthy,
+ Arc::new(FakeChildSubagents {
+ prompt_gate: Some(Arc::clone(&gate)),
+ ..FakeChildSubagents::default()
+ }),
+ )
+ .await;
+ let handle = spawn_child(&sessions).await;
+ sessions.notify_turn_done();
+ gate.copied.notified().await;
+
+ let in_flight = sessions
+ .collect(vec![handle.rlm_child_id.clone()], 0)
+ .await
+ .expect("collect while the prompt is in flight");
+ assert!(
+ !in_flight[0].settled,
+ "a child whose task prompt is not accepted yet must not settle: {:?}",
+ in_flight[0].status
+ );
+
+ gate.release.notify_one();
+ tokio::time::timeout(Duration::from_secs(10), follow_up_rx.recv())
+ .await
+ .expect("the run settles once the prompt lands")
+ .expect("follow_up channel open");
+ let settled = sessions
+ .collect(vec![handle.rlm_child_id.clone()], 0)
+ .await
+ .expect("collect after the settle");
+ assert_eq!(settled[0].status, "done");
+ assert_eq!(
+ settled[0].answer_text.as_deref(),
+ Some("the child final answer")
+ );
+}
+
/// The settle grace re-marks only a BUSY child as running: a worker that
/// leaves inside the grace (the idle passivation's stop, a crash) keeps
/// the settled verdict, and the settle tail (notice, funnel) still runs.
@@ -862,7 +926,7 @@ fn assert_failure_row(follow_up: &Value, child_id: &str, error: &str) {
#[tokio::test]
async fn a_child_whose_task_prompt_cannot_be_routed_delivers_the_failure_notice() {
let (follow_up_tx, mut follow_up_rx) = mpsc::unbounded_channel();
- let (sessions, _kill_rx) =
+ let (sessions, mut kill_rx) =
sessions_with_fake_supervisor(follow_up_tx, 0, FakeKill::Success, FakeChild::PromptFails)
.await;
let (hook_tx, mut hook_rx) = mpsc::unbounded_channel();
@@ -888,6 +952,12 @@ async fn a_child_whose_task_prompt_cannot_be_routed_delivers_the_failure_notice(
.await
.expect("the failed child releases the owed continuation")
.expect("hook channel open");
+ assert!(
+ !sessions.any_running().await,
+ "the failed run must mark settled: an unsettled run parks the quiescence barrier"
+ );
+ let kill = kill_rx.try_recv().expect("the unadmitted child is killed");
+ assert_eq!(kill["activeSessionId"], "child-live");
// Exactly one failure row lands: the claim admits one writer.
let extra = tokio::time::timeout(Duration::from_millis(300), follow_up_rx.recv()).await;
assert!(extra.is_err(), "no second notice may arrive");
@@ -973,70 +1043,6 @@ async fn a_verdict_landing_inside_the_unreachable_give_up_still_runs_the_settle_
);
}
-/// The review's C1 interleaving: a `collect` that lands inside the
-/// prompt-failure window (after the detached task flips
-/// `prompt_admitted`, before the retry verdict) reads the alive-but-idle
-/// worker as `done` — `refresh_record`'s admission-window misread, not a
-/// settle verdict. The prompt arm's failure claim must ignore it: the
-/// failure row still lands, the roster reports `error`, the hook fires,
-/// and the run marks settled (post-#3171 an unsettled failed run parks
-/// `waitForRlmQuiescence` forever).
-#[tokio::test]
-async fn a_collect_inside_the_prompt_failure_window_does_not_swallow_the_failure_row() {
- let (follow_up_tx, mut follow_up_rx) = mpsc::unbounded_channel();
- let (sessions, _kill_rx) =
- sessions_with_fake_supervisor(follow_up_tx, 0, FakeKill::Success, FakeChild::PromptFails)
- .await;
- let (hook_tx, mut hook_rx) = mpsc::unbounded_channel();
- sessions.set_settle_hook(Arc::new(move || {
- let _ = hook_tx.send(());
- }));
- let handle = spawn_child(&sessions).await;
- // The window's entry condition, set deterministically: the detached
- // prompt task flips `prompt_admitted` BEFORE its first
- // `prompt_child` (host.rs), and the collect below races that task in
- // production. With the flag set and the worker alive-but-idle, the
- // real collect path scores the misread.
- sessions.inner.children.lock().await[0]
- .lock()
- .await
- .prompt_admitted = true;
- let misread = sessions
- .collect(vec![handle.rlm_child_id.clone()], 0)
- .await
- .expect("collect inside the window");
- assert_eq!(
- misread[0].status, "done",
- "the premise: the collect misreads the pre-prompt idle worker as done"
- );
-
- // The task prompt now runs and fails (prompt + retry) inside the
- // window the collect already scored.
- sessions.notify_turn_done();
-
- let follow_up = tokio::time::timeout(Duration::from_secs(10), follow_up_rx.recv())
- .await
- .expect("the failure row must land despite the collect's misread")
- .expect("follow_up channel open");
- assert_failure_row(
- &follow_up,
- &handle.rlm_child_id,
- "prompt RLM child session child-live: refused by the fake supervisor",
- );
- let entries = sessions.list_subagents().await.expect("child roster");
- assert_eq!(entries[0].status, "error");
- tokio::time::timeout(Duration::from_secs(10), hook_rx.recv())
- .await
- .expect("the settle funnel fires despite the misread")
- .expect("hook channel open");
- assert!(
- !sessions.any_running().await,
- "the failed run must mark settled: an unsettled run parks the quiescence barrier"
- );
- let extra = tokio::time::timeout(Duration::from_millis(300), follow_up_rx.recv()).await;
- assert!(extra.is_err(), "no second notice may arrive");
-}
-
/// A child that already replied still delivers the failure row when its
/// task prompt fails: TS sends the catch-arm row regardless of reply
/// count (`agent-session.ts:13026-13045`).
@@ -1628,21 +1634,21 @@ fn an_already_settled_child_never_re_scores_as_an_unreachable_error() {
rename_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
};
// A running child that goes unreachable is the error class.
- assert!(super::lifecycle::should_mark_unreachable_error(&base()));
+ assert!(super::lifecycle::should_mark_error(&base()));
// A settled child keeps its positive verdict.
let mut settled = base();
settled.settled_status = Some("done");
assert!(
- !super::lifecycle::should_mark_unreachable_error(&settled),
+ !super::lifecycle::should_mark_error(&settled),
"an idle-passivated (or post-settle crashed) child keeps its settled verdict"
);
// A parent-closed child and a noticed child never re-score.
let mut closed = base();
closed.closed_by_parent = true;
- assert!(!super::lifecycle::should_mark_unreachable_error(&closed));
+ assert!(!super::lifecycle::should_mark_error(&closed));
let mut noticed = base();
noticed.notice_delivered = true;
- assert!(!super::lifecycle::should_mark_unreachable_error(&noticed));
+ assert!(!super::lifecycle::should_mark_error(&noticed));
}
/// The unreachable give-up's exit capture is a wasted round trip when a
@@ -1709,11 +1715,7 @@ async fn the_unreachable_give_up_skips_the_exit_capture_when_a_capture_stands()
}));
let claimed = sessions
.inner
- .settle_failed(
- &record,
- "Child worker unreachable".to_string(),
- super::lifecycle::FailedArm::Unreachable,
- )
+ .settle_failed(&record, "Child worker unreachable".to_string())
.await;
assert!(claimed, "the give-up claims the settle");
assert_eq!(