llm.test.ts 27 KB

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