[PR #4754] [MERGED] feat(storage): shard every chat-keyed table (#4708, part 3 — storage format 4) #6488

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

📋 Pull Request Information

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

Base: staging ← Head: feat/4708-shard-remaining-tables


📝 Commits (10+)

  • aa109b5 feat(storage): shard the remaining six chat-keyed tables (#4708 PR 3)
  • 277fca3 feat(storage): full chat-keyed scope + review fixes for PR 3
  • f443a5e fix(storage): persist SET_NULL cascades for sharded children + missing chat cascades
  • fdbacdb Merge feat/4708-downgrade-guard (verified/unverified guard fixes) into feat/4708-shard-remaining-tables
  • 6e6f049 test(regressions): harden the SHARDED_TABLES pairing-pin parser
  • e16e1ac Merge feat/4708-downgrade-guard (bak-only manifest + ls-tree guard fixes) into feat/4708-shard-remaining-tables
  • 9c31fb4 Merge branch 'staging' into feat/4708-shard-remaining-tables
  • 9666a0c Merge feat/4708-downgrade-guard (third review round) into feat/4708-shard-remaining-tables
  • 607d6b4 Merge feat/4708-downgrade-guard (regression hygiene) into feat/4708-shard-remaining-tables
  • 8bb3060 Merge branch 'staging' into feat/4708-shard-remaining-tables

📊 Changes

7 files changed (+392 additions, -57 deletions)

View changed files

📝 docs/TROUBLESHOOTING.md (+2 -2)
📝 docs/development/file-storage.md (+4 -2)
📝 packages/server/src/db/file-backed-store.ts (+110 -44)
📝 scripts/protect-launcher-data.mjs (+19 -2)
📝 scripts/regressions/launcher-format-guard.regression.mjs (+37 -2)
📝 scripts/regressions/message-sharding.regression.ts (+219 -4)
📝 storage-format.json (+1 -1)

📄 Description

Note

Stacked on #4738 (which is stacked on #4735). This diff includes both until they merge; the PR 3-only changes are the two commits touching file-backed-store.ts, storage-format.json, protect-launcher-data.mjs, two docs, and two regression files. Completes the maintainer-mandated full table scope from the approved plan on #4708.

Linked issue

Part 3 of #4708 — with this, every chat-keyed table on a per-turn write path is sharded (two documented exceptions below). The issue can close once the compat-cleanup follow-up is filed (see checklist there).

Why this change

  • #4735 sharded messages and message_swipes because they sat on the per-message write path. The same write-amplification applies to every other chat-keyed table: memory chunks and agent memory rewrite per turn (setMemories is the store's own named hot path), game state/engine/storyboards per game-mode turn, agent runs per agent call, call sessions/messages per utterance, gallery and scene-video rows per generation, influences/notes per conversation turn — each previously re-serialized the full table across all chats on every write. The maintainer mandated full scope across follow-up PRs (decision 3 on #4708, re-confirmed on Discord).

What changed

  • Fourteen more sharded tables (sixteen total) — memory_chunks, chat_images, agent_runs, agent_memory, conversation_call_sessions, conversation_call_messages, game_state_snapshots, game_engine_state, game_checkpoints, game_turn_storyboards, game_scene_videos, spatial_context_snapshots, ooc_influences, conversation_notes join SHARDED_TABLES.
    • Scope note for review: the #4708 checklist named six tables; the pre-PR adversarial review caught that list under-scoping the full-table mandate (agent_memory alone is the per-turn setMemories hot path). Doing all of them now means one format bump and one migration event for users instead of two. If you'd rather split, the added tables are one list entry each.
    • Two documented exceptions stay monoliths: lorebooks (nullable chatId — a chat-linked library entity, not per-chat data) and game_turn_storyboard_keyframes (no chat column; sharding it cleanly wants a denormalized chatId, which is a schema decision — proposed as a follow-up on #4708).
  • One resolver instead of scattered ternaries — shardKeyForRow(table, row) is the single source of truth for row→shard mapping: message_swipes resolves through the parent-message index (keeping the orphan-marker machinery), ooc_influences/conversation_notes shard by targetChatId (their read-side key — they're injected per roleplay turn of the target chat) via a small per-table key-column map, and everything else by its own chatId, with the orphaned-rows fallback. Migration, downgrade-artifact quarantine, crash recovery, foreign-row healing, and canonical dedup from #4735 apply to all new tables unchanged — they key off SHARDED_TABLES membership. Key-column changes on existing rows (conflict upserts during profile import) are already covered generically: insert/update dirty both the old and new rows' keys.
  • Storage format 3 → 4 — STORAGE_VERSION and root storage-format.json bump together (regression-pinned pairing). The #4738 guard machinery handles the new boundary with no changes: a format-4 data dir refuses format-3 and format-2 targets in the launchers, installer, and in-app updater. STORAGE_VERSION is now exported so regressions pin against the current version rather than chasing literals on every bump.
  • .pre-shard backups survive re-migration (review finding) — a migrate → unshard → migrate round trip previously renamed the rebuilt monolith over the pristine pre-migration backup, silently breaking the docs' "never deleted by the Engine" promise. Subsequent backups now take a timestamped .pre-shard-<ts> name. Regression-pinned.
  • unshard covers all sixteen tables — the mirrored list in protect-launcher-data.mjs is extended (the pairing regression fails the build if the lists diverge), and its messages no longer hardcode stale format numbers. Honest note on 4 → 3 downgrades: unshard rebuilds all sharded tables to monoliths and lands the manifest on format 2; a format-3 build booted on that data simply re-runs its own messages/swipes migration — correct, just one extra migration pass.
  • SET_NULL cascades persist for sharded children (write-path audit finding) — applySetNullRelations was the one mutation path calling markDirty without shard keys; for a sharded child (game_checkpoints is a SET_NULL child of spatial_context_snapshots) the null-out landed in memory but never reached disk, so a restart resurrected the dangling spatialSnapshotId. Regression asserts the null reaches the shard file on disk.
  • ⚠️ Behavior fix worth reviewer attention: missing chat cascades for influences/notes — ooc_influences and conversation_notes declare onDelete: cascade on both chat FKs in their schemas, but the store's cascade graph never carried the relations, so their rows outlived their chats. Invisible inside the old monolith; a permanently leaked per-chat shard file once sharded, plus stale injections if a chat id is ever reused via profile import. Both FK directions are now in the graph (this also makes the mari-db dangling-reference validator aware of them). If you'd rather keep behavior changes out of a storage-layout PR, say the word and I'll split it out.
  • Docs — docs/development/file-storage.md sharded-tables section rewritten with the full enumerated list, the two key-column exceptions, and the two deliberate monolith exceptions with reasons; the TROUBLESHOOTING downgrade section wording broadened from "messages" to per-chat data generally.
  • Regressions — per-chat flush granularity + cascade deletion for the direct-chatId family, a fourteen-monolith one-boot migration sweep asserting row survival per table (including the targetChatId grouping, never sourceChatId), the .pre-shard round-trip preservation pin, and an unshard conversion case for a non-message table asserting content.

Deferred, unchanged from the plan: the backup .bak-exclusion follow-up (decision 4) — sixteen shard families grow the backup ZIP entry count further (the ZIP32 entry ceiling gets ~4× closer for very large installs), so the measurement-gated follow-up on #4708 stands, now with more reason.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • Manually verify a real upgrade: boot this build on an existing profile with populated memories/gallery/game/call data and confirm the tables migrate (shard dirs appear, .pre-shard originals preserved) and the app behaves normally (memory recall, agent memory, gallery, game mode incl. checkpoints/storyboards, calls, OOC influences/notes).
  • Manually verify the guard round-trip on format-4 data: an older target is refused; unshard + downgrade + re-upgrade works, and the original .pre-shard backups survive the round trip.
  • Commands run: pnpm check (green, twice — before and after the scope expansion), message-sharding lane incl. the fourteen-table migration sweep and .pre-shard round-trip pin (green), launcher-format-guard lane incl. the pairing pins and unshard conversion case (green), file-backed-shutdown + autonomous-scheduler-gate lanes (green).

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Translated docs on the docs-i18n branch updated to match, or a [docs-i18n] follow-up issue opened (see CONTRIBUTING.md § Translated documentation)
  • Version/release files updated (only if this PR includes a version bump)

The previous follow-up #4739 is closed (translations landed), so a new [docs-i18n] docs/TROUBLESHOOTING.md docs/development/file-storage.md follow-up issue accompanies this PR.

Summary by CodeRabbit

  • New Features
    • Added per-chat storage sharding for messages, swipes, notes, influences, and related data.
    • Added tools to check storage-format compatibility and safely convert sharded data back to a unified format.
  • Bug Fixes
    • Improved chat deletion cleanup and preservation of migration backups.
    • Added safeguards to prevent incompatible downgrades from damaging stored chats.
  • Documentation
    • Expanded storage layout documentation, troubleshooting steps, Docker/Podman guidance, backup behavior, and recovery procedures.

🔄 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/4754 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/8/2026 **Status:** ✅ Merged **Merged:** 8/8/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/4708-shard-remaining-tables` --- ### 📝 Commits (10+) - [`aa109b5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/aa109b5dab56a1dc765b3bff7845cf8e8a0ba78a) feat(storage): shard the remaining six chat-keyed tables (#4708 PR 3) - [`277fca3`](https://github.com/Pasta-Devs/Marinara-Engine/commit/277fca35e3eb7879a01e19a4c908cc1b785ed709) feat(storage): full chat-keyed scope + review fixes for PR 3 - [`f443a5e`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f443a5e54d7ee8d0aba872b050d546b57c086719) fix(storage): persist SET_NULL cascades for sharded children + missing chat cascades - [`fdbacdb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fdbacdbbb130abd25750d54540e955d80a6d91ac) Merge feat/4708-downgrade-guard (verified/unverified guard fixes) into feat/4708-shard-remaining-tables - [`6e6f049`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6e6f04990aac10f7ac9711b7d9710ba660885239) test(regressions): harden the SHARDED_TABLES pairing-pin parser - [`e16e1ac`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e16e1acdc012fbf0f24acaaf2ef036ef2c703767) Merge feat/4708-downgrade-guard (bak-only manifest + ls-tree guard fixes) into feat/4708-shard-remaining-tables - [`9c31fb4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9c31fb499fa2e4fa1d3e68d3ab34e83571914ed4) Merge branch 'staging' into feat/4708-shard-remaining-tables - [`9666a0c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9666a0c475db43cd5757fe2f0503f555f3507d3f) Merge feat/4708-downgrade-guard (third review round) into feat/4708-shard-remaining-tables - [`607d6b4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/607d6b4e48cc94147719ce623231c024d993fb22) Merge feat/4708-downgrade-guard (regression hygiene) into feat/4708-shard-remaining-tables - [`8bb3060`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8bb3060763d08db96a65ce0e419b4cbb8a8d1b41) Merge branch 'staging' into feat/4708-shard-remaining-tables ### 📊 Changes **7 files changed** (+392 additions, -57 deletions) <details> <summary>View changed files</summary> 📝 `docs/TROUBLESHOOTING.md` (+2 -2) 📝 `docs/development/file-storage.md` (+4 -2) 📝 `packages/server/src/db/file-backed-store.ts` (+110 -44) 📝 `scripts/protect-launcher-data.mjs` (+19 -2) 📝 `scripts/regressions/launcher-format-guard.regression.mjs` (+37 -2) 📝 `scripts/regressions/message-sharding.regression.ts` (+219 -4) 📝 `storage-format.json` (+1 -1) </details> ### 📄 Description > [!NOTE] > **Stacked on #4738** (which is stacked on #4735). This diff includes both until they merge; the PR 3-only changes are the two commits touching `file-backed-store.ts`, `storage-format.json`, `protect-launcher-data.mjs`, two docs, and two regression files. Completes the maintainer-mandated full table scope from the approved plan on #4708. ## Linked issue Part 3 of #4708 — with this, every chat-keyed table on a per-turn write path is sharded (two documented exceptions below). The issue can close once the compat-cleanup follow-up is filed (see checklist there). ## Why this change - #4735 sharded `messages` and `message_swipes` because they sat on the per-message write path. The same write-amplification applies to every other chat-keyed table: memory chunks and agent memory rewrite per turn (`setMemories` is the store's own named hot path), game state/engine/storyboards per game-mode turn, agent runs per agent call, call sessions/messages per utterance, gallery and scene-video rows per generation, influences/notes per conversation turn — each previously re-serialized the full table across all chats on every write. The maintainer mandated full scope across follow-up PRs (decision 3 on #4708, re-confirmed on Discord). ## What changed - **Fourteen more sharded tables** (sixteen total) — `memory_chunks`, `chat_images`, `agent_runs`, `agent_memory`, `conversation_call_sessions`, `conversation_call_messages`, `game_state_snapshots`, `game_engine_state`, `game_checkpoints`, `game_turn_storyboards`, `game_scene_videos`, `spatial_context_snapshots`, `ooc_influences`, `conversation_notes` join `SHARDED_TABLES`. - **Scope note for review:** the #4708 checklist named six tables; the pre-PR adversarial review caught that list under-scoping the full-table mandate (`agent_memory` alone is the per-turn `setMemories` hot path). Doing all of them now means **one** format bump and **one** migration event for users instead of two. If you'd rather split, the added tables are one list entry each. - Two documented exceptions stay monoliths: `lorebooks` (nullable `chatId` — a chat-linked library entity, not per-chat data) and `game_turn_storyboard_keyframes` (no chat column; sharding it cleanly wants a denormalized `chatId`, which is a schema decision — proposed as a follow-up on #4708). - **One resolver instead of scattered ternaries** — `shardKeyForRow(table, row)` is the single source of truth for row→shard mapping: `message_swipes` resolves through the parent-message index (keeping the orphan-marker machinery), `ooc_influences`/`conversation_notes` shard by `targetChatId` (their read-side key — they're injected per roleplay turn of the *target* chat) via a small per-table key-column map, and everything else by its own `chatId`, with the `orphaned-rows` fallback. Migration, downgrade-artifact quarantine, crash recovery, foreign-row healing, and canonical dedup from #4735 apply to all new tables unchanged — they key off `SHARDED_TABLES` membership. Key-column *changes* on existing rows (conflict upserts during profile import) are already covered generically: insert/update dirty both the old and new rows' keys. - **Storage format 3 → 4** — `STORAGE_VERSION` and root `storage-format.json` bump together (regression-pinned pairing). The #4738 guard machinery handles the new boundary with no changes: a format-4 data dir refuses format-3 and format-2 targets in the launchers, installer, and in-app updater. `STORAGE_VERSION` is now exported so regressions pin against the current version rather than chasing literals on every bump. - **`.pre-shard` backups survive re-migration** (review finding) — a migrate → unshard → migrate round trip previously renamed the rebuilt monolith *over* the pristine pre-migration backup, silently breaking the docs' "never deleted by the Engine" promise. Subsequent backups now take a timestamped `.pre-shard-<ts>` name. Regression-pinned. - **unshard covers all sixteen tables** — the mirrored list in `protect-launcher-data.mjs` is extended (the pairing regression fails the build if the lists diverge), and its messages no longer hardcode stale format numbers. Honest note on 4 → 3 downgrades: `unshard` rebuilds *all* sharded tables to monoliths and lands the manifest on format 2; a format-3 build booted on that data simply re-runs its own messages/swipes migration — correct, just one extra migration pass. - **SET_NULL cascades persist for sharded children** (write-path audit finding) — `applySetNullRelations` was the one mutation path calling `markDirty` without shard keys; for a sharded child (`game_checkpoints` is a SET_NULL child of `spatial_context_snapshots`) the null-out landed in memory but never reached disk, so a restart resurrected the dangling `spatialSnapshotId`. Regression asserts the null reaches the shard file on disk. - **⚠️ Behavior fix worth reviewer attention: missing chat cascades for influences/notes** — `ooc_influences` and `conversation_notes` declare `onDelete: cascade` on *both* chat FKs in their schemas, but the store's cascade graph never carried the relations, so their rows outlived their chats. Invisible inside the old monolith; a permanently leaked per-chat shard file once sharded, plus stale injections if a chat id is ever reused via profile import. Both FK directions are now in the graph (this also makes the mari-db dangling-reference validator aware of them). If you'd rather keep behavior changes out of a storage-layout PR, say the word and I'll split it out. - **Docs** — `docs/development/file-storage.md` sharded-tables section rewritten with the full enumerated list, the two key-column exceptions, and the two deliberate monolith exceptions with reasons; the TROUBLESHOOTING downgrade section wording broadened from "messages" to per-chat data generally. - **Regressions** — per-chat flush granularity + cascade deletion for the direct-`chatId` family, a fourteen-monolith one-boot migration sweep asserting **row survival** per table (including the `targetChatId` grouping, never `sourceChatId`), the `.pre-shard` round-trip preservation pin, and an unshard conversion case for a non-message table asserting content. Deferred, unchanged from the plan: the backup `.bak`-exclusion follow-up (decision 4) — sixteen shard families grow the backup ZIP entry count further (the ZIP32 entry ceiling gets ~4× closer for very large installs), so the measurement-gated follow-up on #4708 stands, now with more reason. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - Manually verify a real upgrade: boot this build on an existing profile with populated memories/gallery/game/call data and confirm the tables migrate (shard dirs appear, `.pre-shard` originals preserved) and the app behaves normally (memory recall, agent memory, gallery, game mode incl. checkpoints/storyboards, calls, OOC influences/notes). - Manually verify the guard round-trip on format-4 data: an older target is refused; `unshard` + downgrade + re-upgrade works, and the original `.pre-shard` backups survive the round trip. - Commands run: `pnpm check` (green, twice — before and after the scope expansion), message-sharding lane incl. the fourteen-table migration sweep and `.pre-shard` round-trip pin (green), launcher-format-guard lane incl. the pairing pins and unshard conversion case (green), file-backed-shutdown + autonomous-scheduler-gate lanes (green). ## Docs and release impact - [ ] No docs changes needed - [x] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Translated docs on the `docs-i18n` branch updated to match, or a `[docs-i18n]` follow-up issue opened (see CONTRIBUTING.md § Translated documentation) - [ ] Version/release files updated (only if this PR includes a version bump) The previous follow-up #4739 is closed (translations landed), so a new `[docs-i18n] docs/TROUBLESHOOTING.md docs/development/file-storage.md` follow-up issue accompanies this PR. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added per-chat storage sharding for messages, swipes, notes, influences, and related data. - Added tools to check storage-format compatibility and safely convert sharded data back to a unified format. - **Bug Fixes** - Improved chat deletion cleanup and preservation of migration backups. - Added safeguards to prevent incompatible downgrades from damaging stored chats. - **Documentation** - Expanded storage layout documentation, troubleshooting steps, Docker/Podman guidance, backup behavior, and recovery procedures. <!-- 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:10:53 +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#6488
No description provided.