llm.test.ts 29 KB

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