llm.test.ts 25 KB

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