[GH-ISSUE #1467] [Issue]: Long-Term Memory: the keyword lane rebuilds regexes on every recall and takes 98% of retrieval time #747

Closed
opened 2026-10-20 17:30:20 +07:00 by bsakaguchi · 2 comments
Owner

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

Originally assigned to: @SpicyMarinara, @Promansis on GitHub.

Summary

Every recall's keyword search compiles fresh Unicode regexes for each in-scope keyword, against the query and against every query term. On a vault of about 200 memories this is 98% of warm retrieval time, synchronous on the server thread. It grows faster than linearly once V8's regex cache stops reusing compiled patterns: 10 times the keywords takes about 1.1 s per recall, and 50 times about 55 s. The search also runs when the keyword weight is 0.

Affected package

long-term-memory 1.4.53 (upstream/staging 2a3c37bb2).

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

Expected behavior

  • The keyword lane costs a few milliseconds per recall at this size and grows roughly linearly with the number of in-scope keywords.
  • No keyword search runs when the keyword weight is 0.

Actual behavior

  • containsKeywordToken (S/recall/keyword-index.ts:61-64) builds a new RegExp on every call.
  • The fuzzy loop (:183-201) calls it twice per in-scope keyword for the whole query and, when that misses, up to twice per query term. A long window has about 100 query terms, so one recall can build several hundred thousand patterns.
  • S/recall/retrieval.ts:178 runs the search before the weight check at :179.

Measurement

A private fixture: 206 memories, 4,670 distinct keywords, 900–1,712 in scope per chat, 76 query windows run short and long. Query terms per window: median 31 short, 102 long. Warm index, embeddings memoized, 10 repetitions. Only aggregate numbers are shared here.

Per recall Median 95th percentile
Warm retrieval 90 ms 180 ms
Same, with an empty keyword index 1.8 ms 2.3 ms
Keyword lane, short windows 49 ms 63 ms
Keyword lane, long windows 163 ms 181 ms
Growth of the keyword lane (median) Time
Today 98 ms
10× in-scope keywords 1.1 s
50× in-scope keywords 55 s
10× / 50× vault keywords, in-scope unchanged 132 ms / 247 ms

At 50 times the keywords, a 5-fold increase in data costs 49 times the time; linear would be 5. A microbenchmark shows why: re-running a pattern costs about 1–12 µs while fewer than about 5,000 distinct patterns are live, and about 415 µs (a full recompile) beyond 10,000.

Audit finding 08's correctness problem is already fixed: scope filters before the cap (1.4.10) and the cap ranks by overlap (1.4.16). Today 0 of 76 windows exceed the 512-entry fuzzy cap; at 10 times the keywords every sampled window would.

Steps to reproduce

  1. Use a vault with a few thousand distinct keywords in one chat's scope.
  2. Recall with a long chat window (many distinct words).
  3. Time searchLtmKeywordIndex, or compare a recall against the same recall with an empty keyword index. Recall time grows with the keyword count much faster than the rest of retrieval.

Minimal fix

One PR, patch bump.

  • S/recall/keyword-index.ts:61-64: replace the new RegExp in containsKeywordToken with an indexOf scan over every occurrence, plus a boundary check on the code point before and after each one against a single module-level /[\p{L}\p{N}]/u. Keep today's rule exactly. A later occurrence still counts when an earlier one sits inside a word. An empty needle matches as the regex does, but indexOf clamps an empty needle's start to the string length, so the loop needs an explicit end condition or it never ends.
  • S/recall/retrieval.ts:178: call searchLtmKeywordIndex only when (input.keywordWeight ?? 1) > 0. Only the keyword lane at :179 uses its result.
  • CHANGELOG under ## Unreleased: one bullet.

A probe of this fix on the same fixture used a warm index, embeddings off and 5 repetitions:

Check Result
Old and new helper, every call the lane makes across 152 windows 14,328,040 pairs, 0 differences
Edge cases: hyphens, apostrophes, digits, accents, CJK, Hangul, astral-plane letters, emoji, regex metacharacters, empty strings (both argument orders) 78 pairs, 0 differences
Retrieval over 152 windows: candidates, relevance, fused score, rank identical
Retrieval, embeddings off Before (median / 95th) After (median / 95th)
Short windows 50.9 / 65.6 ms 5.0 / 5.6 ms
Long windows 166.4 / 183.8 ms 9.6 / 10.6 ms

The probe did not re-measure the 10× and 50× growth with the fix. The remaining work is a plain string scan per keyword and query term, so there is no compile cache left to overflow.

Not included

  • A token index for the fuzzy loop. Add one only if the lane is still slow after this fix at a larger scale.
  • Changes to the 512-entry fuzzy cap or to scoring.

Overlap: #1465 also changes S/recall/keyword-index.ts and S/recall/retrieval.ts:178. Land the two one after the other, not in parallel.

Regression proof

  • tests/long-term-memory-index-keys.regression.ts: pin containsKeywordToken's whole-token rule through searchLtmKeywordIndex. king must not fuzzy-match inside looking, a second occurrence after a non-boundary one must still match, and boundaries next to hyphens, apostrophes, digits, CJK and astral-plane letters must behave as they do today.
  • A retrieval case with keywordWeight: 0 that shows the keyword lane is absent and the selection is unchanged.

Environment

  • Marinara Engine version: 2.5.0 line (staging 2039583ca)
  • Package version: long-term-memory 1.4.53 (upstream/staging 2a3c37bb2)
  • Install type: source (measurement on a private fixture)
  • OS + version: Linux, Node 24.15.0 (V8 13.6)
  • Browser or app shell: n/a (server)

Logs, screenshots, or video

None. Timings come from a private harness on a 12-core host.

Additional context

Tracker item RS-3 (recall scoring audit, finding 08). #1364 removed the per-turn vault scan; this per-recall keyword scan remains.

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 19, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1467 Originally assigned to: @SpicyMarinara, @Promansis on GitHub. ## Summary Every recall's keyword search compiles fresh Unicode regexes for each in-scope keyword, against the query and against every query term. On a vault of about 200 memories this is 98% of warm retrieval time, synchronous on the server thread. It grows faster than linearly once V8's regex cache stops reusing compiled patterns: 10 times the keywords takes about 1.1 s per recall, and 50 times about 55 s. The search also runs when the keyword weight is 0. ## Affected package `long-term-memory` 1.4.53 (`upstream/staging` 2a3c37bb2). `S` = `packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory` ## Expected behavior - The keyword lane costs a few milliseconds per recall at this size and grows roughly linearly with the number of in-scope keywords. - No keyword search runs when the keyword weight is 0. ## Actual behavior - `containsKeywordToken` (`S/recall/keyword-index.ts:61-64`) builds a `new RegExp` on every call. - The fuzzy loop (`:183-201`) calls it twice per in-scope keyword for the whole query and, when that misses, up to twice per query term. A long window has about 100 query terms, so one recall can build several hundred thousand patterns. - `S/recall/retrieval.ts:178` runs the search before the weight check at `:179`. ### Measurement A private fixture: 206 memories, 4,670 distinct keywords, 900–1,712 in scope per chat, 76 query windows run short and long. Query terms per window: median 31 short, 102 long. Warm index, embeddings memoized, 10 repetitions. Only aggregate numbers are shared here. | Per recall | Median | 95th percentile | |---|---|---| | Warm retrieval | 90 ms | 180 ms | | Same, with an empty keyword index | 1.8 ms | 2.3 ms | | Keyword lane, short windows | 49 ms | 63 ms | | Keyword lane, long windows | 163 ms | 181 ms | | Growth of the keyword lane (median) | Time | |---|---| | Today | 98 ms | | 10× in-scope keywords | 1.1 s | | 50× in-scope keywords | 55 s | | 10× / 50× vault keywords, in-scope unchanged | 132 ms / 247 ms | At 50 times the keywords, a 5-fold increase in data costs 49 times the time; linear would be 5. A microbenchmark shows why: re-running a pattern costs about 1–12 µs while fewer than about 5,000 distinct patterns are live, and about 415 µs (a full recompile) beyond 10,000. Audit finding 08's correctness problem is already fixed: scope filters before the cap (1.4.10) and the cap ranks by overlap (1.4.16). Today 0 of 76 windows exceed the 512-entry fuzzy cap; at 10 times the keywords every sampled window would. ## Steps to reproduce 1. Use a vault with a few thousand distinct keywords in one chat's scope. 2. Recall with a long chat window (many distinct words). 3. Time `searchLtmKeywordIndex`, or compare a recall against the same recall with an empty keyword index. Recall time grows with the keyword count much faster than the rest of retrieval. ## Minimal fix One PR, patch bump. - **`S/recall/keyword-index.ts:61-64`**: replace the `new RegExp` in `containsKeywordToken` with an `indexOf` scan over every occurrence, plus a boundary check on the code point before and after each one against a single module-level `/[\p{L}\p{N}]/u`. Keep today's rule exactly. A later occurrence still counts when an earlier one sits inside a word. An empty needle matches as the regex does, but `indexOf` clamps an empty needle's start to the string length, so the loop needs an explicit end condition or it never ends. - **`S/recall/retrieval.ts:178`**: call `searchLtmKeywordIndex` only when `(input.keywordWeight ?? 1) > 0`. Only the keyword lane at `:179` uses its result. - **CHANGELOG under `## Unreleased`**: one bullet. A probe of this fix on the same fixture used a warm index, embeddings off and 5 repetitions: | Check | Result | |---|---| | Old and new helper, every call the lane makes across 152 windows | 14,328,040 pairs, 0 differences | | Edge cases: hyphens, apostrophes, digits, accents, CJK, Hangul, astral-plane letters, emoji, regex metacharacters, empty strings (both argument orders) | 78 pairs, 0 differences | | Retrieval over 152 windows: candidates, relevance, fused score, rank | identical | | Retrieval, embeddings off | Before (median / 95th) | After (median / 95th) | |---|---|---| | Short windows | 50.9 / 65.6 ms | 5.0 / 5.6 ms | | Long windows | 166.4 / 183.8 ms | 9.6 / 10.6 ms | The probe did not re-measure the 10× and 50× growth with the fix. The remaining work is a plain string scan per keyword and query term, so there is no compile cache left to overflow. **Not included** - A token index for the fuzzy loop. Add one only if the lane is still slow after this fix at a larger scale. - Changes to the 512-entry fuzzy cap or to scoring. **Overlap:** #1465 also changes `S/recall/keyword-index.ts` and `S/recall/retrieval.ts:178`. Land the two one after the other, not in parallel. ## Regression proof - **`tests/long-term-memory-index-keys.regression.ts`**: pin `containsKeywordToken`'s whole-token rule through `searchLtmKeywordIndex`. `king` must not fuzzy-match inside `looking`, a second occurrence after a non-boundary one must still match, and boundaries next to hyphens, apostrophes, digits, CJK and astral-plane letters must behave as they do today. - A retrieval case with `keywordWeight: 0` that shows the keyword lane is absent and the selection is unchanged. ## Environment - Marinara Engine version: 2.5.0 line (`staging` 2039583ca) - Package version: long-term-memory 1.4.53 (`upstream/staging` 2a3c37bb2) - Install type: source (measurement on a private fixture) - OS + version: Linux, Node 24.15.0 (V8 13.6) - Browser or app shell: n/a (server) ## Logs, screenshots, or video None. Timings come from a private harness on a 12-core host. ## Additional context Tracker item RS-3 (recall scoring audit, finding 08). #1364 removed the per-turn vault scan; this per-recall keyword scan remains. ## 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-20 17:30:20 +07:00
Author
Owner

@SpicyMarinara commented on GitHub (Oct 19, 2026):

@Promansis the maintainer asked us to land this for the release, so it is in Pasta-Devs/Marinara-Agents#1472, together with Pasta-Devs/Marinara-Agents#1465 as you suggested (two commits, Long-Term Memory 1.4.54). containsKeywordToken is now the indexOf scan with one module-level /[\p{L}\p{N}]/u boundary check, and the keyword search is skipped at keyword weight 0. One addition to your fix: the scan also skips positions inside a surrogate pair, because the old u regex never matched there. Without that, an empty needle next to an astral-plane letter differed. An equivalence probe found 0 differences over about 300k pairs, including lone surrogates. Thank you for the measurements and the exact fix; they made this quick to land.

<!-- gh-comment-id:6264346286 --> @SpicyMarinara commented on GitHub (Oct 19, 2026): @Promansis the maintainer asked us to land this for the release, so it is in Pasta-Devs/Marinara-Agents#1472, together with Pasta-Devs/Marinara-Agents#1465 as you suggested (two commits, Long-Term Memory 1.4.54). `containsKeywordToken` is now the `indexOf` scan with one module-level `/[\p{L}\p{N}]/u` boundary check, and the keyword search is skipped at keyword weight 0. One addition to your fix: the scan also skips positions inside a surrogate pair, because the old `u` regex never matched there. Without that, an empty needle next to an astral-plane letter differed. An equivalence probe found 0 differences over about 300k pairs, including lone surrogates. Thank you for the measurements and the exact fix; they made this quick to land.
Author
Owner

@SpicyMarinara commented on GitHub (Oct 19, 2026):

Fixed on staging by #1472; update Long-Term Memory from the catalog to get it.

<!-- gh-comment-id:6265128778 --> @SpicyMarinara commented on GitHub (Oct 19, 2026): Fixed on staging by #1472; update Long-Term Memory from the catalog to get it.
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#747
No description provided.