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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: serialize local LLM (Ollama/LM Studio) stage calls per endpoint
[._.]/ Adam Eivy029350a7f1af
diff --git a/server/lib/stageRunner.js b/server/lib/stageRunner.jsindex 04c585ca72..fd4102df5a 100644--- a/server/lib/stageRunner.js+++ b/server/lib/stageRunner.js@@ -126,6 +126,51 @@ const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?const isLocalEndpoint = (endpoint) =>typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());+// ── Local-backend concurrency gate ─────────────────────────────────────────+// A local LLM server (Ollama / LM Studio on localhost) runs inference on one+// GPU. Firing N stage calls at it concurrently (e.g. the 3 parallel+// canon-extraction kinds) gains nothing — the backend serializes on the GPU+// regardless — and, if the backend is configured for parallelism+// (OLLAMA_NUM_PARALLEL > 1), it loads N model contexts at once and can spike+// VRAM into an OOM/thrash. Cloud HTTP and CLI/TUI providers have no such+// constraint. So we cap concurrent IN-FLIGHT stage calls per LOCAL endpoint and+// queue the rest (FIFO). Default 1 (serialize); a beefy box can lift it with+// LOCAL_LLM_MAX_CONCURRENCY. Keyed by endpoint so two distinct local servers+// still run in parallel with each other.+export const LOCAL_LLM_MAX_CONCURRENCY = Math.max(1, Number(process.env.LOCAL_LLM_MAX_CONCURRENCY) || 1);+const localEndpointGates = new Map(); // endpoint -> { active: number, queue: (()=>void)[] }++function acquireLocalSlot(endpoint) {+ let gate = localEndpointGates.get(endpoint);+ if (!gate) { gate = { active: 0, queue: [] }; localEndpointGates.set(endpoint, gate); }+ if (gate.active < LOCAL_LLM_MAX_CONCURRENCY) {+ gate.active += 1;+ return Promise.resolve();+ }+ return new Promise((resolve) => { gate.queue.push(resolve); });+}++function releaseLocalSlot(endpoint) {+ const gate = localEndpointGates.get(endpoint);+ if (!gate) return;+ const next = gate.queue.shift();+ if (next) next(); // hand the slot straight to the next waiter (active unchanged)+ else gate.active = Math.max(0, gate.active - 1);+}++// Run `fn` under the local-endpoint gate when `provider` is a local API backend;+// otherwise run it immediately (cloud / CLI / TUI are unconstrained).+export async function withLocalConcurrencyGate(provider, fn) {+ const endpoint = provider?.endpoint;+ if (!(provider?.type === 'api' && isLocalEndpoint(endpoint))) return fn();+ await acquireLocalSlot(endpoint);+ try {+ return await fn();+ } finally {+ releaseLocalSlot(endpoint);+ }+}+// CLI/TUI providers (Claude Code, Codex, Antigravity) are frontier models;// non-local API providers are cloud. Local backends (ollama/lmstudio on// localhost) are the only genuinely small-window case.@@ -427,10 +472,10 @@ async function executeStagePrompt({ stage, label, prompt, options }) {// (runId / model / providerId) here so the persisted stage result points// at the run that actually produced the text — otherwise pipeline history// / restore links land on a failed record.- const runResult2 = await runPromptThroughProvider({+ const runResult2 = await withLocalConcurrencyGate(effectiveProvider, () => runPromptThroughProvider({provider: effectiveProvider, model: effectiveModel, prompt, source: options.source || 'staged-llm', runId,timeout: effectiveTimeout,- });+ }));const { text } = runResult2;let finalRunId = runId;let finalProvider = effectiveProvider;diff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.jsindex 1a3c9daaa3..826f2ec595 100644--- a/server/lib/stageRunner.test.js+++ b/server/lib/stageRunner.test.js@@ -34,6 +34,8 @@ const {knownModelContextWindow,knownProviderContextWindow,resolveStageContext,+ withLocalConcurrencyGate,+ LOCAL_LLM_MAX_CONCURRENCY,} = await import('./stageRunner.js');const apiProvider = (extra = {}) => ({@@ -511,3 +513,45 @@ describe('stageRunner — runStagedLLM dispatch', () => {);});});++describe('withLocalConcurrencyGate', () => {+ // Build a fn that records peak concurrency while it runs.+ const makeTracker = () => {+ const state = { active: 0, peak: 0 };+ const fn = () => {+ state.active += 1;+ state.peak = Math.max(state.peak, state.active);+ return new Promise((resolve) => setTimeout(() => { state.active -= 1; resolve('ok'); }, 5));+ };+ return { state, fn };+ };++ it('serializes concurrent calls to a LOCAL api endpoint (peak ≤ limit)', async () => {+ const provider = { type: 'api', endpoint: 'http://localhost:11434' };+ const { state, fn } = makeTracker();+ await Promise.all(Array.from({ length: 6 }, () => withLocalConcurrencyGate(provider, fn)));+ expect(state.peak).toBeLessThanOrEqual(LOCAL_LLM_MAX_CONCURRENCY);+ expect(LOCAL_LLM_MAX_CONCURRENCY).toBe(1); // default — serialized+ });++ it('does NOT gate a remote api endpoint (runs concurrently)', async () => {+ const provider = { type: 'api', endpoint: 'https://api.openai.com' };+ const { state, fn } = makeTracker();+ await Promise.all(Array.from({ length: 4 }, () => withLocalConcurrencyGate(provider, fn)));+ expect(state.peak).toBeGreaterThan(1); // ungated+ });++ it('does NOT gate CLI/TUI providers (no endpoint)', async () => {+ const provider = { type: 'cli', id: 'codex' };+ const { state, fn } = makeTracker();+ await Promise.all(Array.from({ length: 4 }, () => withLocalConcurrencyGate(provider, fn)));+ expect(state.peak).toBeGreaterThan(1);+ });++ it('releases the slot even when the gated fn throws (no deadlock)', async () => {+ const provider = { type: 'api', endpoint: 'http://127.0.0.1:1234' };+ await expect(withLocalConcurrencyGate(provider, () => Promise.reject(new Error('boom')))).rejects.toThrow('boom');+ // A subsequent call still acquires the freed slot and resolves.+ await expect(withLocalConcurrencyGate(provider, () => Promise.resolve('after'))).resolves.toBe('after');+ });+});