[GH-ISSUE #2796] [Issue]: Memory recall re-attempts embedding every turn with no short-circuit when no embedder is configured (log spam + repeated wasted re-chunking) #1419

Closed
opened 2026-10-21 05:33:32 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 22, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2796

AI-investigated against the released 2.0.0 code. Please verify each trace before fixing.

Summary

A user reported that "starting a conversation wedges the engine" — phone/CPU heat, inability to create new conversations or open characters, and a crash on refresh — and pointed at memory-recall embedding as the cause when no embedder is configured.

Reading the actual 2.0.0 code, part of the report is real and part is not:

  • Real (this issue): In conversation/scene mode, memory recall is on by default and there is no cache/short-circuit for the "no embedder available" verdict. So on every send the engine re-attempts embedding, fails cheaply, and logs a warning — and once a chat has 5+ messages it also re-builds and re-fails the same never-persisted memory chunk on every subsequent turn, forever. This is per-turn wasted CPU + log spam, bounded by message count.
  • Not reproduced by this code path: the wedge itself (cannot create convos, character-open errors, crash on refresh, sustained device heat). The embedder does not force-load or download a model on a binding-missing host, there is no in-request loop, no promise pile-up, and the generation lock is per-chatId so it cannot block other chats/characters. Those symptoms point to a different fault (e.g. a failing generation the user repeatedly retries, or a separate backend error) and should be triaged separately. The repeating warnings are a correlated symptom, not the cause.

Severity: medium — log spam + repeated wasted re-work on misconfigured/unsupported hosts (Termux/Android, Node-arch mismatch), no crash and no wedge from this path.

Symptom & UX impact

  • On a host where local embeddings are unavailable (onnxruntime-node native binding missing) and no embedding connection is configured:
    • Server log emits [memory-recall] Local embeddings are unavailable and no embedding connection is configured on every conversation-mode send.
    • After the chat reaches 5+ messages, it additionally emits [memory-recall] Skipping N memory chunk(s) for chat <id> because embedding generation returned 0/N usable vectors on every subsequent send — with the same chunk count each time, because the failed chunk is never persisted.
    • Result: continuous log spam and a small fixed slice of wasted CPU per turn (DB scan + chunk build + failed embed).
  • The reported "wedge" symptoms are NOT caused by this path (verify in the user's environment):
    • Cannot create new conversations / open other characters: the per-chatId generation lock cannot block them; the failed-embed path holds no global lock and exhausts no memory.
    • Crash on refresh / sustained phone heat: not produced here. The embedder caches loadFailed after the first availability check and never loads/downloads a model, so there is no runaway CPU. These must be triaged as a separate issue with the real failing-request stack captured.

Steps to reproduce

  1. Run Marinara v2.0.0 on a host where local embeddings are unavailable (onnxruntime-node native binding missing — e.g. Termux/Android, or a Node arch mismatch) and with no embedding connection configured.
  2. Start a Conversation-mode chat (memory recall defaults ON there) and send messages.
  3. Observe on every send: [memory-recall] Local embeddings are unavailable and no embedding connection is configured (memory-recall.ts:90).
  4. After the chat reaches 5+ messages, observe additionally on every subsequent send: [memory-recall] Skipping 1 memory chunk(s) for chat <id> because embedding generation returned 0/1 usable vectors (memory-recall.ts:174) — same count forever.
  5. Negative repro (verify): the embedder does NOT load/download a model and does NOT spin CPU (loadFailed cached after the first availability check). Creating a NEW conversation and opening OTHER characters is NOT blocked by this path (lock is per-chatId). If those operations do fail in the user's environment, that is a separate fault — capture the actual error/stack on the failing create-chat / open-character / refresh request, because it is not produced by memory-recall.

Root cause (file:line trace)

1. Recall defaults ON in conversation/scene mode → runs every generation.

  • packages/server/src/routes/generate.routes.ts:4200
    const memoryRecallDefault = chatMode === "conversation" || isSceneChat;
    
  • generate.routes.ts:4203-4214 — if (enableMemoryRecall) { await injectMemoryRecallContext({...}) }. This is why the user noticed it "especially in Convo Mode."

2. No cache / short-circuit for the "no embedder available" verdict.
embedMemoryRecallTexts re-runs the full resolution on every call and never memoizes failure:

  • packages/server/src/services/memory-recall.ts:77-92
    if (options.embeddingSource) {                 // null on this setup
      const configured = await options.embeddingSource.embed(texts, options.signal);
      if (configured) return configured;
      return [];
    }
    const localEmbedder = options.localEmbedder ?? localEmbed;
    const localEmbeddings = await localEmbedder(texts, options.signal);
    if (localEmbeddings) return localEmbeddings;   // null: binding missing
    logger.warn("[memory-recall] Local embeddings are unavailable and no embedding connection is configured"); // ← WARN :90, once per send
    return [];
    
  • The local embedder cheap-fails (no force-load): packages/server/src/services/local-embedder.ts:64-67
    if (!hasNativeOnnxRuntimeBinding()) { loadFailed = true; return null; }
    
    and local-embedder.ts:112-113 returns null immediately once loadFailed is set. It never reaches createPipeline/HuggingFace download (local-embedder.ts:70-100). The binding-missing notice itself is single-shot (local-embedder.ts:44-51, guarded by nativeBindingChecked), but the :90 warn in embedMemoryRecallTexts is not guarded.
  • A grep for any disable/availability cache (embedderUnavailable / recallDisabled / similar) returns zero hits — there is no flag anywhere.

3. Repeated re-chunking of the same never-persisted chunk (the per-turn re-work loop).

  • generate.routes.ts:10731-10736 fire-and-forgets chunkAndEmbedMessages(...).catch(...) after each generation (one per turn; awaited internally; .catch-guarded — does not accumulate).
  • The resume cursor is derived only from the last chunk that has an embedding: memory-recall.ts:107-114
    .where(and(eq(memoryChunks.chatId, chatId), isNull(memoryChunks.sourceChatId), isNotNull(memoryChunks.embedding)))
    
  • memory-recall.ts:133 — if (unchunked.length < CHUNK_SIZE) return; (CHUNK_SIZE = 5).
  • memory-recall.ts:168 — const embeddings = await embedMemoryRecallTexts(texts, options); → returns [].
  • memory-recall.ts:169-181 — length mismatch → logger.warn("[memory-recall] Skipping %d memory chunk(s) … returned %d/%d usable vectors", …); return; (WARN :174) without inserting. Because nothing is persisted, the resume cursor never advances, so the identical DB-scan + chunk-build + failed-embed + warn repeats on every subsequent turn.

Two additional embed call-sites also cheap-fail through the same path (no extra harm, but should be gated by the same verdict):

  • generate.routes.ts:2042-2046 — chat-context embedding (gated behind hasVectorizedEntries at :2036).
  • generate.routes.ts:5278 — knowledge router embeddingSource.

Why this is NOT a wedge (verify before assuming otherwise):

  • generate.routes.ts:1234-1246 — activeGenerations Map is keyed by input.chatId; release deletes only that chat's entry. It cannot block creating new chats or opening other characters.
  • The cheap-fail embed path holds no global lock, exhausts no memory, performs no loop, and accumulates no promises.

Suggested fix

Goal: stop the per-turn re-attempt + log spam, and decouple conversation/character operations from embedding entirely when no vectorizer exists.

1. Cache the "no vectorizer available" verdict.
In packages/server/src/services/memory-recall-embedding.ts, memoize isMemoryRecallVectorizerAvailable (and/or resolveMemoryRecallEmbeddingSource) with a short TTL keyed by (connectionId, chat embeddingConnectionId):

let cachedVerdict: { key: string; available: boolean; at: number } | null = null;
const VERDICT_TTL_MS = 60_000;
// build key from options; if fresh + matching, return cached; else compute + store.
export function resetMemoryRecallVectorizerCache() { cachedVerdict = null; }

Call resetMemoryRecallVectorizerCache() from connection create/update/delete and from /memories/refresh so reconfiguring an embedder takes effect immediately.

2. Gate recall injection and post-gen chunking on availability so neither runs (nor logs) when no embedder exists:

  • generate.routes.ts:4203 — if (enableMemoryRecall && (await isMemoryRecallVectorizerAvailable(app.db, {...cached}))) { … }
  • generate.routes.ts:10731 — only call chunkAndEmbedMessages when the cached verdict is available.
  • Gate the two extra embed sites the same way using one verdict computed near generate.routes.ts:1389 (or wherever memoryRecallEmbeddingSource is resolved): generate.routes.ts:2042 and generate.routes.ts:5278.

This stops the repeated identical re-work because the functions are not invoked at all when no embedder is present.

3. Log the "unavailable" warning at most once per process (or per TTL) so a misconfig produces one actionable line instead of per-turn spam (memory-recall.ts:90):

let warnedUnavailable = false;
// …
if (!warnedUnavailable) {
  warnedUnavailable = true;
  logger.warn("[memory-recall] No embedder configured; memory recall disabled. Configure an embedding connection or install local embeddings.");
}
return [];

Reset warnedUnavailable when a vectorizer becomes available again (same hook as the verdict cache reset).

4. Demote the per-chunk "Skipping N memory chunk(s)" warn at memory-recall.ts:173 to logger.debug. With fix (2) it should rarely fire, and "no embedder" is a normal condition, not a fault.

5. Keep chunkAndEmbedMessages fire-and-forget (already is at generate.routes.ts:10731-10736) — fixes (1)+(2) eliminate the re-work by not calling it.

Separately: the wedge symptoms (cannot create conversations, open-character errors, crash on refresh, device heat) are not reproduced by this path. File a distinct issue and capture the real failing-request stack; there is a separately-reported new-conversation-button problem that may be the actual culprit — do not assume memory-recall is the cause. The fixes above ensure that even if recall is misconfigured, it cannot contribute to such a wedge.

Affected files

  • packages/server/src/services/memory-recall.ts
  • packages/server/src/services/memory-recall-embedding.ts
  • packages/server/src/services/local-embedder.ts
  • packages/server/src/services/generation/memory-recall-context.ts
  • packages/server/src/routes/generate.routes.ts

Validation

  • pnpm check passes (TypeScript + ESLint).
  • Verdict cache added in memory-recall-embedding.ts with TTL + resetMemoryRecallVectorizerCache() export.
  • Recall injection gated on availability at generate.routes.ts:4203.
  • Post-gen chunkAndEmbedMessages gated on availability at generate.routes.ts:10731.
  • Extra embed sites generate.routes.ts:2042 and generate.routes.ts:5278 gated by the same verdict.
  • embedMemoryRecallTexts "unavailable" warn fires at most once per process/TTL (memory-recall.ts:90).
  • Per-chunk "Skipping N memory chunk(s)" log demoted to debug (memory-recall.ts:173).
  • Cache + warn flag reset wired to connection create/update/delete and /memories/refresh.
  • Manual: start a conversation with no embedder configured and confirm no CPU spin, no per-turn log spam (at most one unavailable line), and that conversations are still creatable and characters still openable.
  • Manual: configure an embedding connection mid-session and confirm recall starts working without a restart (cache invalidation).
  • Manual (separate-issue link): reproduce the user's wedge (cannot create convos / crash on refresh) and capture the actual failing-request stack to confirm it is unrelated to memory-recall; cross-link the new-conversation-button issue.
Originally created by @kolacheee on GitHub (Jun 22, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2796 > AI-investigated against the released 2.0.0 code. Please verify each trace before fixing. ## Summary A user reported that "starting a conversation wedges the engine" — phone/CPU heat, inability to create new conversations or open characters, and a crash on refresh — and pointed at memory-recall embedding as the cause when no embedder is configured. Reading the actual 2.0.0 code, **part of the report is real and part is not**: - **Real (this issue):** In conversation/scene mode, memory recall is on by default and there is **no cache/short-circuit for the "no embedder available" verdict**. So on every send the engine re-attempts embedding, fails cheaply, and logs a warning — and once a chat has 5+ messages it *also* re-builds and re-fails the *same* never-persisted memory chunk on every subsequent turn, forever. This is **per-turn wasted CPU + log spam**, bounded by message count. - **Not reproduced by this code path:** the **wedge** itself (cannot create convos, character-open errors, crash on refresh, sustained device heat). The embedder does **not** force-load or download a model on a binding-missing host, there is no in-request loop, no promise pile-up, and the generation lock is **per-`chatId`** so it cannot block other chats/characters. Those symptoms point to a *different* fault (e.g. a failing generation the user repeatedly retries, or a separate backend error) and should be triaged separately. The repeating warnings are a **correlated symptom, not the cause**. Severity: **medium** — log spam + repeated wasted re-work on misconfigured/unsupported hosts (Termux/Android, Node-arch mismatch), no crash and no wedge from this path. ## Symptom & UX impact - On a host where local embeddings are unavailable (onnxruntime-node native binding missing) **and** no embedding connection is configured: - Server log emits `[memory-recall] Local embeddings are unavailable and no embedding connection is configured` on **every** conversation-mode send. - After the chat reaches 5+ messages, it *additionally* emits `[memory-recall] Skipping N memory chunk(s) for chat <id> because embedding generation returned 0/N usable vectors` on **every** subsequent send — with the **same** chunk count each time, because the failed chunk is never persisted. - Result: continuous log spam and a small fixed slice of wasted CPU per turn (DB scan + chunk build + failed embed). - **The reported "wedge" symptoms are NOT caused by this path** (verify in the user's environment): - Cannot create new conversations / open other characters: the per-`chatId` generation lock cannot block them; the failed-embed path holds no global lock and exhausts no memory. - Crash on refresh / sustained phone heat: not produced here. The embedder caches `loadFailed` after the first availability check and never loads/downloads a model, so there is no runaway CPU. **These must be triaged as a separate issue with the real failing-request stack captured.** ## Steps to reproduce 1. Run Marinara v2.0.0 on a host where local embeddings are unavailable (onnxruntime-node native binding missing — e.g. Termux/Android, or a Node arch mismatch) **and** with no embedding connection configured. 2. Start a Conversation-mode chat (memory recall defaults ON there) and send messages. 3. Observe on **every** send: `[memory-recall] Local embeddings are unavailable and no embedding connection is configured` (`memory-recall.ts:90`). 4. After the chat reaches 5+ messages, observe additionally on **every** subsequent send: `[memory-recall] Skipping 1 memory chunk(s) for chat <id> because embedding generation returned 0/1 usable vectors` (`memory-recall.ts:174`) — same count forever. 5. **Negative repro (verify):** the embedder does NOT load/download a model and does NOT spin CPU (`loadFailed` cached after the first availability check). Creating a NEW conversation and opening OTHER characters is NOT blocked by this path (lock is per-`chatId`). If those operations *do* fail in the user's environment, that is a **separate fault** — capture the actual error/stack on the failing create-chat / open-character / refresh request, because it is not produced by memory-recall. ## Root cause (file:line trace) **1. Recall defaults ON in conversation/scene mode → runs every generation.** - `packages/server/src/routes/generate.routes.ts:4200` ```ts const memoryRecallDefault = chatMode === "conversation" || isSceneChat; ``` - `generate.routes.ts:4203-4214` — `if (enableMemoryRecall) { await injectMemoryRecallContext({...}) }`. This is why the user noticed it "especially in Convo Mode." **2. No cache / short-circuit for the "no embedder available" verdict.** `embedMemoryRecallTexts` re-runs the full resolution on every call and never memoizes failure: - `packages/server/src/services/memory-recall.ts:77-92` ```ts if (options.embeddingSource) { // null on this setup const configured = await options.embeddingSource.embed(texts, options.signal); if (configured) return configured; return []; } const localEmbedder = options.localEmbedder ?? localEmbed; const localEmbeddings = await localEmbedder(texts, options.signal); if (localEmbeddings) return localEmbeddings; // null: binding missing logger.warn("[memory-recall] Local embeddings are unavailable and no embedding connection is configured"); // ← WARN :90, once per send return []; ``` - The local embedder **cheap-fails** (no force-load): `packages/server/src/services/local-embedder.ts:64-67` ```ts if (!hasNativeOnnxRuntimeBinding()) { loadFailed = true; return null; } ``` and `local-embedder.ts:112-113` returns `null` immediately once `loadFailed` is set. It never reaches `createPipeline`/HuggingFace download (`local-embedder.ts:70-100`). The binding-missing notice itself is single-shot (`local-embedder.ts:44-51`, guarded by `nativeBindingChecked`), but the `:90` warn in `embedMemoryRecallTexts` is **not** guarded. - A grep for any disable/availability cache (`embedderUnavailable` / `recallDisabled` / similar) returns **zero hits** — there is no flag anywhere. **3. Repeated re-chunking of the same never-persisted chunk (the per-turn re-work loop).** - `generate.routes.ts:10731-10736` fire-and-forgets `chunkAndEmbedMessages(...).catch(...)` after each generation (one per turn; awaited internally; `.catch`-guarded — does **not** accumulate). - The resume cursor is derived only from the last chunk that **has** an embedding: `memory-recall.ts:107-114` ```ts .where(and(eq(memoryChunks.chatId, chatId), isNull(memoryChunks.sourceChatId), isNotNull(memoryChunks.embedding))) ``` - `memory-recall.ts:133` — `if (unchunked.length < CHUNK_SIZE) return;` (`CHUNK_SIZE = 5`). - `memory-recall.ts:168` — `const embeddings = await embedMemoryRecallTexts(texts, options);` → returns `[]`. - `memory-recall.ts:169-181` — length mismatch → `logger.warn("[memory-recall] Skipping %d memory chunk(s) … returned %d/%d usable vectors", …); return;` (**WARN :174**) **without inserting**. Because nothing is persisted, the resume cursor never advances, so the **identical** DB-scan + chunk-build + failed-embed + warn repeats on every subsequent turn. **Two additional embed call-sites also cheap-fail through the same path** (no extra harm, but should be gated by the same verdict): - `generate.routes.ts:2042-2046` — chat-context embedding (gated behind `hasVectorizedEntries` at `:2036`). - `generate.routes.ts:5278` — knowledge router `embeddingSource`. **Why this is NOT a wedge (verify before assuming otherwise):** - `generate.routes.ts:1234-1246` — `activeGenerations` Map is keyed by `input.chatId`; release deletes only that chat's entry. It cannot block creating new chats or opening other characters. - The cheap-fail embed path holds no global lock, exhausts no memory, performs no loop, and accumulates no promises. ## Suggested fix Goal: stop the per-turn re-attempt + log spam, and **decouple conversation/character operations from embedding entirely** when no vectorizer exists. **1. Cache the "no vectorizer available" verdict.** In `packages/server/src/services/memory-recall-embedding.ts`, memoize `isMemoryRecallVectorizerAvailable` (and/or `resolveMemoryRecallEmbeddingSource`) with a short TTL keyed by (connectionId, chat embeddingConnectionId): ```ts let cachedVerdict: { key: string; available: boolean; at: number } | null = null; const VERDICT_TTL_MS = 60_000; // build key from options; if fresh + matching, return cached; else compute + store. export function resetMemoryRecallVectorizerCache() { cachedVerdict = null; } ``` Call `resetMemoryRecallVectorizerCache()` from connection create/update/delete and from `/memories/refresh` so reconfiguring an embedder takes effect immediately. **2. Gate recall injection and post-gen chunking on availability** so neither runs (nor logs) when no embedder exists: - `generate.routes.ts:4203` — `if (enableMemoryRecall && (await isMemoryRecallVectorizerAvailable(app.db, {...cached}))) { … }` - `generate.routes.ts:10731` — only call `chunkAndEmbedMessages` when the cached verdict is `available`. - Gate the two extra embed sites the same way using one verdict computed near `generate.routes.ts:1389` (or wherever `memoryRecallEmbeddingSource` is resolved): `generate.routes.ts:2042` and `generate.routes.ts:5278`. This stops the repeated identical re-work because the functions are not invoked at all when no embedder is present. **3. Log the "unavailable" warning at most once per process (or per TTL)** so a misconfig produces one actionable line instead of per-turn spam (`memory-recall.ts:90`): ```ts let warnedUnavailable = false; // … if (!warnedUnavailable) { warnedUnavailable = true; logger.warn("[memory-recall] No embedder configured; memory recall disabled. Configure an embedding connection or install local embeddings."); } return []; ``` Reset `warnedUnavailable` when a vectorizer becomes available again (same hook as the verdict cache reset). **4. Demote the per-chunk "Skipping N memory chunk(s)" warn** at `memory-recall.ts:173` to `logger.debug`. With fix (2) it should rarely fire, and "no embedder" is a normal condition, not a fault. **5. Keep `chunkAndEmbedMessages` fire-and-forget** (already is at `generate.routes.ts:10731-10736`) — fixes (1)+(2) eliminate the re-work by not calling it. **Separately:** the wedge symptoms (cannot create conversations, open-character errors, crash on refresh, device heat) are **not** reproduced by this path. File a distinct issue and capture the real failing-request stack; there is a separately-reported new-conversation-button problem that may be the actual culprit — do **not** assume memory-recall is the cause. The fixes above ensure that even if recall is misconfigured, it cannot contribute to such a wedge. ## Affected files - `packages/server/src/services/memory-recall.ts` - `packages/server/src/services/memory-recall-embedding.ts` - `packages/server/src/services/local-embedder.ts` - `packages/server/src/services/generation/memory-recall-context.ts` - `packages/server/src/routes/generate.routes.ts` ## Validation - [ ] `pnpm check` passes (TypeScript + ESLint). - [ ] Verdict cache added in `memory-recall-embedding.ts` with TTL + `resetMemoryRecallVectorizerCache()` export. - [ ] Recall injection gated on availability at `generate.routes.ts:4203`. - [ ] Post-gen `chunkAndEmbedMessages` gated on availability at `generate.routes.ts:10731`. - [ ] Extra embed sites `generate.routes.ts:2042` and `generate.routes.ts:5278` gated by the same verdict. - [ ] `embedMemoryRecallTexts` "unavailable" warn fires at most once per process/TTL (`memory-recall.ts:90`). - [ ] Per-chunk "Skipping N memory chunk(s)" log demoted to `debug` (`memory-recall.ts:173`). - [ ] Cache + warn flag reset wired to connection create/update/delete and `/memories/refresh`. - [ ] Manual: start a conversation with **no embedder configured** and confirm **no CPU spin**, **no per-turn log spam** (at most one unavailable line), and that **conversations are still creatable** and characters still openable. - [ ] Manual: configure an embedding connection mid-session and confirm recall starts working without a restart (cache invalidation). - [ ] Manual (separate-issue link): reproduce the user's wedge (cannot create convos / crash on refresh) and capture the actual failing-request stack to confirm it is unrelated to memory-recall; cross-link the new-conversation-button issue.
Author
Owner

@kolacheee commented on GitHub (Jun 22, 2026):

Cross-reference: this issue is the memory-recall log-spam / repeated re-chunking part of the "starting a conversation bugs out" report. The more severe wedge symptoms from that same report (cannot create new conversations / open characters, crash on refresh, device heat) are not caused by this path — they are tracked in #2791 (per-chat abortControllers + server activeGenerations lock leaks + silent create/delete failures). The repeating embedding warnings here are a correlated symptom, not the wedge cause.

<!-- gh-comment-id:4771355929 --> @kolacheee commented on GitHub (Jun 22, 2026): Cross-reference: this issue is the **memory-recall log-spam / repeated re-chunking** part of the "starting a conversation bugs out" report. The more severe **wedge** symptoms from that same report (cannot create new conversations / open characters, crash on refresh, device heat) are **not** caused by this path — they are tracked in #2791 (per-chat `abortControllers` + server `activeGenerations` lock leaks + silent create/delete failures). The repeating embedding warnings here are a correlated symptom, not the wedge cause.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 22, 2026):

Addressed in PR #2790 / commit acab1fba: memory recall now short-circuits when no embedder is available, caches vectorizer availability briefly, throttles the no-embedder warning, skips semantic routing without an embedder, and resets the cache when embedding connections/settings change.

<!-- gh-comment-id:4772440960 --> @SpicyMarinara commented on GitHub (Jun 22, 2026): Addressed in PR #2790 / commit acab1fba: memory recall now short-circuits when no embedder is available, caches vectorizer availability briefly, throttles the no-embedder warning, skips semantic routing without an embedder, and resets the cache when embedding connections/settings change.
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#1419
No description provided.