mirror of
https://github.com/Pasta-Devs/Marinara-Engine.git
synced 2026-12-03 19:00:50 +07:00
[GH-ISSUE #5592] File-native store keeps every row of every chat heap-resident — bound residency instead of tuning heap caps #3098
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#3098
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 28, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/5592
Originally assigned to: @kolacheee on GitHub.
Termux servers keep OOM-crashing (#4730, #4936, #5470, #5506, #5585) because the file-native store holds every row of every table in memory for the whole process lifetime, and a phone's heap is the one place that can't absorb it. Heap-cap tuning has now been tried in both directions — 2048 (#4736), 1024 (#5471), dynamic 1024–1536 (#5515), and #5587's RAM-scaled grant — and each round closed an issue while the resident set kept growing with the user's history. This issue exists so the structural work has standing tracking that survives the next launcher tweak: the diagnosis below is already written, in nearly identical words, in #5517 (closed unmerged), #5515's notes, and #5587's own body — three authors, no tracking issue, no fix.
The evidence, from a current crash
A user on
2.4.4+1a299369ac70(which contains the #5515 dynamic heap) crashed with exit 134. Their diagnostics and GC trace tell the whole story:Steady-state live set ~1.1 GiB (that is the resident store), then a ~430 MiB allocation burst in 422 ms rode it over the ceiling. A full Mark-Compact reclaimed only 82 MiB — this is capacity, not garbage. No cap in [1024, 2048] fixes both this user and the Android-kill reports (#5470/#5506): raise it and Android's killer takes the whole app silently; lower it and V8 aborts. Only shrinking the resident set resolves the tension.
Where the memory goes (all verified on staging
7ff304c0d)1. Full residency, no exit.
packages/server/src/db/file-backed-store.ts:1726holds one flatRow[]per table; the boot loader reads every shard of all 81 tables into it. There is no eviction, lazy load, ortables.delete(anywhere in the file. A year of roleplay history is heap-resident before the first request arrives.2. Embeddings are resident as JSON strings.
memory_chunks.embedding(schema/chats.ts:120-140) stores each semantic-recall vector as a serialized float array string, held forever for every chat — whether or not recall is ever used. For heavy users this is plausibly the largest single block in that 1.1 GiB.3. Per-write whole-table clones. Insert does
target.map(cloneRow)— every row object in the table copied per statement (:2437, unchanged since 2026-07-15). Inside a transaction the snapshot at:2400-2407makes it a second full-table copy. Update allocates a full-length array per statement. These are the 100s-of-MiB transient spikes that finish off a near-capacity heap — the 422 ms burst above is their shape.4. Reads are O(table) too.
SelectQuery.run(:3405) materializes ~2 objects for every row of the table before the WHERE filter runs, and applieslimitlast (:3440). Fetching one message allocates proportional to all messages ever stored. This is a clean mechanism for #4936's "navigate around like normal → crash".(The flush itself is no longer a whole-table stringify — the #4708/#5303 sharding bounded serialization to one shard, and the old
JSON.stringify(rows)at:3333is now dead code. That was real progress. But the flush still re-groups every row of a dirty table each 750 ms cycle, and none of the four items above changed.)Why this is newly tractable: sharding already built the escape hatch
Since #5303,
SHARD_KEY_COLUMNS(:348) shards the heavy per-chat tables —messages,memory_chunks,agent_runs,game_state_snapshots,game_engine_state,chat_images, etc. — bychatId. The on-disk layout is already exactly "one file per chat per table". The client has had the equivalent for ages:messagesPerPage(default 20) plus a 3-page cache for inactive chats bounds what the browser holds, which is why PC users feel this as adjustable UI lag rather than a crash. The server is the only layer still unbounded.Suggested directions (independently useful, roughly in order of value/effort)
memory_chunks.embeddingin a binary sidecar per shard (or at minimum parse-on-demand rather than resident strings), loaded only while a recall query runs.37bb8f758needs an index, not a full clone); drop the duplicate transaction snapshot for tables the statement itself already cloned.eq(primaryKey)/eq(chatId)predicates, filter before materializing contexts — or maintain the per-shard-key row index that (1) needs anyway.Item 1 alone converts server memory from O(total history) to O(active chats), which is the property every launcher heap heuristic has been trying to approximate from the outside.
Try it yourself
Grow a profile to ≥ ~700 MiB under
data/storage(a long roleplay with recall enabled gets there), run on any heap ≤1536 MiB (NODE_OPTIONS="--max-old-space-size=1536" pnpm starton desktop reproduces phone scale), and use the app normally — the 85% heap warning from #5515's telemetry fires at boot before a single message is sent, and normal use aborts within minutes.Related: #5585/#5587 (current launcher mitigation — good and worth merging, but its own body defers exactly this work), #4708/#5303 (the sharding this builds on), #4730/#4936/#5470/#5506 (the closure history).
@kolacheee commented on GitHub (Aug 28, 2026):
Pre-implementation regression audit of the lazy-residency direction — result: do NOT implement it as sketched above. A full sweep of every consumer of the sharded tables (132 classifications, each "safe" verdict then adversarially attacked) found 51 hazards, several of them data-loss class. The design is still right, but it has hard prerequisites and a safer sequencing. Recording the constraints here so the eventual PR inherits them.
The headline break (found by attacking the "safe" rating on in-chat search)
The search query is fine (
eq(messages.chatId)— one shard). But opening search fetches the unpaginated message list, whosecountSwipesByMessageIdcompanion runs a deliberately WHERE-less full scan ofmessage_swipes(chats.storage.ts:604, the #3402 stall fix). Under naive lazy residency that one click force-loads every swipe shard, and the load-time self-heal (file-backed-store.ts:3120-3143) — which resolves swipe shards throughmessageShardIndex, built only from resident messages (:2756) — computes "foreign rows" for every swipe whose parent chat isn't loaded. The next 750 ms flush then re-homes the entire install's swipe history intoorphaned-rows.jsonand unlinks the per-chat shard files including their.baks. One search click, permanent mis-sharding.Same family, worse ambiguity: the flush treats "dirty key with no in-memory rows" as "shard emptied by deletes" and deletes the shard file +
.bak(:3303-3311). Under partial residency, non-resident is indistinguishable from emptied — an evicted-but-dirty shard gets its file deleted.Hazard classes (51 total; representative examples)
createInfluenceinserts into another chat'sooc_influencesshard with no read-back — flush then rewrites that shard file containing only the new row (conversation-side-effect-command-runtime.ts:120→chats.storage.ts:2281).filePathscans over tables sharded by other columns (gallery-file-lifecycle.ts:88-99,avatar-file-lifecycle.ts:124-129). A non-resident shard = a reference not seen = permanent deletion.db.select().from(table)for all 81 tables (backup.routes.ts:798,:1535); under partial residency it exports resident rows only and its own counts agree with the truncation. A quietly-lossy backup is worse than a failed one.deleteWhereonly deletes resident rows; unloaded shard files survive and reload next boot (admin.routes.ts:157-165).CASCADESentries key on a column ≠ the child's shard key (e.g.chats → ooc_influences.sourceChatIdwhile sharded bytargetChatId— reinstating exactly the leak the cascade was added to fix, per the comment at:602-605); bothSET_NULL_RELATIONSare cross-shard; unique keys on PK-sharded tables (noodle/slurp handles, emoji/sticker names, capability idempotency keys) lose enforcement entirely.noodle_postsby id (25 call sites vs 11 by the shard key),agent_runsby id,chat_imagesbyfilePath— each needs a reverse index or forces a full load.count()is a second scan path (:2417) independent ofSelectQuery.run; if only select learns shard pushdown,GET /chats/:id/message-countundercounts — which mis-numbers the transcript (upperRowid) and breaks search-jump offsets.listMessagesfor every autonomous-enabled chat every 60 s (conversation.routes.ts:946-950), reloading exactly what eviction released.:2400-2407,:2320-2322).mari db validatereports false dangling-reference errors against non-resident parents (mari-db.service.ts:5302-5313) — destructive diagnostics users act on.Also two premise corrections to the issue text: there are no unsharded tables (tables outside
SHARD_KEY_COLUMNSshard one-file-per-row by primary key —:1556-1578), so parents likechats/characters/presetsmust be declared an always-resident tier; andmessage_swipesresolves its shard through the in-memorymessageShardIndex, making messages+swipes one indivisible residency unit and a persistedmessageId → chatIdindex a hard prerequisite.Re-sequenced plan
Phase 0 — prerequisites (each independently a bugfix/perf win today, zero behavior change):
countSwipesByMessageId/listSwipesByMessageIdsby chat (kills a full-table scan on the hottest read path — worth doing regardless of #5592).count()the same shard treatment as select — one shared resolution path.messageId → chatIdindex (also fixes today's fragility where a boot-order quirk can misfile swipes).Phase 1 — the big memory win with near-zero regression surface: move
memory_chunks.embeddingout of the hot rows (binary sidecar per shard, parse-on-demand). Independent of residency entirely; for heavy recall users this is plausibly the largest single block in the heap.Phase 2 — two-tier residency, only after 0+1: always-resident tier for PK-sharded parents + tables with cross-shard unique keys; lazy tier for the ~14 chatId/characterId/lorebookId child tables; messages+swipes as one unit; explicit
loadAllShards()leases for backup/export, import, admin expunge,mari db validate, file GC, and cross-shard cascades (or reverse indexes where hot); eviction synchronized with the flush choke point and forbidden for in-flight dirty shards and mid-transaction loads.Phase 0 + 1 can ship as focused PRs now. Phase 2 should not start until the Phase 0 invariants are regression-pinned (the audit produced the precondition list to pin).
@kolacheee commented on GitHub (Aug 28, 2026):
Phase 0 + Phase 1 implementation starting (per the audit plan above) — owner: @kolacheee. Draft PR to follow on a staging-targeted branch. Phase 2 (residency tiers) stays parked until these land and their invariants are regression-pinned.
@kolacheee commented on GitHub (Aug 28, 2026):
Phase 0 + Phase 1 merged (#5596). Phase 2 implementation starting — owner: @kolacheee — split in two stacked PRs to keep the audit's hazard surface tractable:
The audit comment above is the constraint list both PRs are built against.
@kolacheee commented on GitHub (Aug 28, 2026):
Phase 2 PR-A is up as draft: #5597 (lazy per-chat unit loading, no eviction — kill switch
MARINARA_EAGER_STORAGE=1). PR-B (eviction) follows once PR-A settles. Implementation matches the plan above; the one deliberate deviation is storyboard stale-run recovery, which moved from a startup-wide sweep to per-chat recovery at first read with a process-start cutoff floor (the startup sweep would have leased the whole storyboards table on every boot).@kolacheee commented on GitHub (Aug 28, 2026):
PR-B is up as draft: #5603 (LRU eviction of clean chat units behind
MARINARA_MAX_RESIDENT_CHATS, Termux launcher defaults it to 8, off everywhere else). Includes the two prerequisite fixes the pre-implementation audit surfaced in existing code (post-boot shard discovery registration; stale-cleanup residency gate) and ~20 storage-layer PK-write scopings so mid-flow eviction degrades to a reload instead of an irreversible whole-table load. Adversarial verification pass runs next before I mark it ready-adjacent.@kolacheee commented on GitHub (Aug 28, 2026):
Phase 2 is complete: #5597 (lazy per-chat unit loading) and #5603 (LRU eviction of clean units behind
MARINARA_MAX_RESIDENT_CHATS, Termux launcher defaults to 8) are both merged. Between them, a Termux profile with dozens of large chats drops from everything-resident-at-boot to a bounded working set — roughly 50–120+ MB of live heap reclaimed for the profiles in the original reports, plus a far lower boot peak — with autonomous messaging, cross-chat awareness, backups, and imports verified unchanged (idle autonomous checks are now storage-free after a one-time seed, so background polling no longer touches evicted chats at all).Still open under this issue, in rough value order: the per-write O(resident) clone (
target.map(cloneRow)on insert/update — the remaining spike contributor), the tx-rollback stale-mark desync (#5606, pre-existing data-loss corner found during PR-B verification),lorebook_entries.embeddinggetting the same one-line Float64Array treatment as memory chunks, the non-array-shard-root recovery gap (#5601), and the known lease-irreversibility limitation (a cold by-id read on a lazy table pins it resident for the process — logged when it happens; un-leasing would need eviction-aware machinery of its own).@kolacheee commented on GitHub (Aug 28, 2026):
Phase 3 opening salvo — three stacked drafts, in merge order:
Each verified locally with the full node suite (155/161 — only the six known Windows-checkout lanes). Remaining after these: #5601 (non-array shard roots through the recovery pipeline) and the lease-irreversibility limitation.