[PR #4735] [MERGED] feat(storage): shard messages and message_swipes per chat (#4708 PR 1) #6483

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

📋 Pull Request Information

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

Base: staging ← Head: feat/4708-message-shards


📝 Commits (10+)

  • fc65583 feat(storage): shard messages and message_swipes per chat
  • 9f3e951 Merge branch 'staging' into feat/4708-message-shards
  • fd308ec fix(storage): check the format version before migration side effects
  • ca2bde0 fix(storage): heal a lagging manifest version on the next startup
  • a448aff fix(storage): rewrite or delete physical shard files whose rows moved
  • efc4421 Merge branch 'staging' into feat/4708-message-shards
  • 606c2d7 fix(storage): review round on the stacked guard PR (#4738)
  • 453054f Merge remote feat/4708-message-shards (maintainer branch update)
  • acab6e2 Merge branch 'staging' into feat/4708-message-shards
  • a5d9873 fix(storage): dirty swipe shards when an inserted message adopts orphans

📊 Changes

4 files changed (+1606 additions, -12 deletions)

View changed files

📝 docs/development/file-storage.md (+11 -1)
📝 package.json (+1 -1)
📝 packages/server/src/db/file-backed-store.ts (+863 -10)
➕ scripts/regressions/message-sharding.regression.ts (+731 -0)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.
Outside and first-time contributors also require an approving review from SpicyMarinara.

Linked issue

Part of #4708 (PR 1 of the approved plan — see the maintainer-approved decisions and my confirmation in the issue thread). PR 2 (the launcher/updater downgrade guard) must ship in the same release as this PR — merging this alone is safe for staging users going forward, but the release that ships it needs the guard so a later downgrade can't silently confuse users.

Why this change

  • On the file-native store (the default backend), every saved message re-serialized and rewrote the entire message history of every chat: a dirty flush stringified all rows of the largest table and atomically rewrote the whole file, debounced at 750 ms. On long-lived phone-hosted (Termux) installs this is the dominant active-use server cost and the biggest flash-wear multiplier — the last major item from the mobile-battery investigation (#4628–#4631, #4704–#4707).
  • With per-chat shards, a saved message rewrites only that chat's file. Verified on the production build: one message into chat A flushes exactly messages/<A>.json — nothing else.

What changed

All storage changes in file-backed-store.ts; tables stay registered in FILE_BACKED_TABLES (schema/backup/query machinery untouched) — only load/save/dirty plumbing consults the new SHARDED_TABLES marker.

  • Per-chat shards for messages and message_swipes: storage/tables/<table>/<encoded-chat-id>.json, storage format 2 → 3. Dirty tracking runs at shard granularity through a structure parallel to the table-level dirty set (never encoded into it — the transaction context's table-name set doubles as the rollback-snapshot key set), mirrored at every dirty-state path: flush snapshot/reset and failure re-add, transaction deep-snapshot/rollback-restore, the durable-rollback re-add, cascade deletes, and load-time self-heal. The #4705 write-generation contract stays keyed on the bare table name.
  • Swipes resolve their shard in O(1) through a messageId → chatId index (rebuilt on load and on rollback), including during cascade deletes — a live lookup would have reintroduced the O(n²) write-path class this store has already been bitten by. Orphan swipes (no parent message) persist in a reserved orphaned-rows shard instead of vanishing.
  • The flush never stats clean shards: the write condition is dirty-or-not-yet-on-disk via an in-memory known-files set — no per-shard existsSync on the hot path. Zero-row dirty shards delete their file and .bak (deleted chats leave no litter).
  • One-way migration, loud and crash-safe (maintainer-approved): on first boot, monolith rows group per chat and write as shards; then the monolith and its .bak rename to .pre-shard — those files are the mandated automatic backup, never deleted by the Engine, no extra copies (per the backup-weight decision). A .migrating sentinel plus a shard-data check make every crash state decidable; a monolith recreated by an older build beside live shards is quarantined with a timestamped suffix and never merged. Data written by a newer storage format refuses to load (StorageFormatTooNewError) — honestly scoped: it protects future format changes; the guard for this transition is PR 2's launcher work, since pre-shard builds never read the version.
  • Shard filenames are a security boundary: chat ids arrive from profile imports with no charset validation, so every byte outside [a-z0-9-] is percent-encoded — uppercase included (NTFS/APFS are case-insensitive; case-variant ids must never share a file) — with hash fallbacks for overlong and Windows-reserved names. Filenames are containers only; rows carry their own keys.
  • New regression (message-sharding.regression.ts, wired into regression:issues) drives the real store end-to-end: fresh-install sharding; the single-shard flush granularity claim; migration with rename set and orphan handling; crashed-migration retry (including the empty-dir and between-renames crash states); downgrade-artifact quarantine; version gate; transaction rollback; chat-delete cleanup; bak-only shard recovery; cross-shard duplicate dedup; and the encoding boundary.

The adversarial review pass (verifiers ran live probes against the real store) caught five defects in the first cut, all fixed and pinned: a crash between mkdir and the sentinel write would have classified the next boot as a downgrade and quarantined the monolith in favor of empty shards (classification now requires actual shard data); a crash between the two renames would have retried from the one-flush-stale .bak (the .bak now renames first); case-variant chat ids collided into one file on Windows/macOS (uppercase now encodes); a profile-import upsert that moves a message between chats now dirties its swipes' old and new shards (previously duplicated or silently dropped them); and duplicate primary keys across shards are dropped at load with the affected shards healed on the next flush.

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

  • pnpm check and the full regression:issues lane pass locally (every existing lane runs against the sharded store).
  • Production-build migration smoke (isolated data dir, never live data): seeded a real v2 layout (40-message monolith + .bak, v2 manifest) → boot → Sharded messages: 40 rows into 2 per-chat files (originals preserved as .pre-shard) → shard files under readable names, both .pre-shard backups present, no residual monolith, /api/health ok, messages served correctly per chat, manifest v3 with shard diagnostics.
  • Flush granularity verified via the store's write hook: a message saved into one chat writes exactly that chat's shard.

Still to verify manually (contributor to-do):

  • Manually verify on a real long-lived install copy (Termux ideally): migration completes, chats read correctly, and active chatting rewrites only the open chat's shard (watch the storage dir mtimes).
  • Manually verify a profile import (Import Profile with a full export) round-trips message history onto the sharded layout.

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)

docs/development/file-storage.md updated (layout, sharding, migration semantics) — developer docs, not part of the translated packs. User-facing TROUBLESHOOTING/UPGRADING recovery steps land with PR 2 (the guard), where they belong.

Summary by CodeRabbit

  • New Features
    • Message and swipe data is now stored in separate chat-specific files, improving isolation and reducing the impact of individual storage operations.
    • Existing storage is automatically upgraded while preserving recoverable backups.
  • Bug Fixes
    • Improved recovery after interrupted migrations or failed writes.
    • Prevented data loss from duplicate, malformed, orphaned, or deleted chat records.
    • Added safeguards when opening storage created by a newer format.
  • Tests
    • Added comprehensive regression coverage for migration, recovery, rollback, file recovery, and data cleanup scenarios.

🔄 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/4735 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/7/2026 **Status:** ✅ Merged **Merged:** 8/8/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `feat/4708-message-shards` --- ### 📝 Commits (10+) - [`fc65583`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fc655838bc9e5ad6625a83fb2eb40c78310fa646) feat(storage): shard messages and message_swipes per chat - [`9f3e951`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9f3e9516f37b6f815d7cd6bc58dd5a4635ac05eb) Merge branch 'staging' into feat/4708-message-shards - [`fd308ec`](https://github.com/Pasta-Devs/Marinara-Engine/commit/fd308eca29f86700a89dde2e299bab00d85d6f46) fix(storage): check the format version before migration side effects - [`ca2bde0`](https://github.com/Pasta-Devs/Marinara-Engine/commit/ca2bde069884454c064e41acb759213ae499210d) fix(storage): heal a lagging manifest version on the next startup - [`a448aff`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a448aff8a2de4f93c0abeff35e21b023e5c009d6) fix(storage): rewrite or delete physical shard files whose rows moved - [`efc4421`](https://github.com/Pasta-Devs/Marinara-Engine/commit/efc4421e1076df072d2829273a5b5848520e667b) Merge branch 'staging' into feat/4708-message-shards - [`606c2d7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/606c2d71389de02427accd8cbd74cd047e8313a0) fix(storage): review round on the stacked guard PR (#4738) - [`453054f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/453054fa4580863fd581299cf2c117fe5768655f) Merge remote feat/4708-message-shards (maintainer branch update) - [`acab6e2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/acab6e2767973dcf4d712bda145873d20034a1e2) Merge branch 'staging' into feat/4708-message-shards - [`a5d9873`](https://github.com/Pasta-Devs/Marinara-Engine/commit/a5d9873aaf2c24a7716c63f8ca27429a08d559f5) fix(storage): dirty swipe shards when an inserted message adopts orphans ### 📊 Changes **4 files changed** (+1606 additions, -12 deletions) <details> <summary>View changed files</summary> 📝 `docs/development/file-storage.md` (+11 -1) 📝 `package.json` (+1 -1) 📝 `packages/server/src/db/file-backed-store.ts` (+863 -10) ➕ `scripts/regressions/message-sharding.regression.ts` (+731 -0) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. > Outside and first-time contributors also require an approving review from `SpicyMarinara`. ## Linked issue Part of #4708 (PR 1 of the approved plan — see the maintainer-approved decisions and my confirmation in the issue thread). **PR 2 (the launcher/updater downgrade guard) must ship in the same release as this PR** — merging this alone is safe for `staging` users going forward, but the release that ships it needs the guard so a later downgrade can't silently confuse users. ## Why this change - On the file-native store (the default backend), **every saved message re-serialized and rewrote the entire message history of every chat**: a dirty flush stringified all rows of the largest table and atomically rewrote the whole file, debounced at 750 ms. On long-lived phone-hosted (Termux) installs this is the dominant active-use server cost and the biggest flash-wear multiplier — the last major item from the mobile-battery investigation (#4628–#4631, #4704–#4707). - With per-chat shards, a saved message rewrites only that chat's file. Verified on the production build: one message into chat A flushes exactly `messages/<A>.json` — nothing else. ## What changed All storage changes in [`file-backed-store.ts`](packages/server/src/db/file-backed-store.ts); tables stay registered in `FILE_BACKED_TABLES` (schema/backup/query machinery untouched) — only load/save/dirty plumbing consults the new `SHARDED_TABLES` marker. - **Per-chat shards** for `messages` and `message_swipes`: `storage/tables/<table>/<encoded-chat-id>.json`, storage format 2 → 3. Dirty tracking runs at shard granularity through a structure parallel to the table-level dirty set (never encoded into it — the transaction context's table-name set doubles as the rollback-snapshot key set), mirrored at every dirty-state path: flush snapshot/reset and failure re-add, transaction deep-snapshot/rollback-restore, the durable-rollback re-add, cascade deletes, and load-time self-heal. The #4705 write-generation contract stays keyed on the bare table name. - **Swipes resolve their shard in O(1)** through a `messageId → chatId` index (rebuilt on load and on rollback), including during cascade deletes — a live lookup would have reintroduced the O(n²) write-path class this store has already been bitten by. Orphan swipes (no parent message) persist in a reserved `orphaned-rows` shard instead of vanishing. - **The flush never stats clean shards**: the write condition is dirty-or-not-yet-on-disk via an in-memory known-files set — no per-shard `existsSync` on the hot path. Zero-row dirty shards delete their file and `.bak` (deleted chats leave no litter). - **One-way migration, loud and crash-safe** (maintainer-approved): on first boot, monolith rows group per chat and write as shards; then the monolith **and its `.bak`** rename to `.pre-shard` — those files are the mandated automatic backup, never deleted by the Engine, no extra copies (per the backup-weight decision). A `.migrating` sentinel plus a shard-data check make every crash state decidable; a monolith recreated by an older build beside live shards is quarantined with a timestamped suffix and **never merged**. Data written by a *newer* storage format refuses to load (`StorageFormatTooNewError`) — honestly scoped: it protects future format changes; the guard for *this* transition is PR 2's launcher work, since pre-shard builds never read the version. - **Shard filenames are a security boundary**: chat ids arrive from profile imports with no charset validation, so every byte outside `[a-z0-9-]` is percent-encoded — **uppercase included** (NTFS/APFS are case-insensitive; case-variant ids must never share a file) — with hash fallbacks for overlong and Windows-reserved names. Filenames are containers only; rows carry their own keys. - **New regression** ([`message-sharding.regression.ts`](scripts/regressions/message-sharding.regression.ts), wired into `regression:issues`) drives the real store end-to-end: fresh-install sharding; the single-shard flush granularity claim; migration with rename set and orphan handling; crashed-migration retry (including the empty-dir and between-renames crash states); downgrade-artifact quarantine; version gate; transaction rollback; chat-delete cleanup; bak-only shard recovery; cross-shard duplicate dedup; and the encoding boundary. The adversarial review pass (verifiers ran live probes against the real store) caught five defects in the first cut, all fixed and pinned: a crash between `mkdir` and the sentinel write would have classified the next boot as a downgrade and quarantined the monolith in favor of *empty* shards (classification now requires actual shard data); a crash between the two renames would have retried from the one-flush-stale `.bak` (the `.bak` now renames first); case-variant chat ids collided into one file on Windows/macOS (uppercase now encodes); a profile-import upsert that moves a message between chats now dirties its swipes' old and new shards (previously duplicated or silently dropped them); and duplicate primary keys across shards are dropped at load with the affected shards healed on the next flush. ## 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 - `pnpm check` and the full `regression:issues` lane pass locally (every existing lane runs against the sharded store). - **Production-build migration smoke** (isolated data dir, never live data): seeded a real v2 layout (40-message monolith + `.bak`, v2 manifest) → boot → `Sharded messages: 40 rows into 2 per-chat files (originals preserved as .pre-shard)` → shard files under readable names, both `.pre-shard` backups present, no residual monolith, `/api/health` ok, messages served correctly per chat, manifest v3 with shard diagnostics. - Flush granularity verified via the store's write hook: a message saved into one chat writes exactly that chat's shard. Still to verify manually (contributor to-do): - Manually verify on a real long-lived install copy (Termux ideally): migration completes, chats read correctly, and active chatting rewrites only the open chat's shard (watch the storage dir mtimes). - Manually verify a profile import (Import Profile with a full export) round-trips message history onto the sharded layout. ## 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) `docs/development/file-storage.md` updated (layout, sharding, migration semantics) — developer docs, not part of the translated packs. User-facing TROUBLESHOOTING/UPGRADING recovery steps land with PR 2 (the guard), where they belong. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Message and swipe data is now stored in separate chat-specific files, improving isolation and reducing the impact of individual storage operations. * Existing storage is automatically upgraded while preserving recoverable backups. * **Bug Fixes** * Improved recovery after interrupted migrations or failed writes. * Prevented data loss from duplicate, malformed, orphaned, or deleted chat records. * Added safeguards when opening storage created by a newer format. * **Tests** * Added comprehensive regression coverage for migration, recovery, rollback, file recovery, and data cleanup scenarios. <!-- 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:51 +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#6483
No description provided.