Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(embeddings): block cross-dimension failover in embedding combos (#3256)

Diego Rodrigues de Sa e Souza2ad2bcb13fca
diff --git a/open-sse/config/embeddingRegistry.ts b/open-sse/config/embeddingRegistry.ts
index 69994c323a..63ce9d30f7 100644
--- a/open-sse/config/embeddingRegistry.ts
+++ b/open-sse/config/embeddingRegistry.ts
@@ -324,6 +324,41 @@ export function parseEmbeddingModel(
return { provider: null, model: modelStr };
}
+/**
+ * Resolve the known vector dimension of an embedding model string
+ * (format: "provider/model"). Returns undefined when the provider/model is
+ * unknown or the registry has no dimension recorded for it (e.g. local/custom
+ * providers) — callers treat undefined as "can't assert", not "zero".
+ */
+export function getEmbeddingDimension(modelStr: string): number | undefined {
+ const { provider, model } = parseEmbeddingModel(modelStr);
+ if (!provider || !model) return undefined;
+ const config = getEmbeddingProvider(provider);
+ if (!config) return undefined;
+ return config.models.find((m) => m.id === model)?.dimensions;
+}
+
+/**
+ * Detect whether a set of embedding model strings spans more than one known
+ * vector dimension. Vectors from models of different dimensions live in
+ * incompatible spaces, so failing over between them silently corrupts any
+ * vector store built on top of the proxy. Models with an *unknown* dimension
+ * are ignored (conservative: we never flag a conflict we can't prove).
+ */
+export function detectEmbeddingDimensionConflict(modelStrs: string[]): {
+ conflict: boolean;
+ dimensions: Record<string, number>;
+ distinct: number[];
+} {
+ const dimensions: Record<string, number> = {};
+ for (const modelStr of modelStrs) {
+ const dim = getEmbeddingDimension(modelStr);
+ if (typeof dim === "number") dimensions[modelStr] = dim;
+ }
+ const distinct = [...new Set(Object.values(dimensions))].sort((a, b) => a - b);
+ return { conflict: distinct.length > 1, dimensions, distinct };
+}
+
/**
* Get all embedding models as a flat list
*/
diff --git a/src/lib/embeddings/familyGuard.ts b/src/lib/embeddings/familyGuard.ts
new file mode 100644
index 0000000000..154377afc2
--- /dev/null
+++ b/src/lib/embeddings/familyGuard.ts
@@ -0,0 +1,24 @@
+import { resolveComboTargets } from "@omniroute/open-sse/services/combo.ts";
+import { detectEmbeddingDimensionConflict } from "@omniroute/open-sse/config/embeddingRegistry.ts";
+
+/**
+ * Embedding-combo family guard.
+ *
+ * When an embeddings request is routed through a combo, the generic combo
+ * engine fails over between targets with no notion of vector-space family.
+ * If a combo mixes embedding models of different dimensions, that failover
+ * silently corrupts any vector store built on top of the proxy (vectors from
+ * different models are not comparable).
+ *
+ * This resolves the combo's full leaf-target list (nested combos expanded) and
+ * reports whether those targets span more than one known dimension, so the
+ * caller can reject the request loudly instead of corrupting data on failover.
+ */
+export function findEmbeddingComboDimensionConflict(
+ combo: Parameters<typeof resolveComboTargets>[0],
+ allCombos: Parameters<typeof resolveComboTargets>[1]
+): ReturnType<typeof detectEmbeddingDimensionConflict> {
+ const targets = resolveComboTargets(combo, allCombos);
+ const modelStrs = targets.map((t) => t.modelStr).filter(Boolean);
+ return detectEmbeddingDimensionConflict(modelStrs);
+}
diff --git a/src/lib/embeddings/service.ts b/src/lib/embeddings/service.ts
index ea9c1b0741..131f7554b9 100644
--- a/src/lib/embeddings/service.ts
+++ b/src/lib/embeddings/service.ts
@@ -13,6 +13,7 @@ import { toJsonErrorPayload } from "@/shared/utils/upstreamError";
import { getProviderCredentials, clearRecoveredProviderState } from "@/sse/services/auth";
import { getProviderNodes, getComboByName, getCombos, getDatabaseSettings } from "@/lib/localDb";
import { handleComboChat } from "@omniroute/open-sse/services/combo.ts";
+import { findEmbeddingComboDimensionConflict } from "./familyGuard";
type ValidatedEmbeddingBody = Record<string, unknown> & { model: string };
type ProviderCredentialsResult = Awaited<ReturnType<typeof getProviderCredentials>>;
@@ -43,6 +44,24 @@ export async function createEmbeddingResponse(
allCombos = await getCombos();
} catch {}
+ // Guard: an embedding combo whose targets span multiple vector
+ // dimensions would corrupt any vector store on failover (vectors from
+ // different models are not comparable). The generic combo engine has no
+ // notion of embedding families, so reject loudly here before dispatch.
+ // See _tasks/features-v3.8.12/01-embeddings-combo-family-guard.plan.md.
+ const dimConflict = findEmbeddingComboDimensionConflict(
+ combo as any,
+ allCombos as any
+ );
+ if (dimConflict.conflict) {
+ return errorResponse(
+ HTTP_STATUS.BAD_REQUEST,
+ `Embedding combo "${modelStr}" mixes models with incompatible vector ` +
+ `dimensions (${dimConflict.distinct.join(", ")}). Failover between them ` +
+ `would corrupt your vector store — use a single embedding dimension per combo.`
+ );
+ }
+
let settings = {};
try {
settings = getDatabaseSettings();
diff --git a/tests/unit/embedding-family-guard.test.ts b/tests/unit/embedding-family-guard.test.ts
new file mode 100644
index 0000000000..d68eb2057c
--- /dev/null
+++ b/tests/unit/embedding-family-guard.test.ts
@@ -0,0 +1,104 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+// familyGuard imports combo.ts which transitively touches DB modules at load;
+// give it a throwaway DATA_DIR so it uses defaults instead of the real store.
+process.env.DATA_DIR = mkdtempSync(join(tmpdir(), "omniroute-embed-family-"));
+
+const { getEmbeddingDimension, detectEmbeddingDimensionConflict } = await import(
+ "../../open-sse/config/embeddingRegistry.ts"
+);
+const { findEmbeddingComboDimensionConflict } = await import(
+ "../../src/lib/embeddings/familyGuard.ts"
+);
+
+test("getEmbeddingDimension resolves known dimensions from the registry", () => {
+ assert.equal(getEmbeddingDimension("openai/text-embedding-3-small"), 1536);
+ assert.equal(getEmbeddingDimension("openai/text-embedding-3-large"), 3072);
+ assert.equal(getEmbeddingDimension("nebius/Qwen/Qwen3-Embedding-8B"), 4096);
+ assert.equal(getEmbeddingDimension("gemini/text-embedding-004"), 768);
+ // OpenRouter re-exports OpenAI ids under its own prefix at the same dimension.
+ assert.equal(getEmbeddingDimension("openrouter/openai/text-embedding-3-small"), 1536);
+});
+
+test("getEmbeddingDimension returns undefined for unknown/local models", () => {
+ assert.equal(getEmbeddingDimension("localembed/my-model"), undefined);
+ assert.equal(getEmbeddingDimension("mystery/whatever"), undefined);
+});
+
+test("detectEmbeddingDimensionConflict flags mixed vector spaces", () => {
+ const res = detectEmbeddingDimensionConflict([
+ "openai/text-embedding-3-small", // 1536
+ "nebius/Qwen/Qwen3-Embedding-8B", // 4096
+ ]);
+ assert.equal(res.conflict, true);
+ assert.deepEqual(res.distinct, [1536, 4096]);
+});
+
+test("detectEmbeddingDimensionConflict accepts a uniform dimension", () => {
+ const res = detectEmbeddingDimensionConflict([
+ "openai/text-embedding-3-small", // 1536
+ "openrouter/openai/text-embedding-3-small", // 1536
+ ]);
+ assert.equal(res.conflict, false);
+ assert.deepEqual(res.distinct, [1536]);
+});
+
+test("detectEmbeddingDimensionConflict ignores unknown dimensions (no false positive)", () => {
+ const res = detectEmbeddingDimensionConflict([
+ "openai/text-embedding-3-small", // 1536 (known)
+ "localembed/unknown", // undefined (ignored)
+ ]);
+ assert.equal(res.conflict, false);
+ assert.deepEqual(res.distinct, [1536]);
+});
+
+test("detectEmbeddingDimensionConflict is a no-op for empty / all-unknown lists", () => {
+ assert.equal(detectEmbeddingDimensionConflict([]).conflict, false);
+ assert.equal(
+ detectEmbeddingDimensionConflict(["localembed/a", "localembed/b"]).conflict,
+ false
+ );
+});
+
+test("findEmbeddingComboDimensionConflict flags a mixed-dimension embedding combo", () => {
+ const combo = {
+ name: "mixed-embeds",
+ models: [
+ { model: "openai/text-embedding-3-small" }, // 1536
+ { model: "nebius/Qwen/Qwen3-Embedding-8B" }, // 4096
+ ],
+ };
+ const res = findEmbeddingComboDimensionConflict(combo, [combo]);
+ assert.equal(res.conflict, true);
+ assert.deepEqual(res.distinct, [1536, 4096]);
+});
+
+test("findEmbeddingComboDimensionConflict passes a uniform embedding combo", () => {
+ const combo = {
+ name: "uniform-embeds",
+ models: [
+ { model: "openai/text-embedding-3-small" }, // 1536
+ { model: "openrouter/openai/text-embedding-3-small" }, // 1536
+ ],
+ };
+ const res = findEmbeddingComboDimensionConflict(combo, [combo]);
+ assert.equal(res.conflict, false);
+});
+
+test("findEmbeddingComboDimensionConflict expands nested combos before checking", () => {
+ const child = {
+ name: "child-embeds",
+ models: [
+ { model: "openai/text-embedding-3-small" }, // 1536
+ { model: "nebius/Qwen/Qwen3-Embedding-8B" }, // 4096
+ ],
+ };
+ const parent = { name: "parent-embeds", models: [{ model: "child-embeds" }] };
+ const res = findEmbeddingComboDimensionConflict(parent, [parent, child]);
+ assert.equal(res.conflict, true);
+ assert.deepEqual(res.distinct, [1536, 4096]);
+});
diff --git a/tests/unit/embeddings-combo-family-reject.test.ts b/tests/unit/embeddings-combo-family-reject.test.ts
new file mode 100644
index 0000000000..f277cfdb49
--- /dev/null
+++ b/tests/unit/embeddings-combo-family-reject.test.ts
@@ -0,0 +1,78 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+// Real DB-backed integration: seed a mixed-dimension embedding combo, then prove
+// the service rejects it before any upstream dispatch (no vector-store corruption
+// path is reachable). Uses a throwaway DATA_DIR so migrations run against a temp DB.
+process.env.DATA_DIR = mkdtempSync(join(tmpdir(), "omniroute-embed-combo-reject-"));
+
+const { createCombo } = await import("../../src/lib/db/combos.ts");
+const { resetDbInstance } = await import("../../src/lib/db/core.ts");
+const { createEmbeddingResponse } = await import("../../src/lib/embeddings/service.ts");
+
+test.after(() => {
+ // Release the SQLite handle so the native test runner can exit (CLAUDE.md #3).
+ resetDbInstance();
+});
+
+test("createEmbeddingResponse rejects a mixed-dimension embedding combo without dispatching upstream", async () => {
+ await createCombo({
+ name: "mixed-embeds-combo",
+ strategy: "priority",
+ models: [
+ "openai/text-embedding-3-small", // 1536
+ "nebius/Qwen/Qwen3-Embedding-8B", // 4096
+ ],
+ });
+
+ const originalFetch = globalThis.fetch;
+ let fetchCalls = 0;
+ globalThis.fetch = async (...args: Parameters<typeof originalFetch>) => {
+ fetchCalls++;
+ return originalFetch(...args);
+ };
+
+ try {
+ const res = await createEmbeddingResponse({
+ model: "mixed-embeds-combo",
+ input: "hello world",
+ });
+
+ assert.equal(res.status, 400);
+ const body = JSON.stringify(await res.json());
+ assert.match(body, /incompatible vector dimensions/);
+ assert.match(body, /1536/);
+ assert.match(body, /4096/);
+ assert.equal(fetchCalls, 0, "must not dispatch upstream for a mixed-dimension combo");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test("createEmbeddingResponse allows a uniform-dimension embedding combo to proceed", async () => {
+ await createCombo({
+ name: "uniform-embeds-combo",
+ strategy: "priority",
+ models: [
+ "openai/text-embedding-3-small", // 1536
+ "openrouter/openai/text-embedding-3-small", // 1536
+ ],
+ });
+
+ // Uniform combo must NOT be blocked by the family guard — it should pass the
+ // guard and attempt real dispatch (which then fails on missing credentials,
+ // a 4xx that proves the guard did not short-circuit with the 400 dimension error).
+ const res = await createEmbeddingResponse({
+ model: "uniform-embeds-combo",
+ input: "hello world",
+ });
+ const body = JSON.stringify(await res.json());
+ assert.doesNotMatch(
+ body,
+ /incompatible vector dimensions/,
+ "uniform combo must not trip the dimension guard"
+ );
+});