llm.test.ts 32 KB

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