parse-pool.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /**
  2. * ParseWorkerPool — the worker pool that parses files across cores during a full
  3. * `codegraph index` (issue #1015). These tests drive the pool's queue / growth /
  4. * recycle / crash-recovery / timeout / teardown logic with INJECTED fake
  5. * workers, so they exercise the real scheduling code without spawning threads or
  6. * needing a built dist.
  7. *
  8. * End-to-end behavior with real worker threads (each worker owns a tree-sitter
  9. * WASM heap and runs extractFromSource) is covered by the extraction suite
  10. * against a real temp project; here we pin the orchestration that makes the
  11. * parallelism safe.
  12. */
  13. import { describe, it, expect } from 'vitest';
  14. import { ParseWorkerPool, resolveParseBudgetMs, resolveParsePoolSize, resolveParseTimeoutMs, type ParsePoolWorker, type ParseTask } from '../src/extraction/parse-pool';
  15. import type { Language, ExtractionResult } from '../src/types';
  16. const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
  17. interface ParseMsg { type: 'parse'; id: number; filePath: string; content: string; language: Language }
  18. type Action = { result: ExtractionResult } | { crash: true } | { hang: true } | { wait: Promise<ExtractionResult> };
  19. /**
  20. * Fake worker speaking the same {load-grammars → grammars-loaded} /
  21. * {parse → parse-result} protocol as the real parse-worker. `behavior` decides
  22. * per parse whether to return a result, crash (exit≠0), hang (never reply —
  23. * exercises the timeout), or wait on a promise (hold a parse in-flight to
  24. * observe concurrency). Emits 'grammars-loaded' on a macrotask so the pool has
  25. * wired its listeners first.
  26. */
  27. class FakeWorker implements ParsePoolWorker {
  28. private msgCb?: (m: unknown) => void;
  29. private exitCb?: (code: number) => void;
  30. alive = true;
  31. constructor(private behavior: (m: ParseMsg) => Action, private onTerminate?: () => void) {}
  32. on(event: string, cb: (...args: any[]) => void): void {
  33. if (event === 'message') this.msgCb = cb;
  34. else if (event === 'exit') this.exitCb = cb;
  35. // 'error' unused by the fakes
  36. }
  37. private reply(id: number, result: ExtractionResult): void {
  38. if (this.alive) this.msgCb?.({ type: 'parse-result', id, result });
  39. }
  40. postMessage(msg: unknown): void {
  41. const m = msg as { type: string } & Partial<ParseMsg>;
  42. if (m.type === 'load-grammars') {
  43. setTimeout(() => { if (this.alive) this.msgCb?.({ type: 'grammars-loaded' }); }, 0);
  44. return;
  45. }
  46. if (m.type !== 'parse') return;
  47. const action = this.behavior(m as ParseMsg);
  48. if ('crash' in action) {
  49. this.alive = false;
  50. setTimeout(() => this.exitCb?.(1), 0); // simulate a WASM-OOM exit(1)
  51. return;
  52. }
  53. if ('hang' in action) return; // never reply → timeout path
  54. if ('wait' in action) { void action.wait.then((r) => this.reply(m.id!, r)); return; }
  55. setTimeout(() => this.reply(m.id!, action.result), 0);
  56. }
  57. terminate(): Promise<number> { this.alive = false; this.onTerminate?.(); return Promise.resolve(0); }
  58. }
  59. const task = (filePath: string, content = 'code'): ParseTask => ({ filePath, content, language: 'typescript' as Language });
  60. const result = (tag = 0): ExtractionResult => ({ nodes: [], edges: [], unresolvedReferences: [], errors: [], durationMs: tag });
  61. /** Build a pool with a counting fake-worker factory. */
  62. function makePool(
  63. size: number,
  64. behavior: (m: ParseMsg) => Action,
  65. opts: Partial<{ recycleInterval: number; parseTimeoutMs: number }> = {}
  66. ) {
  67. let spawned = 0, terminated = 0;
  68. const pool = new ParseWorkerPool({
  69. languages: ['typescript'] as Language[],
  70. size,
  71. recycleInterval: opts.recycleInterval,
  72. parseTimeoutMs: opts.parseTimeoutMs,
  73. createWorker: () => { spawned++; return new FakeWorker(behavior, () => { terminated++; }); },
  74. });
  75. return { pool, counts: () => ({ spawned, terminated }) };
  76. }
  77. describe('resolveParseTimeoutMs', () => {
  78. it('honors a positive numeric override (CODEGRAPH_PARSE_TIMEOUT_MS)', () => {
  79. expect(resolveParseTimeoutMs('30000')).toBe(30000);
  80. expect(resolveParseTimeoutMs('1500.9')).toBe(1500);
  81. });
  82. it('falls back to the 10s default when unset/blank/non-numeric/non-positive', () => {
  83. expect(resolveParseTimeoutMs(undefined)).toBe(10_000);
  84. expect(resolveParseTimeoutMs('')).toBe(10_000);
  85. expect(resolveParseTimeoutMs('abc')).toBe(10_000);
  86. expect(resolveParseTimeoutMs('0')).toBe(10_000);
  87. expect(resolveParseTimeoutMs('-5')).toBe(10_000);
  88. });
  89. });
  90. describe('resolveParseBudgetMs', () => {
  91. it('caps near-limit blob headers at a 20s soft / 60s hard window (#1555)', () => {
  92. expect(resolveParseBudgetMs(10_000, 940_800)).toBe(20_000);
  93. expect(resolveParseBudgetMs(10_000, 857_376)).toBe(20_000);
  94. });
  95. it('does not clamp an explicit larger base timeout', () => {
  96. expect(resolveParseBudgetMs(45_000, 940_800)).toBe(45_000);
  97. });
  98. });
  99. describe('resolveParsePoolSize', () => {
  100. it('treats explicit 0 and 1 as a single worker (the rollback path)', () => {
  101. expect(resolveParsePoolSize('0', 8)).toBe(1);
  102. expect(resolveParsePoolSize('1', 8)).toBe(1);
  103. });
  104. it('honors a numeric override, capped at the hard ceiling', () => {
  105. expect(resolveParsePoolSize('4', 8)).toBe(4);
  106. expect(resolveParsePoolSize('999', 8)).toBe(16);
  107. });
  108. it('defaults to clamp(cores-1, 1, 8) when unset/blank/non-numeric', () => {
  109. expect(resolveParsePoolSize(undefined, 8)).toBe(7);
  110. expect(resolveParsePoolSize('', 8)).toBe(7);
  111. expect(resolveParsePoolSize('abc', 8)).toBe(7);
  112. expect(resolveParsePoolSize(undefined, 1)).toBe(1); // never zero
  113. expect(resolveParsePoolSize(undefined, 2)).toBe(1); // leave a core
  114. expect(resolveParsePoolSize(undefined, 64)).toBe(8); // never above the default cap
  115. });
  116. });
  117. describe('ParseWorkerPool', () => {
  118. it('parses a file and returns the worker result', async () => {
  119. const { pool } = makePool(1, () => ({ result: result(42) }));
  120. const res = await pool.requestParse(task('a.ts'));
  121. expect(res.durationMs).toBe(42);
  122. await pool.destroy();
  123. });
  124. it('runs N parses in parallel across the pool (not serialized)', async () => {
  125. let active = 0, maxActive = 0;
  126. let release!: () => void;
  127. const gate = new Promise<void>((r) => { release = r; });
  128. const { pool } = makePool(4, () => ({
  129. wait: (async () => { active++; maxActive = Math.max(maxActive, active); await gate; active--; return result(); })(),
  130. }));
  131. const ps = [0, 1, 2, 3].map((i) => pool.requestParse(task(`f${i}.ts`)));
  132. await sleep(60); // let the pool grow to size and dispatch all four
  133. expect(maxActive).toBe(4);
  134. release();
  135. await Promise.all(ps);
  136. await pool.destroy();
  137. });
  138. it('grows lazily — a single parse does not spawn the whole pool', async () => {
  139. const { pool, counts } = makePool(8, () => ({ result: result() }));
  140. await pool.requestParse(task('only.ts'));
  141. expect(counts().spawned).toBe(1); // just the eager warm worker
  142. await pool.destroy();
  143. });
  144. it('recycles a worker after recycleInterval parses', async () => {
  145. const { pool, counts } = makePool(1, () => ({ result: result() }), { recycleInterval: 3 });
  146. for (let i = 0; i < 4; i++) await pool.requestParse(task(`f${i}.ts`));
  147. // 3 parses on the first worker → recycle (terminate + respawn); the 4th runs
  148. // on the fresh worker.
  149. expect(counts().spawned).toBe(2);
  150. expect(counts().terminated).toBeGreaterThanOrEqual(1);
  151. await pool.destroy();
  152. });
  153. it('rejects a parse whose worker crashes (retry-pass-recognisable message) and keeps serving', async () => {
  154. const { pool, counts } = makePool(1, (m) => (m.filePath === 'poison.ts' ? { crash: true } : { result: result(7) }));
  155. // The message must contain "Worker exited" so the orchestrator's retry pass
  156. // re-attempts it (that's the filter it uses).
  157. await expect(pool.requestParse(task('poison.ts'))).rejects.toThrow(/Worker exited/);
  158. const ok = await pool.requestParse(task('good.ts'));
  159. expect(ok.durationMs).toBe(7);
  160. expect(counts().spawned).toBe(2); // respawned after the crash
  161. await pool.destroy();
  162. });
  163. it('times out a hung parse (at the hard-kill backstop) and stays usable', async () => {
  164. const { pool } = makePool(1, (m) => (m.filePath === 'hang.ts' ? { hang: true } : { result: result(9) }), { parseTimeoutMs: 30 });
  165. const t0 = Date.now();
  166. // The base timer (30ms) only marks the job late; the kill happens at the
  167. // 3× backstop (90ms), and the message carries the full window.
  168. await expect(pool.requestParse(task('hang.ts'))).rejects.toThrow(/timed out after 90ms/i);
  169. expect(Date.now() - t0).toBeGreaterThanOrEqual(80);
  170. const ok = await pool.requestParse(task('ok.ts'));
  171. expect(ok.durationMs).toBe(9);
  172. await pool.destroy();
  173. });
  174. it('accepts a result that arrives after the base timeout instead of killing the worker (#1231 false-timeout fix)', async () => {
  175. // Simulates the HDD stall: the parse "finished" but its result is only
  176. // delivered after the base timer fired. Old behaviour killed the worker and
  177. // rejected; now the late result is accepted and the worker keeps serving.
  178. const { pool, counts } = makePool(
  179. 1,
  180. (m) => (m.filePath === 'late.ts' ? { wait: sleep(80).then(() => result(11)) } : { result: result(9) }),
  181. { parseTimeoutMs: 50 }
  182. );
  183. const res = await pool.requestParse(task('late.ts')); // base timer 50ms < delivery 80ms < backstop 150ms
  184. expect(res.durationMs).toBe(11);
  185. expect(counts().terminated).toBe(0); // no kill…
  186. expect(counts().spawned).toBe(1); // …and no respawn churn
  187. const ok = await pool.requestParse(task('next.ts'));
  188. expect(ok.durationMs).toBe(9); // same worker still serving
  189. await pool.destroy();
  190. });
  191. it('forwards pre-read grammar WASM bytes to every spawned worker (#1231 respawn I/O fix)', async () => {
  192. const grammarBuffers = { typescript: new Uint8Array([1, 2, 3]) };
  193. const loadMsgs: Array<{ grammarBuffers?: Record<string, Uint8Array> }> = [];
  194. let worker!: FakeWorker;
  195. const pool = new ParseWorkerPool({
  196. languages: ['typescript'] as Language[],
  197. size: 1,
  198. grammarBuffers,
  199. createWorker: () => {
  200. worker = new FakeWorker(() => ({ result: result() }));
  201. const orig = worker.postMessage.bind(worker);
  202. worker.postMessage = (msg: unknown) => {
  203. const m = msg as { type: string; grammarBuffers?: Record<string, Uint8Array> };
  204. if (m.type === 'load-grammars') loadMsgs.push(m);
  205. orig(msg);
  206. };
  207. return worker;
  208. },
  209. });
  210. await pool.requestParse(task('a.ts'));
  211. expect(loadMsgs).toHaveLength(1);
  212. expect(loadMsgs[0].grammarBuffers).toBe(grammarBuffers);
  213. await pool.destroy();
  214. });
  215. it('serves a queue larger than the pool size', async () => {
  216. const { pool } = makePool(2, (m) => ({ result: result(Number(m.filePath.replace(/\D/g, ''))) }));
  217. const ps = Array.from({ length: 10 }, (_, i) => pool.requestParse(task(`${i}.ts`)));
  218. const res = await Promise.all(ps);
  219. expect(res.map((r) => r.durationMs).sort((a, b) => a - b)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  220. await pool.destroy();
  221. });
  222. it('destroy() rejects in-flight and subsequent parses', async () => {
  223. const { pool } = makePool(1, () => ({ hang: true }));
  224. const p = pool.requestParse(task('x.ts'));
  225. p.catch(() => {}); // avoid an unhandled rejection before we assert
  226. await sleep(10);
  227. await pool.destroy();
  228. await expect(p).rejects.toThrow(/destroyed/);
  229. await expect(pool.requestParse(task('y.ts'))).rejects.toThrow(/destroyed/);
  230. });
  231. });