Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(host-core): prevent queued tools from starving unrelated sessions

vastsafe4f4812f0af
diff --git a/crates/host-core/src/tool_budget.rs b/crates/host-core/src/tool_budget.rs
index 3e224d2a9..1fef9e988 100644
--- a/crates/host-core/src/tool_budget.rs
+++ b/crates/host-core/src/tool_budget.rs
@@ -1,9 +1,8 @@
-use std::collections::HashMap;
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
+use std::collections::{HashMap, VecDeque};
+use std::sync::{Arc, Mutex, MutexGuard};
use std::time::Duration;
-use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
+use tokio::sync::Notify;
pub const MAX_IN_FLIGHT_TOOLS: usize = 16;
pub const MAX_IN_FLIGHT_SHELL: usize = 4;
@@ -13,7 +12,7 @@ pub const MAX_IN_FLIGHT_MUTATIONS_PER_SESSION: usize = 1;
pub const MAX_IN_FLIGHT_PLUGINS: usize = 4;
pub const MAX_IN_FLIGHT_PER_SESSION: usize = 4;
pub const MAX_QUEUED_TOOLS: usize = 64;
-/// How long a call waits for its class permit before admission fails. A call
+/// How long a call waits for execution capacity before admission fails. A call
/// waits here after the permission gate and before it runs, so the transport
/// deadline has to carry it too. Mirrored by `TOOL_QUEUE_WAIT_MS` in
/// `packages/shared/src/rpc-timeouts.ts`.
@@ -63,10 +62,16 @@ impl AdmissionError {
}
pub struct ToolPermit {
- _total: OwnedSemaphorePermit,
- _class: OwnedSemaphorePermit,
- _session: OwnedSemaphorePermit,
- _session_mutation: Option<OwnedSemaphorePermit>,
+ budget: ToolBudget,
+ request: Request,
+}
+
+impl Drop for ToolPermit {
+ fn drop(&mut self) {
+ let mut state = self.budget.lock();
+ state.release(&self.request);
+ state.dispatch();
+ }
}
#[derive(Debug, Clone, Copy)]
@@ -81,250 +86,237 @@ pub struct ToolBudgetSnapshot {
}
#[derive(Clone)]
-pub struct ToolBudget {
- total: Arc<Semaphore>,
- reads: Arc<Semaphore>,
- mutations: Arc<Semaphore>,
- shell: Arc<Semaphore>,
- plugins: Arc<Semaphore>,
- sessions: Arc<Mutex<HashMap<String, Arc<Semaphore>>>>,
- session_mutations: Arc<Mutex<HashMap<String, Arc<Semaphore>>>>,
- queued: Arc<AtomicUsize>,
+struct Request {
+ session_id: String,
+ class: ToolClass,
}
-impl ToolBudget {
- pub fn new() -> Self {
- Self {
- total: Arc::new(Semaphore::new(MAX_IN_FLIGHT_TOOLS)),
- reads: Arc::new(Semaphore::new(MAX_IN_FLIGHT_READS)),
- mutations: Arc::new(Semaphore::new(MAX_IN_FLIGHT_MUTATIONS)),
- shell: Arc::new(Semaphore::new(MAX_IN_FLIGHT_SHELL)),
- plugins: Arc::new(Semaphore::new(MAX_IN_FLIGHT_PLUGINS)),
- sessions: Arc::new(Mutex::new(HashMap::new())),
- session_mutations: Arc::new(Mutex::new(HashMap::new())),
- queued: Arc::new(AtomicUsize::new(0)),
- }
- }
-
- pub async fn acquire(
- &self,
- session_id: &str,
- tool_name: &str,
- ) -> Result<ToolPermit, AdmissionError> {
- let class = ToolClass::from_name(tool_name);
- let class_semaphore = self.class_semaphore(class);
- let session_semaphore = self.session_semaphore(session_id).await;
- let session_mutation_semaphore = match class {
- ToolClass::Mutation => Some(self.session_mutation_semaphore(session_id).await),
- _ => None,
- };
-
- if let Some(permit) = Self::try_acquire(
- self.total.clone(),
- class_semaphore.clone(),
- session_semaphore.clone(),
- session_mutation_semaphore.clone(),
- ) {
- return Ok(permit);
- }
+#[derive(Default)]
+struct SessionUsage {
+ active: usize,
+ mutations: usize,
+}
- let queue_depth = self.queued.fetch_add(1, Ordering::SeqCst) + 1;
- if queue_depth > MAX_QUEUED_TOOLS {
- self.queued.fetch_sub(1, Ordering::SeqCst);
- return Err(AdmissionError::QueueFull { queue_depth });
- }
+struct WaitingRequest {
+ id: u64,
+ request: Request,
+ ready: Arc<Notify>,
+ granted: bool,
+}
- let result = tokio::time::timeout(
- QUEUE_WAIT,
- Self::acquire_all(
- self.total.clone(),
- class_semaphore,
- session_semaphore,
- session_mutation_semaphore,
- ),
- )
- .await;
- self.queued.fetch_sub(1, Ordering::SeqCst);
+#[derive(Default)]
+struct BudgetState {
+ active: usize,
+ classes: [usize; 4],
+ sessions: HashMap<String, SessionUsage>,
+ waiting: VecDeque<WaitingRequest>,
+ queued: usize,
+ next_id: u64,
+}
- match result {
- Ok(permit) => Ok(permit),
- Err(_) => Err(AdmissionError::QueueWaitTimeout),
+impl ToolClass {
+ fn limit(self) -> usize {
+ match self {
+ Self::Read => MAX_IN_FLIGHT_READS,
+ Self::Mutation => MAX_IN_FLIGHT_MUTATIONS,
+ Self::Shell => MAX_IN_FLIGHT_SHELL,
+ Self::Plugin => MAX_IN_FLIGHT_PLUGINS,
}
}
+}
- pub fn snapshot(&self) -> ToolBudgetSnapshot {
- let active = MAX_IN_FLIGHT_TOOLS - self.total.available_permits();
- ToolBudgetSnapshot {
- active,
- queued: self.queued.load(Ordering::SeqCst),
- total: MAX_IN_FLIGHT_TOOLS,
- shell: MAX_IN_FLIGHT_SHELL - self.shell.available_permits(),
- reads: MAX_IN_FLIGHT_READS - self.reads.available_permits(),
- mutations: MAX_IN_FLIGHT_MUTATIONS - self.mutations.available_permits(),
- plugins: MAX_IN_FLIGHT_PLUGINS - self.plugins.available_permits(),
+impl BudgetState {
+ fn can_admit(&self, request: &Request) -> bool {
+ if self.active >= MAX_IN_FLIGHT_TOOLS
+ || self.classes[request.class as usize] >= request.class.limit()
+ {
+ return false;
}
+ self.sessions.get(&request.session_id).is_none_or(|usage| {
+ usage.active < MAX_IN_FLIGHT_PER_SESSION
+ && (request.class != ToolClass::Mutation
+ || usage.mutations < MAX_IN_FLIGHT_MUTATIONS_PER_SESSION)
+ })
}
- fn class_semaphore(&self, class: ToolClass) -> Arc<Semaphore> {
- match class {
- ToolClass::Read => self.reads.clone(),
- ToolClass::Mutation => self.mutations.clone(),
- ToolClass::Shell => self.shell.clone(),
- ToolClass::Plugin => self.plugins.clone(),
+ fn reserve(&mut self, request: &Request) {
+ self.active += 1;
+ self.classes[request.class as usize] += 1;
+ let usage = self.sessions.entry(request.session_id.clone()).or_default();
+ usage.active += 1;
+ if request.class == ToolClass::Mutation {
+ usage.mutations += 1;
}
}
- async fn session_semaphore(&self, session_id: &str) -> Arc<Semaphore> {
- let mut sessions = self.sessions.lock().await;
- sessions
- .entry(session_id.to_string())
- .or_insert_with(|| Arc::new(Semaphore::new(MAX_IN_FLIGHT_PER_SESSION)))
- .clone()
+ fn release(&mut self, request: &Request) {
+ self.active -= 1;
+ self.classes[request.class as usize] -= 1;
+ let usage = self
+ .sessions
+ .get_mut(&request.session_id)
+ .expect("admitted tool owns session capacity");
+ usage.active -= 1;
+ if request.class == ToolClass::Mutation {
+ usage.mutations -= 1;
+ }
+ if usage.active == 0 {
+ self.sessions.remove(&request.session_id);
+ }
}
- async fn session_mutation_semaphore(&self, session_id: &str) -> Arc<Semaphore> {
- let mut sessions = self.session_mutations.lock().await;
- sessions
- .entry(session_id.to_string())
- .or_insert_with(|| Arc::new(Semaphore::new(MAX_IN_FLIGHT_MUTATIONS_PER_SESSION)))
- .clone()
+ fn dispatch(&mut self) {
+ // Scan the bounded queue in arrival order. A blocked class/session
+ // must not prevent unrelated runnable work from using spare capacity.
+ for index in 0..self.waiting.len() {
+ let entry = &self.waiting[index];
+ if entry.granted || !self.can_admit(&entry.request) {
+ continue;
+ }
+ let request = entry.request.clone();
+ self.reserve(&request);
+ self.queued -= 1;
+ let entry = &mut self.waiting[index];
+ entry.granted = true;
+ // notify_one retains a notification if acquire has not yet awaited.
+ entry.ready.notify_one();
+ }
}
+}
- fn try_acquire(
- total: Arc<Semaphore>,
- class: Arc<Semaphore>,
- session: Arc<Semaphore>,
- session_mutation: Option<Arc<Semaphore>>,
- ) -> Option<ToolPermit> {
- // Reserve the narrow per-session mutation slot first. This keeps a
- // queued second Write/Edit from consuming a global mutation permit
- // while it waits for the first mutation in the same session.
- let session_mutation_permit = match session_mutation {
- Some(semaphore) => Some(semaphore.try_acquire_owned().ok()?),
- None => None,
- };
- let total_permit = total.try_acquire_owned().ok()?;
- let class_permit = class.try_acquire_owned().ok()?;
- let session_permit = session.try_acquire_owned().ok()?;
- Some(ToolPermit {
- _total: total_permit,
- _class: class_permit,
- _session: session_permit,
- _session_mutation: session_mutation_permit,
- })
- }
+// Own the queue entry across every await. Cancellation may occur after
+// dispatch reserves capacity but before the caller receives its ToolPermit.
+struct QueueGuard {
+ budget: ToolBudget,
+ id: Option<u64>,
+}
- async fn acquire_all(
- total: Arc<Semaphore>,
- class: Arc<Semaphore>,
- session: Arc<Semaphore>,
- session_mutation: Option<Arc<Semaphore>>,
- ) -> ToolPermit {
- // Keep the per-session mutation permit outside the global capacity
- // wait so one session cannot reserve global slots while its earlier
- // mutation is still running.
- let session_mutation_permit = match session_mutation {
- Some(semaphore) => Some(
- semaphore
- .acquire_owned()
- .await
- .expect("session mutation semaphore cannot be closed"),
- ),
- None => None,
- };
- let total_permit = total
- .acquire_owned()
- .await
- .expect("tool total semaphore cannot be closed");
- let class_permit = class
- .acquire_owned()
- .await
- .expect("tool class semaphore cannot be closed");
- let session_permit = session
- .acquire_owned()
- .await
- .expect("tool session semaphore cannot be closed");
+impl QueueGuard {
+ fn into_permit(mut self) -> ToolPermit {
+ let mut state = self.budget.lock();
+ let id = self.id.take().expect("waiting request has a queue id");
+ let index = state
+ .waiting
+ .iter()
+ .position(|entry| entry.id == id)
+ .expect("waiting request remains registered until claimed");
+ let entry = state.waiting.remove(index).expect("queue index exists");
+ assert!(
+ entry.granted,
+ "notified request owns all execution capacity"
+ );
ToolPermit {
- _total: total_permit,
- _class: class_permit,
- _session: session_permit,
- _session_mutation: session_mutation_permit,
+ budget: self.budget.clone(),
+ request: entry.request,
}
}
}
-impl Default for ToolBudget {
- fn default() -> Self {
- Self::new()
+impl Drop for QueueGuard {
+ fn drop(&mut self) {
+ let Some(id) = self.id else {
+ return;
+ };
+ let mut state = self.budget.lock();
+ let index = state
+ .waiting
+ .iter()
+ .position(|entry| entry.id == id)
+ .expect("waiting request remains registered until cleanup");
+ let entry = state.waiting.remove(index).expect("queue index exists");
+ if entry.granted {
+ state.release(&entry.request);
+ } else {
+ state.queued -= 1;
+ }
+ state.dispatch();
}
}
-#[cfg(test)]
-mod tests {
- use super::ToolBudget;
- use std::time::Duration;
+#[derive(Clone, Default)]
+pub struct ToolBudget {
+ state: Arc<Mutex<BudgetState>>,
+}
- #[tokio::test]
- async fn limits_shell_concurrency_and_reports_active_work() {
- let budget = ToolBudget::new();
- let mut permits = Vec::new();
- for index in 0..4 {
- permits.push(
- budget
- .acquire(&format!("session-{index}"), "Bash")
- .await
- .unwrap(),
- );
- }
+impl ToolBudget {
+ pub fn new() -> Self {
+ Self::default()
+ }
- let snapshot = budget.snapshot();
- assert_eq!(snapshot.active, 4);
- assert_eq!(snapshot.shell, 4);
- assert_eq!(snapshot.queued, 0);
+ fn lock(&self) -> MutexGuard<'_, BudgetState> {
+ // Only bounded in-memory bookkeeping runs under this synchronous lock.
+ // No filesystem operation, callback, or await is allowed here.
+ self.state
+ .lock()
+ .expect("tool budget state lock is not poisoned")
+ }
- let waiting_budget = budget.clone();
- let waiter =
- tokio::spawn(async move { waiting_budget.acquire("session-waiter", "Bash").await });
- drop(permits);
- assert!(waiter.await.unwrap().is_ok());
- assert_eq!(budget.snapshot().active, 0);
+ pub async fn acquire(
+ &self,
+ session_id: &str,
+ tool_name: &str,
+ ) -> Result<ToolPermit, AdmissionError> {
+ self.acquire_with_timeout(session_id, tool_name, QUEUE_WAIT)
+ .await
}
- #[tokio::test]
- async fn separates_session_capacity() {
- let budget = ToolBudget::new();
- let mut first = Vec::new();
- for _ in 0..4 {
- first.push(budget.acquire("session-a", "Read").await.unwrap());
+ async fn acquire_with_timeout(
+ &self,
+ session_id: &str,
+ tool_name: &str,
+ wait: Duration,
+ ) -> Result<ToolPermit, AdmissionError> {
+ let request = Request {
+ session_id: session_id.to_string(),
+ class: ToolClass::from_name(tool_name),
+ };
+ let ready = Arc::new(Notify::new());
+ let guard = {
+ let mut state = self.lock();
+ if state.can_admit(&request) {
+ state.reserve(&request);
+ return Ok(ToolPermit {
+ budget: self.clone(),
+ request,
+ });
+ }
+ let queue_depth = state.queued + 1;
+ if queue_depth > MAX_QUEUED_TOOLS {
+ return Err(AdmissionError::QueueFull { queue_depth });
+ }
+ let id = state.next_id;
+ state.next_id = state.next_id.wrapping_add(1);
+ state.queued += 1;
+ state.waiting.push_back(WaitingRequest {
+ id,
+ request,
+ ready: ready.clone(),
+ granted: false,
+ });
+ QueueGuard {
+ budget: self.clone(),
+ id: Some(id),
+ }
+ };
+ match tokio::time::timeout(wait, ready.notified()).await {
+ Ok(()) => Ok(guard.into_permit()),
+ Err(_) => Err(AdmissionError::QueueWaitTimeout),
}
-
- let second = budget.acquire("session-b", "Read").await;
- assert!(second.is_ok());
- let waiting_budget = budget.clone();
- let waiter = tokio::spawn(async move { waiting_budget.acquire("session-a", "Read").await });
- drop(first);
- assert!(waiter.await.unwrap().is_ok());
}
- #[tokio::test]
- async fn serializes_mutations_within_a_session() {
- let budget = ToolBudget::new();
- let first = budget.acquire("session-a", "Edit").await.unwrap();
- let mut waiter = tokio::spawn({
- let budget = budget.clone();
- async move { budget.acquire("session-a", "Write").await }
- });
-
- assert!(tokio::time::timeout(Duration::from_millis(50), &mut waiter)
- .await
- .is_err());
- assert_eq!(budget.snapshot().mutations, 1);
-
- drop(first);
- assert!(tokio::time::timeout(Duration::from_secs(1), &mut waiter)
- .await
- .unwrap()
- .unwrap()
- .is_ok());
+ pub fn snapshot(&self) -> ToolBudgetSnapshot {
+ let state = self.lock();
+ ToolBudgetSnapshot {
+ active: state.active,
+ queued: state.queued,
+ total: MAX_IN_FLIGHT_TOOLS,
+ shell: state.classes[ToolClass::Shell as usize],
+ reads: state.classes[ToolClass::Read as usize],
+ mutations: state.classes[ToolClass::Mutation as usize],
+ plugins: state.classes[ToolClass::Plugin as usize],
+ }
}
}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/host-core/src/tool_budget/tests.rs b/crates/host-core/src/tool_budget/tests.rs
new file mode 100644
index 000000000..599c41afc
--- /dev/null
+++ b/crates/host-core/src/tool_budget/tests.rs
@@ -0,0 +1,421 @@
+use super::{AdmissionError, ToolBudget, ToolPermit, MAX_QUEUED_TOOLS};
+use std::future::Future;
+use std::pin::Pin;
+use std::task::{Context, Poll, Waker};
+use std::time::Duration;
+
+// A first poll is the synchronization point: the request has entered the
+// admission queue, but no executor timing or wall-clock delay is involved.
+fn poll_once<F: Future>(future: Pin<&mut F>) -> Poll<F::Output> {
+ future.poll(&mut Context::from_waker(Waker::noop()))
+}
+
+fn admitted<F>(future: Pin<&mut F>) -> ToolPermit
+where
+ F: Future<Output = Result<ToolPermit, AdmissionError>>,
+{
+ match poll_once(future) {
+ Poll::Ready(Ok(permit)) => permit,
+ Poll::Ready(Err(error)) => panic!("unexpected admission failure: {error:?}"),
+ Poll::Pending => panic!("request with available capacity must be admitted"),
+ }
+}
+
+#[tokio::test]
+async fn limits_shell_concurrency_and_reports_active_work() {
+ let budget = ToolBudget::new();
+ let mut permits = Vec::new();
+ for index in 0..4 {
+ permits.push(
+ budget
+ .acquire(&format!("session-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let snapshot = budget.snapshot();
+ assert_eq!(snapshot.active, 4);
+ assert_eq!(snapshot.shell, 4);
+ assert_eq!(snapshot.queued, 0);
+
+ let mut waiter = Box::pin(budget.acquire("session-waiter", "Bash"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ drop(permits);
+ drop(admitted(waiter.as_mut()));
+ assert_eq!(budget.snapshot().active, 0);
+}
+
+#[tokio::test]
+async fn separates_session_capacity() {
+ let budget = ToolBudget::new();
+ let mut first = Vec::new();
+ for _ in 0..4 {
+ first.push(budget.acquire("session-a", "Read").await.unwrap());
+ }
+ let second = budget.acquire("session-b", "Read").await;
+ assert!(second.is_ok());
+ let mut waiter = Box::pin(budget.acquire("session-a", "Read"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ drop(first);
+ drop(admitted(waiter.as_mut()));
+}
+
+#[tokio::test]
+async fn serializes_mutations_within_a_session() {
+ let budget = ToolBudget::new();
+ let first = budget.acquire("session-a", "Edit").await.unwrap();
+ let mut waiter = Box::pin(budget.acquire("session-a", "Write"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().mutations, 1);
+
+ drop(first);
+ drop(admitted(waiter.as_mut()));
+ assert_eq!(budget.snapshot().mutations, 0);
+}
+
+#[tokio::test]
+async fn shell_backlog_does_not_reserve_global_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("running-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiting = Vec::new();
+ for _ in 0..12 {
+ let mut request = Box::pin(budget.acquire("shell-backlog", "Bash"));
+ assert!(poll_once(request.as_mut()).is_pending());
+ waiting.push(request);
+ }
+ let snapshot = budget.snapshot();
+ assert_eq!(snapshot.active, 4);
+ assert_eq!(snapshot.shell, 4);
+ assert_eq!(snapshot.queued, 12);
+
+ let read = admitted(Box::pin(budget.acquire("interactive", "Read")).as_mut());
+ let write = admitted(Box::pin(budget.acquire("interactive", "Write")).as_mut());
+ assert_eq!(budget.snapshot().active, 6);
+ assert_eq!(budget.snapshot().queued, 12);
+ drop((read, write, waiting, running));
+ assert_eq!(budget.snapshot().active, 0);
+ assert_eq!(budget.snapshot().queued, 0);
+}
+
+#[tokio::test]
+async fn session_backlog_does_not_reserve_read_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for _ in 0..4 {
+ running.push(budget.acquire("busy", "Read").await.unwrap());
+ }
+ let mut waiting = Vec::new();
+ for _ in 0..4 {
+ let mut request = Box::pin(budget.acquire("busy", "Read"));
+ assert!(poll_once(request.as_mut()).is_pending());
+ waiting.push(request);
+ }
+ assert_eq!(budget.snapshot().reads, 4);
+ assert_eq!(budget.snapshot().active, 4);
+ assert_eq!(budget.snapshot().queued, 4);
+ let read = admitted(Box::pin(budget.acquire("other", "Read")).as_mut());
+ drop((read, waiting, running));
+ assert_eq!(budget.snapshot().queued, 0);
+}
+
+#[tokio::test]
+async fn class_backlog_does_not_reserve_session_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("shell-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiting = Vec::new();
+ for _ in 0..4 {
+ let mut request = Box::pin(budget.acquire("busy", "Bash"));
+ assert!(poll_once(request.as_mut()).is_pending());
+ waiting.push(request);
+ }
+ let read = admitted(Box::pin(budget.acquire("busy", "Read")).as_mut());
+ assert_eq!(budget.snapshot().active, 5);
+ assert_eq!(budget.snapshot().queued, 4);
+ drop((read, waiting, running));
+}
+
+#[tokio::test]
+async fn cancelling_waiter_removes_queue_entry_and_releases_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("shell-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiter = Box::pin(budget.acquire("cancelled", "Bash"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().queued, 1);
+ drop(waiter);
+ assert_eq!(budget.snapshot().queued, 0);
+ assert_eq!(budget.snapshot().active, 4);
+ drop(running);
+ assert_eq!(budget.snapshot().active, 0);
+}
+
+#[tokio::test]
+async fn cancelling_notified_waiter_returns_reserved_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("shell-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiter = Box::pin(budget.acquire("cancelled", "Bash"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ drop(running);
+ // Cancellation must also work after a release has notified the waiter,
+ // before the executor polls it to return the admitted permit.
+ drop(waiter);
+ assert_eq!(budget.snapshot().active, 0);
+ assert_eq!(budget.snapshot().queued, 0);
+ assert_eq!(budget.snapshot().shell, 0);
+
+ let mut recovered = Vec::new();
+ for index in 0..4 {
+ recovered.push(admitted(
+ Box::pin(budget.acquire(&format!("recovered-{index}"), "Bash")).as_mut(),
+ ));
+ }
+ assert_eq!(budget.snapshot().active, 4);
+}
+
+#[tokio::test]
+async fn global_capacity_is_released_without_reserving_waiting_class() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for (session, tool, count) in [
+ ("reads-a", "Read", 4),
+ ("reads-b", "Glob", 4),
+ ("shells", "Bash", 4),
+ ("plugins", "custom_tool", 4),
+ ] {
+ for _ in 0..count {
+ running.push(budget.acquire(session, tool).await.unwrap());
+ }
+ }
+ assert_eq!(budget.snapshot().active, 16);
+ let mut waiter = Box::pin(budget.acquire("mutator", "Write"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().active, 16);
+ assert_eq!(budget.snapshot().mutations, 0);
+ drop(running.pop());
+ let admitted = admitted(waiter.as_mut());
+ assert_eq!(budget.snapshot().active, 16);
+ assert_eq!(budget.snapshot().mutations, 1);
+ drop((admitted, running));
+ assert_eq!(budget.snapshot().active, 0);
+}
+
+#[tokio::test]
+async fn all_tool_classes_enforce_shared_alias_limits() {
+ for (tool, alias, limit) in [
+ ("Read", "Grep", 8),
+ ("Write", "Edit", 2),
+ ("Bash", "Bash", 4),
+ ("plugin_first", "plugin_second", 4),
+ ] {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..limit {
+ running.push(
+ budget
+ .acquire(&format!("session-{index}"), tool)
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiter = Box::pin(budget.acquire("waiting", alias));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().active, limit);
+ assert_eq!(budget.snapshot().queued, 1);
+ drop(running.pop());
+ let next = admitted(waiter.as_mut());
+ assert_eq!(budget.snapshot().active, limit);
+ assert_eq!(budget.snapshot().queued, 0);
+ drop((next, running));
+ }
+}
+
+#[tokio::test]
+async fn session_capacity_applies_across_classes() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for _ in 0..4 {
+ running.push(budget.acquire("busy", "Read").await.unwrap());
+ }
+ let mut waiter = Box::pin(budget.acquire("busy", "Bash"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().shell, 0);
+ let other = admitted(Box::pin(budget.acquire("other", "Bash")).as_mut());
+ drop(running.pop());
+ let next = admitted(waiter.as_mut());
+ assert_eq!(budget.snapshot().active, 5);
+ drop((next, other, running));
+}
+
+#[tokio::test]
+async fn mutation_backlog_does_not_reserve_other_sessions_mutation_capacity() {
+ let budget = ToolBudget::new();
+ let first = budget.acquire("busy", "Write").await.unwrap();
+ let mut waiter = Box::pin(budget.acquire("busy", "Edit"));
+ assert!(poll_once(waiter.as_mut()).is_pending());
+ let other = admitted(Box::pin(budget.acquire("other", "Write")).as_mut());
+ assert_eq!(budget.snapshot().mutations, 2);
+ drop(first);
+ let next = admitted(waiter.as_mut());
+ assert_eq!(budget.snapshot().mutations, 2);
+ drop((next, other));
+}
+
+#[tokio::test]
+async fn bounded_queue_rejects_overflow_and_recovers_after_cancellation() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("running-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut waiting = Vec::new();
+ for _ in 0..MAX_QUEUED_TOOLS {
+ let mut request = Box::pin(budget.acquire("waiting", "Bash"));
+ assert!(poll_once(request.as_mut()).is_pending());
+ waiting.push(request);
+ }
+ assert_eq!(budget.snapshot().queued, MAX_QUEUED_TOOLS);
+ let mut overflow = Box::pin(budget.acquire("overflow", "Bash"));
+ match poll_once(overflow.as_mut()) {
+ Poll::Ready(Err(error @ AdmissionError::QueueFull { queue_depth })) => {
+ assert_eq!(queue_depth, MAX_QUEUED_TOOLS + 1);
+ assert_eq!(error.code(), "HOST_OVERLOADED");
+ }
+ _ => panic!("queue overflow must reject admission immediately"),
+ }
+ assert_eq!(budget.snapshot().queued, MAX_QUEUED_TOOLS);
+ drop(waiting.pop());
+ assert_eq!(budget.snapshot().queued, MAX_QUEUED_TOOLS - 1);
+ let mut replacement = Box::pin(budget.acquire("replacement", "Bash"));
+ assert!(poll_once(replacement.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().queued, MAX_QUEUED_TOOLS);
+ drop((replacement, waiting, running));
+ assert_eq!(budget.snapshot().queued, 0);
+ assert_eq!(budget.snapshot().active, 0);
+}
+
+#[tokio::test]
+async fn older_eligible_waiter_is_admitted_before_new_requests() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("running-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut older = Box::pin(budget.acquire("older", "Bash"));
+ assert!(poll_once(older.as_mut()).is_pending());
+ drop(running.pop());
+ let mut newer = Box::pin(budget.acquire("newer", "Bash"));
+ assert!(poll_once(newer.as_mut()).is_pending());
+ let old_permit = admitted(older.as_mut());
+ assert_eq!(budget.snapshot().queued, 1);
+ drop(old_permit);
+ let new_permit = admitted(newer.as_mut());
+ assert_eq!(budget.snapshot().queued, 0);
+ drop((new_permit, running));
+}
+
+#[tokio::test]
+async fn timeout_removes_only_its_queue_entry_and_preserves_running_capacity() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for index in 0..4 {
+ running.push(
+ budget
+ .acquire(&format!("running-{index}"), "Bash")
+ .await
+ .unwrap(),
+ );
+ }
+ let mut older = Box::pin(budget.acquire("older", "Bash"));
+ assert!(poll_once(older.as_mut()).is_pending());
+ let result = budget
+ .acquire_with_timeout("timed-out", "Bash", Duration::ZERO)
+ .await;
+ match result {
+ Err(error @ AdmissionError::QueueWaitTimeout) => {
+ assert_eq!(error.code(), "HOST_OVERLOADED");
+ }
+ _ => panic!("exhausted capacity must time out without admission"),
+ }
+ assert_eq!(budget.snapshot().queued, 1);
+ assert_eq!(budget.snapshot().active, 4);
+ assert_eq!(budget.snapshot().shell, 4);
+ drop(running.pop());
+ let permit = admitted(older.as_mut());
+ assert_eq!(budget.snapshot().queued, 0);
+ drop((permit, running));
+ assert_eq!(budget.snapshot().active, 0);
+}
+
+#[tokio::test]
+async fn dispatch_skips_a_blocked_class_for_the_oldest_runnable_request() {
+ let budget = ToolBudget::new();
+ let mut running = Vec::new();
+ for (session, tool) in [
+ ("reads-a", "Read"),
+ ("reads-b", "Read"),
+ ("shells", "Bash"),
+ ("plugins", "plugin_tool"),
+ ] {
+ for _ in 0..4 {
+ running.push(budget.acquire(session, tool).await.unwrap());
+ }
+ }
+ let mut shell = Box::pin(budget.acquire("queued-shell", "Bash"));
+ let mut write = Box::pin(budget.acquire("queued-write", "Write"));
+ assert!(poll_once(shell.as_mut()).is_pending());
+ assert!(poll_once(write.as_mut()).is_pending());
+ drop(running.pop());
+ let write_permit = admitted(write.as_mut());
+ assert!(poll_once(shell.as_mut()).is_pending());
+ assert_eq!(budget.snapshot().active, 16);
+ assert_eq!(budget.snapshot().queued, 1);
+ assert_eq!(budget.snapshot().mutations, 1);
+ // Release a shell, rather than another plugin, to unblock the older call.
+ drop(running.remove(8));
+ let shell_permit = admitted(shell.as_mut());
+ assert_eq!(budget.snapshot().active, 16);
+ assert_eq!(budget.snapshot().queued, 0);
+ drop((write_permit, shell_permit, running));
+ assert_eq!(budget.snapshot().active, 0);
+}
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 64b4e79a6..5a09a8d86 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -53,9 +53,14 @@ Permission prompts do not consume an execution slot. A full queue returns
`HOST_OVERLOADED` with retryable semantics in the tool result instead of
waiting indefinitely or spawning more work. The limits are host-owned so
Electron and the sidecar cannot independently over-admit the same resources.
-The per-session mutation permit is acquired before the global mutation slot;
-queued `Write`/`Edit` calls therefore do not hold global capacity while waiting
-for an earlier mutation in the same session.
+Admission reserves total, tool-class, session, and session-mutation capacity
+atomically. A queued call holds no execution capacity. When capacity returns,
+the oldest runnable request is admitted; a request blocked by one class or
+session does not block unrelated runnable work. Calls wait at most 30 seconds.
+Dropping a waiting admission future or letting it time out removes its queue
+entry and releases any reservation made before the caller receives its permit. The health counters report only
+fully admitted reservations, including those awaiting delivery to the caller;
+`queued` counts only requests still waiting for capacity.
Electron's `HostProcess` treats an explicit `HOST_OVERLOADED` response as
retryable backpressure for renderer-facing calls. It waits 50, 100, 200, and
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index cd249260d..a0a2a705b 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -627,7 +627,11 @@ identify the platform validation still needed.
restart. 5) Allow the persistence outbox to flush.
- **Expected**: Active shell processes never exceed the configured global and
per-session limits. Excess work returns `HOST_OVERLOADED` or waits in the
- bounded queue. Only one restart loop runs; stale-generation calls fail fast
+ bounded queue. Queued requests do not reserve execution capacity: with four
+ running Bash calls and twelve queued Bash calls, another session can still
+ Read and Write. A saturated session cannot reserve spare class capacity, and
+ admission-future cancellation/timeout restores queue and execution counters.
+ Only one restart loop runs; stale-generation calls fail fast
as `HOST_UNAVAILABLE`; no repeated `ERR_STREAM_DESTROYED` persistence storm
is emitted. Temporary OS thread pressure during the same burst does not
terminate host-core through its stdio control path; the host remains on one
@@ -638,7 +642,10 @@ identify the platform validation still needed.
`03-runtime/09-logging-and-observability.md`, ADR 0051
- **Acceptance**: A (runtime health), C (tool execution and recovery)
- **Milestone**: M5
-- **Status**: Documented; automation pending
+- **Status**: Cross-session admission is automated by
+ `node scripts/e2e-tool-admission.mjs` against an isolated real host. Class,
+ session, global, mutation, queue bounds, fairness, cancellation, and timeout
+ are unit-covered by `tool_budget/tests.rs`; restart coverage remains pending.
### Release & Packaging
diff --git a/scripts/README.md b/scripts/README.md
index aba50fadb..d35d3e8f0 100644
--- a/scripts/README.md
+++ b/scripts/README.md
@@ -42,13 +42,16 @@ disagrees, so a green `check:release-docs` is a precondition, not a substitute.
## End-to-end
-Do not run these from an agent session, and do not trigger the remote jobs by
-hand, unless the request explicitly asks for it (see `AGENTS.md`). The scenarios
-they cover are specified in
+Run relevant task-candidate E2E from the dedicated request worktree, reusing
+the provisioned host environment as required by `AGENTS.md`. `verify:ui:*`,
+live providers, paid APIs, and the user's running desktop require explicit
+request authorization. Use isolated profiles and deterministic local fixtures.
+The scenarios are specified in
[the E2E test plan](../docs/spec/06-delivery/04-e2e-test-plan.md).
| Script | Alias | Purpose |
|---|---|---|
+| `e2e-tool-admission.mjs` | `node scripts/e2e-tool-admission.mjs` | Isolated real-host tool admission: queued Bash burst leaves capacity for another session's Read/Write and recovers all counters |
| `e2e-smoke.mjs` | `pnpm test:e2e` | Protocol-level E2E against host-core, plus an optional live model |
| `e2e-plan.mjs` | `pnpm test:e2e:plan` | Plan state, checkpoint artifact, and approval transitions |
| `e2e-plan-ui.mjs` | `pnpm test:e2e:plan-ui` | Plan approval through the rendered UI |
diff --git a/scripts/e2e-tool-admission.mjs b/scripts/e2e-tool-admission.mjs
new file mode 100644
index 000000000..2f038a0d8
--- /dev/null
+++ b/scripts/e2e-tool-admission.mjs
@@ -0,0 +1,139 @@
+#!/usr/bin/env node
+/**
+ * Headless tool-admission regression for issue #1286. Uses only an isolated
+ * host, workspace, and local shell commands; no provider or desktop instance.
+ * Run with PI_DESKTOP_HOST_BIN pointing to the candidate's built host binary.
+ */
+import { existsSync } from "node:fs";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";
+import { assert, assertToolSuccess, shortJson } from "./e2e/assert.mjs";
+import { withScenario } from "./e2e/fixture.mjs";
+import { resolveHostBinary } from "./e2e/host.mjs";
+import { configureSession, createSession } from "./e2e/session.mjs";
+import { waitFor } from "./e2e/wait.mjs";
+
+function posixQuote(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+function powerShellQuote(value) {
+ return `'${String(value).replaceAll("'", "''")}'`;
+}
+
+function gateCommand(dialect, marker, gate) {
+ if (dialect === "posix") {
+ return `printf started > ${posixQuote(marker)}; while [ ! -f ${posixQuote(gate)} ]; do sleep 0.025; done; printf released`;
+ }
+ const script = `[IO.File]::WriteAllText(${powerShellQuote(marker)}, 'started'); while (-not [IO.File]::Exists(${powerShellQuote(gate)})) { Start-Sleep -Milliseconds 25 }; [Console]::Out.Write('released')`;
+ if (dialect === "powershell") return script;
+ if (dialect === "cmd") {
+ // Windows cmd uses the same built-in PowerShell fixture as e2e-plan.mjs.
+ return `powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ${Buffer.from(script, "utf16le").toString("base64")}`;
+ }
+ throw new Error(`unsupported shell dialect: ${dialect}`);
+}
+
+async function main() {
+ const binary = resolveHostBinary();
+ const tempRoot = await mkdtemp(join(tmpdir(), "pi-tool-admission-e2e-"));
+ try {
+ await withScenario("E2E-097-admission", async ({ host, workspace }) => {
+ const shellSessions = [];
+ for (let index = 0; index < 16; index += 1) {
+ const session = await createSession(host, workspace, `Shell admission fixture ${index}`);
+ await configureSession(host, session, "agent", "auto");
+ shellSessions.push(session);
+ }
+ const independentSession = await createSession(host, workspace, "Independent tool fixture");
+ await configureSession(host, independentSession, "agent", "auto");
+ const shell = (await host.call("commandShells.list")).effective;
+ assert(shell?.id && shell.available, "no available effective shell: " + shortJson(shell));
+
+ const gate = join(workspace, "release-shells");
+ const readFixture = "read-fixture.txt";
+ await writeFile(join(workspace, readFixture), "independent read fixture\n", "utf8");
+ const calls = [];
+ const markers = [];
+ const dispatch = (index) => {
+ const marker = join(workspace, `shell-${index}-started`);
+ markers.push(marker);
+ // Capture rejection immediately so an earlier assertion failure can
+ // release the gate and clean up all pending RPCs without unhandled errors.
+ calls.push(host.call("tools.execute", {
+ sessionId: shellSessions[index].id,
+ toolCallId: `admission-shell-${index}`,
+ toolName: "Bash",
+ args: { command: gateCommand(shell.dialect, marker, gate) },
+ mode: "agent",
+ expectedCommandShellId: shell.id,
+ expectedCommandShellDialect: shell.dialect,
+ }, 15_000).then(
+ (result) => ({ result }),
+ (error) => ({ error }),
+ ));
+ };
+
+ try {
+ for (let index = 0; index < 4; index += 1) dispatch(index);
+ await waitFor(() => markers.every((marker) => existsSync(marker)), 5_000, "four active shell markers");
+ for (let index = 4; index < 16; index += 1) dispatch(index);
+ let saturatedBudget;
+ await waitFor(async () => {
+ saturatedBudget = (await host.call("app.health", {}, 1_000)).toolBudget;
+ return saturatedBudget?.queued === 12;
+ }, 5_000, "twelve queued shells");
+ assert(saturatedBudget.active === 4 && saturatedBudget.shell === 4,
+ "queued shells reserved execution capacity: " + shortJson(saturatedBudget));
+
+ const read = await host.call("tools.execute", {
+ sessionId: independentSession.id,
+ toolCallId: "admission-independent-read",
+ toolName: "Read",
+ args: { path: readFixture },
+ mode: "agent",
+ }, 3_000);
+ assertToolSuccess(read, "admission-independent-read");
+ assert(JSON.stringify(read.content).includes("independent read fixture"),
+ "Read returned unexpected content: " + shortJson(read));
+ const write = await host.call("tools.execute", {
+ sessionId: independentSession.id,
+ toolCallId: "admission-independent-write",
+ toolName: "Write",
+ args: { path: "written-fixture.txt", content: "independent write fixture\n" },
+ mode: "agent",
+ }, 3_000);
+ assertToolSuccess(write, "admission-independent-write");
+ assert(await readFile(join(workspace, "written-fixture.txt"), "utf8") === "independent write fixture\n",
+ "Write did not persist the independent fixture");
+ const afterIndependent = (await host.call("app.health")).toolBudget;
+ assert(afterIndependent.active === 4 && afterIndependent.queued === 12,
+ "independent work did not release its capacity: " + shortJson(afterIndependent));
+ } finally {
+ // Release both active and subsequently admitted commands before the
+ // isolated host is stopped, including when a regression assertion fails.
+ await writeFile(gate, "release\n", "utf8");
+ await Promise.all(calls);
+ }
+
+ for (const [index, outcome] of (await Promise.all(calls)).entries()) {
+ if (outcome.error) throw outcome.error;
+ assertToolSuccess(outcome.result, `admission-shell-${index}`);
+ }
+ const idleBudget = (await host.call("app.health")).toolBudget;
+ assert(["active", "queued", "shell", "reads", "mutations", "plugins"].every((key) => idleBudget[key] === 0),
+ "tool capacity did not drain: " + shortJson(idleBudget));
+ console.log("PASS E2E-097-admission: 4 active + 12 queued shells leave independent Read/Write capacity and drain cleanly");
+ }, binary, tempRoot, PROTOCOL_VERSION);
+ } finally {
+ await rm(tempRoot, { recursive: true, force: true });
+ }
+}
+
+main().catch((error) => {
+ console.error("FAIL E2E-097-admission: " + (error?.message || String(error)));
+ process.exitCode = 1;
+});