[GH-ISSUE #2718] [Issue]: Local sidecar embeddings can never succeed (no --embeddings flag, MLX has no embeddings endpoint, configured embedder silently ignored) #1362

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

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The sidecar is advertised as a first-class embedding source (ConnectionEditor 'Local Model (sidecar)', /api/sidecar/v1/embeddings, lorebook vectorize, memory recall), but it can never produce a vector on either backend, force-loads the heavy chat model to fail, and even when a remote embedder is configured the local ONNX path silently overrides it. Failures are then swallowed in ways that permanently degrade recall.


1. No --embeddings flag + 404-only fallback (high)

How it breaks the pipeline: buildLlamaArgs never emits --embeddings, so the chat llama-server rejects /v1/embeddings with HTTP 501 ('not enabled'), not 404. isNotFoundError matches only /(404)|\b404\b/, so the legacy /embedding fallback never fires and the error rethrows. Lorebook vectorize 500s; memory recall using the sidecar silently produces zero embeddings.

Steps to replicate: Select 'Local Model (sidecar)' as the embedding source and run lorebook Vectorize (or POST /api/sidecar/v1/embeddings). It fails unconditionally on llama.cpp.

Trace: buildLlamaArgs produces no --embeddings (sidecar-launch-plan.ts:8-44; repo-wide grep confirms zero matches). requestOpenAIEmbeddings throws ...failed (501): ... (local-sidecar.provider.ts:98-100); isNotFoundError (9-11) is false for 501 → rethrow (83). Even if reached, requestLegacyEmbeddings POSTs /embedding (109) which also requires --embeddings. lorebooks.routes.ts:860 is unguarded → 500; memory-recall-embedding.ts:68-71 catches → null.

Suggested Fix: Either do not advertise the sidecar as an embedding source for llama.cpp (the ONNX local embedder already covers zero-config local embeddings), or launch a separate --embeddings (with --pooling mean) instance on its own port for the embed path; broaden isNotFoundError/fallback to treat 501/'not enabled' as a trigger; wrap lorebooks.routes.ts:860 in try/catch.


2. MLX has no embeddings endpoint at all (high)

How it breaks the pipeline: mlx_lm.server (the macOS backend) implements only chat/completions and /v1/models — neither /v1/embeddings nor /embedding. The dual OpenAI/legacy fallback was designed for llama.cpp; both URLs 404 and the error rethrows, so sidecar embeddings are 100% non-functional on Apple Silicon.

Steps to replicate: On Apple Silicon, select the sidecar as the embedding source; every embed fails (502 / silent null).

Trace: Backend 'mlx' spawns mlx_lm.server (sidecar-process.service.ts:358-360) installed from upstream main (mlx-runtime.service.ts:22); upstream has no embeddings route. embed() 404s on /v1/embeddings then 404s on /embedding (local-sidecar.provider.ts:76-128). isMemoryRecallVectorizerAvailable still reports it usable (memory-recall-embedding.ts:120-131).

Suggested Fix: Detect backend==='mlx' before attempting sidecar embeddings and report embeddings as unsupported on MLX (so callers fall back to a remote embedder) or route them through a supported mechanism.


3. Embed path force-starts the heavy chat model just to fail (low)

How it breaks the pipeline: embed() calls ensureReady({forceStart:true}), booting the multi-GB chat model even when the sidecar is otherwise disabled and idle — then returns 502 because of #1/#2. Pure cost for zero result, and it leaves a resident server the user never opted into.

Steps to replicate: With trackers/game-scene off, POST /api/sidecar/v1/embeddings; the chat model loads for seconds then errors.

Trace: ensureReady({forceStart:true}) (local-sidecar.provider.ts:77) bypasses the !isEnabled() stop guard (sidecar-process.service.ts:256) and starts the model; no idle auto-unload exists. The direct /v1/embeddings route (sidecar.routes.ts:153-175) is ungated and always force-starts.

Suggested Fix: Do not forceStart for embeddings; require an intentionally-enabled embedding-capable server and fail fast with a clear message when embeddings are unsupported.


4. Configured embedder silently ignored when ONNX is installed (medium)

How it breaks the pipeline: embedMemoryRecallTexts always tries the local ONNX (384-d MiniLM) embedder FIRST and only uses the configured embeddingSource as a fallback, so a user who sets text-embedding-3-small / an endpoint URL / 'Local Model (sidecar)' gets a complete no-op on the default desktop install (onnxruntime-node is a hard dependency).

Steps to replicate: Configure a remote Embedding Model in ConnectionEditor; vectorize a lorebook. It still runs on the bundled MiniLM.

Trace: localEmbedder(texts) first; if (localEmbeddings) return BEFORE options.embeddingSource is consulted (memory-recall.ts:64-77). Every caller passes only embeddingSource, never overriding localEmbedder. UI advertises the settings as functional (ConnectionEditor.tsx:1817-1889).

Suggested Fix: When a non-default embeddingSource is explicitly configured, prefer it over local ONNX (or add an explicit 'use local embeddings' toggle); only fall back to localEmbed when no source was configured.


5. Null embeddings persisted but cursor advances → permanent recall blind spot (high)

How it breaks the pipeline: On any transient embedder failure, embedMemoryRecallTexts returns []; the insert loop still writes every chunk with embedding: null and records lastMessageAt, and the next run's cursor (computed from the latest chunk regardless of null) skips those messages forever. recallMemories filters isNotNull(embedding), so null chunks are dead.

Steps to replicate: Cause a transient embedder failure (sidecar not ready / remote 429) during chunking; after the embedder recovers, that conversation range is never re-embedded and is unrecallable until a manual rebuild.

Trace: failure → [] (memory-recall.ts:60-80); loop inserts null chunks with lastMessageAt (155-172); cursor query has no embedding filter (95-102); recallMemories requires isNotNull(embedding) (231); only rebuildMemoryChunks (delete+recreate) repairs it.

Suggested Fix: Do not insert null-embedding chunks (skip so they stay before the cursor and retry), or compute the cursor only from non-null chunks, or add a background re-embed sweep; assert embeddings.length === chunksToCreate.length before persisting.


6. Mixed dimensions silently corrupt the vector store (medium)

How it breaks the pipeline: Chunks are stored as bare JSON float arrays with no model/dimension column. When the embedder identity differs between write and read (ONNX present on one run/machine, absent on another), cosineSimilarity returns 0 for length mismatches and chunks are silently dropped with one warn line.

Steps to replicate: Embed chunks with ONNX available, then read with onnxruntime-node missing (or DB moved between machines); recall returns nothing for those chunks.

Trace: local-first selection (memory-recall.ts:64-66); no dim/model column (db/schema/chats.ts:103-111); cosineSimilarity returns 0 on length mismatch (memory-recall.ts:27) then >= 0.25 filter drops them (259); mismatch logged once (243-250).

Suggested Fix: Record the embedding model/dimension per chunk (and lorebook entry); refuse to mix dimensions in one store (or auto-rebuild on change); make embedder selection deterministic for a chat so write/read share a space.


7. Batched embeddings mapped positionally, ignoring index (low)

How it breaks the pipeline: parseEmbeddingResponse does data.map(item => item.embedding) and never reads item.index. If an OpenAI-compatible backend returns the data array out of input order, vectors are attached to the wrong text, producing subtly wrong matches with no error.

Steps to replicate: Point the local sidecar at an embedding backend that reorders data; batched lorebook/memory vectors are misassigned.

Trace: data.map(item => item.embedding) with no sort (base-provider.ts:653-665); consumers map positionally (lorebooks.routes.ts:855-868; memory-recall.ts:155-172); the local OpenAI path routes through the same parser (local-sidecar.provider.ts:102).

Suggested Fix: When items carry numeric index, scatter by index into a fixed-length array before returning; validate returned count equals input count and throw on mismatch.


Affected files

  • packages/server/src/services/sidecar/sidecar-launch-plan.ts
  • packages/server/src/services/llm/providers/local-sidecar.provider.ts
  • packages/server/src/services/memory-recall.ts
  • packages/server/src/services/memory-recall-embedding.ts
  • packages/server/src/routes/sidecar.routes.ts
  • packages/server/src/routes/lorebooks.routes.ts
  • packages/server/src/services/llm/base-provider.ts

Audit provenance

Found by a multi-agent static audit of the sidecar/local-model subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: HIGH. Line numbers are against the staging working tree.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2718 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The sidecar is advertised as a first-class embedding source (ConnectionEditor 'Local Model (sidecar)', `/api/sidecar/v1/embeddings`, lorebook vectorize, memory recall), but it can never produce a vector on either backend, force-loads the heavy chat model to fail, and even when a remote embedder is configured the local ONNX path silently overrides it. Failures are then swallowed in ways that permanently degrade recall. --- ### 1. No --embeddings flag + 404-only fallback (high) **How it breaks the pipeline:** `buildLlamaArgs` never emits `--embeddings`, so the chat llama-server rejects `/v1/embeddings` with HTTP 501 ('not enabled'), not 404. `isNotFoundError` matches only `/(404)|\b404\b/`, so the legacy `/embedding` fallback never fires and the error rethrows. Lorebook vectorize 500s; memory recall using the sidecar silently produces zero embeddings. **Steps to replicate:** Select 'Local Model (sidecar)' as the embedding source and run lorebook Vectorize (or POST `/api/sidecar/v1/embeddings`). It fails unconditionally on llama.cpp. **Trace:** `buildLlamaArgs` produces no `--embeddings` (sidecar-launch-plan.ts:8-44; repo-wide grep confirms zero matches). `requestOpenAIEmbeddings` throws `...failed (501): ...` (local-sidecar.provider.ts:98-100); `isNotFoundError` (9-11) is false for 501 → rethrow (83). Even if reached, `requestLegacyEmbeddings` POSTs `/embedding` (109) which also requires `--embeddings`. lorebooks.routes.ts:860 is unguarded → 500; memory-recall-embedding.ts:68-71 catches → null. **Suggested Fix:** Either do not advertise the sidecar as an embedding source for llama.cpp (the ONNX local embedder already covers zero-config local embeddings), or launch a separate `--embeddings` (with `--pooling mean`) instance on its own port for the embed path; broaden `isNotFoundError`/fallback to treat 501/'not enabled' as a trigger; wrap lorebooks.routes.ts:860 in try/catch. --- ### 2. MLX has no embeddings endpoint at all (high) **How it breaks the pipeline:** `mlx_lm.server` (the macOS backend) implements only chat/completions and `/v1/models` — neither `/v1/embeddings` nor `/embedding`. The dual OpenAI/legacy fallback was designed for llama.cpp; both URLs 404 and the error rethrows, so sidecar embeddings are 100% non-functional on Apple Silicon. **Steps to replicate:** On Apple Silicon, select the sidecar as the embedding source; every embed fails (502 / silent null). **Trace:** Backend 'mlx' spawns `mlx_lm.server` (sidecar-process.service.ts:358-360) installed from upstream main (mlx-runtime.service.ts:22); upstream has no embeddings route. `embed()` 404s on `/v1/embeddings` then 404s on `/embedding` (local-sidecar.provider.ts:76-128). `isMemoryRecallVectorizerAvailable` still reports it usable (memory-recall-embedding.ts:120-131). **Suggested Fix:** Detect `backend==='mlx'` before attempting sidecar embeddings and report embeddings as unsupported on MLX (so callers fall back to a remote embedder) or route them through a supported mechanism. --- ### 3. Embed path force-starts the heavy chat model just to fail (low) **How it breaks the pipeline:** `embed()` calls `ensureReady({forceStart:true})`, booting the multi-GB chat model even when the sidecar is otherwise disabled and idle — then returns 502 because of #1/#2. Pure cost for zero result, and it leaves a resident server the user never opted into. **Steps to replicate:** With trackers/game-scene off, POST `/api/sidecar/v1/embeddings`; the chat model loads for seconds then errors. **Trace:** `ensureReady({forceStart:true})` (local-sidecar.provider.ts:77) bypasses the `!isEnabled()` stop guard (sidecar-process.service.ts:256) and starts the model; no idle auto-unload exists. The direct `/v1/embeddings` route (sidecar.routes.ts:153-175) is ungated and always force-starts. **Suggested Fix:** Do not `forceStart` for embeddings; require an intentionally-enabled embedding-capable server and fail fast with a clear message when embeddings are unsupported. --- ### 4. Configured embedder silently ignored when ONNX is installed (medium) **How it breaks the pipeline:** `embedMemoryRecallTexts` always tries the local ONNX (384-d MiniLM) embedder FIRST and only uses the configured `embeddingSource` as a fallback, so a user who sets text-embedding-3-small / an endpoint URL / 'Local Model (sidecar)' gets a complete no-op on the default desktop install (onnxruntime-node is a hard dependency). **Steps to replicate:** Configure a remote Embedding Model in ConnectionEditor; vectorize a lorebook. It still runs on the bundled MiniLM. **Trace:** `localEmbedder(texts)` first; `if (localEmbeddings) return` BEFORE `options.embeddingSource` is consulted (memory-recall.ts:64-77). Every caller passes only `embeddingSource`, never overriding `localEmbedder`. UI advertises the settings as functional (ConnectionEditor.tsx:1817-1889). **Suggested Fix:** When a non-default `embeddingSource` is explicitly configured, prefer it over local ONNX (or add an explicit 'use local embeddings' toggle); only fall back to `localEmbed` when no source was configured. --- ### 5. Null embeddings persisted but cursor advances → permanent recall blind spot (high) **How it breaks the pipeline:** On any transient embedder failure, `embedMemoryRecallTexts` returns `[]`; the insert loop still writes every chunk with `embedding: null` and records `lastMessageAt`, and the next run's cursor (computed from the latest chunk regardless of null) skips those messages forever. `recallMemories` filters `isNotNull(embedding)`, so null chunks are dead. **Steps to replicate:** Cause a transient embedder failure (sidecar not ready / remote 429) during chunking; after the embedder recovers, that conversation range is never re-embedded and is unrecallable until a manual rebuild. **Trace:** failure → `[]` (memory-recall.ts:60-80); loop inserts null chunks with `lastMessageAt` (155-172); cursor query has no embedding filter (95-102); `recallMemories` requires `isNotNull(embedding)` (231); only `rebuildMemoryChunks` (delete+recreate) repairs it. **Suggested Fix:** Do not insert null-embedding chunks (skip so they stay before the cursor and retry), or compute the cursor only from non-null chunks, or add a background re-embed sweep; assert `embeddings.length === chunksToCreate.length` before persisting. --- ### 6. Mixed dimensions silently corrupt the vector store (medium) **How it breaks the pipeline:** Chunks are stored as bare JSON float arrays with no model/dimension column. When the embedder identity differs between write and read (ONNX present on one run/machine, absent on another), `cosineSimilarity` returns 0 for length mismatches and chunks are silently dropped with one warn line. **Steps to replicate:** Embed chunks with ONNX available, then read with onnxruntime-node missing (or DB moved between machines); recall returns nothing for those chunks. **Trace:** local-first selection (memory-recall.ts:64-66); no dim/model column (db/schema/chats.ts:103-111); `cosineSimilarity` returns 0 on length mismatch (memory-recall.ts:27) then `>= 0.25` filter drops them (259); mismatch logged once (243-250). **Suggested Fix:** Record the embedding model/dimension per chunk (and lorebook entry); refuse to mix dimensions in one store (or auto-rebuild on change); make embedder selection deterministic for a chat so write/read share a space. --- ### 7. Batched embeddings mapped positionally, ignoring `index` (low) **How it breaks the pipeline:** `parseEmbeddingResponse` does `data.map(item => item.embedding)` and never reads `item.index`. If an OpenAI-compatible backend returns the data array out of input order, vectors are attached to the wrong text, producing subtly wrong matches with no error. **Steps to replicate:** Point the local sidecar at an embedding backend that reorders `data`; batched lorebook/memory vectors are misassigned. **Trace:** `data.map(item => item.embedding)` with no sort (base-provider.ts:653-665); consumers map positionally (lorebooks.routes.ts:855-868; memory-recall.ts:155-172); the local OpenAI path routes through the same parser (local-sidecar.provider.ts:102). **Suggested Fix:** When items carry numeric `index`, scatter by index into a fixed-length array before returning; validate returned count equals input count and throw on mismatch. --- ### Affected files - `packages/server/src/services/sidecar/sidecar-launch-plan.ts` - `packages/server/src/services/llm/providers/local-sidecar.provider.ts` - `packages/server/src/services/memory-recall.ts` - `packages/server/src/services/memory-recall-embedding.ts` - `packages/server/src/routes/sidecar.routes.ts` - `packages/server/src/routes/lorebooks.routes.ts` - `packages/server/src/services/llm/base-provider.ts` ### Audit provenance Found by a multi-agent static audit of the sidecar/local-model subsystem (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified). Severity: **HIGH**. Line numbers are against the `staging` working tree.
Author
Owner

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

Veracity self-review — correction / clarification
Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it.

Correction to Claim 4 (Configured embedder silently ignored when ONNX is installed):

The ONNX-first override in embedMemoryRecallTexts (memory-recall.ts:64-66 — localEmbed is tried first and returned before options.embeddingSource is consulted) is real, but the repro and scope are wrong about the lorebook path:

  • The MANUAL lorebook "Vectorize" button is NOT affected. It calls POST /lorebooks/:id/vectorize (client: LorebookEditor.tsx:2296), whose handler (lorebooks.routes.ts:826-868) calls provider.embed() DIRECTLY on the configured connection (or the sidecar provider for LOCAL_SIDECAR_CONNECTION_ID) at line 860. It never routes through embedMemoryRecallTexts, so a configured text-embedding-3-small / endpoint URL / sidecar IS honored there. The step "vectorize a lorebook; it still runs on the bundled MiniLM" is incorrect — please drop it.

  • The defect DOES affect two live paths:

    1. Memory recall: chunkAndEmbedMessages and recallMemories both call embedMemoryRecallTexts (memory-recall.ts:156, 212).
    2. The AUTOMATIC lorebook semantic path: lorebook/embeddings.ts:71-76 (embedLorebookTexts -> embedMemoryRecallTexts), used by warmLorebookEntryEmbeddings and semanticShortlistLorebookEntries, which runs during generation via the knowledge router (knowledge-router.ts:226). So when ONNX is present, automatic lorebook semantic matching also runs on the bundled 384-d MiniLM regardless of the configured embedder — including the case where the user pre-vectorized entries with a different embedder, which then mismatches dimensions (ties into Claim 6).

Scope the Claim 4 fix accordingly: prefer an explicitly-configured embeddingSource over local ONNX inside embedMemoryRecallTexts (so it applies to BOTH memory recall and the automatic lorebook path), and leave the manual Vectorize route as-is since it already honors the configured embedder.

<!-- gh-comment-id:4761102758 --> @kolacheee commented on GitHub (Jun 21, 2026): > **Veracity self-review — correction / clarification** > _Automated post-filing review of this issue against the current working tree. The reported bug remains valid; the notes below refine its scope, accuracy, or suggested fix for whoever implements it._ Correction to Claim 4 (Configured embedder silently ignored when ONNX is installed): The ONNX-first override in embedMemoryRecallTexts (memory-recall.ts:64-66 — localEmbed is tried first and returned before options.embeddingSource is consulted) is real, but the repro and scope are wrong about the lorebook path: - The MANUAL lorebook "Vectorize" button is NOT affected. It calls POST /lorebooks/:id/vectorize (client: LorebookEditor.tsx:2296), whose handler (lorebooks.routes.ts:826-868) calls provider.embed() DIRECTLY on the configured connection (or the sidecar provider for LOCAL_SIDECAR_CONNECTION_ID) at line 860. It never routes through embedMemoryRecallTexts, so a configured text-embedding-3-small / endpoint URL / sidecar IS honored there. The step "vectorize a lorebook; it still runs on the bundled MiniLM" is incorrect — please drop it. - The defect DOES affect two live paths: 1. Memory recall: chunkAndEmbedMessages and recallMemories both call embedMemoryRecallTexts (memory-recall.ts:156, 212). 2. The AUTOMATIC lorebook semantic path: lorebook/embeddings.ts:71-76 (embedLorebookTexts -> embedMemoryRecallTexts), used by warmLorebookEntryEmbeddings and semanticShortlistLorebookEntries, which runs during generation via the knowledge router (knowledge-router.ts:226). So when ONNX is present, automatic lorebook semantic matching also runs on the bundled 384-d MiniLM regardless of the configured embedder — including the case where the user pre-vectorized entries with a different embedder, which then mismatches dimensions (ties into Claim 6). Scope the Claim 4 fix accordingly: prefer an explicitly-configured embeddingSource over local ONNX inside embedMemoryRecallTexts (so it applies to BOTH memory recall and the automatic lorebook path), and leave the manual Vectorize route as-is since it already honors the configured embedder.
Author
Owner

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

Fixed in be161eea on the issue-sweep branch. The llama.cpp sidecar now launches with embeddings enabled, sidecar embedding calls no longer force-start a disabled chat model and reject MLX with a clear unsupported error, automatic memory/lorebook semantic embedding now prefers explicitly configured sources over local ONNX, null/partial embedding batches are no longer persisted as memory chunks, old null chunks no longer advance the cursor, memory and lorebook paths guard against dimension mixing, manual lorebook vectorize returns clear 502/409 errors for failed or incompatible batches, and shared embedding parsing now honors response indexes.

<!-- gh-comment-id:4761703223 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Fixed in be161eea on the issue-sweep branch. The llama.cpp sidecar now launches with embeddings enabled, sidecar embedding calls no longer force-start a disabled chat model and reject MLX with a clear unsupported error, automatic memory/lorebook semantic embedding now prefers explicitly configured sources over local ONNX, null/partial embedding batches are no longer persisted as memory chunks, old null chunks no longer advance the cursor, memory and lorebook paths guard against dimension mixing, manual lorebook vectorize returns clear 502/409 errors for failed or incompatible batches, and shared embedding parsing now honors response indexes.
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#1362
No description provided.