mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2715] [Issue]: Local sidecar inference path diverges from the remote provider (malformed structured-output, dropped reasoning, wall-clock timeout, swallowed stream errors) #1359
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#1359
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/2715
Originally assigned to: @SpicyMarinara on GitHub.
Summary
The dedicated sidecar inference path (
sidecar-inference.service.ts—streamChatCompletion,analyzeScene,runTrackerPrompt) hand-rolls its own request body andfetchinstead of going through the auditedOpenAIProvider/llmFetchpath thatLocalSidecarProviderchat uses. As a result it diverges from the remote provider in many ways that break Game-Mode scene analysis and trackers for the no-API-key local user. These are the LOCAL equivalents of the remote structured-output / timeout / silent-failure bugs already filed against the remote pipeline.1. Malformed
response_formatdisables grammar-constrained JSON (high)How it breaks the pipeline:
analyzeSceneis the entire local scene-direction path. The grammar that should force valid JSON is never installed because theresponse_formatis shaped wrong, so the model free-forms prose and the downstream parse fails.Steps to replicate: Enable Game Mode scene analysis (default
useForGameScene: true) on the local sidecar (llama.cpp); trigger a scene. Observe intermittent HTTP 500Sidecar returned invalid JSONand no background/music/effects applied.Trace:
analyzeScenepassesresponseFormat: { type: "json_schema", schema: SCENE_ANALYSIS_SCHEMA }(sidecar-inference.service.ts:499-502).streamChatCompletionforwards it verbatim asresponse_format(sidecar-inference.service.ts:170) with no normalization. llama.cpp's server (tools/server/server-common.cpp) fortype == "json_schema"reads onlyresponse_format.json_schema.schema; a top-levelschemadefaults to{}(no grammar). Contrast the correct shape built by the OpenAI provider at openai.provider.ts:197 (json_schema: { name, schema, strict }). Unconstrained output then hitsextractJsonPayload(sidecar-inference.service.ts:112-122) which throws; route returns 500 (sidecar.routes.ts:370,433-437).Suggested Fix: Send
response_format: { type: "json_schema", json_schema: { name: "scene_analysis", schema: SCENE_ANALYSIS_SCHEMA, strict: true } }(or route scene analysis throughOpenAIProvider.normalizeChatCompletionsResponseFormat). For broad build compatibility,{ type: "json_object", schema: SCENE_ANALYSIS_SCHEMA }also works.2.
[DONE]returns before the reasoning fallback (medium)How it breaks the pipeline: When a thinking model emits its answer into
reasoning_contentand leavescontentempty, the function returns"", so scene analysis 500s and trackers return empty.Steps to replicate: Use a thinking/reasoning BYO GGUF, enable Native Tool Calls (so
--jinjaruns and llama.cpp separatesreasoning_content), and run scene analysis or a tracker. Output is empty even though the model produced a full answer in its reasoning channel.Trace: The SSE loop accumulates
contentandreasoningseparately (sidecar-inference.service.ts:213-214). Ondata: [DONE]it doesreturn content;(sidecar-inference.service.ts:203-204), bypassing the post-loop fallbacktrimmedContent || reasoning.trim()(238-243), which is therefore dead code in normal operation. Contrast openai.provider.ts whichbreaks on[DONE]and then flushes reasoning.Suggested Fix: On
[DONE]returncontent.trim() || reasoning.trim()(mirror lines 238-243) instead of raw un-trimmedcontent.3. Wall-clock 5-minute timeout truncates long generations and drops partials (high)
How it breaks the pipeline:
AbortSignal.timeout(5*60_000)is a wall-clock cap on the entire stream, not a TTFB/idle cap, so a healthy-but-slow CPU generation is killed mid-stream and the accumulatedcontentis discarded.Steps to replicate: On CPU-only local inference, run a large tracker (maxTokens up to 8192) that takes >5 min. Request fails with an opaque
AbortError/TimeoutError; already-streamed tokens are lost.Trace: sidecar-inference.service.ts:172 sets the only timeout as
AbortSignal.timeout(5 * 60_000). The read loop (190-219) has no try/catch aroundawait reader.read(), so the rejection propagates and abandonscontent(187). Contrast base-provider.ts:13-14 (bodyTimeout: 0, headersTimeout: 5min) used by the remote path to avoid killing long streams.Suggested Fix: Replace the wall-clock timeout with an idle/inter-chunk timeout reset on each successful
reader.read(), and wrap the loop so the accumulatedcontentis returned on abort instead of lost.4. Mid-stream error chunks silently swallowed (medium)
How it breaks the pipeline: When llama-server reports an error inside the SSE stream after a 200 (context overflow, slot unavailable, template error), the parser drops it and returns empty, masking the real cause as
Sidecar returned invalid JSON.Steps to replicate: Send a scene/tracker prompt that overflows the per-slot context; observe an empty result /
invalid JSON500 rather than the real overflow error.Trace: The loop does
const choice = parsed.choices?.[0]; if (!choice) continue;(sidecar-inference.service.ts:210-211) and a swallowingcatch {}(215-217); an error chunk ({"error":{...}}, nochoices) is dropped.contentstays empty;extractJsonPayload("")throws (112-122). Contrast openai.provider.ts:1012-1017 which extracts and throws the provider error.Suggested Fix: When a parsed chunk lacks
choices, extractparsed.error?.messageand throw it (sanitized), like the OpenAI provider; distinguish 'empty completion' from 'stream error'.5. No context fitting; oversized prompts hard-fail (medium)
How it breaks the pipeline: This path sends
messagesverbatim and never trims to context, unlike the provider path which runsfitMessagesToContext. A near-context scene/tracker prompt plusmax_tokensoverruns the per-slot window and llama-server rejects it.Steps to replicate: Submit a large scene narration (route allows up to 16000 chars) or tracker prompt (16000+16000 chars) with default
contextSize(8192); request 500s withScene analysis failed/Tracker inference failed, no recovery.Trace:
messages: options.messagesverbatim (sidecar-inference.service.ts:165);max_tokensclamped only against config (156), never against remaining context. Per-slot context is exactlycontextSize(--parallel 2,--ctx-size = contextSize*2, sidecar-launch-plan.ts:6,17). Contrast local-sidecar.provider.ts:21 →OpenAIProvider.fitMessagesToContext(openai.provider.ts:815). Route caps at sidecar.routes.ts:290-291,441-442.Suggested Fix: Run
fitMessagesToContext(messages, { maxContext: config.contextSize, maxTokens })before building the body and capmax_tokensto remaining context; retry once with reduced budget on a context-overflow error.6. Scene/tracker token budget silently capped by chat 'Max Response Tokens' (medium)
How it breaks the pipeline:
streamChatCompletionclamps the per-call budget down toconfig.maxTokens, so the chat-reply-length knob also governs structured scene/tracker calls that need their full budget to emit complete JSON.Steps to replicate: Lower 'Max Response Tokens' to e.g. 512 to keep chat replies short. Game-Mode scene analysis then returns truncated JSON that fails to parse.
Trace:
getRuntimeGenerationSettingsreturnsmaxTokens = Math.max(64, floor(config.maxTokens))(sidecar-inference.service.ts:142);streamChatCompletionthen doesMath.min(options.maxTokens, generation.maxTokens)(156).analyzeSceneasks for 4096 (498),runTrackerPromptfor 8192 (516) — both clamped. The field isconfig.maxTokens(ModelDownloadModal.tsx:736; default 4096, sidecar.ts:288). Remote scene-wrap uses its owngameGenerationParameters, so this is local-only.Suggested Fix: Do not clamp scene/tracker
max_tokensto chatconfig.maxTokens; use the function-specific budgets bounded only by context, or add a separate structured-output budget setting.7. Structured output not forced greedy (medium)
How it breaks the pipeline: The provider path forces
temperature:0, topP:1, topK:0for structured requests (local-sidecar.provider.ts:41-56), but the dedicated path forwards the user's configured sampling, so high temperature destabilizes/over-lengthens the scene JSON.Steps to replicate: Raise local temperature (up to 2.0). Scene analysis intermittently fails
Sidecar returned invalid JSONwhile the same model works greedily.Trace:
getRuntimeGenerationSettings(sidecar-inference.service.ts:139-147) reads user temp/topP/topK with noresponseFormatbranch;streamChatCompletionsends them verbatim (167-169) alongsideresponse_format. Contrast the deliberate greedy override at local-sidecar.provider.ts:52-54.Suggested Fix: In
streamChatCompletion, whenoptions.responseFormatis set, override sampling to greedy (temp 0, top_p 1, omit top_k) — mirroringapplyRuntimeSettings.8. Raw fetch with no byte cap and no abort propagation (low)
How it breaks the pipeline:
streamChatCompletionuses globalfetch(notllmFetch), so it lacks the 50MBmaxResponseBytescap and identity-encoding handling every other LLM request gets, and threads no callerAbortSignal, so a client navigating away cannot abort the local generation.Steps to replicate: Start scene analysis and navigate away; the local model keeps generating until the 5-min timer. A misbehaving model that ignores
max_tokensgrows server memory unbounded.Trace: Global
fetchat sidecar-inference.service.ts:157, only bound is the timeout (172); read loop (190-219) appends with no ceiling.analyzeScene/runTrackerPromptaccept nosignal; the routes (sidecar.routes.ts:333,445) and client (use-scene-analysis.ts:88) never create one. ContrastllmFetch→safeFetchmaxResponseBytes: 50MB(base-provider.ts:35) and the remote provider'sreader.cancel()abort wiring (openai.provider.ts:966-974).Suggested Fix: Route sidecar inference through
llmFetch; thread anAbortSignalfrom the request throughstreamChatCompletion/analyzeScene/runTrackerPrompt, derive it fromreq.rawclose, register areader.cancel()abort listener, and cap accumulated content defensively.Affected files
packages/server/src/services/sidecar/sidecar-inference.service.tspackages/server/src/services/llm/providers/openai.provider.tspackages/server/src/routes/sidecar.routes.tspackages/server/src/services/llm/base-provider.tsAudit provenance
Found by a multi-agent static audit of the sidecar/local-model subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: HIGH. Line numbers are against the
stagingworking tree.@SpicyMarinara commented on GitHub (Jun 21, 2026):
Fixed in
ef8d2876. The dedicated sidecar inference path now normalizes json_schema response_format, returns content-or-reasoning on [DONE], uses llmFetch with the shared response cap, fits prompts to sidecar context, avoids clamping structured calls to chat maxTokens, forces greedy sampling for structured output, surfaces stream error chunks, uses an idle read timeout with partial-output preservation for abort/idle cases, retries once with a smaller output budget on context overflow, and threads route abort signals into scene/tracker inference.