Skip to content

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

Rust

fix(pa-daemon): idle passivation fences in-flight routes across the stop (#3240)

Sebastian Müller7bbc0adf1d3d
diff --git a/.changes/fix-supervisor-eviction-fence.md b/.changes/fix-supervisor-eviction-fence.md
new file mode 100644
index 0000000000..43c0baab2b
--- /dev/null
+++ b/.changes/fix-supervisor-eviction-fence.md
@@ -0,0 +1 @@
+- Idle passivation now defers while a command to the session is still in flight (for example adding a heartbeat or cron job), so such a job no longer stays dormant until the session is resumed.
diff --git a/crates/pa-daemon/src/backpressure.rs b/crates/pa-daemon/src/backpressure.rs
index 67a6a6177e..c93223b0a4 100644
--- a/crates/pa-daemon/src/backpressure.rs
+++ b/crates/pa-daemon/src/backpressure.rs
@@ -358,4 +358,32 @@ mod tests {
"a full queue never refuses internal traffic"
);
}
+
+ /// The retire-then-release straddle of the idle passivation fence
+ /// (a client route whose readiness check preceded the retire): a
+ /// retired worker refuses the client route after admission, before
+ /// anything is enqueued behind the stop.
+ #[tokio::test]
+ async fn a_retired_worker_admits_no_client_request() {
+ let dir = tempfile::TempDir::new().expect("temp dir");
+ let supervisor = supervisor(dir.path());
+ let resident = resident("w-retired");
+ let (_cmd_tx, mut cmd_rx) = wedged_worker(&resident).await;
+ resident.note_retired();
+ let error = supervisor
+ .route_command_typed(
+ &resident,
+ "cron_add",
+ serde_json::json!({}),
+ 50,
+ RouteAdmission::ClientRequest,
+ )
+ .await
+ .expect_err("a retired worker refuses the client route");
+ assert_eq!(error.to_string(), crate::supervisor::WORKER_NOT_CONNECTED);
+ assert!(
+ cmd_rx.try_recv().is_err(),
+ "nothing was enqueued behind the retire"
+ );
+ }
}
diff --git a/crates/pa-daemon/src/supervisor/routing.rs b/crates/pa-daemon/src/supervisor/routing.rs
index 0c28d09086..3ebddc7856 100644
--- a/crates/pa-daemon/src/supervisor/routing.rs
+++ b/crates/pa-daemon/src/supervisor/routing.rs
@@ -111,6 +111,13 @@ impl Supervisor {
}
}
};
+ // A retired worker admits no client request (the
+ // retire-then-release order of the idle passivation fence): the
+ // check runs after admission, so a route that passed readiness
+ // before the retire cannot enqueue behind it.
+ if matches!(admission, RouteAdmission::ClientRequest) && resident.route_state().retired {
+ return Err(anyhow!(WORKER_NOT_CONNECTED));
+ }
let (reply_tx, reply_rx) = oneshot::channel();
let request_id = uuid::Uuid::new_v4().to_string();
resident
diff --git a/crates/pa-daemon/src/supervisor/tests.rs b/crates/pa-daemon/src/supervisor/tests.rs
index aec8de6887..8bb771591a 100644
--- a/crates/pa-daemon/src/supervisor/tests.rs
+++ b/crates/pa-daemon/src/supervisor/tests.rs
@@ -966,8 +966,9 @@ 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).
+ // sessioned root passes this gate; with a route in flight, its ask
+ // defers instead of stopping the worker underneath it (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();
@@ -1018,6 +1019,12 @@ async fn idle_passivation_refuses_client_owned_and_in_memory_workers() {
descriptor.create_command.no_session = Some(true);
descriptor
};
+ let idle = pa_types::daemon::DaemonWorkerDescriptor {
+ worker_id: "w-idle".to_string(),
+ authentication_token: "idle-token".to_string(),
+ owner_client_id: None,
+ ..descriptor.clone()
+ };
let resident = ResidentWorker::new("w-owned".to_string(), descriptor, dir.path().join("w.d"));
supervisor.registry.insert(resident).await;
let response = supervisor
@@ -1046,6 +1053,32 @@ async fn idle_passivation_refuses_client_owned_and_in_memory_workers() {
.contains("client-owned or in-memory (noSession) worker"),
"the in-memory worker's ask is refused: {response:?}"
);
+ // The eviction fence (TS `withEvictionFence`): a request in flight
+ // when the ask arrives defers the passivation — no stop, no
+ // tombstone — and the same ask stops the worker once the route
+ // drains.
+ let resident = ResidentWorker::new("w-idle".to_string(), idle, dir.path().join("w-idle.d"));
+ supervisor.registry.insert(resident.clone()).await;
+ let in_flight = Arc::clone(&resident.inflight).try_acquire_owned().unwrap();
+ supervisor
+ .handle_worker_idle_passivation("c3", "worker_idle_passivation", "idle-token", None)
+ .await;
+ assert!(
+ supervisor.registry.get("w-idle").await.is_some(),
+ "the deferred ask never stopped the worker"
+ );
+ assert!(
+ resident.descriptor.lock().await.stop_requested_at.is_none(),
+ "the deferred ask left no stop tombstone on the live worker"
+ );
+ drop(in_flight);
+ supervisor
+ .handle_worker_idle_passivation("c4", "worker_idle_passivation", "idle-token", None)
+ .await;
+ assert!(
+ supervisor.registry.get("w-idle").await.is_none(),
+ "the drained worker's ask stops it"
+ );
}
/// The roster wake's reuse arm (Macroscope's concurrent-wake finding,
diff --git a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
index 151e82c448..147c987cd2 100644
--- a/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
+++ b/crates/pa-daemon/src/supervisor/worker_lifecycle.rs
@@ -627,8 +627,9 @@ impl Supervisor {
/// 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
+ /// ask and the stop cancels the passivation. The stop runs under the
+ /// eviction fence (TS `withEvictionFence`) and 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
@@ -683,7 +684,19 @@ impl Supervisor {
return response_success(Some(command_id), type_name, None);
}
}
- match self.stop_worker(&resident).await {
+ // TS `withEvictionFence`: holding every in-flight route permit
+ // proves no routed request is still running on this worker (a
+ // drained `cron_add` or prompt would fail TS's fresh
+ // `canEvictWorker`), and refuses new client routes until the
+ // stop has retired the worker. A request in flight defers the
+ // passivation; the worker's next park re-asks.
+ let Ok(fence) = Arc::clone(&resident.inflight).try_acquire_many_owned(
+ u32::try_from(crate::backpressure::WORKER_INFLIGHT_CAPACITY)
+ .expect("in-flight capacity fits u32"),
+ ) else {
+ return response_success(Some(command_id), type_name, None);
+ };
+ match self.stop_worker_releasing(&resident, Some(fence)).await {
Ok(()) => {
self.log_line(&format!(
"session worker {} passivated idle (idleEvictionMinutes={threshold})",
@@ -703,6 +716,16 @@ impl Supervisor {
pub(crate) async fn stop_worker(
self: &Arc<Self>,
resident: &Arc<ResidentWorker>,
+ ) -> anyhow::Result<()> {
+ self.stop_worker_releasing(resident, None).await
+ }
+
+ /// The graceful stop; `fence` (the idle passivation's) is released
+ /// past the retire. Every other stop caller passes `None`.
+ async fn stop_worker_releasing(
+ self: &Arc<Self>,
+ resident: &Arc<ResidentWorker>,
+ fence: Option<tokio::sync::OwnedSemaphorePermit>,
) -> anyhow::Result<()> {
// The stop's durable intent persists BEFORE the worker is told (TS
// `stopWorkerUntracked(removeDescriptor)` ->
@@ -720,6 +743,12 @@ impl Supervisor {
// The stop is intentional: routes waiting out a replacement must
// fail fast instead of parking on this worker.
resident.note_retired();
+ // The fence releases past the retire (a tombstone-persist failure
+ // fails the stop before it, and the worker stays fully
+ // routable) and before the shutdown route, which needs a permit
+ // of its own. A client route that acquires a freed permit next
+ // sees the retire (the post-admission check in routing.rs).
+ drop(fence);
match self
.route_command_typed(
resident,