A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
send one roster update at a time and read summary inputs outside the worker core lock (#3385)
Sebastian Müller4d669383f1fd
diff --git a/.changes/roster-push-one-in-flight.md b/.changes/roster-push-one-in-flight.mdnew file mode 100644index 0000000000..a3003b972e--- /dev/null+++ b/.changes/roster-push-one-in-flight.md@@ -0,0 +1 @@+- With many agents running, session workers send at most one roster update at a time and no longer look up model details while holding the session lock, which cuts background CPU during subagent fan-outs and keeps state queries responsive.diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex 31565bb287..8c6f774cbe 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -506,6 +506,11 @@ impl SessionEngine for AgentSessionEngine {.expect("effective thinking lock") = None;}+ fn model_identity(&self) -> (Option<String>, Option<String>) {+ let selection = self.current_selection();+ (selection.provider, selection.model)+ }+fn model_metadata(&self) -> Option<Value> {let model = self.resolve_model().ok()?;Some(json!({diff --git a/crates/pa-daemon/src/agent_roster.rs b/crates/pa-daemon/src/agent_roster.rsindex 7a5ead8394..79e2ac4f2f 100644--- a/crates/pa-daemon/src/agent_roster.rs+++ b/crates/pa-daemon/src/agent_roster.rs@@ -35,10 +35,11 @@ pub(crate) struct AgentRoster {bucket_applied_ticket: u64,/// The stale-delta gate of one worker: a single bounded slot naming/// the worker's CURRENT process generation (`instance`) and the- /// newest sequence applied from it. The Rust supervisor link dials- /// one socket per request, so deltas and pulls arrive unordered and- /// the gates drop a delayed older snapshot instead of letting it- /// overwrite a newer one. The slot is bounded (one entry per+ /// newest sequence applied from it. A worker's push consumer+ /// serializes its deltas, but a delta still races an authoritative+ /// pull (the link dials one socket per request), so the gates drop a+ /// delayed older snapshot instead of letting it overwrite a newer+ /// one. The slot is bounded (one entry per/// worker, dropped on stop): a replacement registers a new instance/// and restarts its counter, and [`AgentRoster::note_worker_generation`]/// flips the slot to the replacement — every frame or pull of the@@ -111,6 +112,8 @@ impl AgentRoster {/// The gate for one authoritative pull (registration, adoption, create, refresh):/// applies when its counter is at or above the applied watermark, dropped below it.+ /// The worker captures the counter and state under one core lock: at equal+ /// counters the pull follows the push snapshot and has the newer content./// The caller must run this gate, the summary write, and the watermark raise in ONE/// roster-lock critical section. A summary without the counter stamp always applies;/// a STAMPED counter — zero included — orders against the slot like any other pull.diff --git a/crates/pa-daemon/src/engine.rs b/crates/pa-daemon/src/engine.rsindex 8189d33f2c..a8b7a9f7c9 100644--- a/crates/pa-daemon/src/engine.rs+++ b/crates/pa-daemon/src/engine.rs@@ -295,6 +295,13 @@ pub trait SessionEngine: Send + Sync {Box::pin(async { None })}+ /// The cheap model-selection key used to validate metadata resolved outside+ /// the worker core lock. Implementations that switch models return the+ /// provider and model id from the same selection the resolver reads.+ fn model_identity(&self) -> (Option<String>, Option<String>) {+ (None, None)+ }+/// The engine's resolved model as connection-state wire data/// (`{ id, provider, reasoning }`), for the splash and tray labels.fn model_metadata(&self) -> Option<Value> {diff --git a/crates/pa-daemon/src/roster_activity.rs b/crates/pa-daemon/src/roster_activity.rsindex 20540d53e4..42570cef57 100644--- a/crates/pa-daemon/src/roster_activity.rs+++ b/crates/pa-daemon/src/roster_activity.rs@@ -127,7 +127,7 @@ impl RosterPushQueue {consumer.pending.store(false, std::sync::atomic::Ordering::SeqCst);- crate::worker::push_roster_delta(&context);+ crate::worker::push_roster_delta(&context).await;}});Self { inner: Some(state) }@@ -188,6 +188,8 @@ mod tests {// non-unix targets.#[cfg(unix)]use crate::supervisor_link::SupervisorLink;+ #[cfg(unix)]+ use crate::worker::SessionCore;use serde_json::json;#[cfg(unix)]use serde_json::Value;@@ -195,6 +197,8 @@ mod tests {use std::sync::Mutex;#[cfg(unix)]use std::time::Duration;+ #[cfg(unix)]+ use tokio::io::AsyncWriteExt;fn session_event_frame(event: &serde_json::Value) -> OutboundFrame {let payload = json!({@@ -341,7 +345,6 @@ mod tests {worker_token: "token".to_string(),worker_instance_id: "instance".to_string(),roster_delta_sequence: Arc::new(std::sync::atomic::AtomicU64::new(0)),- roster_push_order: Arc::new(Mutex::new(())),});for _ in 0..50 {queue.push();@@ -364,4 +367,97 @@ mod tests {);server.abort();}++ /// One in-flight request at most: the consumer awaits each push, so a+ /// wedged supervisor holds one connection, and the requests that land+ /// meanwhile collapse into the pending flag — one follow-up flush once+ /// the first request is answered.+ #[cfg(unix)]+ #[tokio::test]+ async fn a_wedged_supervisor_holds_one_in_flight_roster_push() {+ type StubArrival = (Value, tokio::net::unix::OwnedWriteHalf);+ let dir = tempfile::TempDir::new().unwrap();+ let socket = dir.path().join("sup.sock");+ let listener = tokio::net::UnixListener::bind(&socket).unwrap();+ // Every request line reaches the test with its writer half: the+ // supervisor stays wedged on the request until the test answers it.+ let (requests_tx, mut requests_rx) = tokio::sync::mpsc::unbounded_channel::<StubArrival>();+ let server = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ break;+ };+ let requests_tx = requests_tx.clone();+ tokio::spawn(async move {+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};+ let (reader, mut writer) = stream.into_split();+ writer+ .write_all(b"{\"type\":\"daemon_hello\"}\n")+ .await+ .unwrap();+ let mut line = String::new();+ if BufReader::new(reader)+ .read_line(&mut line)+ .await+ .unwrap_or(0)+ == 0+ {+ return;+ }+ let Ok(request) = serde_json::from_str::<Value>(line.trim()) else {+ return;+ };+ requests_tx.send((request, writer)).unwrap();+ });+ }+ });+ let queue = RosterPushQueue::spawn(crate::worker::RosterPushContext {+ core: Arc::new(Mutex::new(SessionCore::test_core(None, "/tmp".to_string()))),+ engine: Arc::new(crate::engine::ScriptedEngine::default()),+ user_bash: Arc::new(crate::user_bash::UserBash::new()),+ roster_link: Arc::new(SupervisorLink::new(socket)),+ worker_token: "token".to_string(),+ worker_instance_id: "instance".to_string(),+ roster_delta_sequence: Arc::new(std::sync::atomic::AtomicU64::new(0)),+ });+ for _ in 0..5 {+ queue.push();+ }+ let (first, mut first_writer) = requests_rx.recv().await.expect("first flush");+ assert_eq!(first["command"]["sequence"], json!(1));+ // The supervisor holds the first request open: the pushes that land+ // now must not open a second connection.+ for _ in 0..5 {+ queue.push();+ }+ assert!(+ tokio::time::timeout(Duration::from_millis(200), requests_rx.recv())+ .await+ .is_err(),+ "a second roster request was in flight while the supervisor held the first open",+ );+ // Answering the first request releases the burst as exactly one+ // follow-up flush.+ let response = serde_json::to_string(&crate::protocol::response_line(+ &crate::protocol::response_success(first["id"].as_str(), "worker_roster_delta", None),+ ))+ .unwrap();+ first_writer+ .write_all(format!("{response}\n").as_bytes())+ .await+ .unwrap();+ let follow_up = requests_rx.recv().await.expect("follow-up flush");+ assert_eq!(+ follow_up.0["command"]["sequence"],+ json!(2),+ "the burst behind the wedged request must collapse into one follow-up"+ );+ assert!(+ tokio::time::timeout(Duration::from_millis(200), requests_rx.recv())+ .await+ .is_err(),+ "the collapsed burst flushed more than one follow-up",+ );+ server.abort();+ }}diff --git a/crates/pa-daemon/src/scheduled_jobs/arms.rs b/crates/pa-daemon/src/scheduled_jobs/arms.rsindex 3b049af97b..381385a0cc 100644--- a/crates/pa-daemon/src/scheduled_jobs/arms.rs+++ b/crates/pa-daemon/src/scheduled_jobs/arms.rs@@ -54,12 +54,9 @@ impl Worker {return response;}let summary = {- let core = self- .core- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);+ let (core, inputs) = self.summary_inputs();self.bind_store_artifact(&core);- self.summary_locked(&core)+ self.summary_locked(&core, inputs)};let heartbeats: Vec<Value> = self.scheduleddiff --git a/crates/pa-daemon/src/state_getters.rs b/crates/pa-daemon/src/state_getters.rsindex c5f7d96d22..fd85938251 100644--- a/crates/pa-daemon/src/state_getters.rs+++ b/crates/pa-daemon/src/state_getters.rs@@ -17,8 +17,8 @@ impl Worker {if let Err(response) = self.require_created("get_connection_state") {return response;}- let core = self.core.lock().unwrap();- let state = self.connection_state_locked(&core);+ let (core, inputs) = self.connection_state_inputs();+ let state = Self::connection_state_locked(&core, inputs);drop(core);let mut value = serde_json::to_value(&state).unwrap_or(Value::Null);value["heartbeat"] = Value::Null;diff --git a/crates/pa-daemon/src/supervisor_roster/delta_push.rs b/crates/pa-daemon/src/supervisor_roster/delta_push.rsindex 5de6fdb481..60041bd30a 100644--- a/crates/pa-daemon/src/supervisor_roster/delta_push.rs+++ b/crates/pa-daemon/src/supervisor_roster/delta_push.rs@@ -84,11 +84,11 @@ fn flip_summary(dir: &Path, busy: bool) -> Value {})}-/// The stale-delta gate at the handler: the worker's per-request-/// supervisor links deliver deltas unordered, so a delayed older-/// snapshot (a lower sequence) must not overwrite a newer one — the-/// TS worker never has this race (its roster deltas ride one ordered-/// supervisor client socket).+/// The stale-delta gate at the handler: a push can race a newer+/// authoritative pull, so a delayed older snapshot (a lower+/// sequence) must not overwrite a newer one — the TS worker never+/// has this race (its roster deltas ride one ordered supervisor+/// client socket).#[tokio::test]async fn worker_roster_delta_drops_stale_sequences() {fn summary(level: &str) -> Value {@@ -165,7 +165,7 @@ async fn worker_roster_delta_drops_stale_sequences() {.map(|entry| entry.summary["thinkingLevel"].clone()).expect("the roster entry")};- // A fresh worker's create/registration pull stamps the ZERO // A fresh worker's create/registration pull stamps the ZERO+ // A fresh worker's create/registration pull stamps the ZERO// counter (the worker has pushed nothing yet): it starts the// slot and applies — the create path's first authoritative// write.@@ -261,6 +261,31 @@ async fn worker_roster_delta_drops_stale_sequences() {"a delayed pre-push pull never overwrites a newer delta");assert_eq!(entry_level(), serde_json::json!("off"));+ // The push snapshot advances the worker counter to 5. A pull at+ // that same counter is captured afterward under the same core lock,+ // so its content is newer even if the push arrived first.+ let applied = delta(&supervisor, "seq-token", "high", Some(5), "i1").await;+ assert!(applied.success, "sequence 5 applies: {applied:?}");+ assert_eq!(entry_level(), serde_json::json!("high"));+ let mut equal_pull = summary("medium");+ equal_pull["rosterDeltaSequence"] = serde_json::json!(5);+ equal_pull["workerInstanceId"] = serde_json::json!("i1");+ assert!(+ supervisor+ .write_roster_summary_for_resident(&resident, &equal_pull)+ .await+ .is_some(),+ "a post-push equal-counter pull has the newer content"+ );+ assert_eq!(entry_level(), serde_json::json!("medium"));+ // The in-flight push at the same counter is now stale, whichever+ // arrival order the supervisor saw. It cannot overwrite that pull.+ let stale_equal = delta(&supervisor, "seq-token", "low", Some(5), "i1").await;+ assert!(+ stale_equal.success,+ "stale equal delta answers: {stale_equal:?}"+ );+ assert_eq!(entry_level(), serde_json::json!("medium"));// A replacement process registers (the registration notes the// new generation) and its counter-restarted sequences apply —// never compared against the predecessor's watermark.diff --git a/crates/pa-daemon/src/worker.rs b/crates/pa-daemon/src/worker.rsindex 2d5ff90246..256606d71c 100644--- a/crates/pa-daemon/src/worker.rs+++ b/crates/pa-daemon/src/worker.rs@@ -36,11 +36,11 @@ mod create;mod turn;use create::{active_session_id_of, worker_server_capabilities};-// session_summary serves the in-crate test modules only, so allow the unused import.+// session_summary/SummaryInputs serve the in-crate test modules only, so allow the unused import.#[allow(unused_imports)]pub(crate) use summary::{compact_action_label, emit_worker_event_with, persist_custom_row, push_roster_delta,- session_snapshot, session_summary, RosterPushContext,+ session_snapshot, session_summary, RosterPushContext, SummaryInputs,};use turn::TurnRunner;@@ -127,8 +127,9 @@ pub struct Worker {/// The concrete agent engine behind `engine` for the create command's/// eager session build (the kernel prewarm).pub(crate) agent_engine: Option<std::sync::Arc<crate::agent_engine::AgentSessionEngine>>,- /// The monotonic roster-delta counter shared with the roster push- /// queue: per-request links deliver pushes unordered.+ /// The monotonic roster-delta counter the roster pushes stamp and the+ /// authoritative pulls embed: a push can race a fresher pull, so the+ /// supervisor's gate drops the stale snapshot.roster_delta_sequence: std::sync::Arc<std::sync::atomic::AtomicU64>,pub(crate) work_notify: Arc<Notify>,pub(crate) idle_notify: Arc<Notify>,@@ -347,7 +348,6 @@ impl Worker {));let worker_token = std::env::var(WORKER_TOKEN_ENV).unwrap_or_default();let roster_delta_sequence = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));- let roster_push_order = std::sync::Arc::new(std::sync::Mutex::new(()));let input_pauses = crate::session_input_pause::InputPauseTable::new();// The shared pane-reporter slot: the worker binds it at create and// the turn runner reads it at every boundary (a slot, not a@@ -638,7 +638,6 @@ impl Worker {worker_token: worker_token.clone(),worker_instance_id: config.worker_instance_id.clone(),roster_delta_sequence: std::sync::Arc::clone(&roster_delta_sequence),- roster_push_order: std::sync::Arc::clone(&roster_push_order),});crate::roster_activity::spawn_roster_activity_watch(&events, roster_pushes.clone());if let Some(children) = agent_enginediff --git a/crates/pa-daemon/src/worker/commands.rs b/crates/pa-daemon/src/worker/commands.rsindex e30ce75dbf..ac794c0193 100644--- a/crates/pa-daemon/src/worker/commands.rs+++ b/crates/pa-daemon/src/worker/commands.rs@@ -404,8 +404,8 @@ impl Worker {if let Err(response) = self.require_created("get_state") {return response;}- let core = self.core.lock().unwrap();- let summary = self.summary_locked(&core);+ let (core, inputs) = self.summary_inputs();+ let summary = self.summary_locked(&core, inputs);response_success(None,"get_state",@@ -683,7 +683,7 @@ impl Worker {if name.trim().is_empty() {return response_failure(None, command, "Session name cannot be empty", None);}- let mut core = self.core.lock().unwrap();+ let (mut core, inputs) = self.summary_inputs();let previous = core.store.as_ref()@@ -693,7 +693,7 @@ impl Worker {return response_failure(None, command, &error.to_string(), None);}}- let summary = self.summary_locked(&core);+ let summary = self.summary_locked(&core, inputs);// TS #2529 `applyStateSessionName`: a rename that changed an// existing name leaves the renamed session a displayed transcript// notice (" by parent" when the rename arrived from the parentdiff --git a/crates/pa-daemon/src/worker/connection.rs b/crates/pa-daemon/src/worker/connection.rsindex 93555e2caa..72ff9b66f2 100644--- a/crates/pa-daemon/src/worker/connection.rs+++ b/crates/pa-daemon/src/worker/connection.rs@@ -801,7 +801,7 @@ impl Worker {.filter(|value| !value.is_null()).and_then(|value| serde_json::from_value::<DaemonResumeCursor>(value).ok());- let mut core = self.core.lock().unwrap();+ let (mut core, summary_inputs, connection_inputs) = self.attach_inputs();// The connection-scoped registry (the fresh bots' release// findings): the attach's retention is keyed by the connection// token so the release on ANY return path (the guard's Drop)@@ -824,7 +824,7 @@ impl Worker {if retained && !core.attached_client_ids.iter().any(|id| id == &client_id) {core.attached_client_ids.push(client_id.clone());}- let summary = self.summary_locked(&core);+ let summary = self.summary_locked(&core, summary_inputs);let mut messages: Vec<Value> = core.store.as_ref()@@ -840,7 +840,7 @@ impl Worker {if crate::snapshot_stream::wants_image_elision(&client_capabilities) {crate::snapshot_stream::elide_snapshot_image_payloads(&mut messages);}- let state = self.connection_state_locked(&core);+ let state = Self::connection_state_locked(&core, connection_inputs);let last_event_sequence = core.last_event_sequence;let generation = core.generation.clone();let active_session_id = core.active_session_id.clone();diff --git a/crates/pa-daemon/src/worker/create.rs b/crates/pa-daemon/src/worker/create.rsindex 12cc5ed96a..53ed743edd 100644--- a/crates/pa-daemon/src/worker/create.rs+++ b/crates/pa-daemon/src/worker/create.rs@@ -18,8 +18,8 @@ impl Worker {// answers with the created summary instead of racing a second init.let _create_gate = self.create_gate.lock().await;let existing_summary = {- let core = self.core.lock().unwrap();- core.created.then(|| self.summary_locked(&core))+ let (core, inputs) = self.summary_inputs();+ core.created.then(|| self.summary_locked(&core, inputs))};if let Some(summary) = existing_summary {// Idempotent re-create after a supervisor restart or respawn.@@ -480,7 +480,7 @@ impl Worker {// The core lock stays inside this block: everything after it may await,// and a std MutexGuard must never ride an await point.let (summary, rlm_depth) = {- let mut core = self.core.lock().unwrap();+ let (mut core, inputs) = self.summary_inputs();core.cwd = cwd;core.steering = steering;core.follow_up = follow_up;@@ -534,7 +534,7 @@ impl Worker {core.parent_active_session_id = parent_active_session_id;core.parent_session_id = parent_session_id;core.child_script.clone_from(&child_script);- (self.summary_locked(&core), rlm_depth)+ (self.summary_locked(&core, inputs), rlm_depth)};// The engine's agent-level queues drain per the same modes the// worker lane delivers by.diff --git a/crates/pa-daemon/src/worker/input.rs b/crates/pa-daemon/src/worker/input.rsindex 5cc20dc44a..3575a9fb26 100644--- a/crates/pa-daemon/src/worker/input.rs+++ b/crates/pa-daemon/src/worker/input.rs@@ -316,7 +316,7 @@ impl Worker {Lane::Steering};let (id, queued, snapshot, target) = {- let mut core = self.core.lock().unwrap();+ let (mut core, inputs) = self.summary_inputs();let pending = core.steering.len() + core.follow_up.len();if let Err(error) =pa_core::session_engine::agent_messaging::assert_agent_message_queue_capacity(@@ -329,7 +329,7 @@ impl Worker {}let id = pa_core::session_engine::agent_messaging::create_agent_session_message_id();let queued = core.busy;- let summary = self.summary_locked(&core);+ let summary = self.summary_locked(&core, inputs);// The receiving session's endpoint: the receipt's `target`// and the delivered row's `details.target` share the one// shape.diff --git a/crates/pa-daemon/src/worker/lifecycle.rs b/crates/pa-daemon/src/worker/lifecycle.rsindex 2994f48c4f..b88f4eb868 100644--- a/crates/pa-daemon/src/worker/lifecycle.rs+++ b/crates/pa-daemon/src/worker/lifecycle.rs@@ -254,10 +254,7 @@ impl Worker {/// runtime call.pub(crate) async fn refresh_replaced_session_state(&self) {let (rlm_depth, summary, child_script) = {- let mut core = self- .core- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);+ let (mut core, inputs) = self.summary_inputs();// The moved-to file's persisted depth wins (the replacement// carries no create-config depth).let rlm_depth = core@@ -267,7 +264,7 @@ impl Worker {.unwrap_or(0);core.rlm_depth = rlm_depth;let child_script = core.child_script.clone();- (rlm_depth, self.summary_locked(&core), child_script)+ (rlm_depth, self.summary_locked(&core, inputs), child_script)};// No thinking flag rides the rebind (the create command's level is// already resolved on the engine), and the TS replacement runtimediff --git a/crates/pa-daemon/src/worker/summary.rs b/crates/pa-daemon/src/worker/summary.rsindex 59ae5cfb8b..84548a160b 100644--- a/crates/pa-daemon/src/worker/summary.rs+++ b/crates/pa-daemon/src/worker/summary.rs@@ -11,21 +11,53 @@ use super::{use crate::types::SessionSummary;impl Worker {- pub(crate) fn summary_locked(&self, core: &SessionCore) -> SessionSummary {+ pub(crate) fn summary_inputs(&self) -> (std::sync::MutexGuard<'_, SessionCore>, SummaryInputs) {+ SummaryInputs::lock(&self.core, self.engine.as_ref(), &self.user_bash)+ }++ pub(crate) fn connection_state_inputs(+ &self,+ ) -> (+ std::sync::MutexGuard<'_, SessionCore>,+ ConnectionStateInputs,+ ) {+ ConnectionStateInputs::lock(&self.core, self.engine.as_ref(), &self.user_bash)+ }++ pub(crate) fn attach_inputs(+ &self,+ ) -> (+ std::sync::MutexGuard<'_, SessionCore>,+ SummaryInputs,+ ConnectionStateInputs,+ ) {+ loop {+ let details = ModelDetails::read(self.engine.as_ref(), ModelDetailScope::Connection);+ let core = self.core.lock().unwrap();+ if self.engine.model_identity() == details.identity {+ let identity = details.identity.clone();+ let summary = SummaryInputs::capture(+ self.engine.as_ref(),+ &self.user_bash,+ details.model.clone(),+ );+ let connection =+ ConnectionStateInputs::capture(self.engine.as_ref(), &self.user_bash, details);+ if self.engine.model_identity() == identity {+ return (core, summary, connection);+ }+ }+ }+ }++ pub(crate) fn summary_locked(+ &self,+ core: &SessionCore,+ inputs: SummaryInputs,+ ) -> SessionSummary {// The one summary composer: the roster feed, `get_state`, and list rows// all serve it, so the live flags never drift between surfaces.- let mut summary = session_summary(- core,- &self- .engine- .effective_thinking_level()- .unwrap_or_else(|| "default".to_string()),- self.engine.model_metadata(),- self.engine.model_fallback_message(),- self.user_bash.is_running(),- self.engine.is_quota_parked(),- self.engine.has_running_subagents(),- );+ let mut summary = session_summary(core, inputs);// The roster-delta counter at snapshot time: the pull gate orders the// summary against its watermark, so a delta still in flight when the pull// answered is dropped instead of overwriting the pull's fresher state.@@ -49,20 +81,19 @@ impl Worker {self.roster_pushes.push();}- pub(crate) fn connection_state_locked(&self, core: &SessionCore) -> AgentConnectionState {+ pub(crate) fn connection_state_locked(+ core: &SessionCore,+ inputs: ConnectionStateInputs,+ ) -> AgentConnectionState {let store = core.store.as_ref();- let model = self.engine.model_metadata();AgentConnectionState {is_streaming: core.busy,is_compacting: core.compacting,active_session_id: Some(core.active_session_id.clone()),cwd: core.cwd.clone(),- model,- thinking_level: self- .engine- .effective_thinking_level()- .unwrap_or_else(|| "default".to_string()),+ model: inputs.model,+ thinking_level: inputs.thinking_level,// The ACTIVE tier: the preference clamped to the model's tier support.service_tier: crate::setting_switches::service_tier_wire_name(core.active_service_tier@@ -72,11 +103,8 @@ impl Worker {// The resolved model's supported levels (TS `getSupportedThinkingLevels`):// a non-reasoning model reports ["off"], which the client treats as no// thinking surface.- available_thinking_levels: self- .engine- .supported_thinking_levels()- .unwrap_or_else(|| vec!["off".to_string()]),- is_bash_running: self.user_bash.is_running(),+ available_thinking_levels: inputs.available_thinking_levels,+ is_bash_running: inputs.is_bash_running,retry_attempt: 0,steering_mode: core.steering_mode.clone(),follow_up_mode: core.follow_up_mode.clone(),@@ -93,7 +121,7 @@ impl Worker {message_count: store.map_or(0, crate::session_store::SessionFile::message_count) as u32,session_actions: session_snapshot(core),compaction_count: store.map_or(0, |store| store.compaction_count() as u32),- goal: self.engine.goal_state_value(),+ goal: inputs.goal,scoped_models: core.scoped_models.clone(),active_tool_names: Vec::new(),// TS `createAgentConnectionState` carries `contextUsage:@@ -106,7 +134,7 @@ impl Worker {// attach already holds: `None` without a model context// window, exactly like the stats response.context_usage: store.and_then(|store| {- crate::session_stats::store_context_usage(store, self.engine.model_context_window())+ crate::session_stats::store_context_usage(store, inputs.model_context_window)}),}}@@ -277,10 +305,12 @@ pub(crate) fn emit_worker_event_with(events.send(OutboundFrame::session_event(payload));}-/// The worker's roster-delta push: the fresh summary rides the supervisor link,-/// fire-and-forget (the refresh backstops it). The link dials an independent-/// socket per request — pushes arrive unordered — so every delta carries the-/// worker's monotonic counter; the stale-delta gate drops the delayed snapshots.+/// The worker's roster-delta push: the fresh summary rides the supervisor+/// link, awaited by the single roster consumer, so at most one push request+/// is in flight at a time. Every delta still carries the worker's monotonic+/// counter: an authoritative pull stamps the same counter, and the+/// stale-delta gate drops a push that raced a fresher pull (the refresh+/// backstops both).pub(crate) struct RosterPushContext {pub(crate) core: Arc<Mutex<SessionCore>>,pub(crate) engine: std::sync::Arc<dyn SessionEngine>,@@ -289,73 +319,189 @@ pub(crate) struct RosterPushContext {pub(crate) worker_token: String,pub(crate) worker_instance_id: String,pub(crate) roster_delta_sequence: std::sync::Arc<std::sync::atomic::AtomicU64>,- pub(crate) roster_push_order: std::sync::Arc<std::sync::Mutex<()>>,}-pub(crate) fn push_roster_delta(context: &RosterPushContext) {+pub(crate) async fn push_roster_delta(context: &RosterPushContext) {if std::env::var_os("PA_WORKER_DISABLE_ROSTER_PUSH").is_some() {return;}if context.worker_token.is_empty() || context.roster_link.socket_path().as_os_str().is_empty() {return;}- // The push-order lock holds the snapshot and its sequence stamp- // together: an older snapshot must never carry the newer sequence- // (the supervisor would keep the stale row and drop the fresh one).- let _order = context.roster_push_order.lock().unwrap();- let mut summary = {- let core = context.core.lock().unwrap();- session_summary(- &core,- &context- .engine- .effective_thinking_level()- .unwrap_or_else(|| "default".to_string()),- context.engine.model_metadata(),- context.engine.model_fallback_message(),- context.user_bash.is_running(),- context.engine.is_quota_parked(),- context.engine.has_running_subagents(),- )- };- // The embedded counter is the pre-stamp value read under the order- // lock: every sequence stamped before the snapshot is at or below it.- summary.roster_delta_sequence = Some(- context+ // A pull may race this push, but both read the counter with their core+ // snapshot held: an equal-counter pull was captured after this push.+ let command = {+ let (core, inputs) =+ SummaryInputs::lock(&context.core, context.engine.as_ref(), &context.user_bash);+ let mut summary = session_summary(&core, inputs);+ // The embedded counter is the pre-stamp value: every sequence+ // stamped before the snapshot is at or below it.+ summary.roster_delta_sequence = Some(+ context+ .roster_delta_sequence+ .load(std::sync::atomic::Ordering::SeqCst),+ );+ let summary = serde_json::to_value(&summary).unwrap_or(serde_json::Value::Null);+ let sequence_value = context.roster_delta_sequence- .load(std::sync::atomic::Ordering::SeqCst),- );- let summary = serde_json::to_value(&summary).unwrap_or(serde_json::Value::Null);- let link = std::sync::Arc::clone(&context.roster_link);- let worker_token = context.worker_token.clone();- let worker_instance_id = context.worker_instance_id.clone();- let sequence_value = context- .roster_delta_sequence- .fetch_add(1, std::sync::atomic::Ordering::SeqCst)- + 1;- tokio::spawn(async move {- let command = serde_json::json!({+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst)+ + 1;+ serde_json::json!({"type": "worker_roster_delta",- "workerToken": worker_token,+ "workerToken": context.worker_token,"summary": summary,"sequence": sequence_value,- "workerInstanceId": worker_instance_id,- });- let _ = link- .request(command, std::time::Duration::from_secs(10))- .await;- });+ "workerInstanceId": context.worker_instance_id,+ })+ };+ let _ = context+ .roster_link+ .request(command, std::time::Duration::from_secs(10))+ .await;}-pub(crate) fn session_summary(- core: &SessionCore,- thinking_level: &str,+/// Registry-derived values are resolved before taking the core lock, then+/// checked against the cheap live selection under that lock. A model switch+/// between the resolve and lock makes the caller retry, not ship a torn row.+#[derive(Clone, Copy)]+enum ModelDetailScope {+ Summary,+ Connection,+}++struct ModelDetails {+ identity: (Option<String>, Option<String>),model: Option<Value>,- model_fallback_message: Option<String>,- bash_running: bool,- quota_parked: bool,- subagents_running: bool,-) -> SessionSummary {+ available_thinking_levels: Option<Vec<String>>,+ model_context_window: Option<u64>,+}++impl ModelDetails {+ fn read(engine: &dyn SessionEngine, scope: ModelDetailScope) -> Self {+ loop {+ let identity = engine.model_identity();+ let model = engine.model_metadata();+ let (available_thinking_levels, model_context_window) = match scope {+ ModelDetailScope::Summary => (None, None),+ ModelDetailScope::Connection => (+ engine.supported_thinking_levels(),+ engine.model_context_window(),+ ),+ };+ // Warm the engine's cached effective level while no core guard is+ // held: an uncached level may also resolve the model registry.+ let _ = engine.effective_thinking_level();+ if engine.model_identity() == identity {+ return Self {+ identity,+ model,+ available_thinking_levels,+ model_context_window,+ };+ }+ }+ }+}++/// Engine and user-bash values captured under the same core lock as the+/// summary, after validating the registry-derived model against its selection.+pub(crate) struct SummaryInputs {+ pub(crate) thinking_level: String,+ pub(crate) model: Option<Value>,+ pub(crate) model_fallback_message: Option<String>,+ pub(crate) bash_running: bool,+ pub(crate) quota_parked: bool,+ pub(crate) subagents_running: bool,+}++impl SummaryInputs {+ fn lock<'a>(+ core: &'a Mutex<SessionCore>,+ engine: &dyn SessionEngine,+ user_bash: &crate::user_bash::UserBash,+ ) -> (std::sync::MutexGuard<'a, SessionCore>, Self) {+ loop {+ let details = ModelDetails::read(engine, ModelDetailScope::Summary);+ let core = core.lock().unwrap();+ if engine.model_identity() == details.identity {+ let identity = details.identity;+ let inputs = Self::capture(engine, user_bash, details.model);+ if engine.model_identity() == identity {+ return (core, inputs);+ }+ }+ }+ }++ fn capture(+ engine: &dyn SessionEngine,+ user_bash: &crate::user_bash::UserBash,+ model: Option<Value>,+ ) -> Self {+ Self {+ thinking_level: engine+ .effective_thinking_level()+ .unwrap_or_else(|| "default".to_string()),+ model,+ model_fallback_message: engine.model_fallback_message(),+ bash_running: user_bash.is_running(),+ quota_parked: engine.is_quota_parked(),+ subagents_running: engine.has_running_subagents(),+ }+ }+}++/// The connection state's engine/user-bash values, captured alongside its+/// core state; registry-derived values resolve before the lock.+pub(crate) struct ConnectionStateInputs {+ model: Option<Value>,+ thinking_level: String,+ available_thinking_levels: Vec<String>,+ is_bash_running: bool,+ goal: Value,+ model_context_window: Option<u64>,+}++impl ConnectionStateInputs {+ fn lock<'a>(+ core: &'a Mutex<SessionCore>,+ engine: &dyn SessionEngine,+ user_bash: &crate::user_bash::UserBash,+ ) -> (std::sync::MutexGuard<'a, SessionCore>, Self) {+ loop {+ let details = ModelDetails::read(engine, ModelDetailScope::Connection);+ let core = core.lock().unwrap();+ if engine.model_identity() == details.identity {+ let identity = details.identity.clone();+ let inputs = Self::capture(engine, user_bash, details);+ if engine.model_identity() == identity {+ return (core, inputs);+ }+ }+ }+ }++ fn capture(+ engine: &dyn SessionEngine,+ user_bash: &crate::user_bash::UserBash,+ details: ModelDetails,+ ) -> Self {+ Self {+ model: details.model,+ thinking_level: engine+ .effective_thinking_level()+ .unwrap_or_else(|| "default".to_string()),+ available_thinking_levels: details+ .available_thinking_levels+ .unwrap_or_else(|| vec!["off".to_string()]),+ is_bash_running: user_bash.is_running(),+ goal: engine.goal_state_value(),+ model_context_window: details.model_context_window,+ }+ }+}++pub(crate) fn session_summary(core: &SessionCore, inputs: SummaryInputs) -> SessionSummary {let store = core.store.as_ref();let streaming = core.busy;let compacting = core.compacting;@@ -400,7 +546,7 @@ pub(crate) fn session_summary(.to_string(),// Running children keep the session working after its own turn// ended: every status surface classifies this activity.- activity: if streaming || compacting || subagents_running {+ activity: if streaming || compacting || inputs.subagents_running {"working"} else {"idle"@@ -417,13 +563,13 @@ pub(crate) fn session_summary(session_file: store.map(|s| s.path.to_string_lossy().to_string()),session_name: store.and_then(|s| s.session_name().map(str::to_string)),cwd: core.cwd.clone(),- thinking_level: Some(thinking_level.to_string()),+ thinking_level: Some(inputs.thinking_level),is_streaming: streaming,is_compacting: compacting,- is_quota_parked: Some(quota_parked),- is_bash_running: Some(bash_running),+ is_quota_parked: Some(inputs.quota_parked),+ is_bash_running: Some(inputs.bash_running),is_running_tools: streaming && !core.running_tool_calls.is_empty(),- has_running_subagents: subagents_running,+ has_running_subagents: inputs.subagents_running,attached_clients: core.attached_client_ids.len() as u32,message_count: store.map_or(0, crate::session_store::SessionFile::message_count) as u32,session_actions: session_snapshot(core),@@ -442,8 +588,8 @@ pub(crate) fn session_summary(// pulls embed the live counter in `summary_locked` instead.roster_delta_sequence: None,worker_instance_id: None,- model,- model_fallback_message,+ model: inputs.model,+ model_fallback_message: inputs.model_fallback_message,runtime_kind: Some(core.runtime_kind.clone()),unfinished_action_count: Some(0),anthropic_warning_shown: storediff --git a/crates/pa-daemon/src/worker/tests/connection_state_tests.rs b/crates/pa-daemon/src/worker/tests/connection_state_tests.rsindex b9ea1fac2b..449113795e 100644--- a/crates/pa-daemon/src/worker/tests/connection_state_tests.rs+++ b/crates/pa-daemon/src/worker/tests/connection_state_tests.rs@@ -52,6 +52,136 @@ impl SessionEngine for WindowedEngine {}}+/// The model resolver may finish with an old selection while a command+/// waits for core. The lock-side selection check retries the resolve instead+/// of pairing that old model with the post-switch core state.+struct SwitchingEngine {+ selection: std::sync::Mutex<String>,+ pause: std::sync::Mutex<Option<(std::sync::mpsc::Sender<()>, std::sync::mpsc::Receiver<()>)>>,+}++impl SessionEngine for SwitchingEngine {+ fn run_prompt(+ &self,+ _: usize,+ _: PromptRequest,+ _: &dyn Fn() -> bool,+ _: &mut dyn FnMut(crate::engine::EngineEvent) -> bool,+ ) {+ }+ fn run_side_question(+ &self,+ request: crate::engine::SideQuestionRequest,+ signal: &pa_agent::abort::AbortSignal,+ sink: &pa_core::session_engine::side_question::SideQuestionSink,+ ) -> crate::engine::SideQuestionOutcome {+ WindowedEngine.run_side_question(request, signal, sink)+ }+ fn run_compaction(+ &self,+ request: crate::engine::CompactionRequest,+ signal: &pa_agent::abort::AbortSignal,+ ) -> crate::engine::CompactionOutcome {+ WindowedEngine.run_compaction(request, signal)+ }+ fn run_branch_summary(+ &self,+ request: crate::engine::BranchSummaryRequest,+ signal: &pa_agent::abort::AbortSignal,+ ) -> crate::engine::BranchSummaryOutcome {+ WindowedEngine.run_branch_summary(request, signal)+ }+ fn rebuild_session_context(+ &self,+ entries: Vec<pa_types::session::FileEntry>,+ reload: pa_core::session_engine::goal_driver::GoalBranchReload,+ ) -> anyhow::Result<()> {+ WindowedEngine.rebuild_session_context(entries, reload)+ }+ fn model_identity(&self) -> (Option<String>, Option<String>) {+ (+ Some("test".to_string()),+ Some(self.selection.lock().unwrap().clone()),+ )+ }+ fn model_metadata(&self) -> Option<Value> {+ let model = self.selection.lock().unwrap().clone();+ if let Some((entered, resume)) = self.pause.lock().unwrap().take() {+ entered.send(()).unwrap();+ resume.recv().unwrap();+ }+ Some(json!({ "provider": "test", "id": model }))+ }+ fn effective_thinking_level(&self) -> Option<String> {+ Some(self.selection.lock().unwrap().clone())+ }+ fn supported_thinking_levels(&self) -> Option<Vec<String>> {+ Some(vec![self.selection.lock().unwrap().clone()])+ }+ fn model_context_window(&self) -> Option<u64> {+ Some(if *self.selection.lock().unwrap() == "new" {+ 200+ } else {+ 100+ })+ }+}++#[tokio::test]+async fn summary_retry_resolves_the_selection_that_owns_the_locked_core() {+ let (entered_tx, entered_rx) = std::sync::mpsc::channel();+ let (resume_tx, resume_rx) = std::sync::mpsc::channel();+ let engine = std::sync::Arc::new(SwitchingEngine {+ selection: std::sync::Mutex::new("old".to_string()),+ pause: std::sync::Mutex::new(Some((entered_tx, resume_rx))),+ });+ let dir = tempfile::tempdir().unwrap();+ let mut worker = Worker::new(+ WorkerConfig {+ socket_path: dir.path().join("worker.sock"),+ supervisor_socket_path: PathBuf::new(),+ token: "switch-test".into(),+ worker_instance_id: String::new(),+ active_session_id: "switch-test".into(),+ agent_dir: dir.path().join("agent"),+ recovery_journal_path: dir.path().join("recovery.jsonl"),+ telemetry_disabled: None,+ script: Some(json!({ "responses": [] })),+ },+ None,+ );+ worker.engine = engine.clone();+ let worker = std::sync::Arc::new(worker);+ let core = worker.core.lock().unwrap();+ let reader = {+ let worker = std::sync::Arc::clone(&worker);+ std::thread::spawn(move || {+ let (core, inputs) = worker.summary_inputs();+ worker.summary_locked(&core, inputs)+ })+ };+ entered_rx+ .recv_timeout(std::time::Duration::from_secs(2))+ .unwrap();+ *engine.selection.lock().unwrap() = "new".to_string();+ resume_tx.send(()).unwrap();+ drop(core);+ let summary = reader.join().unwrap();+ assert_eq!(+ summary.model,+ Some(json!({ "provider": "test", "id": "new" }))+ );+ assert_eq!(summary.thinking_level.as_deref(), Some("new"));+ let (core, inputs) = worker.connection_state_inputs();+ let state = Worker::connection_state_locked(&core, inputs);+ assert_eq!(+ state.model,+ Some(json!({ "provider": "test", "id": "new" }))+ );+ assert_eq!(state.available_thinking_levels, vec!["new".to_string()]);+ assert_eq!(state.context_usage, None);+}+/// The attach snapshot's state carries the tray's context usage exactly as/// `get_session_stats` serves it (TS `createAgentConnectionState`'s/// `contextUsage: session.getContextUsage()`): the same walk, the same@@ -86,8 +216,8 @@ async fn the_attach_state_carries_the_stats_context_usage() {assert!(created.success, "create failed: {created:?}");let snapshot_state = {- let core = worker.core.lock().unwrap();- let sealed = worker.connection_state_locked(&core);+ let (core, inputs) = worker.connection_state_inputs();+ let sealed = Worker::connection_state_locked(&core, inputs);serde_json::to_value(&sealed).unwrap()};assert_eq!(@@ -129,8 +259,8 @@ async fn the_attach_state_carries_the_stats_context_usage() {).await;let modelless = {- let core = worker.core.lock().unwrap();- let sealed = worker.connection_state_locked(&core);+ let (core, inputs) = worker.connection_state_inputs();+ let sealed = Worker::connection_state_locked(&core, inputs);serde_json::to_value(&sealed).unwrap()};assert!(diff --git a/crates/pa-daemon/src/worker/tests/summary_tests.rs b/crates/pa-daemon/src/worker/tests/summary_tests.rsindex 5ad79c357f..36cc8d40bb 100644--- a/crates/pa-daemon/src/worker/tests/summary_tests.rs+++ b/crates/pa-daemon/src/worker/tests/summary_tests.rs@@ -1,6 +1,17 @@//! Worker summary/wire unit tests.use super::*;+fn inputs() -> SummaryInputs {+ SummaryInputs {+ thinking_level: "default".to_string(),+ model: None,+ model_fallback_message: None,+ bash_running: false,+ quota_parked: false,+ subagents_running: false,+ }+}+#[test]fn sender_child_edge_decides_the_relationship_label() {let true_child = json!({@@ -61,24 +72,10 @@ fn sender_child_edge_decides_the_relationship_label() {#[test]fn summary_lifecycle_is_message_based() {let empty = SessionCore::test_core(None, "/tmp".to_string());- assert_eq!(- session_summary(- &empty, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .lifecycle,- "draft"- );+ assert_eq!(session_summary(&empty, inputs()).lifecycle, "draft");let mut subagent = SessionCore::test_core(None, "/tmp".to_string());subagent.runtime_kind = "subagent".to_string();- assert_eq!(- session_summary(- &subagent, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .lifecycle,- "live"- );+ assert_eq!(session_summary(&subagent, inputs()).lifecycle, "live");// The busy-flip roster delta fires before the store flushes the admitted// prompt; a busy turn is live at that wire moment.let mut busy = SessionCore::test_core(None, "/tmp".to_string());@@ -86,48 +83,26 @@ fn summary_lifecycle_is_message_based() {busy.running_tool_calls.insert("call-1".to_string());// `isRunningTools` is the streaming gate over the in-flight tool// set.- assert!(- session_summary(- &busy, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .is_running_tools- );+ assert!(session_summary(&busy, inputs()).is_running_tools);busy.running_tool_calls.clear();- assert!(- !session_summary(- &busy, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .is_running_tools- );+ assert!(!session_summary(&busy, inputs()).is_running_tools);busy.running_tool_calls.insert("call-1".to_string());busy.busy = false;- assert!(- !session_summary(- &busy, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .is_running_tools- );+ assert!(!session_summary(&busy, inputs()).is_running_tools);// The user bash state rides the summary as its own flag.assert_eq!(session_summary(- &busy, "default", None, None, /*bash_running=*/ true,- /*quota_parked=*/ false, /*subagents_running=*/ false+ &busy,+ SummaryInputs {+ bash_running: true,+ ..inputs()+ },).is_bash_running,Some(true));busy.busy = true;- assert_eq!(- session_summary(- &busy, "default", None, None, /*bash_running=*/ false,- /*quota_parked=*/ false, /*subagents_running=*/ false- )- .lifecycle,- "live"- );+ assert_eq!(session_summary(&busy, inputs()).lifecycle, "live");let dir = std::env::temp_dir().join(format!("pa-worker-lc-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();let mut session = crate::session_store::SessionFile::create("/tmp", None, 0);@@ -140,19 +115,7 @@ fn summary_lifecycle_is_message_based() {}));session.rewrite().unwrap();let with_message = SessionCore::test_core(Some(session), "/tmp".to_string());- assert_eq!(- session_summary(- &with_message,- "default",- None,- None,- /*bash_running=*/ false,- /*quota_parked=*/ false,- /*subagents_running=*/ false- )- .lifecycle,- "live"- );+ assert_eq!(session_summary(&with_message, inputs()).lifecycle, "live");let _ = std::fs::remove_dir_all(&dir);}@@ -166,12 +129,10 @@ fn running_subagents_keep_an_idle_session_working() {let summary = |subagents_running| {serde_json::to_value(session_summary(&core,- "default",- None,- None,- /*bash_running=*/ false,- /*quota_parked=*/ false,- subagents_running,+ SummaryInputs {+ subagents_running,+ ..inputs()+ },)).unwrap()};@@ -249,10 +210,7 @@ fn live_summary_usage_is_the_catalog_fold() {"the fixture must serve a windowed open");let core = SessionCore::test_core(Some(store), "/tmp".to_string());- let summary = session_summary(- &core, "default", None, None, /*bash_running=*/ false, /*quota_parked=*/ false,- /*subagents_running=*/ false,- );+ let summary = session_summary(&core, inputs());// The live row equals the saved row, whole-object.let catalog = crate::session_store::read_session_info(&path).unwrap()@@ -292,10 +250,7 @@ fn pathless_summary_usage_folds_the_in_memory_entries() {},}));let core = SessionCore::test_core(Some(store), "/tmp".to_string());- let summary = session_summary(- &core, "default", None, None, /*bash_running=*/ false, /*quota_parked=*/ false,- /*subagents_running=*/ false,- );+ let summary = session_summary(&core, inputs());assert_eq!(json!(summary.usage),json!({ "inputTokens": 100, "outputTokens": 10, "cost": 0.5 })diff --git a/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs b/crates/pa-daemon/src/worker/turn_stream_tests/feed.rsindex eda10239d9..f6239c7de3 100644--- a/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs+++ b/crates/pa-daemon/src/worker/turn_stream_tests/feed.rs@@ -121,7 +121,6 @@ fn live_feed_runner(engine: Arc<dyn SessionEngine>, socket: std::path::PathBuf)worker_token: "token".to_string(),worker_instance_id: "instance".to_string(),roster_delta_sequence: Arc::new(std::sync::atomic::AtomicU64::new(0)),- roster_push_order: Arc::new(std::sync::Mutex::new(())),});crate::roster_activity::spawn_roster_activity_watch(&events, roster_pushes.clone());TurnRunner {