llm.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. /**
  2. * llm.test.ts - Unit tests for the LLM abstraction layer (node-llama-cpp)
  3. *
  4. * Run with: bun test src/llm.test.ts
  5. *
  6. * These tests require the actual models to be downloaded. Run the embed or
  7. * rerank functions first to trigger model downloads.
  8. */
  9. import { describe, test, expect, beforeAll, afterAll, vi } from "vitest";
  10. import {
  11. LlamaCpp,
  12. getDefaultLlamaCpp,
  13. disposeDefaultLlamaCpp,
  14. resolveLlamaGpuMode,
  15. withLLMSession,
  16. canUnloadLLM,
  17. SessionReleasedError,
  18. type RerankDocument,
  19. type ILLMSession,
  20. } from "../src/llm.js";
  21. // =============================================================================
  22. // Singleton Tests (no model loading required)
  23. // =============================================================================
  24. describe("Default LlamaCpp Singleton", () => {
  25. // Test singleton behavior without resetting to avoid orphan instances
  26. test("getDefaultLlamaCpp returns same instance on subsequent calls", () => {
  27. const llm1 = getDefaultLlamaCpp();
  28. const llm2 = getDefaultLlamaCpp();
  29. expect(llm1).toBe(llm2);
  30. expect(llm1).toBeInstanceOf(LlamaCpp);
  31. });
  32. });
  33. // =============================================================================
  34. // Model Existence Tests
  35. // =============================================================================
  36. describe("LlamaCpp.modelExists", () => {
  37. test("returns exists:true for HuggingFace model URIs", async () => {
  38. const llm = getDefaultLlamaCpp();
  39. const result = await llm.modelExists("hf:org/repo/model.gguf");
  40. expect(result.exists).toBe(true);
  41. expect(result.name).toBe("hf:org/repo/model.gguf");
  42. });
  43. test("returns exists:false for non-existent local paths", async () => {
  44. const llm = getDefaultLlamaCpp();
  45. const result = await llm.modelExists("/nonexistent/path/model.gguf");
  46. expect(result.exists).toBe(false);
  47. expect(result.name).toBe("/nonexistent/path/model.gguf");
  48. });
  49. });
  50. describe("QMD_LLAMA_GPU resolution", () => {
  51. test("uses auto when unset or blank", () => {
  52. expect(resolveLlamaGpuMode(undefined)).toBe("auto");
  53. expect(resolveLlamaGpuMode(" ")).toBe("auto");
  54. });
  55. test("maps CPU disable values to false", () => {
  56. expect(resolveLlamaGpuMode("false")).toBe(false);
  57. expect(resolveLlamaGpuMode("OFF")).toBe(false);
  58. expect(resolveLlamaGpuMode(" none ")).toBe(false);
  59. expect(resolveLlamaGpuMode("disabled")).toBe(false);
  60. expect(resolveLlamaGpuMode("0")).toBe(false);
  61. });
  62. test("passes through supported GPU backends", () => {
  63. expect(resolveLlamaGpuMode("metal")).toBe("metal");
  64. expect(resolveLlamaGpuMode("VULKAN")).toBe("vulkan");
  65. expect(resolveLlamaGpuMode(" cuda ")).toBe("cuda");
  66. });
  67. test("warns and falls back to auto for unsupported values", () => {
  68. const stderrSpy = vi.spyOn(process.stderr, "write").mockReturnValue(true);
  69. try {
  70. expect(resolveLlamaGpuMode("rocm")).toBe("auto");
  71. expect(stderrSpy).toHaveBeenCalled();
  72. expect(String(stderrSpy.mock.calls[0]?.[0] || "")).toContain("QMD_LLAMA_GPU");
  73. } finally {
  74. stderrSpy.mockRestore();
  75. }
  76. });
  77. });
  78. describe("LlamaCpp expand context size config", () => {
  79. const defaultExpandContextSize = 2048;
  80. test("uses default expand context size when no config or env is set", () => {
  81. const prev = process.env.QMD_EXPAND_CONTEXT_SIZE;
  82. delete process.env.QMD_EXPAND_CONTEXT_SIZE;
  83. try {
  84. const llm = new LlamaCpp({}) as any;
  85. expect(llm.expandContextSize).toBe(defaultExpandContextSize);
  86. } finally {
  87. if (prev === undefined) delete process.env.QMD_EXPAND_CONTEXT_SIZE;
  88. else process.env.QMD_EXPAND_CONTEXT_SIZE = prev;
  89. }
  90. });
  91. test("uses QMD_EXPAND_CONTEXT_SIZE when set to a positive integer", () => {
  92. const prev = process.env.QMD_EXPAND_CONTEXT_SIZE;
  93. process.env.QMD_EXPAND_CONTEXT_SIZE = "3072";
  94. try {
  95. const llm = new LlamaCpp({}) as any;
  96. expect(llm.expandContextSize).toBe(3072);
  97. } finally {
  98. if (prev === undefined) delete process.env.QMD_EXPAND_CONTEXT_SIZE;
  99. else process.env.QMD_EXPAND_CONTEXT_SIZE = prev;
  100. }
  101. });
  102. test("config value overrides QMD_EXPAND_CONTEXT_SIZE", () => {
  103. const prev = process.env.QMD_EXPAND_CONTEXT_SIZE;
  104. process.env.QMD_EXPAND_CONTEXT_SIZE = "4096";
  105. try {
  106. const llm = new LlamaCpp({ expandContextSize: 1536 }) as any;
  107. expect(llm.expandContextSize).toBe(1536);
  108. } finally {
  109. if (prev === undefined) delete process.env.QMD_EXPAND_CONTEXT_SIZE;
  110. else process.env.QMD_EXPAND_CONTEXT_SIZE = prev;
  111. }
  112. });
  113. test("falls back to default and warns when QMD_EXPAND_CONTEXT_SIZE is invalid", () => {
  114. const prev = process.env.QMD_EXPAND_CONTEXT_SIZE;
  115. process.env.QMD_EXPAND_CONTEXT_SIZE = "bad";
  116. const stderrSpy = vi.spyOn(process.stderr, "write").mockReturnValue(true);
  117. try {
  118. const llm = new LlamaCpp({}) as any;
  119. expect(llm.expandContextSize).toBe(defaultExpandContextSize);
  120. expect(stderrSpy).toHaveBeenCalled();
  121. expect(String(stderrSpy.mock.calls[0]?.[0] || "")).toContain("QMD_EXPAND_CONTEXT_SIZE");
  122. } finally {
  123. stderrSpy.mockRestore();
  124. if (prev === undefined) delete process.env.QMD_EXPAND_CONTEXT_SIZE;
  125. else process.env.QMD_EXPAND_CONTEXT_SIZE = prev;
  126. }
  127. });
  128. test("throws when config expandContextSize is invalid", () => {
  129. expect(() => new LlamaCpp({ expandContextSize: 0 })).toThrow(
  130. "Invalid expandContextSize: 0. Must be a positive integer."
  131. );
  132. });
  133. });
  134. describe("LlamaCpp model resolution (config > env > default)", () => {
  135. const HARDCODED_EMBED = "hf:ggml-org/embeddinggemma-300M-GGUF/embeddinggemma-300M-Q8_0.gguf";
  136. const HARDCODED_RERANK = "hf:ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF/qwen3-reranker-0.6b-q8_0.gguf";
  137. const HARDCODED_GENERATE = "hf:tobil/qmd-query-expansion-1.7B-gguf/qmd-query-expansion-1.7B-q4_k_m.gguf";
  138. test("uses hardcoded default when no config or env is set", () => {
  139. const prev = process.env.QMD_EMBED_MODEL;
  140. delete process.env.QMD_EMBED_MODEL;
  141. try {
  142. const llm = new LlamaCpp({}) as any;
  143. expect(llm.embedModelUri).toBe(HARDCODED_EMBED);
  144. expect(llm.rerankModelUri).toBe(HARDCODED_RERANK);
  145. expect(llm.generateModelUri).toBe(HARDCODED_GENERATE);
  146. } finally {
  147. if (prev === undefined) delete process.env.QMD_EMBED_MODEL;
  148. else process.env.QMD_EMBED_MODEL = prev;
  149. }
  150. });
  151. test("env var overrides hardcoded default", () => {
  152. const prev = process.env.QMD_EMBED_MODEL;
  153. process.env.QMD_EMBED_MODEL = "hf:custom/embed-model.gguf";
  154. try {
  155. const llm = new LlamaCpp({}) as any;
  156. expect(llm.embedModelUri).toBe("hf:custom/embed-model.gguf");
  157. } finally {
  158. if (prev === undefined) delete process.env.QMD_EMBED_MODEL;
  159. else process.env.QMD_EMBED_MODEL = prev;
  160. }
  161. });
  162. test("config overrides env var", () => {
  163. const prev = process.env.QMD_EMBED_MODEL;
  164. process.env.QMD_EMBED_MODEL = "hf:env/model.gguf";
  165. try {
  166. const llm = new LlamaCpp({ embedModel: "hf:config/model.gguf" }) as any;
  167. expect(llm.embedModelUri).toBe("hf:config/model.gguf");
  168. } finally {
  169. if (prev === undefined) delete process.env.QMD_EMBED_MODEL;
  170. else process.env.QMD_EMBED_MODEL = prev;
  171. }
  172. });
  173. });
  174. describe("LlamaCpp rerank deduping", () => {
  175. test("deduplicates identical document texts before scoring", async () => {
  176. const llm = new LlamaCpp({}) as any;
  177. llm._ciMode = false; // allow unit test even in CI (mocked, no real models)
  178. const rankAll = vi.fn(async (_query: string, docs: string[]) =>
  179. docs.map((doc) => doc === "shared chunk" ? 0.9 : 0.2)
  180. );
  181. llm.touchActivity = vi.fn();
  182. llm.ensureRerankContexts = vi.fn().mockResolvedValue([{ rankAll }]);
  183. llm.ensureRerankModel = vi.fn().mockResolvedValue({
  184. tokenize: (text: string) => Array.from(text),
  185. detokenize: (tokens: string[]) => tokens.join(""),
  186. });
  187. const result = await llm.rerank("query", [
  188. { file: "a.md", text: "shared chunk" },
  189. { file: "b.md", text: "shared chunk" },
  190. { file: "c.md", text: "different chunk" },
  191. ]);
  192. expect(rankAll).toHaveBeenCalledTimes(1);
  193. expect(rankAll).toHaveBeenCalledWith("query", ["shared chunk", "different chunk"]);
  194. expect(result.results).toHaveLength(3);
  195. const scoreByFile = new Map(result.results.map((item) => [item.file, item.score]));
  196. expect(scoreByFile.get("a.md")).toBe(0.9);
  197. expect(scoreByFile.get("b.md")).toBe(0.9);
  198. expect(scoreByFile.get("c.md")).toBe(0.2);
  199. });
  200. });
  201. // =============================================================================
  202. // Integration Tests (require actual models)
  203. // =============================================================================
  204. describe.skipIf(!!process.env.CI)("LlamaCpp Integration", () => {
  205. // Use the singleton to avoid multiple Metal contexts
  206. const llm = getDefaultLlamaCpp();
  207. afterAll(async () => {
  208. // Ensure native resources are released to avoid ggml-metal asserts on process exit.
  209. await disposeDefaultLlamaCpp();
  210. });
  211. describe("embed", () => {
  212. test("returns embedding with correct dimensions", async () => {
  213. const result = await llm.embed("Hello world");
  214. expect(result).not.toBeNull();
  215. expect(result!.embedding).toBeInstanceOf(Array);
  216. expect(result!.embedding.length).toBeGreaterThan(0);
  217. // embeddinggemma outputs 768 dimensions
  218. expect(result!.embedding.length).toBe(768);
  219. });
  220. test("returns consistent embeddings for same input", async () => {
  221. const result1 = await llm.embed("test text");
  222. const result2 = await llm.embed("test text");
  223. expect(result1).not.toBeNull();
  224. expect(result2).not.toBeNull();
  225. // Embeddings should be identical for the same input
  226. for (let i = 0; i < result1!.embedding.length; i++) {
  227. expect(result1!.embedding[i]).toBeCloseTo(result2!.embedding[i]!, 5);
  228. }
  229. });
  230. test("returns different embeddings for different inputs", async () => {
  231. const result1 = await llm.embed("cats are great");
  232. const result2 = await llm.embed("database optimization");
  233. expect(result1).not.toBeNull();
  234. expect(result2).not.toBeNull();
  235. // Calculate cosine similarity - should be less than 1.0 (not identical)
  236. let dotProduct = 0;
  237. let norm1 = 0;
  238. let norm2 = 0;
  239. for (let i = 0; i < result1!.embedding.length; i++) {
  240. const v1 = result1!.embedding[i]!;
  241. const v2 = result2!.embedding[i]!;
  242. dotProduct += v1 * v2;
  243. norm1 += v1 ** 2;
  244. norm2 += v2 ** 2;
  245. }
  246. const similarity = dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
  247. expect(similarity).toBeLessThan(0.95); // Should be meaningfully different
  248. });
  249. });
  250. describe("embedBatch", () => {
  251. test("returns embeddings for multiple texts", async () => {
  252. const texts = ["Hello world", "Test text", "Another document"];
  253. const results = await llm.embedBatch(texts);
  254. expect(results).toHaveLength(3);
  255. for (const result of results) {
  256. expect(result).not.toBeNull();
  257. expect(result!.embedding.length).toBe(768);
  258. }
  259. });
  260. test("returns same results as individual embed calls", async () => {
  261. const texts = ["cats are great", "dogs are awesome"];
  262. // Get batch embeddings
  263. const batchResults = await llm.embedBatch(texts);
  264. // Get individual embeddings
  265. const individualResults = await Promise.all(texts.map(t => llm.embed(t)));
  266. // Compare - should be identical
  267. for (let i = 0; i < texts.length; i++) {
  268. expect(batchResults[i]).not.toBeNull();
  269. expect(individualResults[i]).not.toBeNull();
  270. for (let j = 0; j < batchResults[i]!.embedding.length; j++) {
  271. expect(batchResults[i]!.embedding[j]).toBeCloseTo(individualResults[i]!.embedding[j]!, 5);
  272. }
  273. }
  274. });
  275. test("handles empty array", async () => {
  276. const results = await llm.embedBatch([]);
  277. expect(results).toHaveLength(0);
  278. });
  279. test("batch is faster than sequential", async () => {
  280. const texts = Array(10).fill(null).map((_, i) => `Document number ${i} with content`);
  281. // Time batch
  282. const batchStart = Date.now();
  283. await llm.embedBatch(texts);
  284. const batchTime = Date.now() - batchStart;
  285. // Time sequential
  286. const seqStart = Date.now();
  287. for (const text of texts) {
  288. await llm.embed(text);
  289. }
  290. const seqTime = Date.now() - seqStart;
  291. console.log(`Batch: ${batchTime}ms, Sequential: ${seqTime}ms`);
  292. // Performance is machine/load dependent. We only assert batch isn't drastically worse.
  293. expect(batchTime).toBeLessThanOrEqual(seqTime * 3);
  294. });
  295. test("handles concurrent embedBatch calls on fresh instance without race condition", async () => {
  296. // This test verifies the fix for a race condition where concurrent calls to
  297. // ensureEmbedContext() could create multiple contexts. Without the promise guard,
  298. // each concurrent embedBatch call sees embedContext === null and creates its own
  299. // context, causing resource leaks and potential "Context is disposed" errors.
  300. //
  301. // See: https://github.com/tobi/qmd/pull/54
  302. //
  303. // The fix uses a promise guard to ensure only one context creation runs at a time.
  304. // We verify this by instrumenting createEmbeddingContext to count invocations.
  305. const freshLlm = new LlamaCpp({});
  306. let contextCreateCount = 0;
  307. // Instrument the model's createEmbeddingContext to count calls
  308. const originalEnsureEmbedModel = (freshLlm as any).ensureEmbedModel.bind(freshLlm);
  309. let modelInstrumented = false;
  310. (freshLlm as any).ensureEmbedModel = async function() {
  311. const model = await originalEnsureEmbedModel();
  312. if (!modelInstrumented) {
  313. modelInstrumented = true;
  314. const originalCreate = model.createEmbeddingContext.bind(model);
  315. model.createEmbeddingContext = async function(...args: any[]) {
  316. contextCreateCount++;
  317. return originalCreate(...args);
  318. };
  319. }
  320. return model;
  321. };
  322. const texts = Array(10).fill(null).map((_, i) => `Document ${i}`);
  323. // Call embedBatch 5 TIMES in parallel on fresh instance.
  324. // Without the promise guard fix, this would create 5 contexts (one per call).
  325. // With the fix, only 1 context should be created.
  326. const batches = await Promise.all([
  327. freshLlm.embedBatch(texts.slice(0, 2)),
  328. freshLlm.embedBatch(texts.slice(2, 4)),
  329. freshLlm.embedBatch(texts.slice(4, 6)),
  330. freshLlm.embedBatch(texts.slice(6, 8)),
  331. freshLlm.embedBatch(texts.slice(8, 10)),
  332. ]);
  333. const allResults = batches.flat();
  334. expect(allResults).toHaveLength(10);
  335. const successCount = allResults.filter(r => r !== null).length;
  336. expect(successCount).toBe(10);
  337. // THE KEY ASSERTION: Contexts should be created once (by ensureEmbedContexts),
  338. // not duplicated per concurrent embedBatch call. The exact count depends on
  339. // available VRAM (computeParallelism), but should not be 5 (one per call).
  340. // Without the fix, contextCreateCount would be 5× the intended count (one set per concurrent call).
  341. // With the promise guard, contexts are created exactly once regardless of concurrent callers.
  342. // The count depends on VRAM (computeParallelism), but should be ≤ 8 (the cap).
  343. console.log(`Context creation count: ${contextCreateCount} (expected: ≤ 8, not 5× duplicated)`);
  344. expect(contextCreateCount).toBeGreaterThanOrEqual(1);
  345. expect(contextCreateCount).toBeLessThanOrEqual(8);
  346. await freshLlm.dispose();
  347. }, 60000);
  348. });
  349. describe("rerank", () => {
  350. test("scores capital of France question correctly", async () => {
  351. const query = "What is the capital of France?";
  352. const documents: RerankDocument[] = [
  353. { file: "butterflies.txt", text: "Butterflies indeed fly through the garden." },
  354. { file: "france.txt", text: "The capital of France is Paris." },
  355. { file: "canada.txt", text: "The capital of Canada is Ottawa." },
  356. ];
  357. const result = await llm.rerank(query, documents);
  358. expect(result.results).toHaveLength(3);
  359. // The France document should score highest
  360. expect(result.results[0]!.file).toBe("france.txt");
  361. expect(result.results[0]!.score).toBeGreaterThan(0.7);
  362. // Canada should be somewhat relevant (also about capitals)
  363. expect(result.results[1]!.file).toBe("canada.txt");
  364. // Butterflies should score lowest
  365. expect(result.results[2]!.file).toBe("butterflies.txt");
  366. expect(result.results[2]!.score).toBeLessThan(0.6);
  367. });
  368. test("scores authentication query correctly", async () => {
  369. const query = "How do I configure authentication?";
  370. const documents: RerankDocument[] = [
  371. { file: "weather.md", text: "The weather today is sunny with mild temperatures." },
  372. { file: "auth.md", text: "Authentication can be configured by setting the AUTH_SECRET environment variable." },
  373. { file: "pizza.md", text: "Our restaurant serves the best pizza in town." },
  374. { file: "jwt.md", text: "JWT authentication requires a secret key and expiration time." },
  375. ];
  376. const result = await llm.rerank(query, documents);
  377. expect(result.results).toHaveLength(4);
  378. // Auth documents should score highest
  379. const topTwo = result.results.slice(0, 2).map((r) => r.file);
  380. expect(topTwo).toContain("auth.md");
  381. expect(topTwo).toContain("jwt.md");
  382. // Irrelevant documents should score lowest
  383. const bottomTwo = result.results.slice(2).map((r) => r.file);
  384. expect(bottomTwo).toContain("weather.md");
  385. expect(bottomTwo).toContain("pizza.md");
  386. });
  387. test("handles programming queries correctly", async () => {
  388. const query = "How do I handle errors in JavaScript?";
  389. const documents: RerankDocument[] = [
  390. { file: "cooking.md", text: "To make a good pasta, boil water and add salt." },
  391. { file: "errors.md", text: "Use try-catch blocks to handle JavaScript errors gracefully." },
  392. { file: "python.md", text: "Python uses try-except for exception handling." },
  393. ];
  394. const result = await llm.rerank(query, documents);
  395. // JavaScript errors doc should score highest
  396. expect(result.results[0]!.file).toBe("errors.md");
  397. expect(result.results[0]!.score).toBeGreaterThan(0.7);
  398. // Python doc might be somewhat relevant (same concept, different language)
  399. // Cooking should be least relevant
  400. expect(result.results[2]!.file).toBe("cooking.md");
  401. });
  402. test("handles empty document list", async () => {
  403. const result = await llm.rerank("test query", []);
  404. expect(result.results).toHaveLength(0);
  405. });
  406. test("handles single document", async () => {
  407. const result = await llm.rerank("test", [{ file: "doc.md", text: "content" }]);
  408. expect(result.results).toHaveLength(1);
  409. expect(result.results[0]!.file).toBe("doc.md");
  410. });
  411. test("preserves original file paths", async () => {
  412. const documents: RerankDocument[] = [
  413. { file: "path/to/doc1.md", text: "content one" },
  414. { file: "another/path/doc2.md", text: "content two" },
  415. ];
  416. const result = await llm.rerank("query", documents);
  417. const files = result.results.map((r) => r.file).sort();
  418. expect(files).toEqual(["another/path/doc2.md", "path/to/doc1.md"]);
  419. });
  420. test("returns scores between 0 and 1", async () => {
  421. const documents: RerankDocument[] = [
  422. { file: "a.md", text: "The quick brown fox jumps over the lazy dog." },
  423. { file: "b.md", text: "Machine learning algorithms process data efficiently." },
  424. { file: "c.md", text: "React components use JSX syntax for rendering." },
  425. ];
  426. const result = await llm.rerank("Tell me about animals", documents);
  427. for (const doc of result.results) {
  428. expect(doc.score).toBeGreaterThanOrEqual(0);
  429. expect(doc.score).toBeLessThanOrEqual(1);
  430. }
  431. });
  432. test("batch reranks multiple documents efficiently", async () => {
  433. // Create 10 documents to verify batch processing works
  434. const documents: RerankDocument[] = Array(10)
  435. .fill(null)
  436. .map((_, i) => ({
  437. file: `doc${i}.md`,
  438. text: `Document number ${i} with some content about topic ${i % 3}`,
  439. }));
  440. const start = Date.now();
  441. const result = await llm.rerank("topic 1", documents);
  442. const elapsed = Date.now() - start;
  443. expect(result.results).toHaveLength(10);
  444. // Verify all documents are returned with valid scores
  445. for (const doc of result.results) {
  446. expect(doc.score).toBeGreaterThanOrEqual(0);
  447. expect(doc.score).toBeLessThanOrEqual(1);
  448. }
  449. // Log timing for monitoring batch performance
  450. console.log(`Batch rerank of 10 docs took ${elapsed}ms`);
  451. });
  452. test("uses fewer active rerank contexts for small batches", async () => {
  453. const freshLlm = new LlamaCpp({});
  454. const calls: number[] = [];
  455. const fakeModel = {
  456. tokenize: (text: string) => Array.from(text),
  457. detokenize: (tokens: string[]) => tokens.join(""),
  458. };
  459. const fakeContexts = Array.from({ length: 4 }, (_, idx) => ({
  460. rankAll: async (_query: string, docs: string[]) => {
  461. calls.push(idx);
  462. return docs.map(() => 0.5);
  463. },
  464. }));
  465. (freshLlm as any).ensureRerankModel = async () => fakeModel;
  466. (freshLlm as any).ensureRerankContexts = async () => fakeContexts;
  467. const documents: RerankDocument[] = Array.from({ length: 20 }, (_, i) => ({
  468. file: `doc${i}.md`,
  469. text: `Document number ${i}`,
  470. }));
  471. const result = await freshLlm.rerank("topic 1", documents);
  472. expect(result.results).toHaveLength(20);
  473. expect(calls).toEqual([0, 1]);
  474. });
  475. test("truncates and reranks document exceeding 2048 token context size", async () => {
  476. // The reranker context is created with contextSize=2048. Documents that
  477. // exceed the token budget (contextSize - template overhead - query tokens)
  478. // should be silently truncated rather than crashing.
  479. const paragraph = "The quick brown fox jumps over the lazy dog near the riverbank. " +
  480. "Authentication tokens must be validated on every request to ensure security. " +
  481. "Database queries should use prepared statements to prevent SQL injection attacks. " +
  482. "The deployment pipeline includes linting, testing, building, and publishing stages. ";
  483. // ~320 chars per paragraph, repeat 40 times = ~12800 chars ≈ 3200 tokens
  484. const longText = paragraph.repeat(40);
  485. const query = "How do I configure authentication?";
  486. const documents: RerankDocument[] = [
  487. { file: "short-relevant.md", text: "Authentication can be configured by setting AUTH_SECRET." },
  488. { file: "long-doc.md", text: longText },
  489. { file: "short-irrelevant.md", text: "The weather is sunny today." },
  490. ];
  491. console.log(`Long doc length: ${longText.length} chars (~${Math.round(longText.length / 4)} tokens)`);
  492. const result = await llm.rerank(query, documents);
  493. // Should return all 3 documents without crashing
  494. expect(result.results).toHaveLength(3);
  495. // All scores should be valid numbers in [0, 1]
  496. for (const doc of result.results) {
  497. expect(doc.score).toBeGreaterThanOrEqual(0);
  498. expect(doc.score).toBeLessThanOrEqual(1);
  499. expect(Number.isNaN(doc.score)).toBe(false);
  500. }
  501. // The short, directly relevant doc should still rank highest
  502. console.log("Rerank results for long doc test:");
  503. for (const doc of result.results) {
  504. console.log(` ${doc.file}: ${doc.score.toFixed(4)}`);
  505. }
  506. });
  507. });
  508. describe("expandQuery", () => {
  509. test("returns query expansions with correct types", async () => {
  510. const result = await llm.expandQuery("test query");
  511. // Result is Queryable[] containing lex, vec, and/or hyde entries
  512. expect(result.length).toBeGreaterThanOrEqual(1);
  513. // Each result should have a valid type
  514. for (const q of result) {
  515. expect(["lex", "vec", "hyde"]).toContain(q.type);
  516. expect(q.text.length).toBeGreaterThan(0);
  517. }
  518. }, 30000); // 30s timeout for model loading
  519. test("can exclude lexical queries", async () => {
  520. const result = await llm.expandQuery("authentication setup", { includeLexical: false });
  521. // Should not contain any 'lex' type entries
  522. const lexEntries = result.filter(q => q.type === "lex");
  523. expect(lexEntries).toHaveLength(0);
  524. });
  525. });
  526. });
  527. // =============================================================================
  528. // Session Management Tests
  529. // =============================================================================
  530. describe.skipIf(!!process.env.CI)("LLM Session Management", () => {
  531. describe("withLLMSession", () => {
  532. test("session provides access to LLM operations", async () => {
  533. const result = await withLLMSession(async (session) => {
  534. expect(session.isValid).toBe(true);
  535. const embedding = await session.embed("test text");
  536. expect(embedding).not.toBeNull();
  537. expect(embedding!.embedding.length).toBe(768);
  538. return "success";
  539. });
  540. expect(result).toBe("success");
  541. });
  542. test("session is invalid after release", async () => {
  543. let capturedSession: ILLMSession | null = null;
  544. await withLLMSession(async (session) => {
  545. capturedSession = session;
  546. expect(session.isValid).toBe(true);
  547. });
  548. // Session should be invalid after withLLMSession returns
  549. expect(capturedSession).not.toBeNull();
  550. expect(capturedSession!.isValid).toBe(false);
  551. });
  552. test("session prevents idle unload during operations", async () => {
  553. await withLLMSession(async (session) => {
  554. // While inside a session, canUnloadLLM should return false
  555. expect(canUnloadLLM()).toBe(false);
  556. // Perform an operation
  557. await session.embed("test");
  558. // Still should not be able to unload
  559. expect(canUnloadLLM()).toBe(false);
  560. });
  561. // After session ends, should be able to unload
  562. expect(canUnloadLLM()).toBe(true);
  563. });
  564. test("nested sessions increment ref count", async () => {
  565. await withLLMSession(async (outerSession) => {
  566. expect(canUnloadLLM()).toBe(false);
  567. await withLLMSession(async (innerSession) => {
  568. expect(canUnloadLLM()).toBe(false);
  569. expect(innerSession.isValid).toBe(true);
  570. expect(outerSession.isValid).toBe(true);
  571. });
  572. // Inner session released, but outer still active
  573. expect(canUnloadLLM()).toBe(false);
  574. expect(outerSession.isValid).toBe(true);
  575. });
  576. // All sessions released
  577. expect(canUnloadLLM()).toBe(true);
  578. });
  579. test("session embedBatch works correctly", async () => {
  580. await withLLMSession(async (session) => {
  581. const texts = ["Hello world", "Test text", "Another document"];
  582. const results = await session.embedBatch(texts);
  583. expect(results).toHaveLength(3);
  584. for (const result of results) {
  585. expect(result).not.toBeNull();
  586. expect(result!.embedding.length).toBe(768);
  587. }
  588. });
  589. });
  590. test("session rerank works correctly", async () => {
  591. await withLLMSession(async (session) => {
  592. const documents: RerankDocument[] = [
  593. { file: "a.txt", text: "The capital of France is Paris." },
  594. { file: "b.txt", text: "Dogs are great pets." },
  595. ];
  596. const result = await session.rerank("What is the capital of France?", documents);
  597. expect(result.results).toHaveLength(2);
  598. expect(result.results[0]!.file).toBe("a.txt");
  599. expect(result.results[0]!.score).toBeGreaterThan(result.results[1]!.score);
  600. });
  601. });
  602. test("max duration aborts session after timeout", async () => {
  603. let aborted = false;
  604. try {
  605. await withLLMSession(async (session) => {
  606. // Wait longer than max duration
  607. await new Promise(resolve => setTimeout(resolve, 150));
  608. // This operation should throw because session was aborted
  609. await session.embed("test");
  610. }, { maxDuration: 50 }); // 50ms max
  611. } catch (err) {
  612. if (err instanceof SessionReleasedError) {
  613. aborted = true;
  614. } else {
  615. throw err;
  616. }
  617. }
  618. expect(aborted).toBe(true);
  619. }, 5000);
  620. test("external abort signal propagates to session", async () => {
  621. const abortController = new AbortController();
  622. let sessionAborted = false;
  623. const promise = withLLMSession(async (session) => {
  624. // Wait a bit then check if aborted
  625. await new Promise(resolve => setTimeout(resolve, 100));
  626. if (!session.isValid) {
  627. sessionAborted = true;
  628. throw new SessionReleasedError("Session aborted");
  629. }
  630. return "should not reach";
  631. }, { signal: abortController.signal });
  632. // Abort after 20ms
  633. setTimeout(() => abortController.abort(), 20);
  634. try {
  635. await promise;
  636. } catch (err) {
  637. // Expected
  638. }
  639. expect(sessionAborted).toBe(true);
  640. }, 5000);
  641. test("session provides abort signal for monitoring", async () => {
  642. await withLLMSession(async (session) => {
  643. expect(session.signal).toBeInstanceOf(AbortSignal);
  644. expect(session.signal.aborted).toBe(false);
  645. });
  646. });
  647. test("returns value from callback", async () => {
  648. const result = await withLLMSession(async (session) => {
  649. await session.embed("test");
  650. return { status: "complete", count: 42 };
  651. });
  652. expect(result).toEqual({ status: "complete", count: 42 });
  653. });
  654. test("propagates errors from callback", async () => {
  655. const customError = new Error("Custom test error");
  656. await expect(
  657. withLLMSession(async () => {
  658. throw customError;
  659. })
  660. ).rejects.toThrow("Custom test error");
  661. });
  662. });
  663. });