mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #4708] [Feature]: Shard the messages table per chat — every saved message currently rewrites the full message history (dominant active cost on Termux) #2583
Labels
No labels
android
bug
bugfix
ci
client
code freeze pause
container
dependencies
docs
documentation
duplicate
enhancement
feature
feature
feature
feature-creep
fixed-in-refactor
fixed-in-staging
good first issue
help wanted
in-pr
in-pr
needs-codeowner-decision
normal-scope
old-codebase
old-codebase
pull-request
qol
question
refactor
regression
revisit later
roadmap
scope-risk
scope-risk
server
server
shared
soup
upstream
windows
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Pasta-Devs/Marinara-Engine#2583
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @kolacheee on GitHub (Aug 7, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4708
Originally assigned to: @kolacheee on GitHub.
What problem does this solve?
On the file-native store, every saved message rewrites the entire messages table: a dirty flush runs
JSON.stringifyover all rows of all chats and atomically rewrites the whole file (packages/server/src/db/file-backed-store.ts:1418-1426; debounce 750ms:154, safety flush 10s:155). On a long-lived install the messages file is the largest table by far, so each roleplay message costs a full-history serialize + flash write. This is the dominant active-use server cost on phone-hosted (Termux) installs — confirmed as the largest unfixed item in the mobile-battery follow-up audit (after #4628/#4629/#4630/#4643) — and it also multiplies flash wear.Proposed solution
Shard the messages (and
message_swipes) tables per chat:messages/<chatId>.json, with dirty-tracking at shard granularity so saving a message serializes and rewrites only that chat's shard. This is a design change, not a quick fix — the audit produced a concrete plan plus a set of hard-won constraints from an adversarial pass that any implementation must respect:Core:
:1179-1184): (a) transaction rollback restoresthis.dirtyTablesfrom its snapshot (:1012-1013) — the shard-key set needs identical snapshot/restore; (b) thectx.flusheddurable-rollback path re-adds table names fromctx.dirtyTables(:1014-1018) — affected shards must be re-marked there too; (c) cascades / set-null relation writes.FILE_BACKED_TABLESloop entirely — including its recreate-if-missing branch:saveFileSnapshotswrites any table whose file is missing (dirtyTables.has(table) || !existsSync(path),:1422), so leaving "messages" in the flat loop would silently recreate a full monolith on every flush and defeat the sharding. Manifest row counts (:1416-1420) need redefining for shards.Migration (one-way, must be loud):
.pre-shardAND renamemessages.json.bak/message_swipes.json.bakas well —parseJsonFilefalls back to<path>.bakwhen the main file is missing (:617-650), so a leftover.bakwould let a downgraded build silently "recover" a stale monolith, chat on stale history, and diverge.versionfield is written (:1430) but never checked byloadFileSnapshots(:1307-1333), so a version bump cannot make an older build refuse to load. Honest downgrade behavior with the monolith renamed: the old build starts with silently empty message tables and its first flush recreates an empty monolith (:1422self-heal). The downgrade guard therefore has to live outside the store: in the launcher (which self-updates and channel-switches viastart-termux.sh:260-282) and in documented restore steps — not in a retroactive version check.Alternatives considered
Additional context
From the Termux battery follow-up audit (with #4704, #4705, #4706, #4707). Prior related work: the #2528/#2612/#3403 file-store read-path fixes (scans); this is the write-path counterpart. Duplicate-checked: no existing issue covers write sharding (nearest is closed #1933, Tauri warm-cache parity).
Template check
@kolacheee commented on GitHub (Aug 7, 2026):
@SpicyMarinara — I'd like to build this next, and since it's a one-way storage migration on the default backend I want your explicit sign-off on the approach (and four specific decisions) before I write code. The design below was re-verified line-by-line against current staging this week, including the interactions with the write-generation gate from #4716 that landed after this issue was filed.
The payoff: on the file-native store, every saved message currently serializes and rewrites the entire message history of every chat. With per-chat shards, a saved message rewrites only that chat's file — on long-lived Termux installs this is the dominant active-use cost and the biggest flash-wear multiplier we have left.
Shape of the work (details collapsed below): two stacked PRs that must ship in the same release — PR 1 is the sharding + migration + regressions (~750 lines, mostly migration safety, not the sharding itself), PR 2 is the downgrade guard (launcher + in-app updater + docs, no storage code). A small backup follow-up is optional and measurement-gated.
The four decisions I need from you
1. One-way migration — accept, with a manual un-shard escape hatch?
Once a user boots the sharded build, the monolith is renamed aside; older builds would see empty chat history until files are renamed back. My recommendation: accept one-way, and ship an
unshardcommand in the same PR (~60 lines: concatenate shards → rewrite the monolith). That makes the guard's refusal answerable — "run unshard, then downgrade" instead of "you can't downgrade" — and gives support a scriptable recovery for Docker/manual checkouts that no guard reaches. (Dual-writing the monolith for a transition release would keep the exact write-amplification this issue exists to remove, so I don't recommend it.)2. Downgrade guard posture: refuse or warn, per entry point?
Recommendation: refuse on the automatic launcher update path (unattended; the stake is chat history), refuse-with-explicit-confirmation on the in-app channel switch (user-initiated, informed override is legitimate), docs-only for Docker/manual checkout (nothing else is technically possible there — I won't pretend the guard is universal). Sub-decision: the guard needs a machine-readable format marker the shell launchers can check — I propose a root-level
storage-format.jsonadded to the version-truth list in the docs. The alternative (greppingSTORAGE_VERSIONout of a source file at the target ref) works but couples launchers to source text.3. Scope:
messages+message_swipesonly, for now?Six more chat-keyed tables could shard through the identical machinery later, but none are on the per-message write path that dominates. Recommendation: ship the machinery with these two, measure, extend later with zero new design work.
4. Full-backup raw
storage/copy — touch it or not?The raw per-file copy in full backups goes from 2 message entries to up to 4×chat-count after sharding (it's already redundant with the JSONL export, and the bundled RESTORE.txt says it's manual-recovery-only). Recommendation: change nothing in PR 1 (don't mix a backup behavior change into a storage migration); a follow-up can exclude
*.bakfiles from the raw copy (halves the growth, zero information loss) — or you may prefer to leave backups entirely alone. Your call.Design verification highlights (what changed vs the issue text)
loadFileSnapshotsitself marks tables dirty in five self-heal paths (malformed-row repair, migrations, backup recovery) — shard-granular equivalents are in the spec so repairs aren't lost.chatstable's counter; the spec keeps generation bumps keyed on the bare logical table name for every shard write, so the contract stays uniform..migratingsentinel resolves the ambiguous "both monolith and shards exist" state (crashed mid-migration → monolith authoritative; downgrade artifact → shards authoritative, monolith loudly quarantined — never merged). The rename set includes the.bakfiles, since the store's fallback loader would otherwise let a downgraded build silently resurrect stale history.If you're good with the four recommendations as stated, a 👍 on this comment is enough and I'll start on PR 1. If you want different answers on any of them (especially 2's refuse-vs-warn or 4), say the word and the spec adjusts before any code is written.
@SpicyMarinara commented on GitHub (Aug 7, 2026):
Yeah, that sounds sensible and makes sense to implement.
Sure. Just ensure we do a backup of chats for the user if things go wrong before this (automatically).
Don't understand; is this about giving the option to users to refuse the migration? I believe the migration should happen to all users and they shouldn't be given a choice, lol. We need to later delete the artifact code handling the old format instead of keeping it for those who chose to stay on the old format.
I would say let's do the full scope from the get-go, otherwise, we may forget to finish it. It can be in separate PRs, of course.
We would rather not keep too many backups, since they may weigh a lot.
Good call to introduce this change.
@kolacheee commented on GitHub (Aug 7, 2026):
Thanks! Locking in the plan with your adjustments:
1 (automatic backup): yes — and it composes with your point 4: the migration's rename of the old
messages.json/message_swipes.json(and their.baktwins) to.pre-shardis the automatic backup — the originals are preserved byte-for-byte, exactly once, never auto-deleted, and never duplicated into extra copies that would bloat the data dir. If anything goes wrong mid-migration, a sentinel file makes the next boot treat the untouched.pre-shardoriginals as authoritative and retry cleanly. Recovery steps go into TROUBLESHOOTING.2 (clarification — nobody gets to refuse the migration): agreed, and that's already the design: migration happens automatically for every user on first boot of the new build, no choice offered. This item is about something else — downgrade protection. If someone later runs an older Marinara build (launcher rollback, channel switch to a branch predating the change) against already-migrated data, that old build doesn't know the new layout: it would silently see empty chat history and could write a conflicting old-format file. The guard makes the launcher/updater refuse to start a pre-shard build against sharded data (with a recovery path) instead of failing silently. And noted on deleting the old-format handling: once the migration has been out for a few releases, the migration/compat code gets removed in a cleanup PR — I'll file the reminder issue when PR 1 lands.
3 (full scope): will do — the machinery lands with
messages+message_swipes(the tables on the hot per-message write path), and the remaining chat-keyed tables (memory_chunks,chat_images,agent_runs,conversation_call_messages,game_state_snapshots,spatial_context_snapshots) follow in separate PRs through the same mechanism until the full scope is done. I'll track the checklist on this issue so nothing gets forgotten.4 (backup weight): understood — no new backup copies anywhere in this work, and I'll follow up separately with the change that stops the full-backup archive from including redundant
.bakfiles (it shrinks backups, aligned with this concern).Starting on PR 1 now.
@kolacheee commented on GitHub (Aug 7, 2026):
Part 2 (the downgrade guard) is up as draft PR #4738, stacked on #4735 — per the approved plan, both need to land in the same release.
What it covers, per the four decisions above:
node scripts/protect-launcher-data.mjs unshardrebuilds the monolith layout offline. One deviation from the sketch: the plan saidmari db unshard, but themariCLI turned out to be an HTTP forwarder to a running server — a downgrade-recovery tool can't require the very server whose next flush would re-shard the data (and Docker/manual users may have no server at all). It lives in the offline launcher-data script instead; the PR body has the details.start.sh/start.bat/start-termux.shskip an auto-update onto an incompatible target (checked before the data snapshot), the in-app updater refuses with a 409, and the Windows installer's update-over-existing path blocks too. Honest scope note in the PR: manualgit checkoutand Docker tag switches are only protected by the store's own forward version gate from #4735, with documented recovery steps.storage-format.jsondeclares the format a checkout understands (read off the target ref viagit show; absent = format 2). A regression pins it toSTORAGE_VERSIONso a missed bump can't silently disable the guard.The remaining chat-keyed tables (checklist above) come next as separate PRs on the same pattern.
@kolacheee commented on GitHub (Aug 8, 2026):
Part 3 is up as draft PR #4754 (stacked on #4738 → #4735), storage format 4 — and it grew beyond the checklist above, which needs your eyes:
Scope expansion. The pre-PR review caught the six-table checklist under-scoping the full-table mandate:
agent_memory(the per-turnsetMemorieshot path),conversation_call_sessions,game_engine_state,game_checkpoints,game_turn_storyboards, andgame_scene_videosare equally chat-keyed monoliths, andooc_influences/conversation_notesshard bytargetChatId(their read-side key). All fourteen are in #4754 — one format bump and one migration event for users instead of two. Sixteen sharded tables total. Two deliberate exceptions, documented indocs/development/file-storage.md:lorebooks(nullablechatId, library entity) andgame_turn_storyboard_keyframes(no chat column — sharding it cleanly wants a denormalizedchatId, which is a schema call for you; happy to do it as a small follow-up if you want it).One behavior fix flagged in the PR body: the influences/notes schemas declare
onDelete: cascadeon both chat FKs but the store's cascade graph never carried them, so their rows outlived their chats (invisible in a monolith; a permanently leaked shard file once sharded). The PR adds the four graph entries. Veto if you'd rather have that split out.docs-i18n follow-up for this PR: #4755.
Remaining after this: the compat-cleanup reminder issue (delete old-format handling once everything ships) and the measurement-gated backup .bak-exclusion follow-up (decision 4 — sixteen shard families make the ZIP entry growth more relevant).