[GH-ISSUE #1523] [Issue]: Long-Term Memory: every applied suggestion rebuilds the recall index under the vault lock #1503

Closed
opened 2026-10-22 04:02:46 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @Promansis on GitHub (Oct 21, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1523

Originally assigned to: @Promansis on GitHub.

Summary

Long-Term Memory rebuilds the recall index while holding the vault lock, embedding included, after every applied Review suggestion and every extraction that applies memories. "Apply all" over N suggestions sends N requests and runs N rebuilds. Every other save, recall and debug line waits behind each one. After the embedding source changes, the first recall re-embeds the whole vault inline before it answers, also under the lock.

The fix (RT-1) adds one background rebuild job per vault for draft apply and source extraction. It runs 1 s after the last change, at most 10 s after the first, and holds the lock only to read the notes and to publish. Recall flushes it first, so recall still sees every change. After an embedding-source change, recall answers from the keyword lanes at once and re-embeds in the background.

RT-2 (the debug log on its own lock, plus a trim at 2 MB) was planned to ship in the same change. It is on hold because the planned design misses two places that rely on debug appends holding the vault lock.

Affected package

long-term-memory 1.4.55 (upstream/staging 8b72729f1). Line references below are on 8b72729f1. Still present on 1.4.66 (77acb942b): draft apply rebuilds at S/drafts/reconciliation.ts:993, source extraction at S/extraction/source-processing.ts:150, called at :448 and :636.

S = packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory
C = packages/long-term-memory/src/engine/packages/client/src/features/long-term-memory

Expected behavior

  • Apply all. Applying several Review suggestions in a row rebuilds the recall index once, not once per suggestion. Other saves and debug lines do not wait for the embedding.
  • Read your writes. A recall right after an apply or an extraction still sees every applied memory, with its new text and status.
  • Embedding-source change. After the source changes, recall answers straight away from keyword matching while the vault is re-embedded in the background. It uses the new vectors once that finishes.
  • Failures. A background rebuild that fails shows in the index status, and the next change or recall rebuilds the index.
  • Unchanged. The editor, settings, scope-link, identity-repair, explicit and restore rebuilds stay synchronous, because their responses carry the rebuild's counts (scope A).

Actual behavior

  • Every rebuild holds the vault lock. rebuildLongTermMemoryIndexes (S/recall/rebuild.ts:165-235) holds it for the whole build: settings, listNotes, chunking, reusable vectors, embedding every new chunk text (a network call for a remote provider), the BM25, graph, keyword and metadata indexes, and the recall.json write.
  • Draft apply rebuilds after each applied draft (S/drafts/reconciliation.ts:932). The Review Queue's "apply all" sends one request per draft.
  • Source extraction rebuilds after applied mutations (S/extraction/source-processing.ts:147-152, called at :387 and once per batch at :572).
  • Embedding-source upgrade. When an index is current but its vectors are from another embedding source, recall upgrades it inline under the lock (S/recall/rebuild.ts:105-128, from loadOrRebuildLongTermMemoryIndexes at :317).
  • Debug lines. recordLtmDebugEvent takes the vault lock for each append (S/maintenance/debug-log.ts:195), so a turn's debug line waits for any rebuild in progress. Once the log reaches 2 MB, every append rewrites the whole file (appendBounded, :143-165).

Measurement

A private timing harness ran on a copy of the 197-note vault with local MiniLM, as the Engine uses it. It applied 10 drafts on 10 sources in a row, as "apply all" does. Aggregates only:

Step 8b72729f1 With the patch
10 draft applies 4,033 ms, 10 rebuild embed calls 428 ms, 0 calls
First recall after the burst 166 ms 568 ms (runs the one rebuild)
Rebuild embed calls for the whole burst 10 1
First recall after an embedding-source change 4,138 ms (216 texts embedded inline) 5 ms (keyword lanes); the background upgrade finished about 3 s later

The design's earlier measurement found 8.8 s for a full re-embed on the same vault. Linear scaling to 2,000 chunks would put it near 90 s; that was not measured.

Steps to reproduce

  1. Run extraction on several chats so the Review Queue holds several suggestions.
  2. Turn on the debug log and press "Apply all" in Review.
  3. While it runs, save a memory in the Vault: the save waits until every rebuild in the burst has finished. The server log shows one rebuild per suggestion.
  4. Alternatively, switch the embedding source in the Engine's settings and send a chat turn: the turn waits for the whole vault to be re-embedded before recall answers.

Minimal fix

One PR, patch bump. The finished patch touches 14 files, +966/−177. It follows the design, with scope A and a 1 s quiet period capped at 10 s.

  • New S/recall/rebuild-job.ts. One job per resolved root:

    • scheduleLtmIndexRebuild starts or extends the quiet period;
    • flushLtmIndexRebuild runs a pending job now and waits for it, including a follow-up;
    • cancelPendingLtmIndexRebuild drops a pending job when a synchronous rebuild covers it;
    • stopLtmIndexRebuild handles deactivation.

    A failed run is logged once and does not wedge the next.

  • S/recall/rebuild.ts: the background rebuild runs in three phases.

    1. Under the lock: stop words, mark building, list notes.
    2. Without the lock: embed and build.
    3. Under the lock: publish only if the index state's revision, rebuildStartedAt and the stop words are unchanged. Otherwise a write landed, and the job builds again, reusing the vectors it embedded.

    After three dropped tries it runs the existing locked rebuild.

  • Reads flush first. loadOrRebuildLongTermMemoryIndexes, retrieveLongTermMemory, refreshLongTermMemoryIndexes and checkLongTermMemoryIntegrity flush the job before they take the vault lock.

  • Embedding-source upgrade. It becomes an upgrade-only background job that readers do not wait for. The Engine refresh still re-embeds inline.

  • S/persistence/vault-lock.ts gets two helpers:

    • holdsLtmVaultLock: flush and stop throw under the vault lock instead of deadlocking;
    • outsideLtmVaultLock: the job's timer and run start outside the caller's lock context, so a job scheduled inside a mutation waits for it.
  • Call sites:

    • S/drafts/reconciliation.ts:932 schedules and returns indexRebuild: { status: "pending" }; C/review/ReviewQueue.tsx:63 widens its type;
    • S/extraction/source-processing.ts :387 and :572 schedule;
    • S/server-entry.ts stops the job at deactivation.
  • Docs: packages/long-term-memory/docs/ARCHITECTURE.md.

  • Lock order: vault lock → index-state, draft and debug locks. Waits on the job happen only with no lock held.

What users see change

  • Review no longer shows "Changes were saved, but the index rebuild failed" after applying a suggestion, because apply returns before the rebuild runs. A background failure shows in the index status and the server log, and the next change or recall rebuilds the index.
  • After an embedding-source change, recall uses keyword matching until the background re-embed finishes (semantic outcome incompatible, about 3 s at 197 notes).

Not included

  • Scope B: background rebuilds for editor saves. That needs a scheduled rebuild status in the section rebuild schema and the client.
  • RT-2; see below.

CHANGELOG under ## Unreleased: one bullet.

RT-2: on hold

The planned design (option A) takes the debug log off the vault lock onto its own per-file queue. It wraps only retention's prune (S/persistence/retention.ts:203) and the debug-folder rm in restore and Delete all (S/persistence/backup-restore.ts:123) in that queue. At 8b72729f1 two more places depend on debug appends holding the vault lock:

  • Restore swaps the whole vault root. It runs rename(root, previous) and then rename(staging, root) (backup-restore.ts:149-151, and again in its journal recovery). A debug append runs mkdir(dirname(path), { recursive: true }) before taking any lock (S/maintenance/debug-log.ts:193, :270 in clear). Off the vault lock, an append between the two renames recreates root/debug, so the second rename fails on a non-empty root and the restore fails mid-swap. Or the line goes into the old root and is deleted with it.
  • The Engine's vault-mutation hook. withLongTermMemoryVaultMutation (S/runtime.ts:48, given to the Engine as withVaultMutation at S/server-entry.ts:57) runs Engine code under the vault lock. Taking the non-re-entrant debug queue there as well would deadlock as soon as that code recorded a debug event.

The planned design assumed a missed path costs at most a lost debug line; the swap can fail a restore. Options:

  • (i) Extend A to the swap and its recovery, with the mkdir inside a re-entrant queue.
  • (ii) Another mechanism, such as appends that never create the vault root, or a debug log outside the vault root.
  • (iii) Keep the debug log on the vault lock (option B).

With RT-1, draft apply and extraction no longer hold the lock while embedding, so the remaining waits are short except for the editor's synchronous rebuilds. The 2 MB trim does not depend on this choice.

Regression proof

New suite tests/long-term-memory-rebuild-job.regression.ts, wired into .github/workflows/ltm-browser.yml as rebuild-job. It uses fake timers and no real sleeps.

  • On 8b72729f1 it fails at its first check: ten draft applies in one quiet period must rebuild the index once, 10 !== 1.
  • With the patch it passes. It checks:
    • coalescing;
    • the 10 s cap;
    • a follow-up after a request during a run;
    • a write and a debug event during the embed both finish, and the write is in the published index;
    • an older background build does not replace a newer synchronous one;
    • a failed rebuild does not wedge the next one;
    • waiting under the vault lock throws;
    • a job scheduled inside a mutation waits for it;
    • deactivation stops the job.
  • Mutation check: seven deliberate breaks in the fix each make the suite fail.
  • Existing suites: the runtime suite's three inline-upgrade blocks and the extraction-graph #1364 check were adapted to the scheduled rebuild. All other LTM suites pass unchanged.

RT-2's tests wait for the RT-2 decision.

Environment

  • Marinara Engine version: 2.5.0 line (local staging checkout, unchanged)
  • Package version: long-term-memory 1.4.55 (upstream/staging 8b72729f1)
  • Install type: source (tests and the burst harness on temporary roots and a vault copy)
  • OS + version: Linux, Node 24.15.0
  • Browser or app shell: n/a (server)

Logs, screenshots, or video

None. The burst timing, the suite logs on 8b72729f1 and with the fix, and the mutation results are kept privately; the timing is summarized under Measurement.

Additional context

These are tracker items RT-1 (rebuild under the lock, runtime audit) and RT-2 (debug log on the vault lock). The design uses scope A, 1 s capped at 10 s, the debug-log trim, and RT-2 option A. The RT-2 part needs a new decision; see "RT-2: on hold".

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @Promansis on GitHub (Oct 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1523 Originally assigned to: @Promansis on GitHub. ## Summary Long-Term Memory rebuilds the recall index while holding the vault lock, embedding included, after every applied Review suggestion and every extraction that applies memories. "Apply all" over N suggestions sends N requests and runs N rebuilds. Every other save, recall and debug line waits behind each one. After the embedding source changes, the first recall re-embeds the whole vault inline before it answers, also under the lock. The fix (RT-1) adds one background rebuild job per vault for draft apply and source extraction. It runs 1 s after the last change, at most 10 s after the first, and holds the lock only to read the notes and to publish. Recall flushes it first, so recall still sees every change. After an embedding-source change, recall answers from the keyword lanes at once and re-embeds in the background. RT-2 (the debug log on its own lock, plus a trim at 2 MB) was planned to ship in the same change. It is on hold because the planned design misses two places that rely on debug appends holding the vault lock. ## Affected package `long-term-memory` 1.4.55 (`upstream/staging` 8b72729f1). Line references below are on 8b72729f1. Still present on 1.4.66 (77acb942b): draft apply rebuilds at `S/drafts/reconciliation.ts:993`, source extraction at `S/extraction/source-processing.ts:150`, called at `:448` and `:636`. `S` = `packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory` `C` = `packages/long-term-memory/src/engine/packages/client/src/features/long-term-memory` ## Expected behavior - **Apply all.** Applying several Review suggestions in a row rebuilds the recall index once, not once per suggestion. Other saves and debug lines do not wait for the embedding. - **Read your writes.** A recall right after an apply or an extraction still sees every applied memory, with its new text and status. - **Embedding-source change.** After the source changes, recall answers straight away from keyword matching while the vault is re-embedded in the background. It uses the new vectors once that finishes. - **Failures.** A background rebuild that fails shows in the index status, and the next change or recall rebuilds the index. - **Unchanged.** The editor, settings, scope-link, identity-repair, explicit and restore rebuilds stay synchronous, because their responses carry the rebuild's counts (scope A). ## Actual behavior - **Every rebuild holds the vault lock.** `rebuildLongTermMemoryIndexes` (`S/recall/rebuild.ts:165-235`) holds it for the whole build: settings, `listNotes`, chunking, reusable vectors, embedding every new chunk text (a network call for a remote provider), the BM25, graph, keyword and metadata indexes, and the `recall.json` write. - **Draft apply** rebuilds after each applied draft (`S/drafts/reconciliation.ts:932`). The Review Queue's "apply all" sends one request per draft. - **Source extraction** rebuilds after applied mutations (`S/extraction/source-processing.ts:147-152`, called at `:387` and once per batch at `:572`). - **Embedding-source upgrade.** When an index is current but its vectors are from another embedding source, recall upgrades it inline under the lock (`S/recall/rebuild.ts:105-128`, from `loadOrRebuildLongTermMemoryIndexes` at `:317`). - **Debug lines.** `recordLtmDebugEvent` takes the vault lock for each append (`S/maintenance/debug-log.ts:195`), so a turn's debug line waits for any rebuild in progress. Once the log reaches 2 MB, every append rewrites the whole file (`appendBounded`, `:143-165`). ### Measurement A private timing harness ran on a copy of the 197-note vault with local MiniLM, as the Engine uses it. It applied 10 drafts on 10 sources in a row, as "apply all" does. Aggregates only: | Step | 8b72729f1 | With the patch | |---|---:|---:| | 10 draft applies | 4,033 ms, 10 rebuild embed calls | 428 ms, 0 calls | | First recall after the burst | 166 ms | 568 ms (runs the one rebuild) | | Rebuild embed calls for the whole burst | 10 | 1 | | First recall after an embedding-source change | 4,138 ms (216 texts embedded inline) | 5 ms (keyword lanes); the background upgrade finished about 3 s later | The design's earlier measurement found 8.8 s for a full re-embed on the same vault. Linear scaling to 2,000 chunks would put it near 90 s; that was not measured. ## Steps to reproduce 1. Run extraction on several chats so the Review Queue holds several suggestions. 2. Turn on the debug log and press "Apply all" in Review. 3. While it runs, save a memory in the Vault: the save waits until every rebuild in the burst has finished. The server log shows one rebuild per suggestion. 4. Alternatively, switch the embedding source in the Engine's settings and send a chat turn: the turn waits for the whole vault to be re-embedded before recall answers. ## Minimal fix One PR, patch bump. The finished patch touches 14 files, +966/−177. It follows the design, with scope A and a 1 s quiet period capped at 10 s. - **New `S/recall/rebuild-job.ts`.** One job per resolved root: - `scheduleLtmIndexRebuild` starts or extends the quiet period; - `flushLtmIndexRebuild` runs a pending job now and waits for it, including a follow-up; - `cancelPendingLtmIndexRebuild` drops a pending job when a synchronous rebuild covers it; - `stopLtmIndexRebuild` handles deactivation. A failed run is logged once and does not wedge the next. - **`S/recall/rebuild.ts`: the background rebuild runs in three phases.** 1. Under the lock: stop words, mark building, list notes. 2. Without the lock: embed and build. 3. Under the lock: publish only if the index state's revision, `rebuildStartedAt` and the stop words are unchanged. Otherwise a write landed, and the job builds again, reusing the vectors it embedded. After three dropped tries it runs the existing locked rebuild. - **Reads flush first.** `loadOrRebuildLongTermMemoryIndexes`, `retrieveLongTermMemory`, `refreshLongTermMemoryIndexes` and `checkLongTermMemoryIntegrity` flush the job before they take the vault lock. - **Embedding-source upgrade.** It becomes an upgrade-only background job that readers do not wait for. The Engine refresh still re-embeds inline. - **`S/persistence/vault-lock.ts`** gets two helpers: - `holdsLtmVaultLock`: flush and stop throw under the vault lock instead of deadlocking; - `outsideLtmVaultLock`: the job's timer and run start outside the caller's lock context, so a job scheduled inside a mutation waits for it. - **Call sites:** - `S/drafts/reconciliation.ts:932` schedules and returns `indexRebuild: { status: "pending" }`; `C/review/ReviewQueue.tsx:63` widens its type; - `S/extraction/source-processing.ts` `:387` and `:572` schedule; - `S/server-entry.ts` stops the job at deactivation. - **Docs:** `packages/long-term-memory/docs/ARCHITECTURE.md`. - **Lock order:** vault lock → index-state, draft and debug locks. Waits on the job happen only with no lock held. **What users see change** - Review no longer shows "Changes were saved, but the index rebuild failed" after applying a suggestion, because apply returns before the rebuild runs. A background failure shows in the index status and the server log, and the next change or recall rebuilds the index. - After an embedding-source change, recall uses keyword matching until the background re-embed finishes (semantic outcome `incompatible`, about 3 s at 197 notes). **Not included** - Scope B: background rebuilds for editor saves. That needs a `scheduled` rebuild status in the section rebuild schema and the client. - RT-2; see below. **CHANGELOG under `## Unreleased`**: one bullet. ### RT-2: on hold The planned design (option A) takes the debug log off the vault lock onto its own per-file queue. It wraps only retention's prune (`S/persistence/retention.ts:203`) and the debug-folder `rm` in restore and Delete all (`S/persistence/backup-restore.ts:123`) in that queue. At 8b72729f1 two more places depend on debug appends holding the vault lock: - **Restore swaps the whole vault root.** It runs `rename(root, previous)` and then `rename(staging, root)` (`backup-restore.ts:149-151`, and again in its journal recovery). A debug append runs `mkdir(dirname(path), { recursive: true })` before taking any lock (`S/maintenance/debug-log.ts:193`, `:270` in clear). Off the vault lock, an append between the two renames recreates `root/debug`, so the second rename fails on a non-empty root and the restore fails mid-swap. Or the line goes into the old root and is deleted with it. - **The Engine's vault-mutation hook.** `withLongTermMemoryVaultMutation` (`S/runtime.ts:48`, given to the Engine as `withVaultMutation` at `S/server-entry.ts:57`) runs Engine code under the vault lock. Taking the non-re-entrant debug queue there as well would deadlock as soon as that code recorded a debug event. The planned design assumed a missed path costs at most a lost debug line; the swap can fail a restore. Options: - **(i)** Extend A to the swap and its recovery, with the `mkdir` inside a re-entrant queue. - **(ii)** Another mechanism, such as appends that never create the vault root, or a debug log outside the vault root. - **(iii)** Keep the debug log on the vault lock (option B). With RT-1, draft apply and extraction no longer hold the lock while embedding, so the remaining waits are short except for the editor's synchronous rebuilds. The 2 MB trim does not depend on this choice. ## Regression proof New suite `tests/long-term-memory-rebuild-job.regression.ts`, wired into `.github/workflows/ltm-browser.yml` as `rebuild-job`. It uses fake timers and no real sleeps. - **On 8b72729f1** it fails at its first check: `ten draft applies in one quiet period must rebuild the index once`, `10 !== 1`. - **With the patch** it passes. It checks: - coalescing; - the 10 s cap; - a follow-up after a request during a run; - a write and a debug event during the embed both finish, and the write is in the published index; - an older background build does not replace a newer synchronous one; - a failed rebuild does not wedge the next one; - waiting under the vault lock throws; - a job scheduled inside a mutation waits for it; - deactivation stops the job. - **Mutation check:** seven deliberate breaks in the fix each make the suite fail. - **Existing suites:** the runtime suite's three inline-upgrade blocks and the extraction-graph #1364 check were adapted to the scheduled rebuild. All other LTM suites pass unchanged. RT-2's tests wait for the RT-2 decision. ## Environment - Marinara Engine version: 2.5.0 line (local `staging` checkout, unchanged) - Package version: long-term-memory 1.4.55 (`upstream/staging` 8b72729f1) - Install type: source (tests and the burst harness on temporary roots and a vault copy) - OS + version: Linux, Node 24.15.0 - Browser or app shell: n/a (server) ## Logs, screenshots, or video None. The burst timing, the suite logs on 8b72729f1 and with the fix, and the mutation results are kept privately; the timing is summarized under Measurement. ## Additional context These are tracker items RT-1 (rebuild under the lock, runtime audit) and RT-2 (debug log on the vault lock). The design uses scope A, 1 s capped at 10 s, the debug-log trim, and RT-2 option A. The RT-2 part needs a new decision; see "RT-2: on hold". ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-22 04:02:46 +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-Agents#1503
No description provided.