[GH-ISSUE #2710] [Issue]: Game state corruption — journal auto-fill races/clobbers metadata; /session/conclude has no dedup (duplicate summaries + keeper runs) #1355

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/2710

Originally assigned to: @SpicyMarinara on GitHub.

Summary

Two concurrency bugs corrupt game state via unguarded read-modify-write of the chat-metadata blob: game journal auto-fill fires multiple un-awaited full-blob writes per turn (lost updates + clobbered metadata), and /session/conclude has no in-flight dedup or already-concluded guard, so a double-click appends duplicate session summaries and double-runs the lorebook keeper — permanently poisoning carryover.

Expected behavior

Concurrent journal updates and session conclusions should be serialized/idempotent so no entry is lost, no metadata field is clobbered, and a session is concluded exactly once.

Actual behavior

  1. Journal race. updateJournal(db, chatId, transform) reads the whole chat metadata blob, mutates only gameJournal, then writes the entire meta back. In the post-generation loop it's invoked without await for several categories in the same turn (location change, NPC encounter, inventory change, and one per changed quest in a loop). All run concurrently, each get→parse→mutate→write-whole-blob. Classic lost-update race: the last writer wins, discarding other journal entries and overwriting any other metadata other handlers wrote that turn (lastMapPosition, gameMap/activeGameMapId, encounterActive). The per-quest loop is worst — N concurrent writers, most entries lost.
  2. /session/conclude no dedup. Unlike /session/start (which has pendingSessionStarts + cleanup), /session/conclude has no dedup map and no gameSessionStatus === "concluded" early-return. Each call runs a full chatComplete, appends summary to gamePreviousSessionSummaries, creates a "Session N Concluded" narrator message, and queues the lorebook keeper. sessionNumber is computed once at request start, so two concurrent requests compute the same number. A double-click (common because the first click looks stuck) → two summaries for the same session, two narrator messages, two keeper jobs → corrupted carryover feeding every future session.

How it breaks the pipeline

Code trace (staging @ b826f8f4):

  • (1) packages/server/src/services/generation/game-journal-runtime.ts:7-26 (updateJournal full-blob RMW); un-awaited calls in generate.routes.ts:7638 (location), :7913 (NPC), :7977 (inventory), :8086 (per-quest loop); also overwrites fields written at :7624 (gameMap), :8149 (encounterActive).
  • (2) game.routes.ts:4098-4311 (conclude route, no dedup), :4244-4247 (summary append), :4252 (narrator), :4300 (keeper queue), :4116 (sessionNumber once); contrast :3821-3832/:4086-4094 (pendingSessionStarts).

Steps to reproduce

  1. Take a game turn where the GM changes location AND updates a quest AND an NPC is encountered (multiple updateJournal calls) → journal entries drop and/or gameMap/encounterActive revert to the prior turn.
  2. Click "End Session" twice quickly (or a second tab/reload mid-conclude) → two "Session N Concluded" messages, two summaries for the same session number, two keeper jobs.

Suggested fix

  • Serialize journal writes per chat: await each updateJournal sequentially, or funnel all journal mutations through a per-chat async mutex/queue that re-reads fresh metadata immediately before each write and patches only gameJournal (server-side merge — don't write back a stale full-meta blob); batch the per-quest loop into one transform.
  • Add an in-flight dedup keyed by chatId to /session/conclude (mirroring pendingSessionStarts) and an early guard rejecting a conclude when gameSessionStatus is already concluded for the current sessionNumber; make the summary append idempotent.

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. Causes "journal entries missing", "trackers revert after a turn", and corrupted session carryover — classic game-mode "agent weirdness". 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/2710 Originally assigned to: @SpicyMarinara on GitHub. ## Summary Two concurrency bugs corrupt game state via unguarded read-modify-write of the chat-metadata blob: game journal auto-fill fires multiple un-awaited full-blob writes per turn (lost updates + clobbered metadata), and `/session/conclude` has no in-flight dedup or already-concluded guard, so a double-click appends duplicate session summaries and double-runs the lorebook keeper — permanently poisoning carryover. ## Expected behavior Concurrent journal updates and session conclusions should be serialized/idempotent so no entry is lost, no metadata field is clobbered, and a session is concluded exactly once. ## Actual behavior 1. **Journal race.** `updateJournal(db, chatId, transform)` reads the **whole** chat metadata blob, mutates only `gameJournal`, then writes the **entire** meta back. In the post-generation loop it's invoked **without `await`** for several categories in the same turn (location change, NPC encounter, inventory change, and one per changed quest in a loop). All run concurrently, each `get→parse→mutate→write-whole-blob`. Classic lost-update race: the last writer wins, discarding other journal entries **and** overwriting any other metadata other handlers wrote that turn (`lastMapPosition`, `gameMap`/`activeGameMapId`, `encounterActive`). The per-quest loop is worst — N concurrent writers, most entries lost. 2. **`/session/conclude` no dedup.** Unlike `/session/start` (which has `pendingSessionStarts` + cleanup), `/session/conclude` has no dedup map and no `gameSessionStatus === "concluded"` early-return. Each call runs a full `chatComplete`, appends `summary` to `gamePreviousSessionSummaries`, creates a "Session N Concluded" narrator message, and queues the lorebook keeper. `sessionNumber` is computed once at request start, so two concurrent requests compute the same number. A double-click (common because the first click looks stuck) → two summaries for the same session, two narrator messages, two keeper jobs → corrupted carryover feeding every future session. ## How it breaks the pipeline Code trace (staging @ `b826f8f4`): - (1) `packages/server/src/services/generation/game-journal-runtime.ts:7-26` (`updateJournal` full-blob RMW); un-awaited calls in `generate.routes.ts:7638` (location), `:7913` (NPC), `:7977` (inventory), `:8086` (per-quest loop); also overwrites fields written at `:7624` (gameMap), `:8149` (encounterActive). - (2) `game.routes.ts:4098-4311` (conclude route, no dedup), `:4244-4247` (summary append), `:4252` (narrator), `:4300` (keeper queue), `:4116` (sessionNumber once); contrast `:3821-3832`/`:4086-4094` (`pendingSessionStarts`). ## Steps to reproduce 1. Take a game turn where the GM changes location AND updates a quest AND an NPC is encountered (multiple `updateJournal` calls) → journal entries drop and/or `gameMap`/`encounterActive` revert to the prior turn. 2. Click "End Session" twice quickly (or a second tab/reload mid-conclude) → two "Session N Concluded" messages, two summaries for the same session number, two keeper jobs. ## Suggested fix - Serialize journal writes per chat: `await` each `updateJournal` sequentially, or funnel all journal mutations through a per-chat async mutex/queue that re-reads fresh metadata immediately before each write and patches only `gameJournal` (server-side merge — don't write back a stale full-meta blob); batch the per-quest loop into one transform. - Add an in-flight dedup keyed by `chatId` to `/session/conclude` (mirroring `pendingSessionStarts`) and an early guard rejecting a conclude when `gameSessionStatus` is already `concluded` for the current `sessionNumber`; make the summary append idempotent. ## 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. Causes "journal entries missing", "trackers revert after a turn", and corrupted session carryover — classic game-mode "agent weirdness". 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.

Clarifying notes after re-verifying against the current tree (all cited lines confirmed; files live at packages/server/src/routes/generate.routes.ts and game.routes.ts):

  1. Scope - the journal read-modify-write race affects THREE loops, not just per-quest. Both the NPC loop (generate.routes.ts:7896-7914) and the inventory loop (7975-7981) are for-loops that fire one un-awaited updateJournal per element, so each is "N concurrent writers / lost entries," identical to the per-quest loop (8083-8087). Please fix all three (plus the single location write at 7638). Cleanest fix: rewrite updateJournal (game-journal-runtime.ts:7-26) to use chats.patchMetadata(chatId, (freshMeta) => ({ gameJournal: transform(freshMeta.gameJournal ?? createJournal()) ?? freshMeta.gameJournal })). patchMetadata (chats.storage.ts:328-350) serializes via withMetadataPatchQueue AND merges only the gameJournal patch onto freshly re-read metadata, so it fixes the lost-update race and the gameMap (7624) / encounterActive (8149) clobber in one change - and makes per-call awaiting unnecessary. (The issue's "await each sequentially" is a weaker variant of its own "funnel through a queue" recommendation.)

  2. Scope - /session/conclude/apply-json (game.routes.ts:4314-4430) is an unmentioned sibling with the SAME defect as /session/conclude: no in-flight dedup and no already-concluded guard, sessionNumber = prevSummaries.length + 1 (4329), summary appended (4372-4375), narrator created (4381-4386), keeper queued (4421-4427). The dedup + already-concluded guard must be applied here too, not only on /session/conclude. (regenerate-conclusion at 4609-4611 is fine - it replaces by index and edits the existing narrator message rather than appending, so it is correctly out of scope.)

  3. Severity/UX - the standard UI already prevents the naive in-tab double-click: handleConcludeSession (GameSurface.tsx:7295), handleConfirmEndSession (7310), and handleRequestEndSession (7304) all early-return on concludeSession.isPending, and the End Session confirm button is disabled while pending (9469; Cancel button 9462). The server-side conclude race therefore reproduces via the second-tab / reload-mid-conclude window (conclude runs a full LLM chatComplete, so the window is long) or any non-UI/API caller - both still valid, so the server guard is worth adding as defense-in-depth, but please reframe the lead repro from "double-click End Session twice quickly" to the multi-tab/reload/API vector. The journal race (no client mitigation, fires on ordinary turns that change location + quest + NPC) is the higher-frequency half and should lead.

<!-- gh-comment-id:4761102624 --> @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._ Clarifying notes after re-verifying against the current tree (all cited lines confirmed; files live at packages/server/src/routes/generate.routes.ts and game.routes.ts): 1) Scope - the journal read-modify-write race affects THREE loops, not just per-quest. Both the NPC loop (generate.routes.ts:7896-7914) and the inventory loop (7975-7981) are for-loops that fire one un-awaited updateJournal per element, so each is "N concurrent writers / lost entries," identical to the per-quest loop (8083-8087). Please fix all three (plus the single location write at 7638). Cleanest fix: rewrite updateJournal (game-journal-runtime.ts:7-26) to use chats.patchMetadata(chatId, (freshMeta) => ({ gameJournal: transform(freshMeta.gameJournal ?? createJournal()) ?? freshMeta.gameJournal })). patchMetadata (chats.storage.ts:328-350) serializes via withMetadataPatchQueue AND merges only the gameJournal patch onto freshly re-read metadata, so it fixes the lost-update race and the gameMap (7624) / encounterActive (8149) clobber in one change - and makes per-call awaiting unnecessary. (The issue's "await each sequentially" is a weaker variant of its own "funnel through a queue" recommendation.) 2) Scope - /session/conclude/apply-json (game.routes.ts:4314-4430) is an unmentioned sibling with the SAME defect as /session/conclude: no in-flight dedup and no already-concluded guard, sessionNumber = prevSummaries.length + 1 (4329), summary appended (4372-4375), narrator created (4381-4386), keeper queued (4421-4427). The dedup + already-concluded guard must be applied here too, not only on /session/conclude. (regenerate-conclusion at 4609-4611 is fine - it replaces by index and edits the existing narrator message rather than appending, so it is correctly out of scope.) 3) Severity/UX - the standard UI already prevents the naive in-tab double-click: handleConcludeSession (GameSurface.tsx:7295), handleConfirmEndSession (7310), and handleRequestEndSession (7304) all early-return on concludeSession.isPending, and the End Session confirm button is disabled while pending (9469; Cancel button 9462). The server-side conclude race therefore reproduces via the second-tab / reload-mid-conclude window (conclude runs a full LLM chatComplete, so the window is long) or any non-UI/API caller - both still valid, so the server guard is worth adding as defense-in-depth, but please reframe the lead repro from "double-click End Session twice quickly" to the multi-tab/reload/API vector. The journal race (no client mitigation, fires on ordinary turns that change location + quest + NPC) is the higher-frequency half and should lead.
Author
Owner

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

Fixed in 09bdc806. Journal auto-fill now writes through the queued fresh-metadata patch path and only patches gameJournal, so concurrent journal updates no longer clobber other metadata. Both session conclusion endpoints now share an in-flight chatId dedup guard, return the existing summary when already concluded, and make the final summary append idempotent before narrator/checkpoint/keeper side effects run.

<!-- gh-comment-id:4761638171 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in 09bdc806. Journal auto-fill now writes through the queued fresh-metadata patch path and only patches gameJournal, so concurrent journal updates no longer clobber other metadata. Both session conclusion endpoints now share an in-flight chatId dedup guard, return the existing summary when already concluded, and make the final summary append idempotent before narrator/checkpoint/keeper side effects run.
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#1355
No description provided.