llm.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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. describe("LlamaCpp.getDeviceInfo", () => {
  202. test("can skip build attempts for status probes", async () => {
  203. const llm = new LlamaCpp({}) as any;
  204. const fakeLlama = {
  205. gpu: "metal",
  206. supportsGpuOffloading: true,
  207. cpuMathCores: 8,
  208. getGpuDeviceNames: vi.fn().mockResolvedValue(["Apple GPU"]),
  209. getVramState: vi.fn().mockResolvedValue({ total: 1024, used: 256, free: 768 }),
  210. };
  211. llm.ensureLlama = vi.fn().mockResolvedValue(fakeLlama);
  212. const device = await llm.getDeviceInfo({ allowBuild: false });
  213. expect(llm.ensureLlama).toHaveBeenCalledWith(false);
  214. expect(device).toEqual({
  215. gpu: "metal",
  216. gpuOffloading: true,
  217. gpuDevices: ["Apple GPU"],
  218. vram: { total: 1024, used: 256, free: 768 },
  219. cpuCores: 8,
  220. });
  221. });
  222. });
  223. // =============================================================================
  224. // Integration Tests (require actual models)
  225. // =============================================================================
  226. describe.skipIf(!!process.env.CI)("LlamaCpp Integration", () => {
  227. // Use the singleton to avoid multiple Metal contexts
  228. const llm = getDefaultLlamaCpp();
  229. afterAll(async () => {
  230. // Ensure native resources are released to avoid ggml-metal asserts on process exit.
  231. await disposeDefaultLlamaCpp();
  232. });
  233. describe("embed", () => {
  234. test("returns embedding with correct dimensions", async () => {
  235. const result = await llm.embed("Hello world");
  236. expect(result).not.toBeNull();
  237. expect(result!.embedding).toBeInstanceOf(Array);
  238. expect(result!.embedding.length).toBeGreaterThan(0);
  239. // embeddinggemma outputs 768 dimensions
  240. expect(result!.embedding.length).toBe(768);
  241. });
  242. test("returns consistent embeddings for same input", async () => {
  243. const result1 = await llm.embed("test text");
  244. const result2 = await llm.embed("test text");
  245. expect(result1).not.toBeNull();
  246. expect(result2).not.toBeNull();
  247. // Embeddings should be identical for the same input
  248. for (let i = 0; i < result1!.embedding.length; i++) {
  249. expect(result1!.embedding[i]).toBeCloseTo(result2!.embedding[i]!, 5);
  250. }
  251. });
  252. test("returns different embeddings for different inputs", async () => {
  253. const result1 = await llm.embed("cats are great");
  254. const result2 = await llm.embed("database optimization");
  255. expect(result1).not.toBeNull();
  256. expect(result2).not.toBeNull();
  257. // Calculate cosine similarity - should be less than 1.0 (not identical)
  258. let dotProduct = 0;
  259. let norm1 = 0;
  260. let norm2 = 0;
  261. for (let i = 0; i < result1!.embedding.length; i++) {
  262. const v1 = result1!.embedding[i]!;
  263. const v2 = result2!.embedding[i]!;
  264. dotProduct += v1 * v2;
  265. norm1 += v1 ** 2;
  266. norm2 += v2 ** 2;
  267. }
  268. const similarity = dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
  269. expect(similarity).toBeLessThan(0.95); // Should be meaningfully different
  270. });
  271. });
  272. describe("embedBatch", () => {
  273. test("returns embeddings for multiple texts", async () => {
  274. const texts = ["Hello world", "Test text", "Another document"];
  275. const results = await llm.embedBatch(texts);
  276. expect(results).toHaveLength(3);
  277. for (const result of results) {
  278. expect(result).not.toBeNull();
  279. expect(result!.embedding.length).toBe(768);
  280. }
  281. });
  282. test("returns same results as individual embed calls", async () => {
  283. const texts = ["cats are great", "dogs are awesome"];
  284. // Get batch embeddings
  285. const batchResults = await llm.embedBatch(texts);
  286. // Get individual embeddings
  287. const individualResults = await Promise.all(texts.map(t => llm.embed(t)));
  288. // Compare - should be identical
  289. for (let i = 0; i < texts.length; i++) {
  290. expect(batchResults[i]).not.toBeNull();
  291. expect(individualResults[i]).not.toBeNull();
  292. for (let j = 0; j < batchResults[i]!.embedding.length; j++) {
  293. expect(batchResults[i]!.embedding[j]).toBeCloseTo(individualResults[i]!.embedding[j]!, 5);
  294. }
  295. }
  296. });
  297. test("handles empty array", async () => {
  298. const results = await llm.embedBatch([]);
  299. expect(results).toHaveLength(0);
  300. });
  301. test("batch is faster than sequential", async () => {
  302. const texts = Array(10).fill(null).map((_, i) => `Document number ${i} with content`);
  303. // Time batch
  304. const batchStart = Date.now();
  305. await llm.embedBatch(texts);
  306. const batchTime = Date.now() - batchStart;
  307. // Time sequential
  308. const seqStart = Date.now();
  309. for (const text of texts) {
  310. await llm.embed(text);
  311. }
  312. const seqTime = Date.now() - seqStart;
  313. console.log(`Batch: ${batchTime}ms, Sequential: ${seqTime}ms`);
  314. // Performance is machine/load dependent. We only assert batch isn't drastically worse.
  315. expect(batchTime).toBeLessThanOrEqual(seqTime * 3);
  316. });
  317. test("handles concurrent embedBatch calls on fresh instance without race condition", async () => {
  318. // This test verifies the fix for a race condition where concurrent calls to
  319. // ensureEmbedContext() could create multiple contexts. Without the promise guard,
  320. // each concurrent embedBatch call sees embedContext === null and creates its own
  321. // context, causing resource leaks and potential "Context is disposed" errors.
  322. //
  323. // See: https://github.com/tobi/qmd/pull/54
  324. //
  325. // The fix uses a promise guard to ensure only one context creation runs at a time.
  326. // We verify this by instrumenting createEmbeddingContext to count invocations.
  327. const freshLlm = new LlamaCpp({});
  328. let contextCreateCount = 0;
  329. // Instrument the model's createEmbeddingContext to count calls
  330. const originalEnsureEmbedModel = (freshLlm as any).ensureEmbedModel.bind(freshLlm);
  331. let modelInstrumented = false;
  332. (freshLlm as any).ensureEmbedModel = async function() {
  333. const model = await originalEnsureEmbedModel();
  334. if (!modelInstrumented) {
  335. modelInstrumented = true;
  336. const originalCreate = model.createEmbeddingContext.bind(model);
  337. model.createEmbeddingContext = async function(...args: any[]) {
  338. contextCreateCount++;
  339. return originalCreate(...args);
  340. };
  341. }
  342. return model;
  343. };
  344. const texts = Array(10).fill(null).map((_, i) => `Document ${i}`);
  345. // Call embedBatch 5 TIMES in parallel on fresh instance.
  346. // Without the promise guard fix, this would create 5 contexts (one per call).
  347. // With the fix, only 1 context should be created.
  348. const batches = await Promise.all([
  349. freshLlm.embedBatch(texts.slice(0, 2)),
  350. freshLlm.embedBatch(texts.slice(2, 4)),
  351. freshLlm.embedBatch(texts.slice(4, 6)),
  352. freshLlm.embedBatch(texts.slice(6, 8)),
  353. freshLlm.embedBatch(texts.slice(8, 10)),
  354. ]);
  355. const allResults = batches.flat();
  356. expect(allResults).toHaveLength(10);
  357. const successCount = allResults.filter(r => r !== null).length;
  358. expect(successCount).toBe(10);
  359. // THE KEY ASSERTION: Contexts should be created once (by ensureEmbedContexts),
  360. // not duplicated per concurrent embedBatch call. The exact count depends on
  361. // available VRAM (computeParallelism), but should not be 5 (one per call).
  362. // Without the fix, contextCreateCount would be 5× the intended count (one set per concurrent call).
  363. // With the promise guard, contexts are created exactly once regardless of concurrent callers.
  364. // The count depends on VRAM (computeParallelism), but should be ≤ 8 (the cap).
  365. console.log(`Context creation count: ${contextCreateCount} (expected: ≤ 8, not 5× duplicated)`);
  366. expect(contextCreateCount).toBeGreaterThanOrEqual(1);
  367. expect(contextCreateCount).toBeLessThanOrEqual(8);
  368. await freshLlm.dispose();
  369. }, 60000);
  370. });
  371. describe("rerank", () => {
  372. test("scores capital of France question correctly", async () => {
  373. const query = "What is the capital of France?";
  374. const documents: RerankDocument[] = [
  375. { file: "butterflies.txt", text: "Butterflies indeed fly through the garden." },
  376. { file: "france.txt", text: "The capital of France is Paris." },
  377. { file: "canada.txt", text: "The capital of Canada is Ottawa." },
  378. ];
  379. const result = await llm.rerank(query, documents);
  380. expect(result.results).toHaveLength(3);
  381. // The France document should score highest
  382. expect(result.results[0]!.file).toBe("france.txt");
  383. expect(result.results[0]!.score).toBeGreaterThan(0.7);
  384. // Canada should be somewhat relevant (also about capitals)
  385. expect(result.results[1]!.file).toBe("canada.txt");
  386. // Butterflies should score lowest
  387. expect(result.results[2]!.file).toBe("butterflies.txt");
  388. expect(result.results[2]!.score).toBeLessThan(0.6);
  389. });
  390. test("scores authentication query correctly", async () => {
  391. const query = "How do I configure authentication?";
  392. const documents: RerankDocument[] = [
  393. { file: "weather.md", text: "The weather today is sunny with mild temperatures." },
  394. { file: "auth.md", text: "Authentication can be configured by setting the AUTH_SECRET environment variable." },
  395. { file: "pizza.md", text: "Our restaurant serves the best pizza in town." },
  396. { file: "jwt.md", text: "JWT authentication requires a secret key and expiration time." },
  397. ];
  398. const result = await llm.rerank(query, documents);
  399. expect(result.results).toHaveLength(4);
  400. // Auth documents should score highest
  401. const topTwo = result.results.slice(0, 2).map((r) => r.file);
  402. expect(topTwo).toContain("auth.md");
  403. expect(topTwo).toContain("jwt.md");
  404. // Irrelevant documents should score lowest
  405. const bottomTwo = result.results.slice(2).map((r) => r.file);
  406. expect(bottomTwo).toContain("weather.md");
  407. expect(bottomTwo).toContain("pizza.md");
  408. });
  409. test("handles programming queries correctly", async () => {
  410. const query = "How do I handle errors in JavaScript?";
  411. const documents: RerankDocument[] = [
  412. { file: "cooking.md", text: "To make a good pasta, boil water and add salt." },
  413. { file: "errors.md", text: "Use try-catch blocks to handle JavaScript errors gracefully." },
  414. { file: "python.md", text: "Python uses try-except for exception handling." },
  415. ];
  416. const result = await llm.rerank(query, documents);
  417. // JavaScript errors doc should score highest
  418. expect(result.results[0]!.file).toBe("errors.md");
  419. expect(result.results[0]!.score).toBeGreaterThan(0.7);
  420. // Python doc might be somewhat relevant (same concept, different language)
  421. // Cooking should be least relevant
  422. expect(result.results[2]!.file).toBe("cooking.md");
  423. });
  424. test("handles empty document list", async () => {
  425. const result = await llm.rerank("test query", []);
  426. expect(result.results).toHaveLength(0);
  427. });
  428. test("handles single document", async () => {
  429. const result = await llm.rerank("test", [{ file: "doc.md", text: "content" }]);
  430. expect(result.results).toHaveLength(1);
  431. expect(result.results[0]!.file).toBe("doc.md");
  432. });
  433. test("preserves original file paths", async () => {
  434. const documents: RerankDocument[] = [
  435. { file: "path/to/doc1.md", text: "content one" },
  436. { file: "another/path/doc2.md", text: "content two" },
  437. ];
  438. const result = await llm.rerank("query", documents);
  439. const files = result.results.map((r) => r.file).sort();
  440. expect(files).toEqual(["another/path/doc2.md", "path/to/doc1.md"]);
  441. });
  442. test("returns scores between 0 and 1", async () => {
  443. const documents: RerankDocument[] = [
  444. { file: "a.md", text: "The quick brown fox jumps over the lazy dog." },
  445. { file: "b.md", text: "Machine learning algorithms process data efficiently." },
  446. { file: "c.md", text: "React components use JSX syntax for rendering." },
  447. ];
  448. const result = await llm.rerank("Tell me about animals", documents);
  449. for (const doc of result.results) {
  450. expect(doc.score).toBeGreaterThanOrEqual(0);
  451. expect(doc.score).toBeLessThanOrEqual(1);
  452. }
  453. });
  454. test("batch reranks multiple documents efficiently", async () => {
  455. // Create 10 documents to verify batch processing works
  456. const documents: RerankDocument[] = Array(10)
  457. .fill(null)
  458. .map((_, i) => ({
  459. file: `doc${i}.md`,
  460. text: `Document number ${i} with some content about topic ${i % 3}`,
  461. }));
  462. const start = Date.now();
  463. const result = await llm.rerank("topic 1", documents);
  464. const elapsed = Date.now() - start;
  465. expect(result.results).toHaveLength(10);
  466. // Verify all documents are returned with valid scores
  467. for (const doc of result.results) {
  468. expect(doc.score).toBeGreaterThanOrEqual(0);
  469. expect(doc.score).toBeLessThanOrEqual(1);
  470. }
  471. // Log timing for monitoring batch performance
  472. console.log(`Batch rerank of 10 docs took ${elapsed}ms`);
  473. });
  474. test("uses fewer active rerank contexts for small batches", async () => {
  475. const freshLlm = new LlamaCpp({});
  476. const calls: number[] = [];
  477. const fakeModel = {
  478. tokenize: (text: string) => Array.from(text),
  479. detokenize: (tokens: string[]) => tokens.join(""),
  480. };
  481. const fakeContexts = Array.from({ length: 4 }, (_, idx) => ({
  482. rankAll: async (_query: string, docs: string[]) => {
  483. calls.push(idx);
  484. return docs.map(() => 0.5);
  485. },
  486. }));
  487. (freshLlm as any).ensureRerankModel = async () => fakeModel;
  488. (freshLlm as any).ensureRerankContexts = async () => fakeContexts;
  489. const documents: RerankDocument[] = Array.from({ length: 20 }, (_, i) => ({
  490. file: `doc${i}.md`,
  491. text: `Document number ${i}`,
  492. }));
  493. const result = await freshLlm.rerank("topic 1", documents);
  494. expect(result.results).toHaveLength(20);
  495. expect(calls).toEqual([0, 1]);
  496. });
  497. test("truncates and reranks document exceeding 2048 token context size", async () => {
  498. // The reranker context is created with contextSize=2048. Documents that
  499. // exceed the token budget (contextSize - template overhead - query tokens)
  500. // should be silently truncated rather than crashing.
  501. const paragraph = "The quick brown fox jumps over the lazy dog near the riverbank. " +
  502. "Authentication tokens must be validated on every request to ensure security. " +
  503. "Database queries should use prepared statements to prevent SQL injection attacks. " +
  504. "The deployment pipeline includes linting, testing, building, and publishing stages. ";
  505. // ~320 chars per paragraph, repeat 40 times = ~12800 chars ≈ 3200 tokens
  506. const longText = paragraph.repeat(40);
  507. const query = "How do I configure authentication?";
  508. const documents: RerankDocument[] = [
  509. { file: "short-relevant.md", text: "Authentication can be configured by setting AUTH_SECRET." },
  510. { file: "long-doc.md", text: longText },
  511. { file: "short-irrelevant.md", text: "The weather is sunny today." },
  512. ];
  513. console.log(`Long doc length: ${longText.length} chars (~${Math.round(longText.length / 4)} tokens)`);
  514. const result = await llm.rerank(query, documents);
  515. // Should return all 3 documents without crashing
  516. expect(result.results).toHaveLength(3);
  517. // All scores should be valid numbers in [0, 1]
  518. for (const doc of result.results) {
  519. expect(doc.score).toBeGreaterThanOrEqual(0);
  520. expect(doc.score).toBeLessThanOrEqual(1);
  521. expect(Number.isNaN(doc.score)).toBe(false);
  522. }
  523. // The short, directly relevant doc should still rank highest
  524. console.log("Rerank results for long doc test:");
  525. for (const doc of result.results) {
  526. console.log(` ${doc.file}: ${doc.score.toFixed(4)}`);
  527. }
  528. });
  529. });
  530. describe("expandQuery", () => {
  531. test("returns query expansions with correct types", async () => {
  532. const result = await llm.expandQuery("test query");
  533. // Result is Queryable[] containing lex, vec, and/or hyde entries
  534. expect(result.length).toBeGreaterThanOrEqual(1);
  535. // Each result should have a valid type
  536. for (const q of result) {
  537. expect(["lex", "vec", "hyde"]).toContain(q.type);
  538. expect(q.text.length).toBeGreaterThan(0);
  539. }
  540. }, 30000); // 30s timeout for model loading
  541. test("can exclude lexical queries", async () => {
  542. const result = await llm.expandQuery("authentication setup", { includeLexical: false });
  543. // Should not contain any 'lex' type entries
  544. const lexEntries = result.filter(q => q.type === "lex");
  545. expect(lexEntries).toHaveLength(0);
  546. });
  547. });
  548. });
  549. // =============================================================================
  550. // Session Management Tests
  551. // =============================================================================
  552. describe.skipIf(!!process.env.CI)("LLM Session Management", () => {
  553. describe("withLLMSession", () => {
  554. test("session provides access to LLM operations", async () => {
  555. const result = await withLLMSession(async (session) => {
  556. expect(session.isValid).toBe(true);
  557. const embedding = await session.embed("test text");
  558. expect(embedding).not.toBeNull();
  559. expect(embedding!.embedding.length).toBe(768);
  560. return "success";
  561. });
  562. expect(result).toBe("success");
  563. });
  564. test("session is invalid after release", async () => {
  565. let capturedSession: ILLMSession | null = null;
  566. await withLLMSession(async (session) => {
  567. capturedSession = session;
  568. expect(session.isValid).toBe(true);
  569. });
  570. // Session should be invalid after withLLMSession returns
  571. expect(capturedSession).not.toBeNull();
  572. expect(capturedSession!.isValid).toBe(false);
  573. });
  574. test("session prevents idle unload during operations", async () => {
  575. await withLLMSession(async (session) => {
  576. // While inside a session, canUnloadLLM should return false
  577. expect(canUnloadLLM()).toBe(false);
  578. // Perform an operation
  579. await session.embed("test");
  580. // Still should not be able to unload
  581. expect(canUnloadLLM()).toBe(false);
  582. });
  583. // After session ends, should be able to unload
  584. expect(canUnloadLLM()).toBe(true);
  585. });
  586. test("nested sessions increment ref count", async () => {
  587. await withLLMSession(async (outerSession) => {
  588. expect(canUnloadLLM()).toBe(false);
  589. await withLLMSession(async (innerSession) => {
  590. expect(canUnloadLLM()).toBe(false);
  591. expect(innerSession.isValid).toBe(true);
  592. expect(outerSession.isValid).toBe(true);
  593. });
  594. // Inner session released, but outer still active
  595. expect(canUnloadLLM()).toBe(false);
  596. expect(outerSession.isValid).toBe(true);
  597. });
  598. // All sessions released
  599. expect(canUnloadLLM()).toBe(true);
  600. });
  601. test("session embedBatch works correctly", async () => {
  602. await withLLMSession(async (session) => {
  603. const texts = ["Hello world", "Test text", "Another document"];
  604. const results = await session.embedBatch(texts);
  605. expect(results).toHaveLength(3);
  606. for (const result of results) {
  607. expect(result).not.toBeNull();
  608. expect(result!.embedding.length).toBe(768);
  609. }
  610. });
  611. });
  612. test("session rerank works correctly", async () => {
  613. await withLLMSession(async (session) => {
  614. const documents: RerankDocument[] = [
  615. { file: "a.txt", text: "The capital of France is Paris." },
  616. { file: "b.txt", text: "Dogs are great pets." },
  617. ];
  618. const result = await session.rerank("What is the capital of France?", documents);
  619. expect(result.results).toHaveLength(2);
  620. expect(result.results[0]!.file).toBe("a.txt");
  621. expect(result.results[0]!.score).toBeGreaterThan(result.results[1]!.score);
  622. });
  623. });
  624. test("max duration aborts session after timeout", async () => {
  625. let aborted = false;
  626. try {
  627. await withLLMSession(async (session) => {
  628. // Wait longer than max duration
  629. await new Promise(resolve => setTimeout(resolve, 150));
  630. // This operation should throw because session was aborted
  631. await session.embed("test");
  632. }, { maxDuration: 50 }); // 50ms max
  633. } catch (err) {
  634. if (err instanceof SessionReleasedError) {
  635. aborted = true;
  636. } else {
  637. throw err;
  638. }
  639. }
  640. expect(aborted).toBe(true);
  641. }, 5000);
  642. test("external abort signal propagates to session", async () => {
  643. const abortController = new AbortController();
  644. let sessionAborted = false;
  645. const promise = withLLMSession(async (session) => {
  646. // Wait a bit then check if aborted
  647. await new Promise(resolve => setTimeout(resolve, 100));
  648. if (!session.isValid) {
  649. sessionAborted = true;
  650. throw new SessionReleasedError("Session aborted");
  651. }
  652. return "should not reach";
  653. }, { signal: abortController.signal });
  654. // Abort after 20ms
  655. setTimeout(() => abortController.abort(), 20);
  656. try {
  657. await promise;
  658. } catch (err) {
  659. // Expected
  660. }
  661. expect(sessionAborted).toBe(true);
  662. }, 5000);
  663. test("session provides abort signal for monitoring", async () => {
  664. await withLLMSession(async (session) => {
  665. expect(session.signal).toBeInstanceOf(AbortSignal);
  666. expect(session.signal.aborted).toBe(false);
  667. });
  668. });
  669. test("returns value from callback", async () => {
  670. const result = await withLLMSession(async (session) => {
  671. await session.embed("test");
  672. return { status: "complete", count: 42 };
  673. });
  674. expect(result).toEqual({ status: "complete", count: 42 });
  675. });
  676. test("propagates errors from callback", async () => {
  677. const customError = new Error("Custom test error");
  678. await expect(
  679. withLLMSession(async () => {
  680. throw customError;
  681. })
  682. ).rejects.toThrow("Custom test error");
  683. });
  684. });
  685. });