[PR #5603] [MERGED] feat(storage): LRU eviction of clean chat units (#5592 Phase 2, PR-B) #6842

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

📋 Pull Request Information

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

Base: staging ← Head: feat/5592-phase2b-eviction


📝 Commits (8)

  • cc1350a feat(storage): LRU eviction of clean chat units behind MARINARA_MAX_RESIDENT_CHATS
  • 0e2a238 fix(storage): eviction hardening from adversarial review
  • 42093b6 feat(conversation): storage-free autonomous idle checks
  • f7e1004 fix(conversation): CodeRabbit round 1 — seed race, role-ordering guard, invalid-cap warning, harness-only dirty marks
  • 231dccb style: format checkpoint.service.ts (missed in the PR-B prettier pass)
  • ef98279 fix(storage): same-createdAt rows keep insertion order under lazy placement
  • 5cf1ba1 fix(conversation): CodeRabbit round 2 — unhandled seed-cleanup rejection; createdAt in the DM store contract
  • 7ea709b fix(conversation): CodeRabbit round 3 — merge transcript seed into partial presence state; NaN-safe DM timestamps

📊 Changes

27 files changed (+1027 additions, -154 deletions)

View changed files

📝 CHANGELOG.md (+1 -0)
📝 docs/CONFIGURATION.md (+69 -67)
📝 packages/server/src/config/env-watcher.ts (+2 -0)
📝 packages/server/src/config/runtime-config.ts (+31 -0)
📝 packages/server/src/db/file-backed-store.ts (+228 -7)
📝 packages/server/src/routes/agents.routes.ts (+1 -1)
📝 packages/server/src/routes/chats.routes.ts (+5 -1)
📝 packages/server/src/routes/conversation.routes.ts (+63 -16)
📝 packages/server/src/routes/game.routes.ts (+15 -9)
📝 packages/server/src/routes/generate.routes.ts (+11 -3)
📝 packages/server/src/routes/generate/connected-conversation-injections.ts (+2 -2)
📝 packages/server/src/services/conversation/autonomous.service.ts (+38 -3)
📝 packages/server/src/services/game/checkpoint.service.ts (+3 -1)
📝 packages/server/src/services/generation/roleplay-dm-command-runtime.ts (+15 -3)
📝 packages/server/src/services/storage/agents.storage.ts (+5 -4)
📝 packages/server/src/services/storage/chats.storage.ts (+28 -14)
📝 packages/server/src/services/storage/game-engine-state.storage.ts (+10 -4)
📝 packages/server/src/services/storage/game-state.storage.ts (+9 -3)
📝 packages/server/src/services/storage/game-storyboards.storage.ts (+19 -6)
📝 packages/server/src/services/storage/mari-workspace-context.storage.ts (+4 -2)

...and 7 more files

📄 Description

Why

Part of #5592 (Phase 2, PR-B — the second of the two PRs planned there, on top of #5597). PR-A made chats load lazily but kept every loaded chat resident forever, so a long session touching many chats still converges toward the eager memory footprint. This PR bounds it: past a configurable cap, the least-recently-used chat with no unsaved changes is dropped from memory (never from disk) and reloads transparently on next touch.

What

Eviction (MARINARA_MAX_RESIDENT_CHATS, default off; the Termux launcher — which is also what the Android APK runs — defaults it to 8): an LRU sweep runs at the tail of each successful flush. That trigger point carries the safety argument: no flush is in flight (so no captured mark batch is invisible to the clean-check), and every synchronous mutate-then-markDirty stretch has completed — a sweep triggered inside unit loading could run between a write installing rows and its dirty-marking and evict unflushed data. A unit is evictable only when nothing in the live dirty/stale maps names it; the unassigned pseudo-unit and any unit involved in corruption healing (strays, duplicates, canonical replacements) are pinned; leased (fully-resident) tables are never evicted from. Eviction removes rows by array replacement (captured references escape across awaits), clears exactly the unit's own read-once mark, and leaves the complete message index, discovery index, and all persistence marks untouched — they describe the disk, not residency.

Two prerequisite fixes in existing code that only eviction makes reachable (found by the pre-implementation audit):

  • Shard files created after boot registered in knownShardFiles but never in the lazy discovery index (written only at boot). Invisible while units never unloaded — but an evicted fresh chat would have reloaded permanently empty. Writes now register the shard; unlinks deregister it.
  • The stale-file cleanup loop had no residency gate, unlike its structurally parallel zero-row loop: a stale mark surviving to a flush after its rows left memory would delete the shard file and its .bak. It now requires the file to be in the read-once set (a stale mark is created by reading) and defers otherwise — unreachable by construction given the eviction gate, but the same defense-in-depth shape the zero-row path already had.

Also: the messages stray-location index is no longer consumed destructively (the read-once set already dedups), so a reload can find misfiled rows again.

~20 storage-layer writes scoped by their owner: writes that addressed lazy-table rows by bare primary key (swipe mirrors in eight chat flows, agent memory, game state/engine-state/checkpoint/storyboard updates, workspace context removal, influence consumption, note pruning, run-result edits) now carry the owning chatId/messageId conjunct the caller already had. Without this, losing a unit between a flow's read and its write degrades to a whole-table load — which is irreversible (leased tables are pinned resident), so under memory pressure the store could progressively pin its biggest tables and make the cap unreachable. With it, the same race degrades to a cheap unit reload. These are behavior-preserving today and strictly tighten each WHERE.

Config surface: getMaxResidentChatUnits() in runtime-config (hot-reloadable, floor of 2, 0 = disabled); MARINARA_MAX_RESIDENT_CHATS added to the launcher env allowlist and the Termux settings loop with an ${VAR:-8} default placed outside the format-guard's probed byte range; MARINARA_EAGER_STORAGE added to the env-watcher's restart-required keys; docs/CONFIGURATION.md documents both variables (EAGER was previously undocumented). One launcher-regression proximity bound ({0,30000} between the log-tee start and fd restore) is widened to 40000 — the assertion pins ordering, not distance, and the old bound had 55 bytes of headroom left for the whole script.

Diagnostics: the store controller exposes getResidentChatUnits() (residency introspection) and markShardDirty() (regression harness).

Regressions

Five new blocks in lazy-chat-units.regression.ts: cap enforcement with LRU order and full reload correctness (messages + swipes), the post-boot-created-chat evict/reload round trip (pins the discovery-registration fix), dirty-unit skip with next-oldest-clean eviction and eventual evictability, flushed-edit survival across eviction, and eviction-disabled-by-default. Full battery run locally and green: lazy-chat-units, message-sharding in both lazy and eager modes, file-backed-shutdown, chat-branch-lineage, memory-recall-revectorize, agent-runtime, checkpoint-retention, and both launcher guards (format-guard, env).

Test plan

  • pnpm check on a non-Windows checkout
  • pnpm regression (full node suite)
  • Manually verify: with MARINARA_MAX_RESIDENT_CHATS=2 in .env, open several chats in sequence, return to the first — history intact, edits stick, swipes work
  • Manually verify: without the variable, behavior is identical to current staging
  • Manually verify on Termux: launcher prints no errors, .env override of the cap is honored, and long multi-chat sessions no longer grow memory unboundedly

References #5592 (do not auto-close — the issue tracks the remaining follow-ups).

Summary by CodeRabbit

  • New Features

    • Added configurable limits for in-memory resident chats, with least-recently-used cleanup after chats are saved.
    • Termux now retains up to 8 chats by default; setting the limit to 0 disables the cap.
    • Added optional eager chat loading at startup, with transparent reloading as needed.
  • Bug Fixes

    • Improved chat data isolation and autonomous conversation checks.
    • Protected unsaved, active, or corruption-affected chats during cleanup.
  • Documentation

    • Added configuration guidance for the new storage settings.

🔄 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/5603 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/28/2026 **Status:** ✅ Merged **Merged:** 8/28/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5592-phase2b-eviction` --- ### 📝 Commits (8) - [`cc1350a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/cc1350a708fc87ed40830e4cb57bd83144148891) feat(storage): LRU eviction of clean chat units behind MARINARA_MAX_RESIDENT_CHATS - [`0e2a238`](https://github.com/Pasta-Devs/Marinara-Engine/commit/0e2a238fd51eeee4958644e10fdf54fe47b3a559) fix(storage): eviction hardening from adversarial review - [`42093b6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/42093b6d941fad9ab75f374fcc0d053b8743feb0) feat(conversation): storage-free autonomous idle checks - [`f7e1004`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f7e1004523a9190ebf644d5716ebb6a058843065) fix(conversation): CodeRabbit round 1 — seed race, role-ordering guard, invalid-cap warning, harness-only dirty marks - [`231dccb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/231dccb0b9170c59993c2dc5b885d31b05da412e) style: format checkpoint.service.ts (missed in the PR-B prettier pass) - [`ef98279`](https://github.com/Pasta-Devs/Marinara-Engine/commit/ef98279d5295d86fa3904ce1b7ee4ac6c48489fc) fix(storage): same-createdAt rows keep insertion order under lazy placement - [`5cf1ba1`](https://github.com/Pasta-Devs/Marinara-Engine/commit/5cf1ba1c3861a4efcbfbe37df9741427e235fd5f) fix(conversation): CodeRabbit round 2 — unhandled seed-cleanup rejection; createdAt in the DM store contract - [`7ea709b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7ea709bfe3c16202be932807ae7672722b66dc62) fix(conversation): CodeRabbit round 3 — merge transcript seed into partial presence state; NaN-safe DM timestamps ### 📊 Changes **27 files changed** (+1027 additions, -154 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+1 -0) 📝 `docs/CONFIGURATION.md` (+69 -67) 📝 `packages/server/src/config/env-watcher.ts` (+2 -0) 📝 `packages/server/src/config/runtime-config.ts` (+31 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+228 -7) 📝 `packages/server/src/routes/agents.routes.ts` (+1 -1) 📝 `packages/server/src/routes/chats.routes.ts` (+5 -1) 📝 `packages/server/src/routes/conversation.routes.ts` (+63 -16) 📝 `packages/server/src/routes/game.routes.ts` (+15 -9) 📝 `packages/server/src/routes/generate.routes.ts` (+11 -3) 📝 `packages/server/src/routes/generate/connected-conversation-injections.ts` (+2 -2) 📝 `packages/server/src/services/conversation/autonomous.service.ts` (+38 -3) 📝 `packages/server/src/services/game/checkpoint.service.ts` (+3 -1) 📝 `packages/server/src/services/generation/roleplay-dm-command-runtime.ts` (+15 -3) 📝 `packages/server/src/services/storage/agents.storage.ts` (+5 -4) 📝 `packages/server/src/services/storage/chats.storage.ts` (+28 -14) 📝 `packages/server/src/services/storage/game-engine-state.storage.ts` (+10 -4) 📝 `packages/server/src/services/storage/game-state.storage.ts` (+9 -3) 📝 `packages/server/src/services/storage/game-storyboards.storage.ts` (+19 -6) 📝 `packages/server/src/services/storage/mari-workspace-context.storage.ts` (+4 -2) _...and 7 more files_ </details> ### 📄 Description ## Why Part of #5592 (Phase 2, PR-B — the second of the two PRs planned there, on top of #5597). PR-A made chats load lazily but kept every loaded chat resident forever, so a long session touching many chats still converges toward the eager memory footprint. This PR bounds it: past a configurable cap, the least-recently-used chat with no unsaved changes is dropped from memory (never from disk) and reloads transparently on next touch. ## What **Eviction** (`MARINARA_MAX_RESIDENT_CHATS`, default off; the Termux launcher — which is also what the Android APK runs — defaults it to 8): an LRU sweep runs at the tail of each successful flush. That trigger point carries the safety argument: no flush is in flight (so no captured mark batch is invisible to the clean-check), and every synchronous mutate-then-markDirty stretch has completed — a sweep triggered inside unit loading could run *between* a write installing rows and its dirty-marking and evict unflushed data. A unit is evictable only when nothing in the live dirty/stale maps names it; the unassigned pseudo-unit and any unit involved in corruption healing (strays, duplicates, canonical replacements) are pinned; leased (fully-resident) tables are never evicted from. Eviction removes rows by array replacement (captured references escape across awaits), clears exactly the unit's own read-once mark, and leaves the complete message index, discovery index, and all persistence marks untouched — they describe the disk, not residency. **Two prerequisite fixes in existing code that only eviction makes reachable** (found by the pre-implementation audit): - Shard files created after boot registered in `knownShardFiles` but never in the lazy discovery index (written only at boot). Invisible while units never unloaded — but an evicted fresh chat would have reloaded **permanently empty**. Writes now register the shard; unlinks deregister it. - The stale-file cleanup loop had no residency gate, unlike its structurally parallel zero-row loop: a stale mark surviving to a flush after its rows left memory would delete the shard file and its `.bak`. It now requires the file to be in the read-once set (a stale mark is created by reading) and defers otherwise — unreachable by construction given the eviction gate, but the same defense-in-depth shape the zero-row path already had. Also: the messages stray-location index is no longer consumed destructively (the read-once set already dedups), so a reload can find misfiled rows again. **~20 storage-layer writes scoped by their owner**: writes that addressed lazy-table rows by bare primary key (swipe mirrors in eight chat flows, agent memory, game state/engine-state/checkpoint/storyboard updates, workspace context removal, influence consumption, note pruning, run-result edits) now carry the owning chatId/messageId conjunct the caller already had. Without this, losing a unit between a flow's read and its write degrades to a whole-table load — which is *irreversible* (leased tables are pinned resident), so under memory pressure the store could progressively pin its biggest tables and make the cap unreachable. With it, the same race degrades to a cheap unit reload. These are behavior-preserving today and strictly tighten each WHERE. **Config surface**: `getMaxResidentChatUnits()` in runtime-config (hot-reloadable, floor of 2, 0 = disabled); `MARINARA_MAX_RESIDENT_CHATS` added to the launcher env allowlist and the Termux settings loop with an `${VAR:-8}` default placed outside the format-guard's probed byte range; `MARINARA_EAGER_STORAGE` added to the env-watcher's restart-required keys; docs/CONFIGURATION.md documents both variables (EAGER was previously undocumented). One launcher-regression proximity bound (`{0,30000}` between the log-tee start and fd restore) is widened to 40000 — the assertion pins ordering, not distance, and the old bound had 55 bytes of headroom left for the whole script. **Diagnostics**: the store controller exposes `getResidentChatUnits()` (residency introspection) and `markShardDirty()` (regression harness). ## Regressions Five new blocks in `lazy-chat-units.regression.ts`: cap enforcement with LRU order and full reload correctness (messages + swipes), the post-boot-created-chat evict/reload round trip (pins the discovery-registration fix), dirty-unit skip with next-oldest-clean eviction and eventual evictability, flushed-edit survival across eviction, and eviction-disabled-by-default. Full battery run locally and green: lazy-chat-units, message-sharding in both lazy and eager modes, file-backed-shutdown, chat-branch-lineage, memory-recall-revectorize, agent-runtime, checkpoint-retention, and both launcher guards (format-guard, env). ## Test plan - [x] `pnpm check` on a non-Windows checkout - [x] `pnpm regression` (full node suite) - [x] Manually verify: with `MARINARA_MAX_RESIDENT_CHATS=2` in `.env`, open several chats in sequence, return to the first — history intact, edits stick, swipes work - [x] Manually verify: without the variable, behavior is identical to current staging - [x] Manually verify on Termux: launcher prints no errors, `.env` override of the cap is honored, and long multi-chat sessions no longer grow memory unboundedly References #5592 (do not auto-close — the issue tracks the remaining follow-ups). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added configurable limits for in-memory resident chats, with least-recently-used cleanup after chats are saved. * Termux now retains up to 8 chats by default; setting the limit to 0 disables the cap. * Added optional eager chat loading at startup, with transparent reloading as needed. * **Bug Fixes** * Improved chat data isolation and autonomous conversation checks. * Protected unsaved, active, or corruption-affected chats during cleanup. * **Documentation** * Added configuration guidance for the new storage settings. <!-- 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:14:13 +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#6842
No description provided.