eval.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. /**
  2. * Evaluation Tests for QMD Search Quality
  3. *
  4. * Tests search quality against synthetic documents with known-answer queries.
  5. * Validates that search improvements don't regress quality.
  6. *
  7. * Three test suites:
  8. * 1. BM25 (FTS) - lexical search baseline
  9. * 2. Vector Search - semantic search with embeddings
  10. * 3. Hybrid (RRF) - combined lexical + vector with rank fusion
  11. */
  12. import { describe, test, expect, beforeAll, afterAll } from "bun:test";
  13. import { mkdtempSync, rmSync, readFileSync, readdirSync } from "fs";
  14. import { join } from "path";
  15. import { tmpdir } from "os";
  16. import Database from "bun:sqlite";
  17. // Set INDEX_PATH before importing store to prevent using global index
  18. const tempDir = mkdtempSync(join(tmpdir(), "qmd-eval-"));
  19. process.env.INDEX_PATH = join(tempDir, "eval.sqlite");
  20. import {
  21. getDb,
  22. closeDb,
  23. searchFTS,
  24. searchVec,
  25. insertDocument,
  26. insertContent,
  27. ensureVecTable,
  28. insertEmbedding,
  29. chunkDocumentByTokens,
  30. reciprocalRankFusion,
  31. DEFAULT_EMBED_MODEL,
  32. type RankedResult,
  33. } from "./store";
  34. import { getDefaultLlamaCpp, formatDocForEmbedding } from "./llm";
  35. // Eval queries with expected documents
  36. const evalQueries: {
  37. query: string;
  38. expectedDoc: string;
  39. difficulty: "easy" | "medium" | "hard" | "fusion";
  40. }[] = [
  41. // EASY: Exact keyword matches
  42. { query: "API versioning", expectedDoc: "api-design", difficulty: "easy" },
  43. { query: "Series A fundraising", expectedDoc: "fundraising", difficulty: "easy" },
  44. { query: "CAP theorem", expectedDoc: "distributed-systems", difficulty: "easy" },
  45. { query: "overfitting machine learning", expectedDoc: "machine-learning", difficulty: "easy" },
  46. { query: "remote work VPN", expectedDoc: "remote-work", difficulty: "easy" },
  47. { query: "Project Phoenix retrospective", expectedDoc: "product-launch", difficulty: "easy" },
  48. // MEDIUM: Semantic/conceptual queries
  49. { query: "how to structure REST endpoints", expectedDoc: "api-design", difficulty: "medium" },
  50. { query: "raising money for startup", expectedDoc: "fundraising", difficulty: "medium" },
  51. { query: "consistency vs availability tradeoffs", expectedDoc: "distributed-systems", difficulty: "medium" },
  52. { query: "how to prevent models from memorizing data", expectedDoc: "machine-learning", difficulty: "medium" },
  53. { query: "working from home guidelines", expectedDoc: "remote-work", difficulty: "medium" },
  54. { query: "what went wrong with the launch", expectedDoc: "product-launch", difficulty: "medium" },
  55. // HARD: Vague, partial memory, indirect
  56. { query: "nouns not verbs", expectedDoc: "api-design", difficulty: "hard" },
  57. { query: "Sequoia investor pitch", expectedDoc: "fundraising", difficulty: "hard" },
  58. { query: "Raft algorithm leader election", expectedDoc: "distributed-systems", difficulty: "hard" },
  59. { query: "F1 score precision recall", expectedDoc: "machine-learning", difficulty: "hard" },
  60. { query: "quarterly team gathering travel", expectedDoc: "remote-work", difficulty: "hard" },
  61. { query: "beta program 47 bugs", expectedDoc: "product-launch", difficulty: "hard" },
  62. // FUSION: Multi-signal queries that need both lexical AND semantic matching
  63. // These should have weak individual scores but strong combined RRF scores
  64. { query: "how much runway before running out of money", expectedDoc: "fundraising", difficulty: "fusion" },
  65. { query: "datacenter replication sync strategy", expectedDoc: "distributed-systems", difficulty: "fusion" },
  66. { query: "splitting data for training and testing", expectedDoc: "machine-learning", difficulty: "fusion" },
  67. { query: "JSON response codes error messages", expectedDoc: "api-design", difficulty: "fusion" },
  68. { query: "video calls camera async messaging", expectedDoc: "remote-work", difficulty: "fusion" },
  69. { query: "CI/CD pipeline testing coverage", expectedDoc: "product-launch", difficulty: "fusion" },
  70. ];
  71. // Helper to check if result matches expected doc
  72. function matchesExpected(filepath: string, expectedDoc: string): boolean {
  73. return filepath.toLowerCase().includes(expectedDoc);
  74. }
  75. // Helper to calculate hit rate
  76. function calcHitRate(
  77. queries: typeof evalQueries,
  78. searchFn: (query: string) => { filepath: string }[],
  79. topK: number
  80. ): number {
  81. let hits = 0;
  82. for (const { query, expectedDoc } of queries) {
  83. const results = searchFn(query).slice(0, topK);
  84. if (results.some(r => matchesExpected(r.filepath, expectedDoc))) hits++;
  85. }
  86. return hits / queries.length;
  87. }
  88. // =============================================================================
  89. // BM25 (Lexical) Tests - Fast, no model loading needed
  90. // =============================================================================
  91. describe("BM25 Search (FTS)", () => {
  92. let db: Database;
  93. beforeAll(() => {
  94. db = getDb();
  95. // Load and index eval documents
  96. const evalDocsDir = join(import.meta.dir, "../test/eval-docs");
  97. const files = readdirSync(evalDocsDir).filter(f => f.endsWith(".md"));
  98. for (const file of files) {
  99. const content = readFileSync(join(evalDocsDir, file), "utf-8");
  100. const title = content.split("\n")[0]?.replace(/^#\s*/, "") || file;
  101. const hash = Bun.hash(content).toString(16).slice(0, 12);
  102. const now = new Date().toISOString();
  103. insertContent(db, hash, content, now);
  104. insertDocument(db, "eval-docs", file, title, hash, now, now);
  105. }
  106. });
  107. afterAll(() => {
  108. closeDb();
  109. });
  110. test("easy queries: ≥80% Hit@3", () => {
  111. const easyQueries = evalQueries.filter(q => q.difficulty === "easy");
  112. const hitRate = calcHitRate(easyQueries, q => searchFTS(db, q, 5), 3);
  113. expect(hitRate).toBeGreaterThanOrEqual(0.8);
  114. });
  115. test("medium queries: ≥15% Hit@3 (BM25 struggles with semantic)", () => {
  116. const mediumQueries = evalQueries.filter(q => q.difficulty === "medium");
  117. const hitRate = calcHitRate(mediumQueries, q => searchFTS(db, q, 5), 3);
  118. expect(hitRate).toBeGreaterThanOrEqual(0.15);
  119. });
  120. test("hard queries: ≥15% Hit@5 (BM25 baseline)", () => {
  121. const hardQueries = evalQueries.filter(q => q.difficulty === "hard");
  122. const hitRate = calcHitRate(hardQueries, q => searchFTS(db, q, 5), 5);
  123. expect(hitRate).toBeGreaterThanOrEqual(0.15);
  124. });
  125. test("overall Hit@3 ≥40% (BM25 baseline)", () => {
  126. const hitRate = calcHitRate(evalQueries, q => searchFTS(db, q, 5), 3);
  127. expect(hitRate).toBeGreaterThanOrEqual(0.4);
  128. });
  129. });
  130. // =============================================================================
  131. // Vector Search Tests - Requires embedding model
  132. // =============================================================================
  133. describe("Vector Search", () => {
  134. let db: Database;
  135. let hasEmbeddings = false;
  136. beforeAll(async () => {
  137. db = getDb();
  138. // Check if embeddings already exist (from previous test run)
  139. const vecTable = db.prepare(
  140. `SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`
  141. ).get();
  142. if (vecTable) {
  143. const count = db.prepare(`SELECT COUNT(*) as cnt FROM vectors_vec`).get() as { cnt: number };
  144. if (count.cnt > 0) {
  145. hasEmbeddings = true;
  146. return;
  147. }
  148. }
  149. // Generate embeddings for test documents
  150. const llm = getDefaultLlamaCpp();
  151. ensureVecTable(db, 768); // embeddinggemma uses 768 dimensions
  152. const evalDocsDir = join(import.meta.dir, "../test/eval-docs");
  153. const files = readdirSync(evalDocsDir).filter(f => f.endsWith(".md"));
  154. for (const file of files) {
  155. const content = readFileSync(join(evalDocsDir, file), "utf-8");
  156. const hash = Bun.hash(content).toString(16).slice(0, 12);
  157. const title = content.split("\n")[0]?.replace(/^#\s*/, "") || file;
  158. // Chunk and embed
  159. const chunks = await chunkDocumentByTokens(content, llm);
  160. for (let seq = 0; seq < chunks.length; seq++) {
  161. const chunk = chunks[seq];
  162. const formatted = formatDocForEmbedding(chunk.text, title);
  163. const result = await llm.embed(formatted, { model: DEFAULT_EMBED_MODEL, isQuery: false });
  164. if (result?.embedding) {
  165. // Convert to Float32Array for sqlite-vec
  166. const embedding = new Float32Array(result.embedding);
  167. const now = new Date().toISOString();
  168. insertEmbedding(db, hash, seq, chunk.pos, embedding, DEFAULT_EMBED_MODEL, now);
  169. }
  170. }
  171. }
  172. hasEmbeddings = true;
  173. }, 120000); // 2 minute timeout for embedding generation
  174. // Note: Don't dispose here - Hybrid tests also use llama.
  175. // Dispose happens in the global afterAll.
  176. test("easy queries: ≥60% Hit@3 (vector should match keywords too)", async () => {
  177. if (!hasEmbeddings) return; // Skip if embedding failed
  178. const easyQueries = evalQueries.filter(q => q.difficulty === "easy");
  179. let hits = 0;
  180. for (const { query, expectedDoc } of easyQueries) {
  181. const results = await searchVec(db, query, DEFAULT_EMBED_MODEL, 5);
  182. if (results.slice(0, 3).some(r => matchesExpected(r.filepath, expectedDoc))) hits++;
  183. }
  184. expect(hits / easyQueries.length).toBeGreaterThanOrEqual(0.6);
  185. }, 60000);
  186. test("medium queries: ≥40% Hit@3 (vector excels at semantic)", async () => {
  187. if (!hasEmbeddings) return;
  188. const mediumQueries = evalQueries.filter(q => q.difficulty === "medium");
  189. let hits = 0;
  190. for (const { query, expectedDoc } of mediumQueries) {
  191. const results = await searchVec(db, query, DEFAULT_EMBED_MODEL, 5);
  192. if (results.slice(0, 3).some(r => matchesExpected(r.filepath, expectedDoc))) hits++;
  193. }
  194. // Vector search should do better on semantic queries than BM25
  195. expect(hits / mediumQueries.length).toBeGreaterThanOrEqual(0.4);
  196. }, 60000);
  197. test("hard queries: ≥30% Hit@5 (vector helps with vague queries)", async () => {
  198. if (!hasEmbeddings) return;
  199. const hardQueries = evalQueries.filter(q => q.difficulty === "hard");
  200. let hits = 0;
  201. for (const { query, expectedDoc } of hardQueries) {
  202. const results = await searchVec(db, query, DEFAULT_EMBED_MODEL, 5);
  203. if (results.some(r => matchesExpected(r.filepath, expectedDoc))) hits++;
  204. }
  205. expect(hits / hardQueries.length).toBeGreaterThanOrEqual(0.3);
  206. }, 60000);
  207. test("overall Hit@3 ≥50% (vector baseline)", async () => {
  208. if (!hasEmbeddings) return;
  209. let hits = 0;
  210. for (const { query, expectedDoc } of evalQueries) {
  211. const results = await searchVec(db, query, DEFAULT_EMBED_MODEL, 5);
  212. if (results.slice(0, 3).some(r => matchesExpected(r.filepath, expectedDoc))) hits++;
  213. }
  214. expect(hits / evalQueries.length).toBeGreaterThanOrEqual(0.5);
  215. }, 60000);
  216. });
  217. // =============================================================================
  218. // Hybrid Search (RRF) Tests - Combines BM25 + Vector
  219. // =============================================================================
  220. describe("Hybrid Search (RRF)", () => {
  221. let db: Database;
  222. let hasVectors = false;
  223. beforeAll(() => {
  224. db = getDb();
  225. // Check if vectors exist
  226. const vecTable = db.prepare(
  227. `SELECT name FROM sqlite_master WHERE type='table' AND name='vectors_vec'`
  228. ).get();
  229. if (vecTable) {
  230. const count = db.prepare(`SELECT COUNT(*) as cnt FROM vectors_vec`).get() as { cnt: number };
  231. hasVectors = count.cnt > 0;
  232. }
  233. });
  234. // Helper: run hybrid search with RRF fusion
  235. async function hybridSearch(query: string, limit: number = 10): Promise<RankedResult[]> {
  236. const rankedLists: RankedResult[][] = [];
  237. // FTS results
  238. const ftsResults = searchFTS(db, query, 20);
  239. if (ftsResults.length > 0) {
  240. rankedLists.push(ftsResults.map(r => ({
  241. file: r.filepath,
  242. displayPath: r.displayPath,
  243. title: r.title,
  244. body: r.body || "",
  245. score: r.score
  246. })));
  247. }
  248. // Vector results
  249. const vecResults = await searchVec(db, query, DEFAULT_EMBED_MODEL, 20);
  250. if (vecResults.length > 0) {
  251. rankedLists.push(vecResults.map(r => ({
  252. file: r.filepath,
  253. displayPath: r.displayPath,
  254. title: r.title,
  255. body: r.body || "",
  256. score: r.score
  257. })));
  258. }
  259. if (rankedLists.length === 0) return [];
  260. // Apply RRF fusion
  261. const fused = reciprocalRankFusion(rankedLists);
  262. return fused.slice(0, limit);
  263. }
  264. test("easy queries: ≥80% Hit@3 (hybrid should match BM25)", async () => {
  265. const easyQueries = evalQueries.filter(q => q.difficulty === "easy");
  266. let hits = 0;
  267. for (const { query, expectedDoc } of easyQueries) {
  268. const results = await hybridSearch(query);
  269. if (results.slice(0, 3).some(r => matchesExpected(r.file, expectedDoc))) hits++;
  270. }
  271. expect(hits / easyQueries.length).toBeGreaterThanOrEqual(0.8);
  272. }, 60000);
  273. test("medium queries: ≥50% Hit@3 with vectors, ≥15% without", async () => {
  274. const mediumQueries = evalQueries.filter(q => q.difficulty === "medium");
  275. let hits = 0;
  276. for (const { query, expectedDoc } of mediumQueries) {
  277. const results = await hybridSearch(query);
  278. if (results.slice(0, 3).some(r => matchesExpected(r.file, expectedDoc))) hits++;
  279. }
  280. // With vectors: hybrid should outperform both BM25 (15%) and vector (40%)
  281. // Without vectors: hybrid is just BM25, so use BM25 threshold
  282. const threshold = hasVectors ? 0.5 : 0.15;
  283. expect(hits / mediumQueries.length).toBeGreaterThanOrEqual(threshold);
  284. }, 60000);
  285. test("hard queries: ≥35% Hit@5 with vectors, ≥15% without", async () => {
  286. const hardQueries = evalQueries.filter(q => q.difficulty === "hard");
  287. let hits = 0;
  288. for (const { query, expectedDoc } of hardQueries) {
  289. const results = await hybridSearch(query);
  290. if (results.some(r => matchesExpected(r.file, expectedDoc))) hits++;
  291. }
  292. const threshold = hasVectors ? 0.35 : 0.15;
  293. expect(hits / hardQueries.length).toBeGreaterThanOrEqual(threshold);
  294. }, 60000);
  295. test("fusion queries: ≥50% Hit@3 (RRF combines weak signals)", async () => {
  296. if (!hasVectors) return; // Fusion requires both methods
  297. const fusionQueries = evalQueries.filter(q => q.difficulty === "fusion");
  298. let hybridHits = 0;
  299. let bm25Hits = 0;
  300. let vecHits = 0;
  301. for (const { query, expectedDoc } of fusionQueries) {
  302. // Hybrid results
  303. const hybridResults = await hybridSearch(query);
  304. if (hybridResults.slice(0, 3).some(r => matchesExpected(r.file, expectedDoc))) hybridHits++;
  305. // BM25 results for comparison
  306. const bm25Results = searchFTS(db, query, 5);
  307. if (bm25Results.slice(0, 3).some(r => matchesExpected(r.filepath, expectedDoc))) bm25Hits++;
  308. // Vector results for comparison
  309. const vecResults = await searchVec(db, query, DEFAULT_EMBED_MODEL, 5);
  310. if (vecResults.slice(0, 3).some(r => matchesExpected(r.filepath, expectedDoc))) vecHits++;
  311. }
  312. const hybridRate = hybridHits / fusionQueries.length;
  313. const bm25Rate = bm25Hits / fusionQueries.length;
  314. const vecRate = vecHits / fusionQueries.length;
  315. // Fusion should achieve at least 50% on these multi-signal queries
  316. expect(hybridRate).toBeGreaterThanOrEqual(0.5);
  317. // Fusion should outperform or match the best individual method
  318. expect(hybridRate).toBeGreaterThanOrEqual(Math.max(bm25Rate, vecRate));
  319. }, 60000);
  320. test("overall Hit@3 ≥60% with vectors, ≥40% without", async () => {
  321. // Filter out fusion queries for overall score (they're tested separately)
  322. const standardQueries = evalQueries.filter(q => q.difficulty !== "fusion");
  323. let hits = 0;
  324. for (const { query, expectedDoc } of standardQueries) {
  325. const results = await hybridSearch(query);
  326. if (results.slice(0, 3).some(r => matchesExpected(r.file, expectedDoc))) hits++;
  327. }
  328. const threshold = hasVectors ? 0.6 : 0.4;
  329. expect(hits / standardQueries.length).toBeGreaterThanOrEqual(threshold);
  330. }, 60000);
  331. });
  332. // =============================================================================
  333. // Cleanup
  334. // =============================================================================
  335. afterAll(() => {
  336. rmSync(tempDir, { recursive: true, force: true });
  337. });