mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2710] [Issue]: Game state corruption — journal auto-fill races/clobbers metadata; /session/conclude has no dedup (duplicate summaries + keeper runs) #1355
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#1355
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/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/concludehas 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
updateJournal(db, chatId, transform)reads the whole chat metadata blob, mutates onlygameJournal, then writes the entire meta back. In the post-generation loop it's invoked withoutawaitfor several categories in the same turn (location change, NPC encounter, inventory change, and one per changed quest in a loop). All run concurrently, eachget→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./session/concludeno dedup. Unlike/session/start(which haspendingSessionStarts+ cleanup),/session/concludehas no dedup map and nogameSessionStatus === "concluded"early-return. Each call runs a fullchatComplete, appendssummarytogamePreviousSessionSummaries, creates a "Session N Concluded" narrator message, and queues the lorebook keeper.sessionNumberis 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):packages/server/src/services/generation/game-journal-runtime.ts:7-26(updateJournalfull-blob RMW); un-awaited calls ingenerate.routes.ts:7638(location),:7913(NPC),:7977(inventory),:8086(per-quest loop); also overwrites fields written at:7624(gameMap),:8149(encounterActive).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
updateJournalcalls) → journal entries drop and/orgameMap/encounterActiverevert to the prior turn.Suggested fix
awaiteachupdateJournalsequentially, or funnel all journal mutations through a per-chat async mutex/queue that re-reads fresh metadata immediately before each write and patches onlygameJournal(server-side merge — don't write back a stale full-meta blob); batch the per-quest loop into one transform.chatIdto/session/conclude(mirroringpendingSessionStarts) and an early guard rejecting a conclude whengameSessionStatusis alreadyconcludedfor the currentsessionNumber; make the summary append idempotent.Environment
b826f8f4)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:
@kolacheee commented on GitHub (Jun 21, 2026):
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):
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.)
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.)
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.
@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.