[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

Closed
opened 2026-10-21 05:32:17 +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/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 and fetch instead of going through the audited OpenAIProvider/llmFetch path that LocalSidecarProvider chat 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_format disables grammar-constrained JSON (high)

How it breaks the pipeline: analyzeScene is the entire local scene-direction path. The grammar that should force valid JSON is never installed because the response_format is 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 500 Sidecar returned invalid JSON and no background/music/effects applied.

Trace: analyzeScene passes responseFormat: { type: "json_schema", schema: SCENE_ANALYSIS_SCHEMA } (sidecar-inference.service.ts:499-502). streamChatCompletion forwards it verbatim as response_format (sidecar-inference.service.ts:170) with no normalization. llama.cpp's server (tools/server/server-common.cpp) for type == "json_schema" reads only response_format.json_schema.schema; a top-level schema defaults 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 hits extractJsonPayload (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 through OpenAIProvider.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_content and leaves content empty, 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 --jinja runs and llama.cpp separates reasoning_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 content and reasoning separately (sidecar-inference.service.ts:213-214). On data: [DONE] it does return content; (sidecar-inference.service.ts:203-204), bypassing the post-loop fallback trimmedContent || reasoning.trim() (238-243), which is therefore dead code in normal operation. Contrast openai.provider.ts which breaks on [DONE] and then flushes reasoning.

Suggested Fix: On [DONE] return content.trim() || reasoning.trim() (mirror lines 238-243) instead of raw un-trimmed content.


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 accumulated content is 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 around await reader.read(), so the rejection propagates and abandons content (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 accumulated content is 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 JSON 500 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 swallowing catch {} (215-217); an error chunk ({"error":{...}}, no choices) is dropped. content stays 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, extract parsed.error?.message and 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 messages verbatim and never trims to context, unlike the provider path which runs fitMessagesToContext. A near-context scene/tracker prompt plus max_tokens overruns 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 with Scene analysis failed/Tracker inference failed, no recovery.

Trace: messages: options.messages verbatim (sidecar-inference.service.ts:165); max_tokens clamped only against config (156), never against remaining context. Per-slot context is exactly contextSize (--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 cap max_tokens to 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: streamChatCompletion clamps the per-call budget down to config.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: getRuntimeGenerationSettings returns maxTokens = Math.max(64, floor(config.maxTokens)) (sidecar-inference.service.ts:142); streamChatCompletion then does Math.min(options.maxTokens, generation.maxTokens) (156). analyzeScene asks for 4096 (498), runTrackerPrompt for 8192 (516) — both clamped. The field is config.maxTokens (ModelDownloadModal.tsx:736; default 4096, sidecar.ts:288). Remote scene-wrap uses its own gameGenerationParameters, so this is local-only.

Suggested Fix: Do not clamp scene/tracker max_tokens to chat config.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:0 for 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 JSON while the same model works greedily.

Trace: getRuntimeGenerationSettings (sidecar-inference.service.ts:139-147) reads user temp/topP/topK with no responseFormat branch; streamChatCompletion sends them verbatim (167-169) alongside response_format. Contrast the deliberate greedy override at local-sidecar.provider.ts:52-54.

Suggested Fix: In streamChatCompletion, when options.responseFormat is set, override sampling to greedy (temp 0, top_p 1, omit top_k) — mirroring applyRuntimeSettings.


8. Raw fetch with no byte cap and no abort propagation (low)

How it breaks the pipeline: streamChatCompletion uses global fetch (not llmFetch), so it lacks the 50MB maxResponseBytes cap and identity-encoding handling every other LLM request gets, and threads no caller AbortSignal, 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_tokens grows server memory unbounded.

Trace: Global fetch at sidecar-inference.service.ts:157, only bound is the timeout (172); read loop (190-219) appends with no ceiling. analyzeScene/runTrackerPrompt accept no signal; the routes (sidecar.routes.ts:333,445) and client (use-scene-analysis.ts:88) never create one. Contrast llmFetch → safeFetch maxResponseBytes: 50MB (base-provider.ts:35) and the remote provider's reader.cancel() abort wiring (openai.provider.ts:966-974).

Suggested Fix: Route sidecar inference through llmFetch; thread an AbortSignal from the request through streamChatCompletion/analyzeScene/runTrackerPrompt, derive it from req.raw close, register a reader.cancel() abort listener, and cap accumulated content defensively.


Affected files

  • packages/server/src/services/sidecar/sidecar-inference.service.ts
  • packages/server/src/services/llm/providers/openai.provider.ts
  • packages/server/src/routes/sidecar.routes.ts
  • packages/server/src/services/llm/base-provider.ts

Audit 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 staging working tree.

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 and `fetch` instead of going through the audited `OpenAIProvider`/`llmFetch` path that `LocalSidecarProvider` chat 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_format` disables grammar-constrained JSON (high) **How it breaks the pipeline:** `analyzeScene` is the entire local scene-direction path. The grammar that should force valid JSON is never installed because the `response_format` is 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 500 `Sidecar returned invalid JSON` and no background/music/effects applied. **Trace:** `analyzeScene` passes `responseFormat: { type: "json_schema", schema: SCENE_ANALYSIS_SCHEMA }` (sidecar-inference.service.ts:499-502). `streamChatCompletion` forwards it verbatim as `response_format` (sidecar-inference.service.ts:170) with no normalization. llama.cpp's server (tools/server/server-common.cpp) for `type == "json_schema"` reads only `response_format.json_schema.schema`; a top-level `schema` defaults 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 hits `extractJsonPayload` (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 through `OpenAIProvider.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_content` and leaves `content` empty, 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 `--jinja` runs and llama.cpp separates `reasoning_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 `content` and `reasoning` separately (sidecar-inference.service.ts:213-214). On `data: [DONE]` it does `return content;` (sidecar-inference.service.ts:203-204), bypassing the post-loop fallback `trimmedContent || reasoning.trim()` (238-243), which is therefore dead code in normal operation. Contrast openai.provider.ts which `break`s on `[DONE]` and then flushes reasoning. **Suggested Fix:** On `[DONE]` return `content.trim() || reasoning.trim()` (mirror lines 238-243) instead of raw un-trimmed `content`. --- ### 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 accumulated `content` is 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 around `await reader.read()`, so the rejection propagates and abandons `content` (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 accumulated `content` is 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 JSON` 500 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 swallowing `catch {}` (215-217); an error chunk (`{"error":{...}}`, no `choices`) is dropped. `content` stays 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`, extract `parsed.error?.message` and 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 `messages` verbatim and never trims to context, unlike the provider path which runs `fitMessagesToContext`. A near-context scene/tracker prompt plus `max_tokens` overruns 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 with `Scene analysis failed`/`Tracker inference failed`, no recovery. **Trace:** `messages: options.messages` verbatim (sidecar-inference.service.ts:165); `max_tokens` clamped only against config (156), never against remaining context. Per-slot context is exactly `contextSize` (`--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 cap `max_tokens` to 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:** `streamChatCompletion` clamps the per-call budget down to `config.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:** `getRuntimeGenerationSettings` returns `maxTokens = Math.max(64, floor(config.maxTokens))` (sidecar-inference.service.ts:142); `streamChatCompletion` then does `Math.min(options.maxTokens, generation.maxTokens)` (156). `analyzeScene` asks for 4096 (498), `runTrackerPrompt` for 8192 (516) — both clamped. The field is `config.maxTokens` (ModelDownloadModal.tsx:736; default 4096, sidecar.ts:288). Remote scene-wrap uses its own `gameGenerationParameters`, so this is local-only. **Suggested Fix:** Do not clamp scene/tracker `max_tokens` to chat `config.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:0` for 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 JSON` while the same model works greedily. **Trace:** `getRuntimeGenerationSettings` (sidecar-inference.service.ts:139-147) reads user temp/topP/topK with no `responseFormat` branch; `streamChatCompletion` sends them verbatim (167-169) alongside `response_format`. Contrast the deliberate greedy override at local-sidecar.provider.ts:52-54. **Suggested Fix:** In `streamChatCompletion`, when `options.responseFormat` is set, override sampling to greedy (temp 0, top_p 1, omit top_k) — mirroring `applyRuntimeSettings`. --- ### 8. Raw fetch with no byte cap and no abort propagation (low) **How it breaks the pipeline:** `streamChatCompletion` uses global `fetch` (not `llmFetch`), so it lacks the 50MB `maxResponseBytes` cap and identity-encoding handling every other LLM request gets, and threads no caller `AbortSignal`, 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_tokens` grows server memory unbounded. **Trace:** Global `fetch` at sidecar-inference.service.ts:157, only bound is the timeout (172); read loop (190-219) appends with no ceiling. `analyzeScene`/`runTrackerPrompt` accept no `signal`; the routes (sidecar.routes.ts:333,445) and client (use-scene-analysis.ts:88) never create one. Contrast `llmFetch` → `safeFetch` `maxResponseBytes: 50MB` (base-provider.ts:35) and the remote provider's `reader.cancel()` abort wiring (openai.provider.ts:966-974). **Suggested Fix:** Route sidecar inference through `llmFetch`; thread an `AbortSignal` from the request through `streamChatCompletion`/`analyzeScene`/`runTrackerPrompt`, derive it from `req.raw` close, register a `reader.cancel()` abort listener, and cap accumulated content defensively. --- ### Affected files - `packages/server/src/services/sidecar/sidecar-inference.service.ts` - `packages/server/src/services/llm/providers/openai.provider.ts` - `packages/server/src/routes/sidecar.routes.ts` - `packages/server/src/services/llm/base-provider.ts` ### Audit 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 `staging` working tree.
Author
Owner

@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.

<!-- gh-comment-id:4761662647 --> @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.
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#1359
No description provided.