llm.test.ts 29 KB

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