mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2746] [Issue]: activeGenerations race conditions (/abort & onClose unconditional delete) + sidecar local-model streaming defects #1387
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#1387
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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,
activeGenerationsis mutated by key without an identity check in both/abortand theonClosedisconnect 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)
/abortaborts the controller then synchronouslyactiveGenerations.delete(chatId)without identity check, freeing the key before the first handler unwinds. A fresh same-chat POST passes thehas(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.generate.routes.ts:10700-10726(unconditional delete 10724) vs identity-checkedreleaseActiveGeneration1172-1176; guard1162-1164.Sub-bug 2: onClose unconditional delete clobbers newer gen (LOW, race)
onCloserunsactiveGenerations.delete(chatId)keyed only by chatId. After/abortfrees 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/abortand the concurrency guard ("No active generation").generate.routes.ts:1354(handler 1345-1362); should callreleaseActiveGeneration.Sub-bug 3: Sidecar masks provider error as success on abort (MEDIUM, wrong-output)
handlePayloadthrows on a provider-error chunk; the catch returns the accumulated partial wheneveroptions.signal?.abortedis 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.flushTrailingPayloadalso swallows any error in the trailing buffer.sidecar-inference.service.ts:279-293/322-329/295-304.Sub-bug 4: Sidecar overflow-retry matches 'slot' (LOW, wrong-output)
isContextOverflowErrorregex includes bareslot/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).sidecar-inference.service.ts:109-112/342-349.Sub-bug 5: Sidecar idle-timeout truncated JSON misreported (LOW, crash/wrong-output)
analyzeScene;extractJsonPayloadthen throws the generic "Sidecar returned invalid JSON" instead of the actionable stall message. Degraded diagnostic, not a process crash.sidecar-inference.service.ts:322-329/160-169/602-622.Sub-bug 6: Sidecar size-cap throws and discards text (LOW, data-loss)
appendTextthrows 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.sidecar-inference.service.ts:271-277/322-329.Sub-bug 7: Sidecar download write-after-end race (LOW, crash-ish)
sendEventguards onlyif (reply.raw.destroyed) return;thenreply.raw.writewith no try/catch (TOCTOU);emitProgressiterates 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.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)
if (done) break;then resetsdownloadProgresswithout parsing residualbufferor flushing the decoder. Latent — server always ends frames with\n\n.sidecar.store.ts:167-235.Sub-bug 9: Sidecar inference parser strict 'data: ' / no flush (LOW, truncation)
streamChatCompletionusesstartsWith('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 emitdata:with a space — latent.sidecar-inference.service.ts:315-320/296-300.Suggested Fix
onClose(1354) and/abort(10724) call the identity-checkedreleaseActiveGeneration()(only delete when the stored controller === this request's), or gate new generations on an in-flight teardown promise.err.name === 'AbortError'or the stall message), and rethrow provider-error (llama-server stream error:) throws; don't swallow provider errors influshTrailingPayload.isContextOverflowErrorsoslot/ctxonly match overflow phrasing, and gate the overflow-retry on errors before any tokens streamed.sendEvent'sreply.raw.writein try/catch and eachemitProgresslistener in try/catch.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:
activeGenerationsis 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 usessignal.abortedas 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)
pnpm checkpnpm db:pushif any server/schema-adjacent change is touchedAffected files
packages/server/src/routes/generate.routes.tspackages/server/src/services/sidecar/sidecar-inference.service.tspackages/server/src/routes/sidecar.routes.tspackages/server/src/services/sidecar/sidecar-model.service.tspackages/client/src/stores/sidecar.store.tsAudit 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
stagingtree. Severity: MEDIUM.@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.