[GH-ISSUE #2725] [Issue]: GameState snapshot storage — missing cascades, checkpoint restores wrong snapshot, swipe/commit ambiguity, unguarded parse, lock-bypassing endpoints #1368

Closed
opened 2026-10-21 05:32:32 +07:00 by bsakaguchi · 1 comment
Owner

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 (and game_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 wins getLatest and 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 captured snapshotId, restoring the wrong turn or failing. getCommittedForMessages ignores activeSwipeIndex when a message has more than one committed swipe (the committed flag is never cleared). parseGameStateRow uses unguarded JSON.parse in 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 via updateLatest, 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/removeMessages delete message rows but never delete the corresponding game_state_snapshots rows; there is no FK cascade. The orphaned snapshot retains the highest created_at, so getLatest/getLatestCommitted (used as the getForGeneration fallback) 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-361 message_id TEXT NOT NULL no FK; schema comment db/schema/game-state.ts:9 claims app-level cascade; only removeSwipe cleans (chats.storage.ts:902-905). Fallback game-state.storage.ts:72-79 getLatest orders by created_at DESC with 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/removeGroup clean agentRuns/agentMemory/chatImages but never call gameStateStore.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-375 no FK on game_state_snapshots.chat_id / game_checkpoints.chat_id (contrast chat_images :395 has cascade); game-state.storage.ts:410-412 deleteForChat wired only to explicit DELETE /:id/game-state (chats.routes.ts:1560); checkpoint.service.ts:84-86 never 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 denormalized messageId, but restore looks the snapshot up by getByMessage(cp.messageId, 0). Checkpoints are created from getLatest(chatId) whose swipeIndex can be non-zero; there is no swipeIndex column, 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:7824 getByMessage(cp.messageId, 0), throw :7825, cp.snapshotId never read; create :5466-5479 from getLatest (game-state.storage.ts:72-79), no swipe persisted (checkpoints.ts:6-30, checkpoint.service.ts:52-69); no getById exists; 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 sets committed=1 and nothing clears it, so a message can have multiple committed swipe rows. getCommittedForMessages filters only committed=1 (no swipe filter, no orderBy) and dedupes per messageId keeping the last-iterated row, ignoring the message's activeSwipeIndex — 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; consumed generate.routes.ts:3988,4015-4017 blindly via committedSnapshots.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 ignores activeSwipeIndex, 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: parseGameStateRow does unguarded JSON.parse on manualOverrides/presentCharacters/recentEvents/playerStats/personaStats — markedly less tolerant than its siblings (parseMaybeJson returns null, parseJsonField documented '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,1017 raw parse); siblings committed-tracker-context.ts:23-30, game.routes.ts:1402,7838-7839; callers generate.routes.ts:7563,7674,7952,8012,8066, retry-agents-route.ts:2096. Reachable via Mari DB import: mari-db.service.ts JSON_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: copySnapshot uses raw JSON.parse as eager arguments to create() for presentCharacters/recentEvents/playerStats/personaStats; the enclosing try/catch is documented to 'Ignore individual snapshot copy failures', so one bad column throws before create() 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,2553 raw 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/advance and /game/weather/update call gameStateStore.updateLatest directly with {time}/{weather,temperature}; _applyUpdate writes them unconditionally (it consults locks only when fields.fieldLocks is 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-5884 and :5899-5902 (weather); updateLatest/_applyUpdate game-state.storage.ts:263-271,365-408 (:400 only reads fieldLocks when present). Reachable automatically from GameSurface.tsx:4310-4320 scene-result.


Suggested Fix

  • Add application-level cascade in removeMessage/removeMessages (delete gameStateSnapshots where messageId in ...) mirroring removeSwipe, OR add a real ON DELETE CASCADE FK. (Bug 1.)
  • Call gameStateStore.deleteForChat(id) and checkpointService.deleteForChat(id) in remove/removeGroup (per chat for groups), OR add FK cascades on chat_id. (Bug 2.)
  • Add getById(snapshotId) to game-state.storage.ts and have restore fetch by cp.snapshotId first (fallback to getByMessage); persist swipeIndex on game_checkpoints. (Bug 3.)
  • Make getCommittedForMessages respect each message's activeSwipeIndex (and clear committed on sibling swipes when committing, or keep the first row per messageId with a deterministic order). (Bug 4.)
  • Wrap each JSON.parse in parseGameStateRow in try/catch returning []/null (match parseJsonField/parseMaybeJson). (Bug 5.)
  • Replace the empty // Non-critical catches with logger.error(err, '...') in the persona/world/custom handlers. (Bug 6.)
  • Wrap each JSON.parse in copySnapshot individually with a default + warn log so the rest of the snapshot still copies. (Bug 7.)
  • Run applyTrackerFieldLocksToGameStatePatch (or have _applyUpdate consult the row's fieldLocks) before the time/weather updateLatest writes. (Bug 8.)

Template checklist

  • pnpm check passes (TypeScript + ESLint)
  • pnpm db:push run (schema/storage changes)
  • Manually verify deleting the latest assistant message clears its tracker state (no orphan injected next turn)
  • Manually verify deleting a chat removes its game_state_snapshots and game_checkpoints rows
  • Manually verify restoring a checkpoint captured on swipe 2 restores that swipe's tracker state
  • Manually verify a multi-committed message injects the active swipe's tracker values
  • Manually verify a corrupt/imported snapshot column degrades gracefully (no silent dropped tracker write, error logged)
  • Manually verify branching a chat preserves each message's tracker snapshot
  • Manually verify a locked weather/temperature/time survives the procedural time/weather update

Affected files

  • packages/server/src/services/storage/chats.storage.ts
  • packages/server/src/services/storage/game-state.storage.ts
  • packages/server/src/db/migrate.ts
  • packages/server/src/routes/game.routes.ts
  • packages/server/src/routes/generate/generate-route-utils.ts
  • packages/server/src/routes/generate.routes.ts
  • packages/server/src/routes/chats.routes.ts

Audit 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 staging working tree.

Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are intentionally left UNCHECKED for a human to verify before close.

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` (and `game_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 wins `getLatest` and 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 captured `snapshotId`, restoring the wrong turn or failing. `getCommittedForMessages` ignores `activeSwipeIndex` when a message has more than one committed swipe (the committed flag is never cleared). `parseGameStateRow` uses unguarded `JSON.parse` in 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 via `updateLatest`, 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`/`removeMessages` delete message rows but never delete the corresponding `game_state_snapshots` rows; there is no FK cascade. The orphaned snapshot retains the highest `created_at`, so `getLatest`/`getLatestCommitted` (used as the `getForGeneration` fallback) 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-361` `message_id TEXT NOT NULL` no FK; schema comment `db/schema/game-state.ts:9` claims app-level cascade; only `removeSwipe` cleans (`chats.storage.ts:902-905`). Fallback `game-state.storage.ts:72-79` `getLatest` orders by `created_at DESC` with 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`/`removeGroup` clean agentRuns/agentMemory/chatImages but never call `gameStateStore.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-375` no FK on `game_state_snapshots.chat_id` / `game_checkpoints.chat_id` (contrast `chat_images` `:395` has cascade); `game-state.storage.ts:410-412` `deleteForChat` wired only to explicit `DELETE /:id/game-state` (`chats.routes.ts:1560`); `checkpoint.service.ts:84-86` never 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 denormalized `messageId`, but restore looks the snapshot up by `getByMessage(cp.messageId, 0)`. Checkpoints are created from `getLatest(chatId)` whose swipeIndex can be non-zero; there is no `swipeIndex` column, 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:7824` `getByMessage(cp.messageId, 0)`, throw `:7825`, `cp.snapshotId` never read; create `:5466-5479` from `getLatest` (`game-state.storage.ts:72-79`), no swipe persisted (`checkpoints.ts:6-30`, `checkpoint.service.ts:52-69`); no `getById` exists; `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 sets `committed=1` and nothing clears it, so a message can have multiple committed swipe rows. `getCommittedForMessages` filters only `committed=1` (no swipe filter, no orderBy) and dedupes per messageId keeping the last-iterated row, ignoring the message's `activeSwipeIndex` — 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`; consumed `generate.routes.ts:3988,4015-4017` blindly via `committedSnapshots.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 ignores `activeSwipeIndex`, 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:** `parseGameStateRow` does unguarded `JSON.parse` on manualOverrides/presentCharacters/recentEvents/playerStats/personaStats — markedly less tolerant than its siblings (`parseMaybeJson` returns null, `parseJsonField` documented '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,1017` raw parse); siblings `committed-tracker-context.ts:23-30`, `game.routes.ts:1402,7838-7839`; callers `generate.routes.ts:7563,7674,7952,8012,8066`, `retry-agents-route.ts:2096`. Reachable via Mari DB import: `mari-db.service.ts` JSON_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:** `copySnapshot` uses raw `JSON.parse` as eager arguments to `create()` for presentCharacters/recentEvents/playerStats/personaStats; the enclosing try/catch is documented to 'Ignore individual snapshot copy failures', so one bad column throws before `create()` 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,2553` raw 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/advance` and `/game/weather/update` call `gameStateStore.updateLatest` directly with `{time}`/`{weather,temperature}`; `_applyUpdate` writes them unconditionally (it consults locks only when `fields.fieldLocks` is 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-5884` and `:5899-5902` (weather); `updateLatest`/`_applyUpdate` `game-state.storage.ts:263-271,365-408` (`:400` only reads fieldLocks when present). Reachable automatically from `GameSurface.tsx:4310-4320` scene-result. --- ## Suggested Fix - Add application-level cascade in `removeMessage`/`removeMessages` (delete `gameStateSnapshots where messageId in ...`) mirroring `removeSwipe`, OR add a real `ON DELETE CASCADE` FK. (Bug 1.) - Call `gameStateStore.deleteForChat(id)` and `checkpointService.deleteForChat(id)` in `remove`/`removeGroup` (per chat for groups), OR add FK cascades on `chat_id`. (Bug 2.) - Add `getById(snapshotId)` to `game-state.storage.ts` and have restore fetch by `cp.snapshotId` first (fallback to `getByMessage`); persist `swipeIndex` on `game_checkpoints`. (Bug 3.) - Make `getCommittedForMessages` respect each message's `activeSwipeIndex` (and clear `committed` on sibling swipes when committing, or keep the first row per messageId with a deterministic order). (Bug 4.) - Wrap each `JSON.parse` in `parseGameStateRow` in try/catch returning `[]`/`null` (match `parseJsonField`/`parseMaybeJson`). (Bug 5.) - Replace the empty `// Non-critical` catches with `logger.error(err, '...')` in the persona/world/custom handlers. (Bug 6.) - Wrap each `JSON.parse` in `copySnapshot` individually with a default + warn log so the rest of the snapshot still copies. (Bug 7.) - Run `applyTrackerFieldLocksToGameStatePatch` (or have `_applyUpdate` consult the row's `fieldLocks`) before the time/weather `updateLatest` writes. (Bug 8.) --- ## Template checklist - [ ] `pnpm check` passes (TypeScript + ESLint) - [ ] `pnpm db:push` run (schema/storage changes) - [ ] Manually verify deleting the latest assistant message clears its tracker state (no orphan injected next turn) - [ ] Manually verify deleting a chat removes its `game_state_snapshots` and `game_checkpoints` rows - [ ] Manually verify restoring a checkpoint captured on swipe 2 restores that swipe's tracker state - [ ] Manually verify a multi-committed message injects the active swipe's tracker values - [ ] Manually verify a corrupt/imported snapshot column degrades gracefully (no silent dropped tracker write, error logged) - [ ] Manually verify branching a chat preserves each message's tracker snapshot - [ ] Manually verify a locked weather/temperature/time survives the procedural time/weather update --- ### Affected files - `packages/server/src/services/storage/chats.storage.ts` - `packages/server/src/services/storage/game-state.storage.ts` - `packages/server/src/db/migrate.ts` - `packages/server/src/routes/game.routes.ts` - `packages/server/src/routes/generate/generate-route-utils.ts` - `packages/server/src/routes/generate.routes.ts` - `packages/server/src/routes/chats.routes.ts` ### Audit 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 `staging` working tree. > Note: this issue was AI-drafted from a static read of the code; the validation/test-plan boxes are intentionally left UNCHECKED for a human to verify before close.
Author
Owner

@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.

<!-- gh-comment-id:4761805558 --> @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.
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#1368
No description provided.