Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: key the endpoint cap by normalized host:port and follow the fallback swap (#4834)

[._.]/ Adam Eivyabc643c1a02f
diff --git a/server/services/cos.js b/server/services/cos.js
index 06504ac282..a6e85a7397 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -596,7 +596,7 @@ export async function forceSpawnTask(taskId) {
// "Run now" would toast "Spawning" for a task the chokepoint immediately holds
// as pending. Checked against the RESOLVED provider (post-fallback), so it
// never refuses a run that would have swapped to a cloud provider anyway.
- const localCapacityError = await localEndpointCapacityError(resolution.provider, state.agents);
+ const localCapacityError = await localEndpointCapacityError(resolution.provider, state.agents, taskId);
if (localCapacityError) {
return { error: localCapacityError };
}
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 8dde629b6b..ee66bfff18 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -43,6 +43,7 @@ import {
reserveLocalEndpointSpawn,
pendingLocalEndpointSpawns,
__resetLocalEndpointSpawnReservations,
+ readEndpointCapacity,
} from './cosLocalEndpointSlots.js';
import { PENDING_MERGE_SWEEP_INTERVAL_MS, MAX_PENDING_MERGE_TICKS } from './prWatcher.js';
@@ -477,16 +478,21 @@ describe('dequeueNextTask — capacity guards', () => {
// tracker — the same pair `dequeueNextTask` wires together — so a regression in
// either half fails here.
-const LOCAL_ENDPOINT = 'http://localhost:1234/v1';
-const OTHER_LOCAL_ENDPOINT = 'http://127.0.0.1:11434';
+// What the PROVIDER RECORD holds, vs the normalized SLOT KEY the cap is keyed
+// by. They differ on purpose: host+port identifies the model server, so
+// `localhost` and `127.0.0.1` on one port must share a single slot.
+const LOCAL_URL = 'http://localhost:1234/v1';
+const LOCAL_ENDPOINT = 'localhost:1234';
+const OTHER_LOCAL_URL = 'http://127.0.0.1:11434';
+const OTHER_LOCAL_ENDPOINT = 'localhost:11434';
// A TUI provider pointed at a local server is exactly the case #4834 exists
// for: PortOS launches the CLI, the CLI talks to the GPU directly.
-const LOCAL_TUI_PROVIDER = { id: 'lmstudio-tui', type: 'tui', endpoint: LOCAL_ENDPOINT };
-const OTHER_LOCAL_PROVIDER = { id: 'ollama-local', type: 'api', endpoint: OTHER_LOCAL_ENDPOINT };
+const LOCAL_TUI_PROVIDER = { id: 'lmstudio-tui', type: 'tui', enabled: true, endpoint: LOCAL_URL };
+const OTHER_LOCAL_PROVIDER = { id: 'ollama-local', type: 'api', enabled: true, endpoint: OTHER_LOCAL_URL };
// No recorded endpoint — PortOS cannot know where it points, so it stays ungated.
-const BARE_CLI_PROVIDER = { id: 'claude-cli', type: 'cli', endpoint: null };
-const CLOUD_PROVIDER = { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com/v1' };
+const BARE_CLI_PROVIDER = { id: 'claude-cli', type: 'cli', enabled: true, endpoint: null };
+const CLOUD_PROVIDER = { id: 'anthropic', type: 'api', enabled: true, endpoint: 'https://api.anthropic.com/v1' };
const ALL_PROVIDERS = [LOCAL_TUI_PROVIDER, OTHER_LOCAL_PROVIDER, BARE_CLI_PROVIDER, CLOUD_PROVIDER];
@@ -735,8 +741,32 @@ describe('countRunningAgentsByLocalEndpoint (#4834)', () => {
describe('localEndpointOfProvider (#4834)', () => {
it('resolves a local endpoint regardless of provider type', () => {
- expect(localEndpointOfProvider({ type: 'tui', endpoint: 'http://localhost:1234/v1' })).toBe('http://localhost:1234/v1');
- expect(localEndpointOfProvider({ type: 'api', endpoint: 'http://127.0.0.1:11434' })).toBe('http://127.0.0.1:11434');
+ expect(localEndpointOfProvider({ type: 'tui', endpoint: 'http://localhost:1234/v1' })).toBe('localhost:1234');
+ expect(localEndpointOfProvider({ type: 'api', endpoint: 'http://127.0.0.1:11434' })).toBe('localhost:11434');
+ });
+
+ it('collapses every spelling of ONE local server onto a single slot key', () => {
+ // Host+port identifies the model server; scheme, path and host spelling do
+ // not. The shipped catalog already mixes spellings (`lmstudio` is seeded at
+ // localhost:1234, everything else at 127.0.0.1), so keying on the raw string
+ // would give one LM Studio process two independent caps — and let two agents
+ // onto the same GPU, the exact OOM this issue exists to prevent.
+ const spellings = [
+ 'http://localhost:1234/v1',
+ 'http://127.0.0.1:1234/v1',
+ 'http://127.0.0.1:1234',
+ 'https://localhost:1234/v1',
+ 'localhost:1234',
+ ' http://0.0.0.0:1234/v1 ',
+ ];
+ for (const endpoint of spellings) {
+ expect(localEndpointOfProvider({ endpoint }), endpoint).toBe('localhost:1234');
+ }
+ });
+
+ it('keeps distinct local servers on distinct keys', () => {
+ expect(localEndpointOfProvider({ endpoint: 'http://127.0.0.1:1234/v1' }))
+ .not.toBe(localEndpointOfProvider({ endpoint: 'http://127.0.0.1:11434/v1' }));
});
it('returns null for a remote endpoint, a missing endpoint, or no provider', () => {
@@ -860,7 +890,7 @@ describe('endpointForAgent — stamped endpoint wins over the id lookup (#4834)'
// Only `providerId` was persisted pre-#4834, so a deleted provider made a
// still-running agent invisible to the cap — freeing a slot the GPU was
// still holding. The stamped endpoint survives the deletion.
- const orphaned = { status: 'running', metadata: { providerId: 'deleted-provider', providerEndpoint: LOCAL_ENDPOINT } };
+ const orphaned = { status: 'running', metadata: { providerId: 'deleted-provider', providerEndpoint: LOCAL_URL } };
expect(slots.endpointForAgent(orphaned)).toBe(LOCAL_ENDPOINT);
expect(countRunningAgentsByLocalEndpoint({ a: orphaned }, slots.endpointForAgent)).toEqual({ [LOCAL_ENDPOINT]: 1 });
});
@@ -868,7 +898,7 @@ describe('endpointForAgent — stamped endpoint wins over the id lookup (#4834)'
it('prefers the stamp when the provider record was re-pointed mid-run', () => {
// The agent is still talking to the endpoint it started on, not the one the
// provider now names.
- const agent = { status: 'running', metadata: { providerId: 'ollama-local', providerEndpoint: LOCAL_ENDPOINT } };
+ const agent = { status: 'running', metadata: { providerId: 'ollama-local', providerEndpoint: LOCAL_URL } };
expect(slots.endpointForAgent(agent)).toBe(LOCAL_ENDPOINT);
});
@@ -882,6 +912,112 @@ describe('endpointForAgent — stamped endpoint wins over the id lookup (#4834)'
});
});
+describe('resolveLocalEndpoint — follows the fallback swap (#4834)', () => {
+ // An unavailable provider is not where the task lands, so the gate follows the
+ // SAME getFallbackProvider spawn uses. Both directions matter: a cloud
+ // fallback must ungate (or the task starves behind a GPU it never touches),
+ // and a fallback on the same local server must stay gated (or the cap
+ // disappears exactly when the endpoint is unhealthy — the shipped catalog has
+ // four providers on 127.0.0.1:18021).
+ const SAME_SERVER_SIBLING = { id: 'lmstudio-api', type: 'api', enabled: true, endpoint: 'http://127.0.0.1:1234' };
+
+ const withFallback = (fallbackProvider) => createLocalEndpointSlotContext({
+ providers: [...ALL_PROVIDERS, SAME_SERVER_SIBLING],
+ activeProvider: CLOUD_PROVIDER,
+ isAvailable: (id) => id !== 'lmstudio-tui',
+ resolveFallback: () => fallbackProvider,
+ });
+
+ it('stays gated when the fallback lands on the SAME local server', () => {
+ // Different provider record, different host spelling, same GPU.
+ expect(withFallback(SAME_SERVER_SIBLING).resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui')))
+ .toBe(LOCAL_ENDPOINT);
+ });
+
+ it('ungates when the fallback is a cloud provider', () => {
+ expect(withFallback(CLOUD_PROVIDER).resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui'))).toBeNull();
+ });
+
+ it('gates on the FALLBACK endpoint when it is a different local server', () => {
+ expect(withFallback(OTHER_LOCAL_PROVIDER).resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui')))
+ .toBe(OTHER_LOCAL_ENDPOINT);
+ });
+
+ it('ungates when no fallback resolves at all', () => {
+ expect(withFallback(null).resolveLocalEndpoint(taskOnProvider('t', 'lmstudio-tui'))).toBeNull();
+ });
+
+ it('passes the task through so a task-level fallback pin is honored', () => {
+ // getFallbackProvider's first tier reads metadata.fallbackProvider /
+ // metadata.fallbackModel off the task; the context must hand them over.
+ const seen = [];
+ const slots = createLocalEndpointSlotContext({
+ providers: ALL_PROVIDERS,
+ activeProvider: CLOUD_PROVIDER,
+ isAvailable: () => false,
+ resolveFallback: (primaryId, providersMap, task) => { seen.push({ primaryId, task }); return null; },
+ });
+ slots.resolveLocalEndpoint({ id: 't', metadata: { provider: 'lmstudio-tui', fallbackProvider: 'ollama-local' } });
+
+ expect(seen).toHaveLength(1);
+ expect(seen[0].primaryId).toBe('lmstudio-tui');
+ expect(seen[0].task.metadata.fallbackProvider).toBe('ollama-local');
+ });
+});
+
+describe('readEndpointCapacity (#4834)', () => {
+ beforeEach(() => __resetLocalEndpointSpawnReservations());
+
+ const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider: CLOUD_PROVIDER, limit: 1 });
+ const runningOn = (providerId, taskId) => ({ status: 'running', taskId, metadata: { providerId } });
+
+ it('counts a running agent against its endpoint', () => {
+ const capacity = readEndpointCapacity(LOCAL_ENDPOINT, { a: runningOn('lmstudio-tui', 'task-a') }, slots);
+ expect(capacity).toMatchObject({ inFlight: 1, limit: 1, atCapacity: true });
+ });
+
+ it('excludes the dispatching task\'s OWN agent so Run-now can supersede a zombie', () => {
+ // forceSpawnTask deliberately supersedes a `running` holder older than the
+ // spawn grace — that is the documented recovery for an agent whose PTY died
+ // without a close handler. Counting the zombie would make the one recovery
+ // the route exists to provide unreachable at a limit of 1.
+ const agents = { a: runningOn('lmstudio-tui', 'task-stuck') };
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, agents, slots, { ignoreTaskId: 'task-stuck' }).atCapacity).toBe(false);
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, agents, slots, { ignoreTaskId: 'other-task' }).atCapacity).toBe(true);
+ });
+
+ it('does not double-count a reservation whose agent already registered', () => {
+ // registerAgent flips the record to `running` well before spawnAgentForTask
+ // returns, so for the whole PTY-launch window the same agent is both in the
+ // running tally and holding its reservation.
+ reserveLocalEndpointSpawn(LOCAL_ENDPOINT, 'task-a');
+ const agents = { a: runningOn('lmstudio-tui', 'task-a') };
+
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, agents, slots).inFlight).toBe(1);
+ });
+
+ it('still counts a reservation that has NOT registered yet', () => {
+ reserveLocalEndpointSpawn(LOCAL_ENDPOINT, 'task-b');
+ const agents = { a: runningOn('lmstudio-tui', 'task-a') };
+
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, agents, slots).inFlight).toBe(2);
+ });
+
+ it('counts an anonymous reservation (no task id) unconditionally', () => {
+ reserveLocalEndpointSpawn(LOCAL_ENDPOINT, null);
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, {}, slots).inFlight).toBe(1);
+ });
+
+ it('ignores agents on other endpoints and non-running agents', () => {
+ const agents = {
+ a: runningOn('ollama-local', 'task-a'),
+ b: runningOn('anthropic', 'task-b'),
+ c: { status: 'completed', taskId: 'task-c', metadata: { providerId: 'lmstudio-tui' } },
+ };
+ expect(readEndpointCapacity(LOCAL_ENDPOINT, agents, slots).inFlight).toBe(0);
+ });
+});
+
// ─── Source-level regression guards ────────────────────────────────────────
//
// These pin two structural invariants of the production code that the
@@ -1255,15 +1391,24 @@ describe('cos.js source — priority + capacity invariants', () => {
.toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));
});
+ it('forceSpawnTask excludes the task\'s own zombie agent from the tally (#4834)', () => {
+ // The route deliberately supersedes a stale `running` holder — counting it
+ // would make that recovery unreachable at a limit of 1.
+ const forceFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function forceSpawnTask'));
+ expect(forceFn).toMatch(/localEndpointCapacityError\(resolution\.provider,\s*state\.agents,\s*taskId\)/);
+ });
+
it('the gate ignores an UNAVAILABLE provider so a held task cannot starve (#4834)', () => {
// A saturated local provider that is down is not where the task lands —
// spawn swaps it for a fallback. Holding on it would wait on a GPU the task
// never touches, with nothing to clear the hold.
const SLOTS_SRC = readFileSync(join(__dirname, 'cosLocalEndpointSlots.js'), 'utf-8');
const ctxFn = extractFnBody(SLOTS_SRC, SLOTS_SRC.indexOf('export function createLocalEndpointSlotContext'));
- expect(ctxFn).toMatch(/if \(!isAvailable\(provider\.id\)\) return null;/);
+ expect(ctxFn).toMatch(/isAvailable\(primary\.id\)\s*\?\s*primary\s*:\s*resolveFallback\(/);
expect(SLOTS_SRC, 'the live context must use the real provider-status predicate')
.toMatch(/isAvailable:\s*isProviderAvailable/);
+ expect(SLOTS_SRC, 'and the REAL fallback resolver, so the prediction cannot drift from spawn')
+ .toMatch(/getFallbackProvider\(/);
});
it('Priority 0 opts out of the local-endpoint cap so a Run is never discarded (#4834)', () => {
diff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.js
index 21450852f7..e08d097b46 100644
--- a/server/services/cosLocalEndpointSlots.js
+++ b/server/services/cosLocalEndpointSlots.js
@@ -24,8 +24,7 @@
import { isLocalEndpoint, LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';
import { listProviders, getActiveProvider } from './providers.js';
-import { isProviderAvailable } from './providerStatus.js';
-import { countRunningAgentsByLocalEndpoint } from './cosDequeue.js';
+import { isProviderAvailable, getFallbackProvider } from './providerStatus.js';
// One knob governs both paths — no new config key. A local box beefy enough to
// hold N model contexts lifts LOCAL_LLM_MAX_CONCURRENCY and gets N agent slots
@@ -42,10 +41,30 @@ export const LOCAL_ENDPOINT_AGENT_LIMIT = LOCAL_LLM_MAX_CONCURRENCY;
*
* Not gated on `provider.type === 'api'` (unlike promptRunner's request gate):
* a TUI provider pointed at a local LM Studio IS the case this exists for.
+ *
+ * The return value is a NORMALIZED SLOT KEY (`localhost:<port>`), not the raw
+ * string — see `LOCAL_SLOT_KEY_RE`. It is only ever used as a Map key and in the
+ * queued-no-slot log line.
*/
export function localEndpointOfProvider(provider) {
- const endpoint = provider?.endpoint;
- return isLocalEndpoint(endpoint) ? endpoint.trim() : null;
+ return localSlotKey(provider?.endpoint);
+}
+
+// Host+port identifies the model server; the scheme, path (`/v1`) and host
+// SPELLING do not. The shipped catalog already mixes spellings — `lmstudio` is
+// seeded at `http://localhost:1234/v1` while everything else uses `127.0.0.1` —
+// so keying on the raw string would give one LM Studio process two independent
+// caps and let two agents onto the same GPU, the exact OOM #4834 prevents.
+// Every loopback host collapses onto one key; the port keeps distinct local
+// servers apart.
+const LOCAL_SLOT_KEY_RE = /^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(?::(\d+))?(?:[/?#]|$)/i;
+
+/** The slot key for `endpoint`, or null when it is remote/absent/unparseable. */
+function localSlotKey(endpoint) {
+ if (!isLocalEndpoint(endpoint)) return null;
+ const match = endpoint.trim().match(LOCAL_SLOT_KEY_RE);
+ if (!match) return null;
+ return match[1] ? `localhost:${match[1]}` : 'localhost';
}
/**
@@ -58,20 +77,26 @@ export function localEndpointOfProvider(provider) {
* - `resolveLocalEndpoint(task)` — the endpoint a QUEUED task would land on.
* Mirrors `resolveAgentProviderAndModel`: a `metadata.provider` pin wins, an
* unknown pin falls back to the active provider, and an UNAVAILABLE provider
- * resolves to null because spawn will swap it for a fallback (often cloud) —
- * gating on it would hold the task behind a GPU it is never going to touch,
- * with nothing to clear the hold. A runtime fallback swap after that point
- * can still move a run: this is avoidance, not a guarantee, and
- * promptRunner's gate plus the OOM nudge/fail-over remain the recovery half.
- *
- * `isAvailable` is injected (rather than imported) so this stays pure and a
- * test can drive the real resolver without provider-status module state.
+ * is followed through the SAME `getFallbackProvider` spawn uses. Following
+ * the swap matters in both directions: gating on a benched provider would
+ * hold the task behind a GPU it never touches (nothing would clear the hold),
+ * while ignoring the swap entirely would drop the cap exactly when the
+ * endpoint is unhealthy — the shipped catalog has four providers sharing
+ * `127.0.0.1:18021`, so a fallback commonly lands on the same server. A
+ * RUNTIME fallback after this point can still move a run: this is avoidance,
+ * not a guarantee, and promptRunner's gate plus the OOM nudge/fail-over
+ * remain the recovery half.
+ *
+ * `isAvailable` / `resolveFallback` are injected (rather than imported) so this
+ * stays pure and a test can drive the real resolver without provider-status
+ * module state.
*/
export function createLocalEndpointSlotContext({
providers = [],
activeProvider = null,
limit = LOCAL_ENDPOINT_AGENT_LIMIT,
isAvailable = () => true,
+ resolveFallback = () => null,
} = {}) {
const byId = new Map();
for (const provider of providers) {
@@ -80,6 +105,9 @@ export function createLocalEndpointSlotContext({
if (activeProvider?.id && !byId.has(activeProvider.id)) byId.set(activeProvider.id, activeProvider);
const endpointById = (id) => localEndpointOfProvider(byId.get(id));
+ // `getFallbackProvider` indexes its providers arg BY ID, so hand it a map —
+ // not the array (mirrors the same note in promptRunner.js / agentProviderResolution.js).
+ const providersMap = Object.fromEntries(byId);
// The provider a queued task would be resolved onto, before the availability
// check below. An unknown pin falls through to the active provider, exactly
@@ -102,14 +130,17 @@ export function createLocalEndpointSlotContext({
return providerId ? endpointById(providerId) : null;
},
resolveLocalEndpoint: (task) => {
- const provider = providerForTask(task);
- if (!provider?.id) return null;
+ const primary = providerForTask(task);
+ if (!primary?.id) return null;
// An unavailable provider is NOT where this task lands — spawn swaps it
- // for a fallback. Holding the task at this endpoint anyway would starve
- // it: the fallback it actually wants may be cloud, and nothing about the
- // busy GPU would ever clear the hold.
- if (!isAvailable(provider.id)) return null;
- return localEndpointOfProvider(provider);
+ // for a fallback, which may be cloud (gating would starve the task behind
+ // a GPU it never touches) or may be another provider on the SAME local
+ // server (ignoring it would drop the cap when the endpoint is unhealthy).
+ // Follow the real resolver rather than guessing either way.
+ const effective = isAvailable(primary.id)
+ ? primary
+ : resolveFallback(primary.id, providersMap, task);
+ return localEndpointOfProvider(effective);
},
};
}
@@ -124,11 +155,22 @@ export function createLocalEndpointSlotContext({
export async function buildLocalEndpointSlotContext() {
const providers = await listProviders();
const activeProvider = await getActiveProvider().catch(() => null);
- return createLocalEndpointSlotContext({ providers, activeProvider, isAvailable: isProviderAvailable });
+ return createLocalEndpointSlotContext({
+ providers,
+ activeProvider,
+ isAvailable: isProviderAvailable,
+ // The REAL resolver spawn uses, so the prediction can't drift from it.
+ resolveFallback: (primaryId, providersMap, task) => getFallbackProvider(
+ primaryId,
+ providersMap,
+ task?.metadata?.fallbackProvider ?? null,
+ task?.metadata?.fallbackModel ?? null
+ )?.provider ?? null,
+ });
}
// ── In-flight spawn reservations ───────────────────────────────────────────
-// A dispatched task is invisible to `countRunningAgentsByLocalEndpoint` until
+// A dispatched task is invisible to the running-agent tally until
// its agent record reaches `running` — a window several awaits wide (provider
// resolution, prompt build, worktree setup, PTY spawn). Two `task:ready`
// dispatches landing inside that window would both read the same snapshot and
@@ -139,31 +181,58 @@ export async function buildLocalEndpointSlotContext() {
// in-process re-entrancy guard over one server's own dispatch loop, not a
// defense against competing actors (see the Security Model in CLAUDE.md).
// Mirrors `spawningJobIds` in cosJobScheduler.js, which bridges the same gap.
-const pendingSpawnsByEndpoint = new Map();
+//
+// Each reservation carries its task id, because `registerAgent` flips the record
+// to `running` well BEFORE `spawnAgentForTask` returns: for the config + PTY
+// launch window one agent would otherwise be counted twice (running tally AND
+// reservation) and under-admit at limits above 1. Counting only reservations
+// whose task has no running agent yet removes the overlap exactly, without
+// releasing early and reopening the window the reservation exists to close.
+const pendingSpawnsByEndpoint = new Map(); // endpoint -> Map<token, taskId|null>
+let reservationSeq = 0;
const NOOP_RELEASE = () => {};
/**
- * Reserve an in-flight spawn slot on `endpoint`. Returns the release function,
- * which is idempotent so a double-release (a throw plus the `finally`) can't
- * drive the count negative and hand out a slot that is still occupied.
+ * Reserve an in-flight spawn slot on `endpoint` for `taskId`. Returns the
+ * release function, which is idempotent so a double-release (a throw plus the
+ * `finally`) can't free a slot that is still occupied.
*/
-export function reserveLocalEndpointSpawn(endpoint) {
+export function reserveLocalEndpointSpawn(endpoint, taskId = null) {
if (!endpoint) return NOOP_RELEASE;
- pendingSpawnsByEndpoint.set(endpoint, (pendingSpawnsByEndpoint.get(endpoint) || 0) + 1);
+ const token = ++reservationSeq;
+ let held = pendingSpawnsByEndpoint.get(endpoint);
+ if (!held) {
+ held = new Map();
+ pendingSpawnsByEndpoint.set(endpoint, held);
+ }
+ held.set(token, taskId);
let released = false;
return () => {
if (released) return;
released = true;
- const remaining = (pendingSpawnsByEndpoint.get(endpoint) || 1) - 1;
- if (remaining > 0) pendingSpawnsByEndpoint.set(endpoint, remaining);
- else pendingSpawnsByEndpoint.delete(endpoint);
+ const current = pendingSpawnsByEndpoint.get(endpoint);
+ if (!current) return;
+ current.delete(token);
+ if (current.size === 0) pendingSpawnsByEndpoint.delete(endpoint);
};
}
-/** Spawns dispatched at `endpoint` that have not yet reached `running`. */
-export function pendingLocalEndpointSpawns(endpoint) {
- return endpoint ? (pendingSpawnsByEndpoint.get(endpoint) || 0) : 0;
+/**
+ * Spawns dispatched at `endpoint` that have not yet reached `running`.
+ *
+ * `excludeTaskIds` drops reservations whose agent HAS already registered — the
+ * running tally counts those, and double-counting them under-admits.
+ */
+export function pendingLocalEndpointSpawns(endpoint, { excludeTaskIds = null } = {}) {
+ const held = endpoint ? pendingSpawnsByEndpoint.get(endpoint) : null;
+ if (!held) return 0;
+ if (!excludeTaskIds?.size) return held.size;
+ let count = 0;
+ for (const taskId of held.values()) {
+ if (!taskId || !excludeTaskIds.has(taskId)) count++;
+ }
+ return count;
}
/** Test hook — drop every outstanding reservation. */
@@ -193,17 +262,34 @@ export async function acquireLocalEndpointSpawnSlot(task, agents) {
const endpoint = slots.resolveLocalEndpoint(task);
if (!endpoint) return { ok: true, release: NOOP_RELEASE };
- const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots);
+ const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots, { ignoreTaskId: task?.id });
if (atCapacity) {
return { ok: false, reason: `local endpoint ${endpoint} is at capacity (${inFlight}/${limit})` };
}
- return { ok: true, release: reserveLocalEndpointSpawn(endpoint) };
+ return { ok: true, release: reserveLocalEndpointSpawn(endpoint, task?.id ?? null) };
}
-/** Running agents plus in-flight reservations on `endpoint`, against the cap. */
-function readEndpointCapacity(endpoint, agents, slots) {
- const running = countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)[endpoint] || 0;
- const inFlight = running + pendingLocalEndpointSpawns(endpoint);
+/**
+ * Running agents plus in-flight reservations on `endpoint`, against the cap.
+ *
+ * `ignoreTaskId` excludes agents belonging to the task being dispatched. A task
+ * never competes with itself, and counting its own agent would break the two
+ * paths that deliberately re-dispatch one: `forceSpawnTask` supersedes a stale
+ * `running` holder (the documented "Run now" recovery for a zombie agent whose
+ * PTY died), and a retry re-runs the same task. Without this, that recovery is
+ * unreachable at a limit of 1 — the zombie it is meant to replace fills the slot.
+ */
+export function readEndpointCapacity(endpoint, agents, slots, { ignoreTaskId = null } = {}) {
+ const runningTaskIds = new Set();
+ let running = 0;
+ for (const agent of Object.values(agents || {})) {
+ if (agent.status !== 'running') continue;
+ if (ignoreTaskId && agent.taskId === ignoreTaskId) continue;
+ if (slots.endpointForAgent(agent) !== endpoint) continue;
+ running++;
+ if (agent.taskId) runningTaskIds.add(agent.taskId);
+ }
+ const inFlight = running + pendingLocalEndpointSpawns(endpoint, { excludeTaskIds: runningTaskIds });
return { inFlight, limit: slots.limit, atCapacity: inFlight >= slots.limit };
}
@@ -218,11 +304,11 @@ function readEndpointCapacity(endpoint, agents, slots) {
* it exists to prevent. Takes the post-fallback provider, so it is strictly more
* accurate than the queued-task prediction in `resolveLocalEndpoint`.
*/
-export async function localEndpointCapacityError(provider, agents) {
+export async function localEndpointCapacityError(provider, agents, taskId = null) {
const endpoint = localEndpointOfProvider(provider);
if (!endpoint) return null;
const slots = await buildLocalEndpointSlotContext();
- const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots);
+ const { atCapacity, inFlight, limit } = readEndpointCapacity(endpoint, agents, slots, { ignoreTaskId: taskId });
if (!atCapacity) return null;
return `Local inference endpoint ${endpoint} is at capacity (${inFlight}/${limit}) — wait for a running agent to finish`;
}