The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(rag): one mismatched chunk vector silently destroyed the whole ranking
purplefa0f584118a3
diff --git a/src/api/__tests__/rag-ranking-nan.test.ts b/src/api/__tests__/rag-ranking-nan.test.tsnew file mode 100644index 00000000..79915599--- /dev/null+++ b/src/api/__tests__/rag-ranking-nan.test.ts@@ -0,0 +1,83 @@+/**+ * RAG ranking must survive a chunk whose embedding does not line up (2026-07-28)+ *+ * Chunk vectors and the query vector can legitimately differ in length — the+ * user switched embedding models, or the app moved from Ollama embeddings to+ * the built-in engine — and a chunk whose embedding call failed can be stored+ * empty. cosineSimilarity used to read past the shorter vector and return NaN,+ * and hybridSearch then normalized every score against Math.max(..., NaN),+ * which is NaN. The sort compared NaNs, so retrieval quietly handed back the+ * document's first chunks instead of the relevant ones.+ *+ * Run: npx vitest run src/api/__tests__/rag-ranking-nan.test.ts+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('../engine', () => ({+ isManagedBuiltinActive: () => false,+ embedBaseUrl: () => 'http://127.0.0.1:8128/v1',+}))++const localFetch = vi.fn()+vi.mock('../backend', () => ({+ localFetch: (...args: any[]) => localFetch(...args),+ ollamaUrl: (path: string) => `http://localhost:11434/api${path}`,+}))++import { cosineSimilarity, retrieveContext } from '../rag'+import type { TextChunk } from '../../types/rag'++function chunk(id: string, content: string, embedding: number[]): TextChunk {+ return { id, documentId: 'doc1', content, embedding, index: Number(id) } as TextChunk+}++describe('cosineSimilarity', () => {+ it('scores identical vectors at 1', () => {+ expect(cosineSimilarity([1, 0, 0], [1, 0, 0])).toBeCloseTo(1)+ })++ it('returns 0 instead of NaN for vectors of different length', () => {+ expect(cosineSimilarity([1, 2, 3, 4], [1, 2, 3])).toBe(0)+ expect(cosineSimilarity([1, 2, 3], [])).toBe(0)+ expect(cosineSimilarity([], [1, 2, 3])).toBe(0)+ })++ it('never returns a non-finite score', () => {+ expect(Number.isFinite(cosineSimilarity([0, 0, 0], [0, 0, 0]))).toBe(true)+ })+})++describe('retrieveContext ranking', () => {+ beforeEach(() => {+ localFetch.mockReset()+ // Ollama /api/embed shape — one vector for the single query.+ localFetch.mockResolvedValue(+ new Response(JSON.stringify({ embeddings: [[1, 0, 0]] }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ )+ })++ it('still ranks the matching chunk first when another chunk has a stale-dimension vector', async () => {+ const chunks = [+ // Irrelevant, and embedded by a different model → wrong dimensions.+ chunk('0', 'completely unrelated filler text about gardening tools', [0.2, 0.9]),+ // The one that actually answers the query.+ chunk('1', 'the deployment key rotation procedure', [1, 0, 0]),+ ]+ const { scoredChunks } = await retrieveContext('key rotation', chunks, 'nomic-embed-text', 2)+ expect(scoredChunks[0].chunk.id).toBe('1')+ expect(scoredChunks.every(r => Number.isFinite(r.score))).toBe(true)+ })++ it('survives a chunk whose embedding never arrived', async () => {+ const chunks = [+ chunk('0', 'unrelated filler about gardening tools', []),+ chunk('1', 'the deployment key rotation procedure', [1, 0, 0]),+ ]+ const { scoredChunks } = await retrieveContext('key rotation', chunks, 'nomic-embed-text', 2)+ expect(scoredChunks[0].chunk.id).toBe('1')+ expect(scoredChunks.every(r => Number.isFinite(r.score))).toBe(true)+ })+})diff --git a/src/api/rag.ts b/src/api/rag.tsindex c0ad6c8b..6cec9c68 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -157,6 +157,15 @@ async function embedViaOllama(texts: string[], model: string): Promise<number[][}export function cosineSimilarity(a: number[], b: number[]): number {+ // Vectors of different length are not comparable — that happens for real:+ // chunks embedded with one model and a query embedded with another (switching+ // the embedding model, or the move from Ollama embeddings to the built-in+ // engine) have different dimensions, and a chunk whose embedding call failed+ // can be stored empty. The old loop read past the shorter vector, multiplied+ // by `undefined` and returned NaN — and a single NaN then poisoned the whole+ // ranking (see hybridSearch), so retrieval silently returned the first chunks+ // of the document instead of the relevant ones.+ if (!a.length || a.length !== b.length) return 0let dot = 0,magA = 0,magB = 0@@ -165,7 +174,8 @@ export function cosineSimilarity(a: number[], b: number[]): number {magA += a[i] * a[i]magB += b[i] * b[i]}- return dot / (Math.sqrt(magA) * Math.sqrt(magB) || 1)+ const score = dot / (Math.sqrt(magA) * Math.sqrt(magB) || 1)+ return Number.isFinite(score) ? score : 0}export function bm25Score(query: string, document: string, allDocs: string[]): number {@@ -206,16 +216,21 @@ function hybridSearch(bm25Score: bm25Score(query, chunk.content, allDocTexts),}))- // Normalize both score sets to 0-1- const maxVector = Math.max(...vectorResults.map((r) => r.vectorScore), 0.001)- const maxBm25 = Math.max(...bm25Results.map((r) => r.bm25Score), 0.001)+ // Normalize both score sets to 0-1. Non-finite scores are dropped from the+ // max: Math.max with a single NaN returns NaN, which would turn EVERY+ // normalized score into NaN and leave the sort comparing NaNs — i.e. no+ // ranking at all.+ const finite = (xs: number[]) => xs.filter((x) => Number.isFinite(x))+ const maxVector = Math.max(...finite(vectorResults.map((r) => r.vectorScore)), 0.001)+ const maxBm25 = Math.max(...finite(bm25Results.map((r) => r.bm25Score)), 0.001)// Combine with 0.7 vector + 0.3 BM25 weighting+ const safe = (x: number) => (Number.isFinite(x) ? x : 0)const combined = chunks.map((chunk, i) => ({chunk,score:- 0.7 * (vectorResults[i].vectorScore / maxVector) +- 0.3 * (bm25Results[i].bm25Score / maxBm25),+ 0.7 * (safe(vectorResults[i].vectorScore) / maxVector) ++ 0.3 * (safe(bm25Results[i].bm25Score) / maxBm25),}))return combined.sort((a, b) => b.score - a.score).slice(0, topK)