[GH-ISSUE #2708] [Issue]: World-gen creation failures — forced maxTokens=16384 can 400 the GM turn; truncated world JSON has no auto-retry and the repair modal can't fix it #1353

Closed
opened 2026-10-21 05:32:03 +07:00 by bsakaguchi · 2 comments
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

World generation routinely fails on creation due to the structured-JSON budget: the forced game maxTokens=16384 is capped only against the context window (not the model's output limit), so it can 400 the GM turn; and when the large world JSON is truncated (a common failure on reasoning models or low connection maxTokens), there is no auto-retry and the repair modal cannot reconstruct truncated JSON.

Expected behavior

World-gen should request a token budget the model can satisfy, auto-retry once on a parse failure, and only surface the repair modal for genuinely repairable (non-truncated) JSON — with a clear "response was cut off, raise max tokens" message otherwise.

Actual behavior

  1. Forced maxTokens=16384 400s. Game mode forces maxTokens=16384; the only automatic reduction is the context-window fitter — it is never clamped to the model's hard output-token ceiling, so for a model whose output cap is below 16384 the request 400s (game-specific instance of #2685).
  2. Truncation has no recovery. On a parse failure the handler does not retry; it immediately sendJsonRepairError and routes to GameJsonRepairModal (/game/setup/apply-json). parseGameJsonish's tolerant path repairs trailing commas/comments/control chars but has no logic to balance/close unterminated braces/arrays — so the most common large-output failure (truncation from hitting maxTokens or a long reasoning run) produces a blob the modal cannot fix by hand.

How it breaks the pipeline

Code trace (staging @ b826f8f4):

  • (1) packages/server/src/routes/generate.routes.ts:3300 (forces maxTokens=16384); cap only via context fitter (base-provider.ts); no model-output-cap clamp (cf. #2685).
  • (2) packages/server/src/routes/game.routes.ts:3653-3684 (sendJsonRepairError on parse failure, no retry); packages/server/src/lib/jsonish.ts:149-170 (tolerant parse), :8-40/:128-132 (extractObjectCandidate/repairJsonish — no brace/bracket closing).

(Related, provider-conditional and verified separately: forced high reasoning effort + a low connection maxTokens override can shrink the visible budget and truncate the world JSON on OpenAI-compatible reasoning models — though native Anthropic adds thinking budget on top. A Math.max(16384, ...) floor on the setup budget, mirroring the keeper/conclusion floors already in this file, would also help.)

Steps to reproduce

  1. Run setup on a model whose output-token cap is < 16384 → the GM turn 400s.
  2. Force a truncated response (low maxTokens, or a verbose reasoning model) → /game/setup returns 422 and the repair modal opens with truncated JSON that cannot be made valid by hand.

Suggested fix

  • Clamp the forced game maxTokens to the model's known output ceiling before sending (as proposed for #2685).
  • Add (a) one bounded automatic regeneration attempt on parse failure before the modal, and (b) a brace/bracket-closing repair pass in jsonish.ts (track unclosed {/[ and append matching closers). Detect truncation (finish_reason: length / unbalanced depth) and surface a "response was cut off — raise max tokens" message instead of the generic repair modal. Floor the setup budget with Math.max(16384, storedMaxTokens).

Environment

  • Marinara Engine version: 2.0.0 (staging @ b826f8f4)
  • Install type: source
  • OS + version: All (code-level defect, platform-independent)
  • Browser or app shell: All

Additional context

Found via a systematic multi-agent audit of Game Mode. The dominant "fails on game creation" cause (the whole GameJsonRepairModal exists because of it). Part of a set of game-mode issues filed together.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2708 Originally assigned to: @SpicyMarinara on GitHub. ## Summary World generation routinely fails on creation due to the structured-JSON budget: the forced game `maxTokens=16384` is capped only against the context window (not the model's output limit), so it can **400 the GM turn**; and when the large world JSON is truncated (a common failure on reasoning models or low connection `maxTokens`), there is **no auto-retry** and the **repair modal cannot reconstruct truncated JSON**. ## Expected behavior World-gen should request a token budget the model can satisfy, auto-retry once on a parse failure, and only surface the repair modal for genuinely repairable (non-truncated) JSON — with a clear "response was cut off, raise max tokens" message otherwise. ## Actual behavior 1. **Forced `maxTokens=16384` 400s.** Game mode forces `maxTokens=16384`; the only automatic reduction is the context-window fitter — it is never clamped to the model's hard output-token ceiling, so for a model whose output cap is below 16384 the request 400s (game-specific instance of #2685). 2. **Truncation has no recovery.** On a parse failure the handler does **not** retry; it immediately `sendJsonRepairError` and routes to `GameJsonRepairModal` (`/game/setup/apply-json`). `parseGameJsonish`'s tolerant path repairs trailing commas/comments/control chars but has **no logic to balance/close unterminated braces/arrays** — so the most common large-output failure (truncation from hitting `maxTokens` or a long reasoning run) produces a blob the modal cannot fix by hand. ## How it breaks the pipeline Code trace (staging @ `b826f8f4`): - (1) `packages/server/src/routes/generate.routes.ts:3300` (forces `maxTokens=16384`); cap only via context fitter (`base-provider.ts`); no model-output-cap clamp (cf. #2685). - (2) `packages/server/src/routes/game.routes.ts:3653-3684` (`sendJsonRepairError` on parse failure, no retry); `packages/server/src/lib/jsonish.ts:149-170` (tolerant parse), `:8-40`/`:128-132` (`extractObjectCandidate`/`repairJsonish` — no brace/bracket closing). *(Related, provider-conditional and verified separately: forced high reasoning effort + a low connection `maxTokens` override can shrink the visible budget and truncate the world JSON on OpenAI-compatible reasoning models — though native Anthropic adds thinking budget on top. A `Math.max(16384, ...)` floor on the setup budget, mirroring the keeper/conclusion floors already in this file, would also help.)* ## Steps to reproduce 1. Run setup on a model whose output-token cap is < 16384 → the GM turn 400s. 2. Force a truncated response (low `maxTokens`, or a verbose reasoning model) → `/game/setup` returns 422 and the repair modal opens with truncated JSON that cannot be made valid by hand. ## Suggested fix - Clamp the forced game `maxTokens` to the model's known output ceiling before sending (as proposed for #2685). - Add (a) one bounded automatic regeneration attempt on parse failure before the modal, and (b) a brace/bracket-closing repair pass in `jsonish.ts` (track unclosed `{`/`[` and append matching closers). Detect truncation (`finish_reason: length` / unbalanced depth) and surface a "response was cut off — raise max tokens" message instead of the generic repair modal. Floor the setup budget with `Math.max(16384, storedMaxTokens)`. ## Environment - Marinara Engine version: 2.0.0 (staging @ `b826f8f4`) - Install type: source - OS + version: All (code-level defect, platform-independent) - Browser or app shell: All ## Additional context Found via a systematic multi-agent audit of Game Mode. The dominant "fails on game creation" cause (the whole `GameJsonRepairModal` exists because of it). Part of a set of game-mode issues filed together. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
Author
Owner

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

Veracity self-review — correction / clarification
Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it.

Two citation corrections (the underlying bug is confirmed real and present on staging @ b826f8f4; these only fix file/line pointers so a fixer lands in the right place):

  1. jsonish.ts path is wrong. The tolerant parser lives at packages/server/src/services/game/jsonish.ts, not packages/server/src/lib/jsonish.ts (the lib path does not exist). The cited line ranges are correct for the services/game path: extractObjectCandidate (:8-40, never closes unbalanced brace/bracket depth — line 38-39 just slices to the last }), repairJsonish (:128-132, only commas/comments/control chars), parseGameJsonish (:149-170). Note the setup handler calls parseJSON (game.routes.ts:1851-1852), which is a thin wrapper over parseGameJsonish — so the repair modal re-runs the exact same parser, which is why truncated JSON can't be fixed by hand.

  2. The forced ~16384 for world-gen creation is at game.routes.ts:3605 (maxTokens: setupGenerationParameters?.maxTokens ?? 16384), which feeds provider.chatComplete directly (line 3634). generate.routes.ts:3300 is a separate path (the in-game GM chat turn, the chatMode === "game" block). Both force ~16384 and both lack a model-output-cap clamp (applyMaxTokensCap at base-provider.ts:560-563 only honors the user's connection-level maxTokensOverride, not the catalog maxOutput read at connections.routes.ts:1010), but the setup endpoint is the one that 400s on creation. The fix's "floor with Math.max(16384, storedMaxTokens) + clamp to model output ceiling" should target game.routes.ts:3605 (and the GM-turn site at generate.routes.ts:3300 for #2685 parity). The proposed Math.max(16384, ...) floor correctly mirrors the existing keeper floor (game.routes.ts:2314, GAME_LOREBOOK_KEEPER_MIN_OUTPUT_TOKENS = 16_384).

Implementation note on truncation detection (provider-conditional): the setup path calls chatComplete without tools. On native Anthropic and Google that delegates to the base chatComplete (base-provider.ts:618), which hardcodes finishReason: "stop" — so finish_reason: length is NOT reliable there. However, the OpenAI provider's chatComplete (openai.provider.ts:1049) does not gate on tools and DOES surface the real finish reason on both the Chat Completions path (line 1197 / stream 1267-1269) and the Responses path (status === "incomplete" → "length"), so finish_reason: length IS reliable on OpenAI-compatible routes — exactly the reasoning/output-capped models this issue centers on. Recommendation: keep the issue's dual signal — use finish_reason: length where available AND unbalanced brace/bracket depth as the universal fallback (the latter is the only reliable signal on the native Anthropic/Google no-tools path).

<!-- gh-comment-id:4761102541 --> @kolacheee commented on GitHub (Jun 21, 2026): > **Veracity self-review — correction / clarification** > _Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it._ Two citation corrections (the underlying bug is confirmed real and present on staging @ b826f8f4; these only fix file/line pointers so a fixer lands in the right place): 1) jsonish.ts path is wrong. The tolerant parser lives at `packages/server/src/services/game/jsonish.ts`, not `packages/server/src/lib/jsonish.ts` (the lib path does not exist). The cited line ranges are correct for the services/game path: `extractObjectCandidate` (:8-40, never closes unbalanced brace/bracket depth — line 38-39 just slices to the last `}`), `repairJsonish` (:128-132, only commas/comments/control chars), `parseGameJsonish` (:149-170). Note the setup handler calls `parseJSON` (game.routes.ts:1851-1852), which is a thin wrapper over `parseGameJsonish` — so the repair modal re-runs the exact same parser, which is why truncated JSON can't be fixed by hand. 2) The forced ~16384 for world-gen *creation* is at `game.routes.ts:3605` (`maxTokens: setupGenerationParameters?.maxTokens ?? 16384`), which feeds `provider.chatComplete` directly (line 3634). `generate.routes.ts:3300` is a separate path (the in-game GM chat turn, the `chatMode === "game"` block). Both force ~16384 and both lack a model-output-cap clamp (`applyMaxTokensCap` at base-provider.ts:560-563 only honors the user's connection-level `maxTokensOverride`, not the catalog `maxOutput` read at connections.routes.ts:1010), but the setup endpoint is the one that 400s on creation. The fix's "floor with `Math.max(16384, storedMaxTokens)` + clamp to model output ceiling" should target game.routes.ts:3605 (and the GM-turn site at generate.routes.ts:3300 for #2685 parity). The proposed `Math.max(16384, ...)` floor correctly mirrors the existing keeper floor (game.routes.ts:2314, `GAME_LOREBOOK_KEEPER_MIN_OUTPUT_TOKENS = 16_384`). Implementation note on truncation detection (provider-conditional): the setup path calls `chatComplete` without tools. On native Anthropic and Google that delegates to the base `chatComplete` (base-provider.ts:618), which hardcodes `finishReason: "stop"` — so `finish_reason: length` is NOT reliable there. However, the OpenAI provider's `chatComplete` (openai.provider.ts:1049) does not gate on tools and DOES surface the real finish reason on both the Chat Completions path (line 1197 / stream 1267-1269) and the Responses path (`status === "incomplete"` → `"length"`), so `finish_reason: length` IS reliable on OpenAI-compatible routes — exactly the reasoning/output-capped models this issue centers on. Recommendation: keep the issue's dual signal — use `finish_reason: length` where available AND unbalanced brace/bracket depth as the universal fallback (the latter is the only reliable signal on the native Anthropic/Google no-tools path).
Author
Owner

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

Fixed in 99105fd0. World setup now floors the requested output budget for game setup/GM turns but clamps to known model and connection caps, retries setup JSON generation once before surfacing a repair path, detects cut-off responses via finish_reason=length or unclosed JSON structure, and the game JSON-ish parser can close common truncated object/array/string endings.

<!-- gh-comment-id:4761624975 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in 99105fd0. World setup now floors the requested output budget for game setup/GM turns but clamps to known model and connection caps, retries setup JSON generation once before surfacing a repair path, detects cut-off responses via finish_reason=length or unclosed JSON structure, and the game JSON-ish parser can close common truncated object/array/string endings.
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#1353
No description provided.