[GH-ISSUE #5592] File-native store keeps every row of every chat heap-resident — bound residency instead of tuning heap caps #3098

Closed
opened 2026-10-21 05:59:34 +07:00 by bsakaguchi · 7 comments
Owner

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:

Server memory: heap 1097.6 / 1632 MiB; RSS 1263.1 MiB          ← steady state
610131 ms: Scavenge    1259.9 (1298.0) -> 1158.0 (1166.4) MB
610553 ms: Mark-Compact 1594.1 (1602.4) -> 1512.3 (1549.9) MB   ← 422 ms later
FATAL ERROR: Reached heap limit Allocation failed

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:1726 holds one flat Row[] per table; the boot loader reads every shard of all 81 tables into it. There is no eviction, lazy load, or tables.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-2407 makes 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 applies limit last (: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 :3333 is 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. — by chatId. 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)

  1. Lazy per-chat shard residency. Load a chat's shards on first touch instead of at boot; evict shards for chats untouched for N minutes (flush-before-evict; the dirty-shard machinery already tracks what must persist). Boot loads only unsharded/small tables plus indexes of shard keys. Server-side consumers of full history (recall, summarization, cross-chat awareness) load-on-demand through the same path, so behavior is unchanged — only residency timing moves.
  2. Get embeddings out of the hot rows. Store memory_chunks.embedding in a binary sidecar per shard (or at minimum parse-on-demand rather than resident strings), loaded only while a recall query runs.
  3. Bound per-write cloning. Copy-on-write only the affected rows (the unique-key check that motivated 37bb8f758 needs an index, not a full clone); drop the duplicate transaction snapshot for tables the statement itself already cloned.
  4. Short-circuit indexed reads. For 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 start on 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).

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: ``` Server memory: heap 1097.6 / 1632 MiB; RSS 1263.1 MiB ← steady state 610131 ms: Scavenge 1259.9 (1298.0) -> 1158.0 (1166.4) MB 610553 ms: Mark-Compact 1594.1 (1602.4) -> 1512.3 (1549.9) MB ← 422 ms later FATAL ERROR: Reached heap limit Allocation failed ``` 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:1726` holds one flat `Row[]` per table; the boot loader reads every shard of all 81 tables into it. There is no eviction, lazy load, or `tables.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-2407` makes 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 applies `limit` last (`: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 `:3333` is 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. — **by `chatId`**. 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) 1. **Lazy per-chat shard residency.** Load a chat's shards on first touch instead of at boot; evict shards for chats untouched for N minutes (flush-before-evict; the dirty-shard machinery already tracks what must persist). Boot loads only unsharded/small tables plus indexes of shard keys. Server-side consumers of full history (recall, summarization, cross-chat awareness) load-on-demand through the same path, so behavior is unchanged — only residency timing moves. 2. **Get embeddings out of the hot rows.** Store `memory_chunks.embedding` in a binary sidecar per shard (or at minimum parse-on-demand rather than resident strings), loaded only while a recall query runs. 3. **Bound per-write cloning.** Copy-on-write only the affected rows (the unique-key check that motivated `37bb8f758` needs an index, not a full clone); drop the duplicate transaction snapshot for tables the statement itself already cloned. 4. **Short-circuit indexed reads.** For `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 start` on 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).
bsakaguchi 2026-10-21 05:59:34 +07:00
Author
Owner

@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 search query is fine (eq(messages.chatId) — one shard). But opening search fetches the unpaginated message list, whose countSwipesByMessageId companion runs a deliberately WHERE-less full scan of message_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 through messageShardIndex, 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 into orphaned-rows.json and 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)

  • Silent data loss on writes into non-resident shards: createInfluence inserts into another chat's ooc_influences shard 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).
  • File GC deletes referenced user files: gallery/avatar cleanup decides "unreferenced" from filePath scans 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.
  • Backups silently truncate: profile export iterates 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.
  • Admin "Delete all data" resurrects: deleteWhere only deletes resident rows; unloaded shard files survive and reload next boot (admin.routes.ts:157-165).
  • Cross-shard integrity: ~1/3 of CASCADES entries key on a column ≠ the child's shard key (e.g. chats → ooc_influences.sourceChatId while sharded by targetChatId — reinstating exactly the leak the cascade was added to fix, per the comment at :602-605); both SET_NULL_RELATIONS are cross-shard; unique keys on PK-sharded tables (noodle/slurp handles, emoji/sticker names, capability idempotency keys) lose enforcement entirely.
  • Wrong-column lookups: noodle_posts by id (25 call sites vs 11 by the shard key), agent_runs by id, chat_images by filePath — each needs a reverse index or forces a full load.
  • count() is a second scan path (:2417) independent of SelectQuery.run; if only select learns shard pushdown, GET /chats/:id/message-count undercounts — which mis-numbers the transcript (upperRowid) and breaks search-jump offsets.
  • Background resurrection: the autonomous scheduler calls listMessages for every autonomous-enabled chat every 60 s (conversation.routes.ts:946-950), reloading exactly what eviction released.
  • Transactions: rollback restores the whole-table snapshot taken at first mutation — a shard lazily loaded mid-transaction is silently erased from memory while the residency map still says "loaded" (:2400-2407, :2320-2322).
  • mari db validate reports 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_COLUMNS shard one-file-per-row by primary key — :1556-1578), so parents like chats/characters/presets must be declared an always-resident tier; and message_swipes resolves its shard through the in-memory messageShardIndex, making messages+swipes one indivisible residency unit and a persisted messageId → chatId index a hard prerequisite.

Re-sequenced plan

Phase 0 — prerequisites (each independently a bugfix/perf win today, zero behavior change):

  1. Scope countSwipesByMessageId / listSwipesByMessageIds by chat (kills a full-table scan on the hottest read path — worth doing regardless of #5592).
  2. Give count() the same shard treatment as select — one shared resolution path.
  3. Persist an incremental messageId → chatId index (also fixes today's fragility where a boot-order quirk can misfile swipes).
  4. Make the flush distinguish "shard emptied" from "shard not resident" before any eviction exists.

Phase 1 — the big memory win with near-zero regression surface: move memory_chunks.embedding out 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).

<!-- gh-comment-id:5453261423 --> @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, whose `countSwipesByMessageId` companion runs a **deliberately WHERE-less full scan of `message_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 through `messageShardIndex`, 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 into `orphaned-rows.json` and **unlinks the per-chat shard files including their `.bak`s**. 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) - **Silent data loss on writes into non-resident shards**: `createInfluence` inserts into another chat's `ooc_influences` shard 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`). - **File GC deletes referenced user files**: gallery/avatar cleanup decides "unreferenced" from `filePath` scans 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. - **Backups silently truncate**: profile export iterates `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. - **Admin "Delete all data" resurrects**: `deleteWhere` only deletes resident rows; unloaded shard files survive and reload next boot (`admin.routes.ts:157-165`). - **Cross-shard integrity**: ~1/3 of `CASCADES` entries key on a column ≠ the child's shard key (e.g. `chats → ooc_influences.sourceChatId` while sharded by `targetChatId` — reinstating exactly the leak the cascade was added to fix, per the comment at `:602-605`); both `SET_NULL_RELATIONS` are cross-shard; unique keys on PK-sharded tables (noodle/slurp handles, emoji/sticker names, capability idempotency keys) lose enforcement entirely. - **Wrong-column lookups**: `noodle_posts` by id (25 call sites vs 11 by the shard key), `agent_runs` by id, `chat_images` by `filePath` — each needs a reverse index or forces a full load. - **`count()` is a second scan path** (`:2417`) independent of `SelectQuery.run`; if only select learns shard pushdown, `GET /chats/:id/message-count` undercounts — which mis-numbers the transcript (`upperRowid`) and breaks search-jump offsets. - **Background resurrection**: the autonomous scheduler calls `listMessages` for every autonomous-enabled chat every 60 s (`conversation.routes.ts:946-950`), reloading exactly what eviction released. - **Transactions**: rollback restores the whole-table snapshot taken at first mutation — a shard lazily loaded mid-transaction is silently erased from memory while the residency map still says "loaded" (`:2400-2407`, `:2320-2322`). - **`mari db validate`** reports 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_COLUMNS` shard one-file-per-row by primary key — `:1556-1578`), so parents like `chats`/`characters`/`presets` must be declared an **always-resident tier**; and `message_swipes` resolves its shard through the in-memory `messageShardIndex`, making **messages+swipes one indivisible residency unit** and a persisted `messageId → chatId` index a hard prerequisite. ## Re-sequenced plan **Phase 0 — prerequisites (each independently a bugfix/perf win today, zero behavior change):** 1. Scope `countSwipesByMessageId` / `listSwipesByMessageIds` by chat (kills a full-table scan on the hottest read path — worth doing regardless of #5592). 2. Give `count()` the same shard treatment as select — one shared resolution path. 3. Persist an incremental `messageId → chatId` index (also fixes today's fragility where a boot-order quirk can misfile swipes). 4. Make the flush distinguish "shard emptied" from "shard not resident" before any eviction exists. **Phase 1 — the big memory win with near-zero regression surface:** move `memory_chunks.embedding` out 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).
Author
Owner

@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.

<!-- gh-comment-id:5453420995 --> @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.
Author
Owner

@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:

  • PR-A: lazy chat-unit loading, no eviction. Boot loads always-resident tables (the PK-sharded parents and everything with cross-shard unique keys) plus a complete messageId→chatId index built without retaining rows; the per-chat child tables load as one indivisible unit per chat on first touch and stay resident for the process lifetime. Unfiltered/cross-unit consumers (backup, import, expunge, mari db validate, file GC, the sourceChatId cascades) take an explicit load-everything lease. This alone moves server memory from O(total history) to O(chats touched this session) — most sessions touch a handful — and none of the eviction race hazards from the audit apply yet.
  • PR-B: eviction, gated on the fullyResidentTables mechanism Phase 0 shipped, synchronized with the flush choke point, forbidden for in-flight dirty shards and mid-transaction loads.

The audit comment above is the constraint list both PRs are built against.

<!-- gh-comment-id:5454334296 --> @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: - **PR-A: lazy chat-unit loading, no eviction.** Boot loads always-resident tables (the PK-sharded parents and everything with cross-shard unique keys) plus a complete messageId→chatId index built without retaining rows; the per-chat child tables load as one indivisible unit per chat on first touch and stay resident for the process lifetime. Unfiltered/cross-unit consumers (backup, import, expunge, mari db validate, file GC, the sourceChatId cascades) take an explicit load-everything lease. This alone moves server memory from O(total history) to O(chats touched this session) — most sessions touch a handful — and none of the eviction race hazards from the audit apply yet. - **PR-B: eviction**, gated on the fullyResidentTables mechanism Phase 0 shipped, synchronized with the flush choke point, forbidden for in-flight dirty shards and mid-transaction loads. The audit comment above is the constraint list both PRs are built against.
Author
Owner

@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).

<!-- gh-comment-id:5454916421 --> @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).
Author
Owner

@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.

<!-- gh-comment-id:5456471439 --> @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.
Author
Owner

@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.embedding getting 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).

<!-- gh-comment-id:5457760923 --> @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.embedding` getting 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).
Author
Owner

@kolacheee commented on GitHub (Aug 28, 2026):

Phase 3 opening salvo — three stacked drafts, in merge order:

  1. #5607 — fixes #5606 (tx rollback re-merges load-created healing marks; the data-loss corner from PR-B's verification, pinned red/green).
  2. #5608 — the per-write O(resident) clone removal: row objects are now immutable-once-installed (the set-null cascade was the last in-place mutator, now copy-on-write), so inserts take a pointer-copy slice instead of cloning every resident row and transaction snapshots become reference arrays. This was the remaining #4730 allocation-spike contributor.
  3. #5609 — lorebook entry embeddings packed as Float64Array (the #5596 sibling; no on-disk change).

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.

<!-- gh-comment-id:5457909624 --> @kolacheee commented on GitHub (Aug 28, 2026): Phase 3 opening salvo — three stacked drafts, in merge order: 1. #5607 — fixes #5606 (tx rollback re-merges load-created healing marks; the data-loss corner from PR-B's verification, pinned red/green). 2. #5608 — the per-write O(resident) clone removal: row objects are now immutable-once-installed (the set-null cascade was the last in-place mutator, now copy-on-write), so inserts take a pointer-copy slice instead of cloning every resident row and transaction snapshots become reference arrays. This was the remaining #4730 allocation-spike contributor. 3. #5609 — lorebook entry embeddings packed as Float64Array (the #5596 sibling; no on-disk change). 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.
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#3098
No description provided.