[PR #5614] [MERGED] fix(storage): scope residual lazy-table queries to their owning chat #6848

Closed
opened 2026-10-23 04:14:16 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5614
Author: @kolacheee
Created: 8/29/2026
Status: ✅ Merged
Merged: 8/29/2026
Merged by: @kolacheee

Base: staging ← Head: fix/5611-residual-lease-scoping


📝 Commits (4)

  • c0ad3de fix(storage): scope residual lazy-table queries to their owning chat
  • 679609b fix(storage): guard repeated chatId query params and update the scene-video delete pin
  • 5493199 style: format the updated scene-video delete pin
  • d9747f3 test: anchor the scene-video delete pin to its one handler

📊 Changes

22 files changed (+312 additions, -118 deletions)

View changed files

📝 packages/server/src/routes/agents.routes.ts (+4 -1)
📝 packages/server/src/routes/characters.routes.ts (+2 -1)
📝 packages/server/src/routes/chats.routes.ts (+5 -5)
📝 packages/server/src/routes/gallery.routes.ts (+7 -5)
📝 packages/server/src/routes/game.routes.ts (+10 -6)
📝 packages/server/src/routes/generate.routes.ts (+39 -20)
📝 packages/server/src/routes/generate/retry-agents-route.ts (+7 -6)
📝 packages/server/src/routes/professor-mari-workspace.routes.ts (+7 -2)
📝 packages/server/src/services/capability-packages/capability-persistence.service.ts (+5 -2)
📝 packages/server/src/services/game/checkpoint.service.ts (+17 -6)
📝 packages/server/src/services/mari-db/mari-images.service.ts (+2 -2)
📝 packages/server/src/services/storage/agents.storage.ts (+4 -3)
📝 packages/server/src/services/storage/chats.storage.ts (+45 -9)
📝 packages/server/src/services/storage/gallery.storage.ts (+16 -5)
📝 packages/server/src/services/storage/game-engine-state.storage.ts (+13 -6)
📝 packages/server/src/services/storage/game-scene-videos.storage.ts (+12 -6)
📝 packages/server/src/services/storage/game-state.storage.ts (+25 -19)
📝 packages/server/src/services/storage/mari-workspace-context.storage.ts (+7 -4)
📝 packages/server/src/services/storage/spatial-context.storage.ts (+2 -1)
📝 packages/shared/src/types/capability-runtime.ts (+2 -1)

...and 2 more files

📄 Description

Closes #5611. Part of the #5592 close-out (follows #5597/#5603/#5607–#5610).

Why

Any query the lazy store cannot scope to specific chats trips the safety fallback: the whole table becomes permanently fully resident for the process (Lazy table <name> is now fully resident in the log). A post-merge audit found the residual sites — and the worst one (getByMessage, funneling ~16 callers including updateByMessage, which already takes the chatId) fires on essentially every Game-mode turn, so on game-heavy installs the game_state_snapshots memory cap silently stopped working the moment a tracker updated.

What changed

  • Game-state hot path: the unscoped getByMessage is deleted; all callers use the already-scoped getByChatAndMessage (compiler-enforced migration). create()'s dedupe delete and getCommittedForMessages gain the chatId conjunct, and the eight bare-PK tracker writes in generate.routes.ts / retry-agents-route.ts are scoped with them — they were only masked because getByMessage leased first, so fixing one without the other just relocates the lease.
  • deleteSwipe: all nine cascade statements across game_state_snapshots / spatial_context_snapshots / game_engine_state now carry msg.chatId (already fetched at the top of the function).
  • Checkpoints: the captured-snapshot reads on create are scoped (which also enforces the cross-chat validation the code already performed by hand); getById/deleteById accept an optional chatId, threaded from the load route.
  • Gallery / scene videos: new listByChatAndFilePath for the image-serving route (the filePath argument literally embeds the chatId); getById/remove accept optional chatId, threaded at every warm caller.
  • Id-only endpoints (gallery DELETE /:id, checkpoint DELETE /:id, workspace DELETE /context/:id, agents PATCH /runs/:runId): accept an optional chatId (query/body) so the client can start passing it; until it does, these few cold endpoints keep the lease, as documented in #5611.
  • Diagnostics: getFullyResidentLazyTables() on the store controller, mirroring getResidentChatUnits() — empty is the healthy state.
  • Deliberately left unscoped (commented in-code, referencing #5611): the game scene-video route's sibling-chat gallery lookup and the character/persona clip-delete lookups, where the owner is only known after the read. galleryFileHasReferences (#5613) and the boot gallery walk (#5612) are tracked separately.

The chatId conjunct is behavior-preserving for reads and writes alike: the store's scope resolver uses it only to decide which chat's shards to load, and every scoped condition still matches exactly the rows it matched before (each site's rows always belonged to the chat being threaded — most sites validated exactly that one line later).

Regression

New block in lazy-chat-units.regression.ts: drives the real createGameStateStorage layer cold (scoped lookup, updateByMessage clone through create()'s dedupe, batch committed fetch) and asserts no table lease forms and the other chat's unit never loads — then runs the pre-fix condition shape and asserts the lease tripwire still fires. Verified red against the pre-fix storage layer (restored game-state.storage.ts from staging → suite fails; restored the fix → passes).

Validation done

  • tsc --noEmit all packages ✅ (shared rebuilt first)
  • Server + shared lint scripts ✅
  • Prettier (--check --end-of-line auto) on all 22 changed files ✅ (repo-wide pnpm check prettier step fails on this Windows box for all files — #5598, pre-existing)
  • Regression lanes: lazy-chat-units (lazy + eager-skip) ✅, message-sharding (lazy + eager) ✅, autonomous-check-storage ✅

Manual verification

  • Play a Game-mode turn with a tracker enabled on an install with MARINARA_MAX_RESIDENT_CHATS set and confirm the log no longer prints Lazy table game_state_snapshots is now fully resident
  • Delete a swipe in a chat with game state and confirm swipes/trackers still shift correctly
  • Create + load + delete a checkpoint in Game mode
  • Browse a chat gallery, delete an image, and delete a scene video
  • Edit a custom agent run's output (PATCH runs path)

Client follow-up (not in this PR)

The four id-only endpoints now accept an optional chatId; the client always has the chat open at those call sites and can start passing it to close the last cold leases. Happy to do that as a follow-up.

Summary by CodeRabbit

  • Bug Fixes

    • Improved chat isolation for game states, snapshots, checkpoints, gallery assets, scene videos, workspace contexts, and agent runs.
    • Prevented cross-chat reads, updates, deletions, and cleanup of shared resources.
    • Improved swipe cleanup to include related game engine state.
    • Preserved safe fallback behavior when chat context is unavailable.
    • Reduced unnecessary loading of unrelated chat data.
  • Tests

    • Added regression coverage for chat-scoped operations and efficient lazy loading.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5614 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/29/2026 **Status:** ✅ Merged **Merged:** 8/29/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/5611-residual-lease-scoping` --- ### 📝 Commits (4) - [`c0ad3de`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c0ad3deeea726269cbf3c097e0f174be4b1dcf7e) fix(storage): scope residual lazy-table queries to their owning chat - [`679609b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/679609b2892e8a2764756d156082dfb31cf32f07) fix(storage): guard repeated chatId query params and update the scene-video delete pin - [`5493199`](https://github.com/Pasta-Devs/Marinara-Engine/commit/54931994db735e40ea5f7943ffe80bc974ced41c) style: format the updated scene-video delete pin - [`d9747f3`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d9747f30603bc352e89937481ab84bdfd2ce4152) test: anchor the scene-video delete pin to its one handler ### 📊 Changes **22 files changed** (+312 additions, -118 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/routes/agents.routes.ts` (+4 -1) 📝 `packages/server/src/routes/characters.routes.ts` (+2 -1) 📝 `packages/server/src/routes/chats.routes.ts` (+5 -5) 📝 `packages/server/src/routes/gallery.routes.ts` (+7 -5) 📝 `packages/server/src/routes/game.routes.ts` (+10 -6) 📝 `packages/server/src/routes/generate.routes.ts` (+39 -20) 📝 `packages/server/src/routes/generate/retry-agents-route.ts` (+7 -6) 📝 `packages/server/src/routes/professor-mari-workspace.routes.ts` (+7 -2) 📝 `packages/server/src/services/capability-packages/capability-persistence.service.ts` (+5 -2) 📝 `packages/server/src/services/game/checkpoint.service.ts` (+17 -6) 📝 `packages/server/src/services/mari-db/mari-images.service.ts` (+2 -2) 📝 `packages/server/src/services/storage/agents.storage.ts` (+4 -3) 📝 `packages/server/src/services/storage/chats.storage.ts` (+45 -9) 📝 `packages/server/src/services/storage/gallery.storage.ts` (+16 -5) 📝 `packages/server/src/services/storage/game-engine-state.storage.ts` (+13 -6) 📝 `packages/server/src/services/storage/game-scene-videos.storage.ts` (+12 -6) 📝 `packages/server/src/services/storage/game-state.storage.ts` (+25 -19) 📝 `packages/server/src/services/storage/mari-workspace-context.storage.ts` (+7 -4) 📝 `packages/server/src/services/storage/spatial-context.storage.ts` (+2 -1) 📝 `packages/shared/src/types/capability-runtime.ts` (+2 -1) _...and 2 more files_ </details> ### 📄 Description Closes #5611. Part of the #5592 close-out (follows #5597/#5603/#5607–#5610). ## Why Any query the lazy store cannot scope to specific chats trips the safety fallback: the whole table becomes **permanently fully resident** for the process (`Lazy table <name> is now fully resident` in the log). A post-merge audit found the residual sites — and the worst one (`getByMessage`, funneling ~16 callers including `updateByMessage`, which already *takes* the chatId) fires on essentially every Game-mode turn, so on game-heavy installs the `game_state_snapshots` memory cap silently stopped working the moment a tracker updated. ## What changed - **Game-state hot path**: the unscoped `getByMessage` is deleted; all callers use the already-scoped `getByChatAndMessage` (compiler-enforced migration). `create()`'s dedupe delete and `getCommittedForMessages` gain the chatId conjunct, and the eight bare-PK tracker writes in `generate.routes.ts` / `retry-agents-route.ts` are scoped with them — they were only masked because `getByMessage` leased first, so fixing one without the other just relocates the lease. - **`deleteSwipe`**: all nine cascade statements across `game_state_snapshots` / `spatial_context_snapshots` / `game_engine_state` now carry `msg.chatId` (already fetched at the top of the function). - **Checkpoints**: the captured-snapshot reads on create are scoped (which also enforces the cross-chat validation the code already performed by hand); `getById`/`deleteById` accept an optional chatId, threaded from the load route. - **Gallery / scene videos**: new `listByChatAndFilePath` for the image-serving route (the filePath argument literally embeds the chatId); `getById`/`remove` accept optional chatId, threaded at every warm caller. - **Id-only endpoints** (gallery `DELETE /:id`, checkpoint `DELETE /:id`, workspace `DELETE /context/:id`, agents `PATCH /runs/:runId`): accept an optional chatId (query/body) so the client can start passing it; until it does, these few cold endpoints keep the lease, as documented in #5611. - **Diagnostics**: `getFullyResidentLazyTables()` on the store controller, mirroring `getResidentChatUnits()` — empty is the healthy state. - **Deliberately left unscoped** (commented in-code, referencing #5611): the game scene-video route's sibling-chat gallery lookup and the character/persona clip-delete lookups, where the owner is only known after the read. `galleryFileHasReferences` (#5613) and the boot gallery walk (#5612) are tracked separately. The chatId conjunct is behavior-preserving for reads and writes alike: the store's scope resolver uses it only to decide which chat's shards to load, and every scoped condition still matches exactly the rows it matched before (each site's rows always belonged to the chat being threaded — most sites validated exactly that one line later). ## Regression New block in `lazy-chat-units.regression.ts`: drives the **real** `createGameStateStorage` layer cold (scoped lookup, `updateByMessage` clone through `create()`'s dedupe, batch committed fetch) and asserts no table lease forms and the other chat's unit never loads — then runs the pre-fix condition shape and asserts the lease tripwire still fires. Verified red against the pre-fix storage layer (restored `game-state.storage.ts` from staging → suite fails; restored the fix → passes). ## Validation done - `tsc --noEmit` all packages ✅ (shared rebuilt first) - Server + shared `lint` scripts ✅ - Prettier (`--check --end-of-line auto`) on all 22 changed files ✅ (repo-wide `pnpm check` prettier step fails on this Windows box for all files — #5598, pre-existing) - Regression lanes: `lazy-chat-units` (lazy + eager-skip) ✅, `message-sharding` (lazy + eager) ✅, `autonomous-check-storage` ✅ ## Manual verification - [ ] Play a Game-mode turn with a tracker enabled on an install with `MARINARA_MAX_RESIDENT_CHATS` set and confirm the log no longer prints `Lazy table game_state_snapshots is now fully resident` - [ ] Delete a swipe in a chat with game state and confirm swipes/trackers still shift correctly - [ ] Create + load + delete a checkpoint in Game mode - [ ] Browse a chat gallery, delete an image, and delete a scene video - [ ] Edit a custom agent run's output (PATCH runs path) ## Client follow-up (not in this PR) The four id-only endpoints now accept an optional `chatId`; the client always has the chat open at those call sites and can start passing it to close the last cold leases. Happy to do that as a follow-up. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved chat isolation for game states, snapshots, checkpoints, gallery assets, scene videos, workspace contexts, and agent runs. * Prevented cross-chat reads, updates, deletions, and cleanup of shared resources. * Improved swipe cleanup to include related game engine state. * Preserved safe fallback behavior when chat context is unavailable. * Reduced unnecessary loading of unrelated chat data. * **Tests** * Added regression coverage for chat-scoped operations and efficient lazy loading. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:14:16 +07:00
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#6848
No description provided.