[GH-ISSUE #2746] [Issue]: activeGenerations race conditions (/abort & onClose unconditional delete) + sidecar local-model streaming defects #1387

Closed
opened 2026-10-21 05:32:48 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @kolacheee on GitHub (Jun 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2746

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Two families share a root cause of treating per-chat/per-request state as a simple key without identity/abort discipline. First, activeGenerations is mutated by key without an identity check in both /abort and the onClose disconnect handler, opening a same-chat concurrency window where a newer generation becomes untrackable (lost stop control + concurrency-guard bypass). Second, the local-model sidecar inference service has several streaming defects: a mid-stream provider error is masked as a successful partial when the request is also aborting; an overly-broad overflow-retry regex re-sends the whole request on transient 'slot' errors (double inference + masked error); an idle-timeout returns truncated partial JSON for structured-output calls (misreported as invalid JSON); the size-cap guard throws and discards already-streamed text; the download SSE writer has an unguarded write-after-end; and the sidecar's own parser has the strict-data: /no-flush robustness gaps (latent on tracker/scene paths only).

Sub-bug 1: /abort deletes before teardown (LOW, race)

  • How it breaks: /abort aborts the controller then synchronously activeGenerations.delete(chatId) without identity check, freeing the key before the first handler unwinds. A fresh same-chat POST passes the has(chatId) guard and registers a new controller while the first run's late DB writes / reasoning cache are still pending, interleaving writes for the same chat.
  • Trace: generate.routes.ts:10700-10726 (unconditional delete 10724) vs identity-checked releaseActiveGeneration 1172-1176; guard 1162-1164.

Sub-bug 2: onClose unconditional delete clobbers newer gen (LOW, race)

  • How it breaks: onClose runs activeGenerations.delete(chatId) keyed only by chatId. After /abort frees the key and Gen B registers, the queued socket-close for the aborted Gen A fires onClose-A, deleting B's entry. B keeps streaming but is invisible to /abort and the concurrency guard ("No active generation").
  • Trace: generate.routes.ts:1354 (handler 1345-1362); should call releaseActiveGeneration.

Sub-bug 3: Sidecar masks provider error as success on abort (MEDIUM, wrong-output)

  • How it breaks: handlePayload throws on a provider-error chunk; the catch returns the accumulated partial whenever options.signal?.aborted is true REGARDLESS of whether the throw was an abort or a real provider error. A disconnect coinciding with a llama-server error frame discards the error and returns a truncated tracker/scene result as success. flushTrailingPayload also swallows any error in the trailing buffer.
  • Trace: sidecar-inference.service.ts:279-293/322-329/295-304.

Sub-bug 4: Sidecar overflow-retry matches 'slot' (LOW, wrong-output)

  • How it breaks: isContextOverflowError regex includes bare slot/ctx, matching transient llama.cpp slot-scheduling errors; the catch then re-sends the full request at half the token budget (without re-fitting the prompt), running inference twice and masking the real error. Affects analyzeScene/runTrackerPrompt (not main chat).
  • Trace: sidecar-inference.service.ts:109-112/342-349.

Sub-bug 5: Sidecar idle-timeout truncated JSON misreported (LOW, crash/wrong-output)

  • How it breaks: On a stall the partial-usable branch returns truncated JSON for analyzeScene; extractJsonPayload then throws the generic "Sidecar returned invalid JSON" instead of the actionable stall message. Degraded diagnostic, not a process crash.
  • Trace: sidecar-inference.service.ts:322-329/160-169/602-622.

Sub-bug 6: Sidecar size-cap throws and discards text (LOW, data-loss)

  • How it breaks: appendText throws once accumulated length exceeds 4,000,000 chars; the message matches neither abort nor stall, so the catch rethrows and discards the buffered content instead of truncating. Near-unreachable (output bounded by max_tokens) and internal-only.
  • Trace: sidecar-inference.service.ts:271-277/322-329.

Sub-bug 7: Sidecar download write-after-end race (LOW, crash-ish)

  • How it breaks: sendEvent guards only if (reply.raw.destroyed) return; then reply.raw.write with no try/catch (TOCTOU); emitProgress iterates listeners with no per-listener try/catch, so a throw escapes into the active download. Ultimately caught (no backend crash; GGUF temp file unlinked, no corruption), but inconsistent with the hardened generate/retry routes.
  • Trace: sidecar.routes.ts:229-243; sidecar-model.service.ts:451-456.

Sub-bug 8: Sidecar download client parser drops trailing buffer/no flush (LOW, truncation)

  • How it breaks: if (done) break; then resets downloadProgress without parsing residual buffer or flushing the decoder. Latent — server always ends frames with \n\n.
  • Trace: sidecar.store.ts:167-235.

Sub-bug 9: Sidecar inference parser strict 'data: ' / no flush (LOW, truncation)

  • How it breaks: streamChatCompletion uses startsWith('data: ') + slice(6) and no trailing flush; brittler than the OpenAI parser. Only powers analyzeScene/runTrackerPrompt/runTestMessage (main local chat goes through OpenAIProvider's robust parser), and llama.cpp/MLX emit data: with a space — latent.
  • Trace: sidecar-inference.service.ts:315-320/296-300.

Suggested Fix

  • Have onClose (1354) and /abort (10724) call the identity-checked releaseActiveGeneration() (only delete when the stored controller === this request's), or gate new generations on an in-flight teardown promise.
  • In the sidecar catch, only return a partial when the thrown error is itself an abort/stall (err.name === 'AbortError' or the stall message), and rethrow provider-error (llama-server stream error:) throws; don't swallow provider errors in flushTrailingPayload.
  • Tighten isContextOverflowError so slot/ctx only match overflow phrasing, and gate the overflow-retry on errors before any tokens streamed.
  • For structured-output (json_schema) sidecar calls, rethrow the stall error instead of returning a partial; for the size cap, stop reading and return the accumulated text (graceful truncation).
  • Wrap sendEvent's reply.raw.write in try/catch and each emitProgress listener in try/catch.
  • Align both sidecar parsers (client store + inference service) to permissive startsWith('data:') + slice/trim, add a final decoder flush + residual-buffer drain.

Root-cause throughline

Both families stem from treating per-key state and stream termination as simple, single-owner operations: activeGenerations is deleted by chatId without verifying ownership (so a stale disconnect clobbers a newer run), and the sidecar inference loop conflates abort, provider-error, overflow, size-cap, and idle-stall into one catch that uses signal.aborted as a blanket "return partial" signal — masking genuine failures — while its parser repeats the same strict-data: /no-flush copy as everywhere else.

Verification checklist (leave all UNCHECKED)

  • Manually verify: Stop then immediately re-send in the same chat keeps the new generation trackable/cancellable
  • Manually verify: a local-model provider error during a disconnect surfaces as an error, not a truncated success
  • Manually verify: a transient llama.cpp 'slot' error is not treated as context overflow / double-generated
  • Manually verify: an analyzeScene stall reports a timeout, not 'Sidecar returned invalid JSON'
  • Manually verify: a model download with a client disconnect mid-progress does not throw an unhandled write-after-end
  • Run pnpm check
  • Run pnpm db:push if any server/schema-adjacent change is touched

Affected files

  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/services/sidecar/sidecar-inference.service.ts
  • packages/server/src/routes/sidecar.routes.ts
  • packages/server/src/services/sidecar/sidecar-model.service.ts
  • packages/client/src/stores/sidecar.store.ts

Audit provenance

Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged staging tree. Severity: MEDIUM.

AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2746 Originally assigned to: @SpicyMarinara on GitHub. ## Summary Two families share a root cause of treating per-chat/per-request state as a simple key without identity/abort discipline. First, `activeGenerations` is mutated by key without an identity check in both `/abort` and the `onClose` disconnect handler, opening a same-chat concurrency window where a newer generation becomes untrackable (lost stop control + concurrency-guard bypass). Second, the local-model sidecar inference service has several streaming defects: a mid-stream provider error is masked as a successful partial when the request is also aborting; an overly-broad overflow-retry regex re-sends the whole request on transient 'slot' errors (double inference + masked error); an idle-timeout returns truncated partial JSON for structured-output calls (misreported as invalid JSON); the size-cap guard throws and discards already-streamed text; the download SSE writer has an unguarded write-after-end; and the sidecar's own parser has the strict-`data: `/no-flush robustness gaps (latent on tracker/scene paths only). ### Sub-bug 1: /abort deletes before teardown (LOW, race) - **How it breaks:** `/abort` aborts the controller then synchronously `activeGenerations.delete(chatId)` without identity check, freeing the key before the first handler unwinds. A fresh same-chat POST passes the `has(chatId)` guard and registers a new controller while the first run's late DB writes / reasoning cache are still pending, interleaving writes for the same chat. - **Trace:** `generate.routes.ts:10700-10726` (unconditional delete 10724) vs identity-checked `releaseActiveGeneration` `1172-1176`; guard `1162-1164`. ### Sub-bug 2: onClose unconditional delete clobbers newer gen (LOW, race) - **How it breaks:** `onClose` runs `activeGenerations.delete(chatId)` keyed only by chatId. After `/abort` frees the key and Gen B registers, the queued socket-close for the aborted Gen A fires onClose-A, deleting B's entry. B keeps streaming but is invisible to `/abort` and the concurrency guard ("No active generation"). - **Trace:** `generate.routes.ts:1354` (handler 1345-1362); should call `releaseActiveGeneration`. ### Sub-bug 3: Sidecar masks provider error as success on abort (MEDIUM, wrong-output) - **How it breaks:** `handlePayload` throws on a provider-error chunk; the catch returns the accumulated partial whenever `options.signal?.aborted` is true REGARDLESS of whether the throw was an abort or a real provider error. A disconnect coinciding with a llama-server error frame discards the error and returns a truncated tracker/scene result as success. `flushTrailingPayload` also swallows any error in the trailing buffer. - **Trace:** `sidecar-inference.service.ts:279-293/322-329/295-304`. ### Sub-bug 4: Sidecar overflow-retry matches 'slot' (LOW, wrong-output) - **How it breaks:** `isContextOverflowError` regex includes bare `slot`/`ctx`, matching transient llama.cpp slot-scheduling errors; the catch then re-sends the full request at half the token budget (without re-fitting the prompt), running inference twice and masking the real error. Affects analyzeScene/runTrackerPrompt (not main chat). - **Trace:** `sidecar-inference.service.ts:109-112/342-349`. ### Sub-bug 5: Sidecar idle-timeout truncated JSON misreported (LOW, crash/wrong-output) - **How it breaks:** On a stall the partial-usable branch returns truncated JSON for `analyzeScene`; `extractJsonPayload` then throws the generic "Sidecar returned invalid JSON" instead of the actionable stall message. Degraded diagnostic, not a process crash. - **Trace:** `sidecar-inference.service.ts:322-329/160-169/602-622`. ### Sub-bug 6: Sidecar size-cap throws and discards text (LOW, data-loss) - **How it breaks:** `appendText` throws once accumulated length exceeds 4,000,000 chars; the message matches neither abort nor stall, so the catch rethrows and discards the buffered content instead of truncating. Near-unreachable (output bounded by max_tokens) and internal-only. - **Trace:** `sidecar-inference.service.ts:271-277/322-329`. ### Sub-bug 7: Sidecar download write-after-end race (LOW, crash-ish) - **How it breaks:** `sendEvent` guards only `if (reply.raw.destroyed) return;` then `reply.raw.write` with no try/catch (TOCTOU); `emitProgress` iterates listeners with no per-listener try/catch, so a throw escapes into the active download. Ultimately caught (no backend crash; GGUF temp file unlinked, no corruption), but inconsistent with the hardened generate/retry routes. - **Trace:** `sidecar.routes.ts:229-243`; `sidecar-model.service.ts:451-456`. ### Sub-bug 8: Sidecar download client parser drops trailing buffer/no flush (LOW, truncation) - **How it breaks:** `if (done) break;` then resets `downloadProgress` without parsing residual `buffer` or flushing the decoder. Latent — server always ends frames with `\n\n`. - **Trace:** `sidecar.store.ts:167-235`. ### Sub-bug 9: Sidecar inference parser strict 'data: ' / no flush (LOW, truncation) - **How it breaks:** `streamChatCompletion` uses `startsWith('data: ')` + `slice(6)` and no trailing flush; brittler than the OpenAI parser. Only powers analyzeScene/runTrackerPrompt/runTestMessage (main local chat goes through OpenAIProvider's robust parser), and llama.cpp/MLX emit `data: ` with a space — latent. - **Trace:** `sidecar-inference.service.ts:315-320/296-300`. ## Suggested Fix - Have `onClose` (`1354`) and `/abort` (`10724`) call the identity-checked `releaseActiveGeneration()` (only delete when the stored controller === this request's), or gate new generations on an in-flight teardown promise. - In the sidecar catch, only return a partial when the thrown error is itself an abort/stall (`err.name === 'AbortError'` or the stall message), and rethrow provider-error (`llama-server stream error:`) throws; don't swallow provider errors in `flushTrailingPayload`. - Tighten `isContextOverflowError` so `slot`/`ctx` only match overflow phrasing, and gate the overflow-retry on errors before any tokens streamed. - For structured-output (json_schema) sidecar calls, rethrow the stall error instead of returning a partial; for the size cap, stop reading and return the accumulated text (graceful truncation). - Wrap `sendEvent`'s `reply.raw.write` in try/catch and each `emitProgress` listener in try/catch. - Align both sidecar parsers (client store + inference service) to permissive `startsWith('data:')` + slice/trim, add a final decoder flush + residual-buffer drain. ## Root-cause throughline Both families stem from treating per-key state and stream termination as simple, single-owner operations: `activeGenerations` is deleted by chatId without verifying ownership (so a stale disconnect clobbers a newer run), and the sidecar inference loop conflates abort, provider-error, overflow, size-cap, and idle-stall into one catch that uses `signal.aborted` as a blanket "return partial" signal — masking genuine failures — while its parser repeats the same strict-`data: `/no-flush copy as everywhere else. ## Verification checklist (leave all UNCHECKED) - [ ] Manually verify: Stop then immediately re-send in the same chat keeps the new generation trackable/cancellable - [ ] Manually verify: a local-model provider error during a disconnect surfaces as an error, not a truncated success - [ ] Manually verify: a transient llama.cpp 'slot' error is not treated as context overflow / double-generated - [ ] Manually verify: an analyzeScene stall reports a timeout, not 'Sidecar returned invalid JSON' - [ ] Manually verify: a model download with a client disconnect mid-progress does not throw an unhandled write-after-end - [ ] Run `pnpm check` - [ ] Run `pnpm db:push` if any server/schema-adjacent change is touched --- ### Affected files - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/services/sidecar/sidecar-inference.service.ts` - `packages/server/src/routes/sidecar.routes.ts` - `packages/server/src/services/sidecar/sidecar-model.service.ts` - `packages/client/src/stores/sidecar.store.ts` ### Audit provenance Found by a multi-agent static audit of the streaming/SSE subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged `staging` tree. Severity: **MEDIUM**. > AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 21, 2026):

Addressed on PR #2747. The activeGenerations race was already fixed here by keeping /abort entries registered until the route's identity-checked release and avoiding onClose deletion. Sidecar inference now distinguishes provider errors from abort/stall partials, keeps structured JSON stalls as actionable stall errors, tightens context-overflow detection so transient slot errors do not trigger retry, gates overflow retry after streamed tokens, truncates size-cap output gracefully, and parses SSE with tolerant data: handling plus decoder flush. Sidecar download SSE writes/listeners are guarded, and the client download parser now handles data: without a space plus trailing-buffer/decoder flush. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.

<!-- gh-comment-id:4763254232 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. The activeGenerations race was already fixed here by keeping /abort entries registered until the route's identity-checked release and avoiding onClose deletion. Sidecar inference now distinguishes provider errors from abort/stall partials, keeps structured JSON stalls as actionable stall errors, tightens context-overflow detection so transient slot errors do not trigger retry, gates overflow retry after streamed tokens, truncates size-cap output gracefully, and parses SSE with tolerant data: handling plus decoder flush. Sidecar download SSE writes/listeners are guarded, and the client download parser now handles data: without a space plus trailing-buffer/decoder flush. Deferred full pnpm validation until the end of the issue sweep, per maintainer request.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1387
No description provided.