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([issue-905]): await drain on local-llm test stream to honor backpressure

Adam Eivy08af273f040b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c013b31bf0..813ae22d76 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -38,6 +38,7 @@
- **[issue-907] Internal: upgraded the server validation library to Zod 4** — Migrated the server's request-validation layer to the Zod 4 major release, preserving the exact accept/reject behavior of every existing rule (including a fix so partial-update saves no longer risk silently resetting fields you didn't touch). No user-facing change.
- **[issue-907] Internal: upgraded the web build tooling to Vite 8** — Moved the client to the Vite 8 major release (and its new Rust-based bundler) for faster builds. The app builds, runs, and tests identically. No user-facing change.
- **[issue-951] Internal: moved the web build to Vite 8's native chunking API** — Switched the client's vendor-chunk splitting from the older Rollup-compatibility form to Vite 8's canonical equivalent, dropping reliance on a compatibility shim that a future Vite may remove. The same vendor bundles are produced. No user-facing change.
+- **[issue-905] Internal: local-LLM playground stream honors socket backpressure** — The streaming model-test endpoint now pauses upstream reading when a slow client can't keep up, instead of buffering the whole response in memory. No user-facing change.
## Fixed
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 8e454130aa..d1b97d347f 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -251,9 +251,28 @@ router.post('/test/stream', asyncHandler(async (req, res) => {
// Once headers are flushed the response is "in stream mode" — never throw past
// here. A write after the client disconnected can throw ERR_STREAM_WRITE_AFTER_END;
// treat any failure as a dead socket and drop the frame.
- const write = (frame) => {
+ //
+ // Honour socket backpressure (mirrors ask.js): when `res.write` returns false the
+ // kernel/send buffer is full, so await the next `drain` (or `close`) before letting
+ // the producer queue more NDJSON. A fast local model writing to a slow reader would
+ // otherwise buffer the whole response in memory. The producer awaits `onToken`, so
+ // returning this promise actually pauses the upstream read until the socket catches
+ // up. Both listeners are torn down on settle so a disconnect mid-drain can't leak them.
+ const write = async (frame) => {
if (res.writableEnded || res.destroyed) return
- try { res.write(`${JSON.stringify(frame)}\n`) } catch { /* client gone */ }
+ let writeOk
+ try { writeOk = res.write(`${JSON.stringify(frame)}\n`) } catch { return /* client gone */ }
+ if (!writeOk) {
+ await new Promise((resolve) => {
+ const settle = () => {
+ res.off('drain', settle)
+ res.off('close', settle)
+ resolve()
+ }
+ res.once('drain', settle)
+ res.once('close', settle)
+ })
+ }
}
// `runLocalLlmTest` resolves for in-stream failures, but can still THROW before
@@ -263,14 +282,14 @@ router.post('/test/stream', asyncHandler(async (req, res) => {
const result = await runLocalLlmTest({
...body,
signal: abortSignalFromResponse(res),
- onToken: (delta) => { if (delta) write({ type: 'token', delta }) },
+ onToken: (delta) => (delta ? write({ type: 'token', delta }) : undefined),
}).catch((err) => ({
backend: body.backend,
modelId: body.modelId,
error: err?.message || 'Local LLM test failed',
text: '',
}))
- write({ type: 'result', result })
+ await write({ type: 'result', result })
res.end()
}))
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index a1b7998521..431e66199f 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -133,7 +133,7 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
throw new Error(`Provider returned a non-JSON response (${response.status})`);
}
const text = data.choices?.[0]?.message?.content || '';
- if (text) onChunk(text);
+ if (text) await onChunk(text);
return text;
}
@@ -143,12 +143,12 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
let output = '';
let reasoning = '';
- const consumeLine = (rawLine) => {
+ const consumeLine = async (rawLine) => {
const delta = extractStreamDelta(rawLine);
if (!delta) return;
if (delta.content) {
output += delta.content;
- onChunk(delta.content);
+ await onChunk(delta.content);
}
if (delta.reasoning) reasoning += delta.reasoning;
};
@@ -165,9 +165,9 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
- for (const line of lines) consumeLine(line);
+ for (const line of lines) await consumeLine(line);
}
- if (buffer.trim()) consumeLine(buffer);
+ if (buffer.trim()) await consumeLine(buffer);
} catch (err) {
err.partialOutput = resolvePartialOutput({ output, reasoning });
throw err;
@@ -176,7 +176,7 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
}
const resolved = resolvePartialOutput({ output, reasoning });
- if (resolved && resolved !== output) onChunk(resolved);
+ if (resolved && resolved !== output) await onChunk(resolved);
return resolved;
}
@@ -232,7 +232,11 @@ export async function runLocalLlmTest({
signal,
onChunk: (chunk) => {
if (!firstChunkAt && chunk) firstChunkAt = Date.now();
- if (chunk) onToken?.(chunk);
+ // Await the consumer so socket backpressure from the streaming route
+ // propagates back up to the upstream read loop (pauses reading until the
+ // client drains). Non-streaming callers pass no onToken, so this no-ops.
+ if (chunk) return onToken?.(chunk);
+ return undefined;
},
}).finally(() => clearTimeout(timeoutHandle));
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 0a5b28a78f..4d14f691f0 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -179,6 +179,43 @@ describe('runLocalLlmTest timeout/abort contract', () => {
expect(result.text).toBe('Hello');
});
+ it('awaits onToken before reading the next upstream chunk (honours backpressure)', async () => {
+ const reader = makeReader([sse({ content: 'a' }), sse({ content: 'b' })], { abort: false });
+ stubStream(reader);
+
+ // A slow consumer (e.g. the streaming route awaiting a socket `drain`): hold
+ // the first token's promise open and assert the read loop has NOT pulled the
+ // next chunk until we let it settle. This is what makes the route's drain-await
+ // actually pause upstream reading instead of buffering unbounded.
+ let releaseFirst;
+ const firstHeld = new Promise((resolve) => { releaseFirst = resolve; });
+ let firstSeen;
+ const firstArrived = new Promise((resolve) => { firstSeen = resolve; });
+ const tokens = [];
+ const onToken = vi.fn((delta) => {
+ tokens.push(delta);
+ if (tokens.length === 1) { firstSeen(); return firstHeld; }
+ return undefined;
+ });
+
+ const promise = runLocalLlmTest({
+ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000, onToken,
+ });
+
+ // Wait until the first token is being handled (it's held open below). At that
+ // point only one read has resolved a line — the second chunk must NOT have been
+ // requested yet, since the loop is parked awaiting our held onToken. This is what
+ // makes the route's drain-await actually pause upstream reading.
+ await firstArrived;
+ expect(tokens).toEqual(['a']);
+ expect(reader.read).toHaveBeenCalledTimes(1);
+
+ releaseFirst();
+ const result = await promise;
+ expect(tokens).toEqual(['a', 'b']);
+ expect(result.text).toBe('ab');
+ });
+
it('forwards a client cancel onto the upstream fetch so the reader tears down early', async () => {
let capturedSignal = null;
global.fetch = vi.fn().mockImplementation((_url, init) => {