[PR #8778] [MERGED] fix(server): stop streamed-output fallbacks, empty JSON replies and partial package completions #8800

Closed
opened 2026-11-07 17:39:47 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/8778
Author: @SpicyMarinara
Created: 11/3/2026
Status: ✅ Merged
Merged: 11/3/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/llm-streaming-fallbacks


📝 Commits (2)

  • 9a8d2c7 fix(server): stop streamed-output fallbacks, empty JSON replies and partial package completions
  • 9b12148 fix(server): let keepalive-only chatComplete callers keep their fallback

📊 Changes

11 files changed (+144 additions, -10 deletions)

View changed files

📝 packages/server/src/routes/game.routes.ts (+6 -0)
📝 packages/server/src/services/agents/agent-progress.ts (+2 -0)
📝 packages/server/src/services/capability-packages/capability-language-model.service.ts (+5 -0)
📝 packages/server/src/services/llm/connection-fallback-provider.ts (+18 -3)
📝 packages/server/src/services/llm/providers/openai.provider.ts (+11 -6)
📝 packages/shared/src/types/generation-integration.ts (+5 -0)
📝 scripts/regressions/agent-progress.regression.ts (+14 -0)
📝 scripts/regressions/game-generation-parameters.regression.ts (+8 -0)
📝 scripts/regressions/llm-inactivity-timeout.regression.ts (+14 -1)
📝 scripts/regressions/openai-json-stream-response.regression.ts (+20 -0)
📝 scripts/regressions/provider-compat.regression.ts (+41 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.

Linked issue

Closes #8777

Why this change

A release-prep audit found three LLM streaming failure paths. Two independent verifiers checked each one.

  1. With an "If it fails" fallback connection, a primary that streamed part of a reply through onToken and then errored on the chatComplete path got the fallback's whole reply appended after it. This hits tool rounds, /api/generate/raw and dry runs, and the garbled reply is saved. Callers that build their result from the streamed chunks (agent calls) got the same mix in the text they parse.
  2. OpenAI-compatible endpoints that ignore stream:true and answer with JSON made the main no-tools reply (provider.chat()) come back empty. The earlier fix covered only chatComplete.
  3. Since this release, the capability package host always streams. A stream that broke after partial text resolved with finishReason "error" instead of rejecting. Packages such as Otome Hearth, Gacha Forge and Long-Term Memory could then parse and save truncated scenes or memories as complete.
    Some callers pass onToken only to keep a watchdog or progress display alive (Game setup, session conclusion, campaign progression, Lorebook Keeper, agent progress). Those still use the fallback, because nothing they streamed reached the user.

No issue is linked: these came from the release-prep audit. Per CONTRIBUTING, an issue should be opened before this PR is submitted.

What changed

  • Behaviour change: a capability package's languageModels chatComplete call now rejects with "The language model stream failed before the reply finished." when the provider stream fails after partial text. Before, it resolved with the partial text and finishReason "error". This matches the OpenAI path and the behaviour before streaming was added. A package that relied on getting the partial text now gets an error.
  • Behaviour change: with a fallback connection configured, when the primary has already streamed text through onToken and then fails, a chatComplete call now surfaces the primary's error instead of appending the fallback's reply. This matches the existing chat() behaviour. It applies to streamed tool rounds, /api/generate/raw, dry runs, Professor Mari, capability integration packages that pass onToken, and streamed agent calls that build their result from the stream: agent-executor's single, retry, lane and batch calls, and the agent scene check. On staging these callers got the fallback's reply mixed with the partial one; now they get an error.
  • Game setup, session conclusion (both routes), campaign progression, Lorebook Keeper and agent calls that stream only for the progress display still use the fallback after a mid-stream primary failure. They only use onToken to show the call is alive, so a new ChatOptions.onTokenKeepaliveOnly flag marks them.
  • OpenAI and OpenAI-compatible chat() and Responses-API streaming replies now read a completed application/json body when the endpoint ignores stream:true. Before, they came back empty.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • Manually verify a streamed Roleplay reply with tools on and an 'If it fails' fallback: when the primary errors mid-stream, the chat shows the error with the partial primary text and no fallback reply appended after it.
  • Manually verify a Game world setup with a main fallback connection configured: when the GM primary errors mid-stream, setup completes from the fallback connection and shows the fallback notice, instead of failing with 'GM connection failed'.
  • Manually verify a Game session conclusion and a campaign progression update with a main fallback: a mid-stream primary error still produces a result from the fallback.
  • Manually verify a streamed tracker agent with an agents fallback configured and agent progress visible: a mid-stream primary error now shows as an agent error, with no tracker result built from mixed partial and fallback text.
  • Manually verify that a plain (no-tools) streamed chat reply works against an OpenAI-compatible endpoint that ignores stream:true and returns application/json, on both a Chat Completions model and a Responses-API model.
  • Manually verify that an Otome Hearth or Gacha Forge generation on an Anthropic or Gemini connection reports a failure, rather than saving a truncated scene, when the provider stream errors mid-reply (for example on an overloaded error).

Agent-run checks (for reference; each regression was shown to fail without its fix):

  • node ./scripts/pnpm-runner.mjs build:shared: succeeded
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/provider-compat.regression (with fix / connection-fallback-provider.ts reverted to round 1): PASSED with fix; FAILED without it at the new keepalive case (provider-compat.regression.ts:2760 rejected with 'stream interrupted after callback output')
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/agent-progress.regression (with fix / agent-progress.ts reverted): PASSED with fix; FAILED without it at :24 (onTokenKeepaliveOnly actual undefined, expected false)
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/game-generation-parameters.regression (with fix / game.routes.ts reverted): PASSED with fix; FAILED without it at :94 (actual undefined, expected true)
  • node ./scripts/run-regressions.mjs --filter scripts/regressions/<name>.regression, run one at a time for 27 regressions: provider-compat, openai-json-stream-res: all 27 passed (each reported 1/1 passed)
  • cd packages/server && node ../../scripts/pnpm-runner.mjs lint (tsc -b ../shared && tsc --noEmit && tsc -p ../../scripts/regressions/tsconfig.character-activity.: exit 0
  • cd packages/shared && node ../../scripts/pnpm-runner.mjs lint (generate-feature-registries + tsc --noEmit): exit 0; no tracked files changed
  • node_modules/.bin/prettier --write, then --check, on every file changed on the branch: All matched files use Prettier code style
  • eslint on changed files: Not applicable: ESLint is configured only for packages/client, and no client files changed. The server and shared lint scripts are tsc, which passed above.

Independent adversarial review: changes, 2 issue(s), all addressed in a fix-up pass.

Known limits and risks:

  1. Default for unmarked callers. A caller that passes onToken and does not set onTokenKeepaliveOnly now gets the primary's error after a mid-stream failure, not the fallback. That is right for callers that show or keep the text. A future keepalive-only caller that forgets the flag would lose its fallback (an error, never garbled output). I chose this default (reviewer option 2) over an opt-in flag because the keepalive set is small and known: five Game call sites plus the agent progress hook. The callers that show text are spread out (tool rounds, raw route, dry run, agent executor, Professor Mari, capability integration packages). An opt-in flag would quietly go back to appending the fallback wherever someone forgot it.

  2. Agents and packages. Streamed agent-executor calls with an agents fallback configured now fail on a mid-stream primary error instead of parsing mixed text. Making them use the fallback would mean changing agent-executor to prefer result.content over the text it accumulated. That is outside this fix. Capability packages that use the integration host's withFallback with a keepalive-only onToken would need to set the new optional ChatOptions.onTokenKeepaliveOnly. No Capability API version was bumped: version files are off limits for this task, and the field is optional.

  3. Package host message. The package-host change rejects any result with finishReason 'error', including an upstream finish_reason 'error' that arrived with complete-looking text. The package gets a generic message, and the provider's own error is only logged (marked with a ponytail: comment). A mid-stream failure on a package call is also not retried by the rate-limit wrapper, because the host rejects after the provider returns.

  4. Reviewer notes I did not act on:

  • The emitted-then-rethrow path does not call onProviderUsed. generationProviderOrigin defaults to the primary, so this is harmless.
  • An SSE stream mislabelled application/json now goes through parseJsonBody. chatCompleteOnce has had the same exposure since afe9ddbd42, and no real endpoint doing this was found.
  • raw-route still sends the base provider's partial content as a complete result. This predates the branch.
  1. Otome Hearth request. The relayed user request (showing off an outfit to a love interest should give +5 affection instead of +20) is not in this diff. Engine has no outfit or affection logic, and Otome Hearth is a downloadable package, so per AGENTS.md that change belongs in Pasta-Devs/Marinara-Agents (staging). The orchestrator needs to route it there.

Nothing was pushed and no PR was opened.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

🤖 Generated with Claude Code


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/8778 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 11/3/2026 **Status:** ✅ Merged **Merged:** 11/3/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/llm-streaming-fallbacks` --- ### 📝 Commits (2) - [`9a8d2c7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9a8d2c760e6970d0a2fca1d29930a572de83ad1b) fix(server): stop streamed-output fallbacks, empty JSON replies and partial package completions - [`9b12148`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9b12148eec9ee567a5fd93befc22bf882037eab6) fix(server): let keepalive-only chatComplete callers keep their fallback ### 📊 Changes **11 files changed** (+144 additions, -10 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/routes/game.routes.ts` (+6 -0) 📝 `packages/server/src/services/agents/agent-progress.ts` (+2 -0) 📝 `packages/server/src/services/capability-packages/capability-language-model.service.ts` (+5 -0) 📝 `packages/server/src/services/llm/connection-fallback-provider.ts` (+18 -3) 📝 `packages/server/src/services/llm/providers/openai.provider.ts` (+11 -6) 📝 `packages/shared/src/types/generation-integration.ts` (+5 -0) 📝 `scripts/regressions/agent-progress.regression.ts` (+14 -0) 📝 `scripts/regressions/game-generation-parameters.regression.ts` (+8 -0) 📝 `scripts/regressions/llm-inactivity-timeout.regression.ts` (+14 -1) 📝 `scripts/regressions/openai-json-stream-response.regression.ts` (+20 -0) 📝 `scripts/regressions/provider-compat.regression.ts` (+41 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. ## Linked issue Closes #8777 ## Why this change A release-prep audit found three LLM streaming failure paths. Two independent verifiers checked each one. 1. With an "If it fails" fallback connection, a primary that streamed part of a reply through onToken and then errored on the chatComplete path got the fallback's whole reply appended after it. This hits tool rounds, /api/generate/raw and dry runs, and the garbled reply is saved. Callers that build their result from the streamed chunks (agent calls) got the same mix in the text they parse. 2. OpenAI-compatible endpoints that ignore stream:true and answer with JSON made the main no-tools reply (provider.chat()) come back empty. The earlier fix covered only chatComplete. 3. Since this release, the capability package host always streams. A stream that broke after partial text resolved with finishReason "error" instead of rejecting. Packages such as Otome Hearth, Gacha Forge and Long-Term Memory could then parse and save truncated scenes or memories as complete. Some callers pass onToken only to keep a watchdog or progress display alive (Game setup, session conclusion, campaign progression, Lorebook Keeper, agent progress). Those still use the fallback, because nothing they streamed reached the user. No issue is linked: these came from the release-prep audit. Per CONTRIBUTING, an issue should be opened before this PR is submitted. ## What changed - Behaviour change: a capability package's languageModels chatComplete call now rejects with "The language model stream failed before the reply finished." when the provider stream fails after partial text. Before, it resolved with the partial text and finishReason "error". This matches the OpenAI path and the behaviour before streaming was added. A package that relied on getting the partial text now gets an error. - Behaviour change: with a fallback connection configured, when the primary has already streamed text through onToken and then fails, a chatComplete call now surfaces the primary's error instead of appending the fallback's reply. This matches the existing chat() behaviour. It applies to streamed tool rounds, /api/generate/raw, dry runs, Professor Mari, capability integration packages that pass onToken, and streamed agent calls that build their result from the stream: agent-executor's single, retry, lane and batch calls, and the agent scene check. On staging these callers got the fallback's reply mixed with the partial one; now they get an error. - Game setup, session conclusion (both routes), campaign progression, Lorebook Keeper and agent calls that stream only for the progress display still use the fallback after a mid-stream primary failure. They only use onToken to show the call is alive, so a new ChatOptions.onTokenKeepaliveOnly flag marks them. - OpenAI and OpenAI-compatible chat() and Responses-API streaming replies now read a completed application/json body when the endpoint ignores stream:true. Before, they came back empty. ## Validation <!-- These are human tasks. Never tick a box for a check that was not actually performed. --> - [ ] `pnpm check` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed `CONTRIBUTING.md` ### Manual verification notes - Manually verify a streamed Roleplay reply with tools on and an 'If it fails' fallback: when the primary errors mid-stream, the chat shows the error with the partial primary text and no fallback reply appended after it. - Manually verify a Game world setup with a main fallback connection configured: when the GM primary errors mid-stream, setup completes from the fallback connection and shows the fallback notice, instead of failing with 'GM connection failed'. - Manually verify a Game session conclusion and a campaign progression update with a main fallback: a mid-stream primary error still produces a result from the fallback. - Manually verify a streamed tracker agent with an agents fallback configured and agent progress visible: a mid-stream primary error now shows as an agent error, with no tracker result built from mixed partial and fallback text. - Manually verify that a plain (no-tools) streamed chat reply works against an OpenAI-compatible endpoint that ignores stream:true and returns application/json, on both a Chat Completions model and a Responses-API model. - Manually verify that an Otome Hearth or Gacha Forge generation on an Anthropic or Gemini connection reports a failure, rather than saving a truncated scene, when the provider stream errors mid-reply (for example on an overloaded error). Agent-run checks (for reference; each regression was shown to fail without its fix): - `node ./scripts/pnpm-runner.mjs build:shared`: succeeded - `node ./scripts/run-regressions.mjs --filter scripts/regressions/provider-compat.regression (with fix / connection-fallback-provider.ts reverted to round 1)`: PASSED with fix; FAILED without it at the new keepalive case (provider-compat.regression.ts:2760 rejected with 'stream interrupted after callback output') - `node ./scripts/run-regressions.mjs --filter scripts/regressions/agent-progress.regression (with fix / agent-progress.ts reverted)`: PASSED with fix; FAILED without it at :24 (onTokenKeepaliveOnly actual undefined, expected false) - `node ./scripts/run-regressions.mjs --filter scripts/regressions/game-generation-parameters.regression (with fix / game.routes.ts reverted)`: PASSED with fix; FAILED without it at :94 (actual undefined, expected true) - `node ./scripts/run-regressions.mjs --filter scripts/regressions/<name>.regression, run one at a time for 27 regressions: provider-compat, openai-json-stream-res`: all 27 passed (each reported 1/1 passed) - `cd packages/server && node ../../scripts/pnpm-runner.mjs lint (tsc -b ../shared && tsc --noEmit && tsc -p ../../scripts/regressions/tsconfig.character-activity.`: exit 0 - `cd packages/shared && node ../../scripts/pnpm-runner.mjs lint (generate-feature-registries + tsc --noEmit)`: exit 0; no tracked files changed - `node_modules/.bin/prettier --write, then --check, on every file changed on the branch`: All matched files use Prettier code style - `eslint on changed files`: Not applicable: ESLint is configured only for packages/client, and no client files changed. The server and shared lint scripts are tsc, which passed above. Independent adversarial review: changes, 2 issue(s), all addressed in a fix-up pass. Known limits and risks: 1. Default for unmarked callers. A caller that passes onToken and does not set onTokenKeepaliveOnly now gets the primary's error after a mid-stream failure, not the fallback. That is right for callers that show or keep the text. A future keepalive-only caller that forgets the flag would lose its fallback (an error, never garbled output). I chose this default (reviewer option 2) over an opt-in flag because the keepalive set is small and known: five Game call sites plus the agent progress hook. The callers that show text are spread out (tool rounds, raw route, dry run, agent executor, Professor Mari, capability integration packages). An opt-in flag would quietly go back to appending the fallback wherever someone forgot it. 2. Agents and packages. Streamed agent-executor calls with an agents fallback configured now fail on a mid-stream primary error instead of parsing mixed text. Making them use the fallback would mean changing agent-executor to prefer result.content over the text it accumulated. That is outside this fix. Capability packages that use the integration host's withFallback with a keepalive-only onToken would need to set the new optional ChatOptions.onTokenKeepaliveOnly. No Capability API version was bumped: version files are off limits for this task, and the field is optional. 3. Package host message. The package-host change rejects any result with finishReason 'error', including an upstream finish_reason 'error' that arrived with complete-looking text. The package gets a generic message, and the provider's own error is only logged (marked with a ponytail: comment). A mid-stream failure on a package call is also not retried by the rate-limit wrapper, because the host rejects after the provider returns. 4. Reviewer notes I did not act on: - The emitted-then-rethrow path does not call onProviderUsed. generationProviderOrigin defaults to the primary, so this is harmless. - An SSE stream mislabelled application/json now goes through parseJsonBody. chatCompleteOnce has had the same exposure since afe9ddbd42, and no real endpoint doing this was found. - raw-route still sends the base provider's partial content as a complete result. This predates the branch. 5. Otome Hearth request. The relayed user request (showing off an outfit to a love interest should give +5 affection instead of +20) is not in this diff. Engine has no outfit or affection logic, and Otome Hearth is a downloadable package, so per AGENTS.md that change belongs in Pasta-Devs/Marinara-Agents (staging). The orchestrator needs to route it there. Nothing was pushed and no PR was opened. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 17:39:47 +07:00
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#8800
No description provided.