mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #2725] [Issue]: GameState snapshot storage — missing cascades, checkpoint restores wrong snapshot, swipe/commit ambiguity, unguarded parse, lock-bypassing endpoints #1368
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#1368
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/2725
Originally assigned to: @SpicyMarinara on GitHub.
Summary
The GameState snapshot storage layer has several integrity gaps.
game_state_snapshots(andgame_checkpoints) have no FK/cascade to messages or chats, and the application-level cleanup the schema comment promises is missing — so deleting a message orphans its snapshot (which then winsgetLatestand injects stale state into the next prompt), and deleting a chat leaks rows forever. Checkpoint restore looks up the snapshot by(messageId, swipeIndex=0)instead of the capturedsnapshotId, restoring the wrong turn or failing.getCommittedForMessagesignoresactiveSwipeIndexwhen a message has more than one committed swipe (the committed flag is never cleared).parseGameStateRowuses unguardedJSON.parsein the hot lock-critical path and is swallowed by silent 'Non-critical' catches, so a corrupt/imported column silently drops tracker writes. Branch/copy-chat drops a whole snapshot on one bad column. And the procedural time/weather endpoints write directly viaupdateLatest, bypassing field locks entirely.Bug 1 — Deleting a message orphans its snapshot, which becomes 'latest' and injects stale state (high)
How it breaks the pipeline:
removeMessage/removeMessagesdelete message rows but never delete the correspondinggame_state_snapshotsrows; there is no FK cascade. The orphaned snapshot retains the highestcreated_at, sogetLatest/getLatestCommitted(used as thegetForGenerationfallback) returns it, and the panel + next prompt advance from the deleted turn's state.Steps to replicate: Generate a turn (writes a snapshot), delete that assistant message; the tracker panel still shows the deleted turn's state and the next generation advances from it.
Code trace:
chats.storage.ts:752-758(removeMessage),:760-782(removeMessages) — no snapshot delete;migrate.ts:344-361message_id TEXT NOT NULLno FK; schema commentdb/schema/game-state.ts:9claims app-level cascade; onlyremoveSwipecleans (chats.storage.ts:902-905). Fallbackgame-state.storage.ts:72-79getLatestorders bycreated_at DESCwith no existence check. (Manifests when the new anchor lacks a swipe-matched snapshot.)Bug 2 — Deleting a chat/group leaks snapshots and checkpoints (medium)
How it breaks the pipeline:
remove/removeGroupclean agentRuns/agentMemory/chatImages but never callgameStateStore.deleteForChat/checkpointService.deleteForChat; no FK cascade exists, so snapshots and checkpoints accumulate as dead rows forever.Code trace:
chats.storage.ts:446-457(remove),:459-472(removeGroup);migrate.ts:344-375no FK ongame_state_snapshots.chat_id/game_checkpoints.chat_id(contrastchat_images:395has cascade);game-state.storage.ts:410-412deleteForChatwired only to explicitDELETE /:id/game-state(chats.routes.ts:1560);checkpoint.service.ts:84-86never called on chat removal.Bug 3 — Checkpoint restore ignores snapshotId, hard-codes swipe 0 (high)
How it breaks the pipeline: Checkpoints store the exact
snapshotId(FK) plus a denormalizedmessageId, but restore looks the snapshot up bygetByMessage(cp.messageId, 0). Checkpoints are created fromgetLatest(chatId)whose swipeIndex can be non-zero; there is noswipeIndexcolumn, so restore picks swipe 0's (different) snapshot or null.Steps to replicate: Swipe a message to swipe 2 (writes snapshot at swipe 2); trigger a checkpoint (combat/session-end); later restore — you get the stale swipe-0 state (or 'Checkpoint snapshot no longer exists').
Code trace: restore
game.routes.ts:7824getByMessage(cp.messageId, 0), throw:7825,cp.snapshotIdnever read; create:5466-5479fromgetLatest(game-state.storage.ts:72-79), no swipe persisted (checkpoints.ts:6-30,checkpoint.service.ts:52-69); nogetByIdexists;create()dedup deletes only same (messageId, swipeIndex) (game-state.storage.ts:237-243).Bug 4 — getCommittedForMessages ignores activeSwipeIndex on multi-committed messages (medium)
How it breaks the pipeline:
commit(id)only ever setscommitted=1and nothing clears it, so a message can have multiple committed swipe rows.getCommittedForMessagesfilters onlycommitted=1(no swipe filter, no orderBy) and dedupes per messageId keeping the last-iterated row, ignoring the message'sactiveSwipeIndex— so the agent/committed context for a historical message can show a different swipe's tracker values than the one accepted.Code trace:
game-state.storage.ts:217-228(getCommittedForMessages), commit:231-233; consumedgenerate.routes.ts:3988,4015-4017blindly viacommittedSnapshots.get(m.id)(the swipe-matched branch only covers the single visible anchor). (Note: not nondeterministic on the file backend — it deterministically keeps the newer-inserted swipe; the defect is that it ignoresactiveSwipeIndex, so swiping back to an older accepted swipe still injects the newer one.)Bug 5 — parseGameStateRow unguarded JSON.parse in the lock-critical path (high, root cause)
How it breaks the pipeline:
parseGameStateRowdoes unguardedJSON.parseon manualOverrides/presentCharacters/recentEvents/playerStats/personaStats — markedly less tolerant than its siblings (parseMaybeJsonreturns null,parseJsonFielddocumented 'malformed JSON must not throw'). It is the central lock/state parser; a corrupt/imported column throws synchronously and, in the world-state/persona/custom handlers, is swallowed by an empty catch, so the locked patch is silently never applied and the agent value is dropped.Code trace:
generate-route-utils.ts:998-1022(:1001,1014,1015,1016,1017raw parse); siblingscommitted-tracker-context.ts:23-30,game.routes.ts:1402,7838-7839; callersgenerate.routes.ts:7563,7674,7952,8012,8066,retry-agents-route.ts:2096. Reachable via Mari DB import:mari-db.service.tsJSON_COLUMNS (:291-301) omit recentEvents/personaStats/manualOverrides/fieldLocks, so a corrupt value in those passes import validation un-checked.Bug 6 — Persona-stats write swallowed under 'Non-critical' catch (high)
How it breaks the pipeline: The persona-stats handler's
lockState: parseGameStateRow(snap)runs inside a try whose catch is empty (// Non-critical). A throw from Bug 5 (or any DB error from the awaits) abandons the entire persona patch (bars+status+inventory) with no log, leaving the panel stale.Code trace:
generate.routes.ts:7931-7985(try:7931,lockState:7952, empty catch:7983-7985); the only logger.debug fires after success (:7961). World-state (catch :7646-7648) and custom-tracker (catch :8027-8029) have the same empty-catch pattern.Bug 7 — Branch/copy-chat drops a whole snapshot on one malformed column (low)
How it breaks the pipeline:
copySnapshotuses rawJSON.parseas eager arguments tocreate()for presentCharacters/recentEvents/playerStats/personaStats; the enclosing try/catch is documented to 'Ignore individual snapshot copy failures', so one bad column throws beforecreate()runs and the branch silently loses that message's entire tracker state (all-or-nothing, worse than the live path's per-field isolation).Code trace:
chats.routes.ts:2520-2562(:2537,2541,2547,2553raw parse; empty catch:2560-2562).Bug 8 — Time/weather auto-update endpoints bypass field locks (high)
How it breaks the pipeline: World-field locks are honored only via
applyTrackerFieldLocksToGameStatePatch, but/game/time/advanceand/game/weather/updatecallgameStateStore.updateLatestdirectly with{time}/{weather,temperature};_applyUpdatewrites them unconditionally (it consults locks only whenfields.fieldLocksis present), so a user-locked weather/temperature/time is silently overwritten by the procedural system.Steps to replicate: Lock weather (e.g. 'Eternal Storm') in the tracker panel, then take a turn that triggers the scene-analyzer weather/time update; the locked value is replaced.
Code trace: lock honoring
tracker-field-locks.ts:591-604; the legit path applies locks first (generate.routes.ts:5945-5949); the game endpoints do NOT —game.routes.ts:5848-5850(time),:5881-5884and:5899-5902(weather);updateLatest/_applyUpdategame-state.storage.ts:263-271,365-408(:400only reads fieldLocks when present). Reachable automatically fromGameSurface.tsx:4310-4320scene-result.Suggested Fix
removeMessage/removeMessages(deletegameStateSnapshots where messageId in ...) mirroringremoveSwipe, OR add a realON DELETE CASCADEFK. (Bug 1.)gameStateStore.deleteForChat(id)andcheckpointService.deleteForChat(id)inremove/removeGroup(per chat for groups), OR add FK cascades onchat_id. (Bug 2.)getById(snapshotId)togame-state.storage.tsand have restore fetch bycp.snapshotIdfirst (fallback togetByMessage); persistswipeIndexongame_checkpoints. (Bug 3.)getCommittedForMessagesrespect each message'sactiveSwipeIndex(and clearcommittedon sibling swipes when committing, or keep the first row per messageId with a deterministic order). (Bug 4.)JSON.parseinparseGameStateRowin try/catch returning[]/null(matchparseJsonField/parseMaybeJson). (Bug 5.)// Non-criticalcatches withlogger.error(err, '...')in the persona/world/custom handlers. (Bug 6.)JSON.parseincopySnapshotindividually with a default + warn log so the rest of the snapshot still copies. (Bug 7.)applyTrackerFieldLocksToGameStatePatch(or have_applyUpdateconsult the row'sfieldLocks) before the time/weatherupdateLatestwrites. (Bug 8.)Template checklist
pnpm checkpasses (TypeScript + ESLint)pnpm db:pushrun (schema/storage changes)game_state_snapshotsandgame_checkpointsrowsAffected files
packages/server/src/services/storage/chats.storage.tspackages/server/src/services/storage/game-state.storage.tspackages/server/src/db/migrate.tspackages/server/src/routes/game.routes.tspackages/server/src/routes/generate/generate-route-utils.tspackages/server/src/routes/generate.routes.tspackages/server/src/routes/chats.routes.tsAudit provenance
Found by a multi-agent static audit of the trackers/widgets subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: HIGH. Line numbers are against the
stagingworking tree.@SpicyMarinara commented on GitHub (Jun 21, 2026):
Fixed in
9d649074. Added application-level cleanup for game-state snapshots/checkpoints on message/chat/group deletion, made committed snapshot lookup respect each message's active swipe, made branch snapshot copy tolerate malformed JSON fields with a warning, routed procedural time/weather updates through tracker field locks, and replaced silent tracker-write catches with logs. Skipped as already fixed in current code: checkpoint restore already loads cp.snapshotId via getById, and parseGameStateRow already uses tolerant parseJsonField helpers.