[PR #5596] [MERGED] Store memory groundwork for #5592: scoped swipe reads, shared scan, and off-heap Memory Recall embeddings #6840

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

📋 Pull Request Information

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

Base: staging ← Head: fix/5592-store-memory-phase0-1


📝 Commits (2)

  • 709a535 perf(db): store memory groundwork for #5592 - Phase 0 + Phase 1
  • 77a9a78 docs(db): state the swipe-scan win precisely

📊 Changes

8 files changed (+465 additions, -39 deletions)

View changed files

📝 CHANGELOG.md (+3 -0)
📝 packages/server/src/db/file-backed-store.ts (+171 -12)
📝 packages/server/src/db/file-schema.ts (+12 -0)
📝 packages/server/src/db/schema/chats.ts (+2 -2)
📝 packages/server/src/routes/chats.routes.ts (+4 -1)
📝 packages/server/src/services/memory-recall.ts (+9 -7)
📝 packages/server/src/services/storage/chats.storage.ts (+16 -16)
📝 scripts/regressions/message-sharding.regression.ts (+248 -1)

📄 Description

Linked issue

Part of #5592 (Phase 0 + Phase 1 of the plan in the issue's audit comment — Phase 2, partial residency, deliberately stays parked, so this PR does not close the issue).

Why this change

Termux servers keep dying with FATAL ERROR: Reached heap limit (#4730, #4936, #5585) because the file-native store holds every row of every table on the V8 heap and several hot paths add O(whole-table) allocation on top. A pre-implementation audit (132 consumer classifications, 51 hazards — recorded on #5592) showed the eventual fix, partial residency, has hard prerequisites. This PR ships those prerequisites plus the single biggest memory win, each independently valuable today and none changing behavior or the on-disk format.

What changed

Phase 0 — store groundwork (no behavior change):

  1. Membership conditions resolve once per query. inArray/notInArray used to re-materialize the values array and run Array.includes for every scanned row — O(rows × values), the measured cause of the #3402 post-generation stall. They now build a Set once per condition object (WeakMap-cached; Set.has and includes share SameValueZero semantics; column/array-valued entries keep the old path — no call site in the repo uses those today).
  2. Swipe reads are chat-scoped again. countSwipesByMessageId and listSwipesByMessageIds dropped their WHERE deliberately in #3402 because of (1); with (1) fixed at the root, the scoped form is exactly as fast as the full scan and stops reading — and in the list case cloning — every other chat's swipes on the hottest read path in the app. No caller changes; both callers already pass the right ids.
  3. count() and no-join selects share one iteration. Previously every select materialized two objects for every row of the table before the WHERE ran (and count() did the same per call). The shared scan reuses a single RowContext — safe because the evaluator never retains it — and allocates contexts only for matching rows. count() keeps exact integer semantics (the paginated-cursor !== 1 check and upperRowid arithmetic depend on it).
  4. Two partial-residency preconditions become structural. Boot loads messages first explicitly (the messageId→chatId swipe-shard index depended on array declaration order enforced only by a comment), and the flush's "dirty key with no rows ⇒ shard emptied ⇒ delete its file" inference is now gated on positive evidence (fullyResidentTables — always true today, inert; exactly the gate Phase 2 needs so an evicted shard can never be mistaken for an emptied one and unlinked).

Phase 1 — Memory Recall embeddings off the V8 heap:

memory_chunks.embedding (a JSON float-array string per 5-message chunk, ~8 KB each, resident forever) is plausibly the largest single heap block for a long roleplay profile with recall enabled — the #5585 reporter's diagnostics showed 1.1 GiB steady-state against a 1.6 GiB cap. The store now packs these to Float64Array at its boundary: ~6 KB of ArrayBuffer outside the V8 heap, which is what the Android 134-aborts actually measure. Recall scoring receives the packed vector directly through its projected select and skips the per-chunk JSON.parse (the recon measured 229 ms → 13 ms for a 20k-chunk scoring pass, and removes ~60 MB of transient parse allocation per recall — the same burst shape as the crash trace).

Compatibility is by construction, not enumeration:

  • On-disk format unchanged — values pack only when re-serialization is byte-identical (non-canonical text like [1.0, 1E-3] stays a string verbatim), and every write site restores the text. No STORAGE_VERSION bump, no migration; the launcher format-guard regression still passes.
  • Unprojected selects return the original string — backup/profile export, mari-db raw reads, and every generic consumer read exactly what they always read, with zero edits in those files. Only projected selects (the recall hot path) see the packed form. The compiler enumerated the three consumers needing widening (parseStoredEmbedding, cosineSimilarity, parseMemoryEmbedding) via the new vectorText column type.

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

Automated, from this branch:

  • pnpm lint and pnpm build pass.
  • Regression lanes green: message-sharding (extended with 4 new blocks / ~20 assertions: chat-scoped swipe counts and listings, inArray/notInArray Set semantics, emptied-shard unlink surviving a failed flush and completing on retry, byte-identical embedding round-trips, string-vs-packed select shapes, isNotNull over packed values, non-canonical text preserved verbatim), memory-recall-revectorize, file-backed-shutdown, storage-writer-lock, slurp-storage, capability-package-lifecycle, agent-runtime, launcher/format-guard.
  • Touched files are Prettier-clean under the repo config (repo-wide format:check fails pre-existing on CRLF Windows checkouts).

Worth a human pass:

  • A real long-roleplay profile with Memory Recall enabled: confirm recall answers are unchanged and Settings → Advanced shows a visibly lower heap number after restart (the Server memory diagnostics line from #5515 makes this directly observable).
  • Chat with multiple swipes: swipe arrows, "Delete only this swipe (2/2)" label, and swipe navigation across two different chats (the counts are now chat-scoped).
  • Export → import a profile containing vectorized memories; export a chat's memories (/memories/export) — payload shapes unchanged.
  • On Termux if available: the #5585 reproduction (heavy profile, normal chatting) with this branch — expected: measurably more headroom before any abort.

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)

Three CHANGELOG entries under [Unreleased] → Fixed. No user-facing docs describe the store internals; no docs-i18n impact. Explicitly: no STORAGE_VERSION/storage-format.json change — the format-guard regression pins that the pairing is intact and this PR alters no on-disk layout.

Summary by CodeRabbit

  • Bug Fixes

    • Improved memory recall embedding storage and retrieval for more reliable performance.
    • Corrected chat-scoped message swipe counts and listings.
    • Hardened file-backed storage filtering, counting, shard loading, and cleanup.
    • Ensured interrupted cleanup safely retries without removing partially available data.
  • Tests

    • Added regression coverage for embedding persistence, swipe queries, filtering, and shard recovery.

🔄 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/5596 **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:** `fix/5592-store-memory-phase0-1` --- ### 📝 Commits (2) - [`709a535`](https://github.com/Pasta-Devs/Marinara-Engine/commit/709a535078f552b862cf0298e89a8a9ec6c095e8) perf(db): store memory groundwork for #5592 - Phase 0 + Phase 1 - [`77a9a78`](https://github.com/Pasta-Devs/Marinara-Engine/commit/77a9a78c7d8df83a1575f3bb202565f9797cc5f7) docs(db): state the swipe-scan win precisely ### 📊 Changes **8 files changed** (+465 additions, -39 deletions) <details> <summary>View changed files</summary> 📝 `CHANGELOG.md` (+3 -0) 📝 `packages/server/src/db/file-backed-store.ts` (+171 -12) 📝 `packages/server/src/db/file-schema.ts` (+12 -0) 📝 `packages/server/src/db/schema/chats.ts` (+2 -2) 📝 `packages/server/src/routes/chats.routes.ts` (+4 -1) 📝 `packages/server/src/services/memory-recall.ts` (+9 -7) 📝 `packages/server/src/services/storage/chats.storage.ts` (+16 -16) 📝 `scripts/regressions/message-sharding.regression.ts` (+248 -1) </details> ### 📄 Description ## Linked issue Part of #5592 (Phase 0 + Phase 1 of the plan in the issue's audit comment — Phase 2, partial residency, deliberately stays parked, so this PR does not close the issue). ## Why this change Termux servers keep dying with `FATAL ERROR: Reached heap limit` (#4730, #4936, #5585) because the file-native store holds every row of every table on the V8 heap and several hot paths add O(whole-table) allocation on top. A pre-implementation audit (132 consumer classifications, 51 hazards — recorded on #5592) showed the eventual fix, partial residency, has hard prerequisites. This PR ships those prerequisites plus the single biggest memory win, each independently valuable today and none changing behavior or the on-disk format. ## What changed **Phase 0 — store groundwork (no behavior change):** 1. **Membership conditions resolve once per query.** `inArray`/`notInArray` used to re-materialize the values array and run `Array.includes` for *every scanned row* — O(rows × values), the measured cause of the #3402 post-generation stall. They now build a `Set` once per condition object (WeakMap-cached; `Set.has` and `includes` share SameValueZero semantics; column/array-valued entries keep the old path — no call site in the repo uses those today). 2. **Swipe reads are chat-scoped again.** `countSwipesByMessageId` and `listSwipesByMessageIds` dropped their WHERE deliberately in #3402 because of (1); with (1) fixed at the root, the scoped form is exactly as fast as the full scan and stops reading — and in the list case *cloning* — every other chat's swipes on the hottest read path in the app. No caller changes; both callers already pass the right ids. 3. **`count()` and no-join selects share one iteration.** Previously every select materialized two objects for *every row of the table* before the WHERE ran (and `count()` did the same per call). The shared scan reuses a single `RowContext` — safe because the evaluator never retains it — and allocates contexts only for matching rows. `count()` keeps exact integer semantics (the paginated-cursor `!== 1` check and `upperRowid` arithmetic depend on it). 4. **Two partial-residency preconditions become structural.** Boot loads `messages` first explicitly (the `messageId→chatId` swipe-shard index depended on array declaration order enforced only by a comment), and the flush's "dirty key with no rows ⇒ shard emptied ⇒ delete its file" inference is now gated on positive evidence (`fullyResidentTables` — always true today, inert; exactly the gate Phase 2 needs so an evicted shard can never be mistaken for an emptied one and unlinked). **Phase 1 — Memory Recall embeddings off the V8 heap:** `memory_chunks.embedding` (a JSON float-array *string* per 5-message chunk, ~8 KB each, resident forever) is plausibly the largest single heap block for a long roleplay profile with recall enabled — the #5585 reporter's diagnostics showed 1.1 GiB steady-state against a 1.6 GiB cap. The store now packs these to `Float64Array` at its boundary: ~6 KB of ArrayBuffer *outside* the V8 heap, which is what the Android 134-aborts actually measure. Recall scoring receives the packed vector directly through its projected select and skips the per-chunk `JSON.parse` (the recon measured 229 ms → 13 ms for a 20k-chunk scoring pass, and removes ~60 MB of transient parse allocation per recall — the same burst shape as the crash trace). Compatibility is by construction, not enumeration: - **On-disk format unchanged** — values pack only when re-serialization is *byte-identical* (non-canonical text like `[1.0, 1E-3]` stays a string verbatim), and every write site restores the text. **No `STORAGE_VERSION` bump, no migration**; the launcher format-guard regression still passes. - **Unprojected selects return the original string** — backup/profile export, mari-db raw reads, and every generic consumer read exactly what they always read, with zero edits in those files. Only projected selects (the recall hot path) see the packed form. The compiler enumerated the three consumers needing widening (`parseStoredEmbedding`, `cosineSimilarity`, `parseMemoryEmbedding`) via the new `vectorText` column type. ## Validation <!-- These are human tasks. Never tick a box for a check that was not actually performed. --> - [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 Automated, from this branch: - `pnpm lint` and `pnpm build` pass. - Regression lanes green: `message-sharding` (extended with 4 new blocks / ~20 assertions: chat-scoped swipe counts and listings, `inArray`/`notInArray` Set semantics, emptied-shard unlink surviving a failed flush and completing on retry, byte-identical embedding round-trips, string-vs-packed select shapes, `isNotNull` over packed values, non-canonical text preserved verbatim), `memory-recall-revectorize`, `file-backed-shutdown`, `storage-writer-lock`, `slurp-storage`, `capability-package-lifecycle`, `agent-runtime`, `launcher/format-guard`. - Touched files are Prettier-clean under the repo config (repo-wide `format:check` fails pre-existing on CRLF Windows checkouts). Worth a human pass: - A real long-roleplay profile with Memory Recall enabled: confirm recall answers are unchanged and Settings → Advanced shows a visibly lower heap number after restart (the `Server memory` diagnostics line from #5515 makes this directly observable). - Chat with multiple swipes: swipe arrows, "Delete only this swipe (2/2)" label, and swipe navigation across two different chats (the counts are now chat-scoped). - Export → import a profile containing vectorized memories; export a chat's memories (`/memories/export`) — payload shapes unchanged. - On Termux if available: the #5585 reproduction (heavy profile, normal chatting) with this branch — expected: measurably more headroom before any abort. ## 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) Three CHANGELOG entries under `[Unreleased] → Fixed`. No user-facing docs describe the store internals; no docs-i18n impact. **Explicitly: no `STORAGE_VERSION`/`storage-format.json` change** — the format-guard regression pins that the pairing is intact and this PR alters no on-disk layout. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved memory recall embedding storage and retrieval for more reliable performance. * Corrected chat-scoped message swipe counts and listings. * Hardened file-backed storage filtering, counting, shard loading, and cleanup. * Ensured interrupted cleanup safely retries without removing partially available data. * **Tests** * Added regression coverage for embedding persistence, swipe queries, filtering, and shard recovery. <!-- 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:11 +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#6840
No description provided.