[PR #5597] [MERGED] feat(storage): lazy per-chat unit loading for chat-scoped tables (#5592 Phase 2, PR-A) #6841

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

📋 Pull Request Information

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

Base: staging ← Head: feat/5592-phase2a-lazy-units


📝 Commits (7)

  • e3871f0 feat(storage): load chat-scoped tables lazily as per-chat units
  • b52f6a0 fix(storage): capture stale-file marks atomically with the flush's dirty keys
  • 7e1f649 fix(storage): track every stray id per table during a shard-file merge
  • 4353228 fix(storage): batch backup-recovery markers with the flush; scope inserts from normalized rows
  • 5f7c817 feat(storage): boot guard — lazy unit tables must be PK-only unique
  • ea062f2 fix(storage): table-wide message-id uniqueness via the harvest index; misfiled rows reachable through their owning unit
  • 19a7dc2 docs(capability): spatial snapshot ids must be globally unique

📊 Changes

8 files changed (+1514 additions, -58 deletions)

View changed files

📝 CHANGELOG.md (+5 -0)
📝 packages/server/src/db/file-backed-store.ts (+876 -26)
📝 packages/server/src/routes/game.routes.ts (+22 -3)
📝 packages/server/src/services/storage/chats.storage.ts (+42 -21)
📝 packages/server/src/services/storage/game-storyboards.storage.ts (+12 -7)
📝 packages/shared/src/types/capability-runtime.ts (+7 -0)
➕ scripts/regressions/lazy-chat-units.regression.ts (+540 -0)
📝 scripts/regressions/message-sharding.regression.ts (+10 -1)

📄 Description

Why

Part of #5592 (Phase 2, PR-A of the two-PR plan posted there). The file-native store keeps every row of every chat heap-resident, which is what pushes long multi-chat Termux profiles into the ~1 GB phone heap and exit-134 territory. Phases 0–1 (#5596) removed the biggest non-structural costs; this PR delivers the structural half: chat-scoped tables stop loading at boot and become resident one chat at a time.

What

Boot now only discovers shards for the 17 chat-scoped tables (messages, message_swipes, memory_chunks, agent_runs, agent_memory, chat_images, the game tables, workspace context, ooc/notes, call tables). For messages it additionally harvests the complete messageId -> chatId index (ids only; rows are dropped), because swipe shard resolution and query scoping depend on that map being total. The unassigned/orphan pseudo-unit still loads at boot — orphan-adoption healing needs it resident and it is tiny by design.

First touch loads a whole chat unit: every lazy table's shard for that chatId, messages before swipes, through the same per-file recovery pipeline the eager loader ran (bak fallback, malformed-row quarantine, self-heal marking — now recorded at load time, when the unit's dirty keys can actually flush). Stray rows found in another unit's file pull their unit in transitively, and a canonical file's copy still beats a stray copy regardless of load order (the eager dedup rule, preserved via stray-provenance tracking).

Scoping: a WHERE-condition extractor computes which units a query can possibly match — directly from the shard column, through the message index for swipes and messages.id, or by probing resident rows for other primary keys — with AND/OR combinators matching the evaluator exactly. Anything it cannot bound (backup export, cross-chat predicates like sourceChatId, agentConfigId cascades) leases the whole table, so correctness never depends on the extractor being clever. Inserts/updates load their destination units before uniqueness checks; intra-unit cascades (messageId/snapshotId/callId children) ride a parent-unit hint instead of leasing.

Consistency machinery: per-unit positive evidence for emptied-shard deletion (with a defensive requeue for dirty keys of unloaded units), scoped message-index rebuild on rollback (the complete harvested map must survive), transaction snapshots mirror mid-transaction unit loads so a rollback reverts the write but keeps the loaded rows, and the manifest reports the harvested messages total while omitting counts it cannot know.

Storage-layer scoping so hot paths do not lease: game-state cleanup on message delete threads the owning chatIds; the chat lastMessageAt backfill queries per chat instead of sweeping all messages; stale-storyboard recovery is per-chat at read time with a process-start cutoff floor, replacing the startup-wide sweep (a chat never read again keeps its stale rows on disk, invisible, until first read — see the storyboard commit note).

Kill switch: MARINARA_EAGER_STORAGE=1 empties the lazy tier and restores the previous eager boot end to end.

Explicitly out of scope (PR-B): unit eviction. This PR changes when rows become resident, never whether loaded rows stay.

Regressions

New lane scripts/regressions/lazy-chat-units.regression.ts: scoped query loads one unit while an untouched unit's file stays byte-identical (no boot healing), first-touch healing, swipes-load-with-unit, cold insert preserves shard siblings, unbounded select leases, chat deletion removes never-read units' files, mid-transaction unit load survives rollback, manifest counts. It self-skips under MARINARA_EAGER_STORAGE.

Adapted message-sharding.regression.ts minimally: four blocks that asserted heal-at-boot now touch the table first (heal-at-first-load); every other assertion is unchanged, and the whole suite also passes with MARINARA_EAGER_STORAGE=1 (verified locally), so the eager path stays pinned.

Also run locally and green: file-backed-shutdown, storage-writer-lock, slurp-storage, memory-recall-revectorize, chat-branch-lineage, agent-runtime, capability-package-lifecycle, checkpoint-retention; full node regression suite run in progress at submission time — result will be posted as a comment if anything surfaces.

Test plan

  • pnpm check on a non-Windows checkout (Windows checkouts currently fail format:check repo-wide on CRLF — unrelated)
  • pnpm regression (full node suite)
  • Manually verify in browser: open an existing multi-chat profile, switch between chats, send messages, swipe, branch, delete a chat — everything behaves as before
  • Manually verify: create a profile backup and re-import it; confirm all chats' histories survive
  • Manually verify with MARINARA_EAGER_STORAGE=1: server boots and behaves identically to v2.4.4
  • Manually verify on Termux (or with a small --max-old-space-size): boot memory with a large profile is visibly lower and chats load on first open

References #5592 (PR-B, eviction, follows separately — do not auto-close).

Summary by CodeRabbit

  • New Features

    • Improved storage efficiency by loading chat data on demand, with an option to enable eager loading.
    • Added automatic per-chat recovery for stale or interrupted game storyboards.
    • Improved recovery and cleanup of damaged, misplaced, duplicate, and malformed message storage.
  • Bug Fixes

    • Prevented unrelated chat data from being affected during cleanup, writes, queries, and recovery operations.
    • Improved consistency when restoring data after interrupted transactions or storage errors.
    • Improved chat timestamp accuracy and game-state cleanup.

🔄 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/5597 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/28/2026 **Status:** ✅ Merged **Merged:** 8/28/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5592-phase2a-lazy-units` --- ### 📝 Commits (7) - [`e3871f0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e3871f00dda3f87c7ae47aef89f53b47feeef1f1) feat(storage): load chat-scoped tables lazily as per-chat units - [`b52f6a0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b52f6a008f8bac6a6649e90e6d1c6879e9f6b8aa) fix(storage): capture stale-file marks atomically with the flush's dirty keys - [`7e1f649`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7e1f649793085acee403c08ea940dd3d3b4037fe) fix(storage): track every stray id per table during a shard-file merge - [`4353228`](https://github.com/Pasta-Devs/Marinara-Engine/commit/435322805e2c21fe7ec53b1c09f1fed621fc80a6) fix(storage): batch backup-recovery markers with the flush; scope inserts from normalized rows - [`5f7c817`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5f7c81730a535d390039864cc175032bbecf654f) feat(storage): boot guard — lazy unit tables must be PK-only unique - [`ea062f2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/ea062f2b312e21c3b8a2faae975433abf6746239) fix(storage): table-wide message-id uniqueness via the harvest index; misfiled rows reachable through their owning unit - [`19a7dc2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/19a7dc2ca25414ee5eaa60d88374609ff2b159d0) docs(capability): spatial snapshot ids must be globally unique ### 📊 Changes **8 files changed** (+1514 additions, -58 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+5 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+876 -26) 📝 `packages/server/src/routes/game.routes.ts` (+22 -3) 📝 `packages/server/src/services/storage/chats.storage.ts` (+42 -21) 📝 `packages/server/src/services/storage/game-storyboards.storage.ts` (+12 -7) 📝 `packages/shared/src/types/capability-runtime.ts` (+7 -0) ➕ `scripts/regressions/lazy-chat-units.regression.ts` (+540 -0) 📝 `scripts/regressions/message-sharding.regression.ts` (+10 -1) </details> ### 📄 Description ## Why Part of #5592 (Phase 2, PR-A of the two-PR plan posted there). The file-native store keeps every row of every chat heap-resident, which is what pushes long multi-chat Termux profiles into the ~1 GB phone heap and exit-134 territory. Phases 0–1 (#5596) removed the biggest non-structural costs; this PR delivers the structural half: chat-scoped tables stop loading at boot and become resident one chat at a time. ## What **Boot** now only *discovers* shards for the 17 chat-scoped tables (messages, message_swipes, memory_chunks, agent_runs, agent_memory, chat_images, the game tables, workspace context, ooc/notes, call tables). For `messages` it additionally harvests the complete `messageId -> chatId` index (ids only; rows are dropped), because swipe shard resolution and query scoping depend on that map being total. The unassigned/orphan pseudo-unit still loads at boot — orphan-adoption healing needs it resident and it is tiny by design. **First touch loads a whole chat unit**: every lazy table's shard for that chatId, messages before swipes, through the same per-file recovery pipeline the eager loader ran (bak fallback, malformed-row quarantine, self-heal marking — now recorded at load time, when the unit's dirty keys can actually flush). Stray rows found in another unit's file pull their unit in transitively, and a canonical file's copy still beats a stray copy regardless of load order (the eager dedup rule, preserved via stray-provenance tracking). **Scoping**: a WHERE-condition extractor computes which units a query can possibly match — directly from the shard column, through the message index for swipes and `messages.id`, or by probing resident rows for other primary keys — with AND/OR combinators matching the evaluator exactly. Anything it cannot bound (backup export, cross-chat predicates like `sourceChatId`, `agentConfigId` cascades) leases the whole table, so correctness never depends on the extractor being clever. Inserts/updates load their destination units before uniqueness checks; intra-unit cascades (messageId/snapshotId/callId children) ride a parent-unit hint instead of leasing. **Consistency machinery**: per-unit positive evidence for emptied-shard deletion (with a defensive requeue for dirty keys of unloaded units), scoped message-index rebuild on rollback (the complete harvested map must survive), transaction snapshots mirror mid-transaction unit loads so a rollback reverts the write but keeps the loaded rows, and the manifest reports the harvested messages total while omitting counts it cannot know. **Storage-layer scoping** so hot paths do not lease: game-state cleanup on message delete threads the owning chatIds; the chat lastMessageAt backfill queries per chat instead of sweeping all messages; stale-storyboard recovery is per-chat at read time with a process-start cutoff floor, replacing the startup-wide sweep (a chat never read again keeps its stale rows on disk, invisible, until first read — see the storyboard commit note). **Kill switch**: `MARINARA_EAGER_STORAGE=1` empties the lazy tier and restores the previous eager boot end to end. Explicitly out of scope (PR-B): unit eviction. This PR changes *when* rows become resident, never *whether* loaded rows stay. ## Regressions New lane `scripts/regressions/lazy-chat-units.regression.ts`: scoped query loads one unit while an untouched unit's file stays byte-identical (no boot healing), first-touch healing, swipes-load-with-unit, cold insert preserves shard siblings, unbounded select leases, chat deletion removes never-read units' files, mid-transaction unit load survives rollback, manifest counts. It self-skips under `MARINARA_EAGER_STORAGE`. Adapted `message-sharding.regression.ts` minimally: four blocks that asserted heal-at-boot now touch the table first (heal-at-first-load); every other assertion is unchanged, and the whole suite also passes with `MARINARA_EAGER_STORAGE=1` (verified locally), so the eager path stays pinned. Also run locally and green: file-backed-shutdown, storage-writer-lock, slurp-storage, memory-recall-revectorize, chat-branch-lineage, agent-runtime, capability-package-lifecycle, checkpoint-retention; full node regression suite run in progress at submission time — result will be posted as a comment if anything surfaces. ## Test plan - [x] `pnpm check` on a non-Windows checkout (Windows checkouts currently fail `format:check` repo-wide on CRLF — unrelated) - [x] `pnpm regression` (full node suite) - [x] Manually verify in browser: open an existing multi-chat profile, switch between chats, send messages, swipe, branch, delete a chat — everything behaves as before - [x] Manually verify: create a profile backup and re-import it; confirm all chats' histories survive - [x] Manually verify with `MARINARA_EAGER_STORAGE=1`: server boots and behaves identically to v2.4.4 - [x] Manually verify on Termux (or with a small `--max-old-space-size`): boot memory with a large profile is visibly lower and chats load on first open References #5592 (PR-B, eviction, follows separately — do not auto-close). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved storage efficiency by loading chat data on demand, with an option to enable eager loading. * Added automatic per-chat recovery for stale or interrupted game storyboards. * Improved recovery and cleanup of damaged, misplaced, duplicate, and malformed message storage. * **Bug Fixes** * Prevented unrelated chat data from being affected during cleanup, writes, queries, and recovery operations. * Improved consistency when restoring data after interrupted transactions or storage errors. * Improved chat timestamp accuracy and game-state cleanup. <!-- 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:13 +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#6841
No description provided.