mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-09 22:33:39 +00:00
* docs(parse): record why dispatchGroups is a required interface member Review finding #10 argued dispatchGroups should be optional to match `getQuarantinedPaths?` / `getStats?`. Those are compatibility accommodation for WorkerPool shapes that predate them, not a convention for new members; optional here would force a `?.` plus an unreachable fallback at the single production call site. Documenting the decision so the next reader does not re-litigate it from the neighbouring optional markers. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> (cherry picked from commit addaab647377f3c4553f752fa3ca1388bcb9ca81) * refactor(parse): simplify round accounting and dispatch setup Simplification pass over the dispatch-rounds change. Behavior preserved: identical graph on a full analyze (51,286 nodes / 163,092 edges). - Drop `roundMissBytes`. `roundBufferedBytes` counts the same bytes plus the cache hits, so it is always the greater of the two and the first disjunct of the close condition could never fire on its own. One counter, one reset, one check. - Measure round bytes with `Buffer.byteLength(content, 'utf8')` instead of `String.length`. UTF-16 code units undercount non-ASCII source by up to 3x, so the cap meant to bound main-thread retention was letting a CJK-heavy repo hold well past its nominal budget. Matches `estimateItemBytes` in the pool. - Reset the durable ParsedFile directories for a round's chunks concurrently. Each targets its own chunk-hash directory, and running them serially put N round trips of fs work on the critical path the round exists to shorten. The try/catch stays inside the mapped callback, so one failure still degrades that chunk alone. - Skip the quarantine filter entirely when nothing is quarantined, which is every run without a worker death. It was an identity copy of every group. - `dispatchChunkParseRound` takes `DispatchGroup<...>` rather than re-declaring that shape inline; the type was already imported and used in its body. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> (cherry picked from commit 527d5b6e0ca8ae7bbc6a414c5ac7e27fd85e9995) * refactor(parse): count round misses with the same idiom startRound uses `drainRound` hand-rolled a reduce to count 'miss' entries while `startRound`, one function above, filters the same predicate over the same union. Same integer, one idiom. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> (cherry picked from commit 7eaa193b0cb5fa515844f36ae1401d6fb2fed7b8) * fix(parse): honor GITNEXUS_WORKER_POOL_SIZE above the auto sizing cap The auto pool size is bounded by source bytes so a tiny repo does not spawn a full idle pool. That bound was also clamping the operator's env override, because the env value is read inside `resolveAutoPoolSize()` and the result went through `Math.min(..., workProportionalCap)`. `DEFAULT_POOL_SIZE_CAP`'s own comment offers `GITNEXUS_WORKER_POOL_SIZE` and `--workers <N>` as equivalent escape hatches for operators on bigger machines. They were not. Measured on a 30MB corpus, where the byte-derived cap is 16: --workers 24 -> pool: 24/24 active GITNEXUS_WORKER_POOL_SIZE=24 -> pool: 16/16 active (silently ignored) Both are deliberate operator input, so both now bypass the work-proportional cap, which goes back to bounding only the auto default. After the fix, on the same corpus, with identical graph output (51,286 nodes / 163,092 edges): GITNEXUS_WORKER_POOL_SIZE=24 -> pool: 24/24 active GITNEXUS_WORKER_POOL_SIZE=4 -> pool: 4/4 active unset -> pool: 16/16 active Verified by hand against the pool's own throughput log; not covered by an automated regression test, since the pool size is only observable through that log line and not through the progress stream a test can read. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> (cherry picked from commit 17ed08608c878079b2927da25cfd39c1608a02a2) * fix(parse): bound the durable-reset fan-out and pin the pool-size override Review follow-ups on #3200. The round's durable ParsedFile directory resets went out as one unbounded `Promise.all` — one recursive rm + mkdir per miss chunk, all at once. A round can hold hundreds of small packs, and those resets compete for descriptors with the chunk prefetch this loop already has in flight. `readFileContents` degrades a losing read SILENTLY by documented contract, so a dropped file would vanish from the chunk, from the graph, and from the chunk hash — shipping a narrowed index with exit 0. Now routed through `mapConcurrent` at the same width the file reads use, which keeps the pipelining win and caps in-flight descriptors. An operator's pool size is now also bounded by the number of files there are to parse, so `GITNEXUS_WORKER_POOL_SIZE=100000` on a five-file repo cannot become the literal thread count. This applies to `--workers` and the env var alike, so the parity the previous commit established is intact. It does NOT shrink an incremental re-analyze: `totalParseable` counts every parseable file in the scan, not the changed ones. Adds the regression test a reviewer asked for. The existing coverage (`worker-pool-resilience` calling `resolveAutoPoolSize` directly, `analyze-worker-pool-size` mocking `runFullAnalysis`) never reaches `runChunkedParseAndResolve`'s `effectivePoolSize`, so both stayed green through a revert of the fix. The new test drives the real parse phase with a worker double that writes a per-`threadId` marker, and counts them: verified it fails on the reverted line with `expected [ 'worker-1' ] to have a length of 3 but got 1`, and passes on HEAD. Also corrects the `GITNEXUS_PARSE_ROUND_BYTES` docstring, which still described the cache-miss counter deleted two commits ago. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(parse): skip caching a chunk with a stale durable generation; warn on over-subscription Closes the two findings left open by the review of #3200. When `prepareDurableParsedFileChunk` fails, the previous generation's shards are still on disk, so a later warm hit would union them with the new ones. The chunk is now recorded and its parse-cache write skipped -- the same posture `finalizeWorkerChunk` already takes for a quarantined chunk, and for the same reason: do not cache what we cannot vouch for. The next run re-dispatches into a directory it can actually clear. Bounding the reset fan-out removed the correlated trigger; this closes the individual case. Pool size over-subscription now warns rather than caps. Silently capping is precisely what the override exists to prevent, so an operator's number is still honored -- but an exported GITNEXUS_WORKER_POOL_SIZE applies to every analyze in a long-lived caller (watch auto-sync, the MCP server), including small incremental ones, and that is easy to set once and forget. The warning names the host's usable core count, so it is a hardware fact rather than an invented threshold. `resolveHostParallelism` is extracted from `resolveAutoPoolSize` rather than re-deriving the cgroup-aware fallback at the new call site. Tests: the stale-generation skip is pinned by a new case asserting nothing is written under any key; verified it fails without the guard with `expected 1 to be +0`. 60 unit and 49 integration tests pass across the affected suites. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(parse): guard dispatch-round cadence with a bench, not a wall-clock budget Round boundaries are deliberately invisible to graph output — batching that changed output would be a bug — so nothing in the repo could see the #3196 win regress. It would have come back as a silent ~1.5x on every cold analyze. Two earlier attempts to pin it as a unit test failed for that exact reason: one scraped a logger line the progress stream does not carry, the other asserted graph content that is identical either way. Extracts the round-close fold into `createRoundBudget`, so the decision is a shared unit the bench measures rather than a copy that drifts. The parse loop is streaming and cannot know chunk sizes up front, so an accumulator is the honest shape — not a planner. Four deterministic arms, one ratio, no millisecond gate: - layout_fingerprint — pack membership. Every cache key derives from it, so drift needs a SCHEMA_BUMP, never a lone re-baseline. - packs / single_file_packs — the FLOOR. `rounds` only asserts something while the corpus over-splits (774 packs where the byte budget needs 5). This is bench/import-target's lesson, where four heap arms read 0 B and passed every ceiling: a ceiling says "not too big", nothing said "still measuring". - rounds — the regression signal, both directions. - cjk_rounds vs ascii_rounds — pins UTF-8 byte accounting. The two corpora share a UTF-16 length and differ only in encoded size, so String.length collapses them to equal. This is the arm no unit test could be. - pack_scaling_ratio — (t_4n/t_n)/4, min-of-15. A ratio because wall-clock is runner-speed-dependent and this repo has the scar: callable-value-flow's ms gate failed twice at 2.07 and 1.975 against 1.9 with correct code, on a sub-11ms measurement. Every arm verified to fail before being recorded: close-every-chunk reads 774 rounds, disabling the close reads 1, reverting roundFileBytes to String.length takes cjk_rounds 8 -> 3, and shrinking the corpus trips the shape floor. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * docs(bench): record the analyze phase breakdown and the rejected optimizations Where analyze time actually goes, measured while landing #3194/#3196/#3200, plus the two optimizations that looked compelling and were measured away. The headline is that the parse work is done: a one-file-edit re-analyze is 36.5s, of which parse is 2.8s (8%). scopeResolution is 40% and the unlogged graph emit + FTS rebuild is 49% — neither is incremental, and the ~18s sits outside the phase runner so every phase log is blind to it. Also records the trap that invalidated an earlier measurement: a non-git corpus never records a schema fingerprint, so every run is a forced rebuild and any "warm" number taken that way is fiction. Rejected, with numbers: more workers (16/20/24 land inside run-to-run spread) and bundling the worker entry (~250ms on a normal filesystem; the 8.6s that motivated it was a 9p-mount artifact). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
415 lines
15 KiB
TypeScript
415 lines
15 KiB
TypeScript
/**
|
|
* Regression coverage for native-worker startup on warm parse-cache runs.
|
|
*
|
|
* A cache-hit chunk must replay cached worker output without spawning the
|
|
* parse-worker. Spawning workers on a warm cache hit still loads tree-sitter
|
|
* native bindings at top level, which was the root trigger for intermittent
|
|
* `libc++abi ... Napi::Error` crashes in linked local builds.
|
|
*/
|
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { pathToFileURL } from 'node:url';
|
|
|
|
import { createKnowledgeGraph } from '../../src/core/graph/graph.js';
|
|
import { runChunkedParseAndResolve } from '../../src/core/ingestion/pipeline-phases/parse-impl.js';
|
|
import { computeChunkHash, fileContentHash } from '../../src/storage/parse-cache.js';
|
|
import type { ParseWorkerResult } from '../../src/core/ingestion/workers/parse-worker.js';
|
|
|
|
const emptyWorkerResult = (filePath: string, name: string): ParseWorkerResult => ({
|
|
nodes: [
|
|
{
|
|
id: `Function:${filePath}:${name}`,
|
|
label: 'Function',
|
|
properties: {
|
|
name,
|
|
filePath,
|
|
startLine: 1,
|
|
endLine: 1,
|
|
language: 'typescript',
|
|
},
|
|
},
|
|
],
|
|
relationships: [],
|
|
symbols: [],
|
|
imports: [],
|
|
calls: [],
|
|
assignments: [],
|
|
heritage: [],
|
|
routes: [],
|
|
fetchCalls: [],
|
|
fetchWrapperDefs: [],
|
|
decoratorRoutes: [],
|
|
routerIncludes: [],
|
|
routerImports: [],
|
|
toolDefs: [],
|
|
ormQueries: [],
|
|
constructorBindings: [],
|
|
fileScopeBindings: [],
|
|
parsedFiles: [],
|
|
skippedLanguages: {},
|
|
fileCount: 1,
|
|
});
|
|
|
|
const writeReadyWorker = (workerPath: string, markerPath: string): void => {
|
|
fs.writeFileSync(
|
|
workerPath,
|
|
`
|
|
const fs = require('node:fs');
|
|
const { parentPort } = require('node:worker_threads');
|
|
fs.writeFileSync(${JSON.stringify(markerPath)}, 'spawned');
|
|
parentPort.postMessage({ type: 'ready' });
|
|
parentPort.on('message', () => {});
|
|
`,
|
|
);
|
|
};
|
|
|
|
const writeResultWorker = (workerPath: string, markerPath: string): void => {
|
|
fs.writeFileSync(
|
|
workerPath,
|
|
`
|
|
const fs = require('node:fs');
|
|
const { parentPort } = require('node:worker_threads');
|
|
const decoder = new TextDecoder('utf-8');
|
|
fs.writeFileSync(${JSON.stringify(markerPath)}, 'spawned');
|
|
parentPort.postMessage({ type: 'ready' });
|
|
const accumulated = {
|
|
nodes: [], relationships: [], symbols: [], imports: [], calls: [], assignments: [], heritage: [],
|
|
routes: [], fetchCalls: [], fetchWrapperDefs: [], decoratorRoutes: [], routerIncludes: [], routerImports: [], toolDefs: [], ormQueries: [], constructorBindings: [],
|
|
fileScopeBindings: [], parsedFiles: [], skippedLanguages: {}, fileCount: 0,
|
|
};
|
|
parentPort.on('message', (msg) => {
|
|
if (msg && msg.type === 'sub-batch') {
|
|
for (const file of msg.files) {
|
|
const filePath = file.path;
|
|
const name = filePath.split('/').pop().replace(/\\.ts$/, '');
|
|
accumulated.nodes.push({
|
|
id: 'Function:' + filePath + ':' + name,
|
|
label: 'Function',
|
|
properties: { name, filePath, startLine: 1, endLine: 1, language: 'typescript' },
|
|
});
|
|
accumulated.fileCount++;
|
|
// Decode to exercise the same transfer-list shape as production.
|
|
if (file.content && typeof file.content !== 'string') decoder.decode(file.content);
|
|
}
|
|
parentPort.postMessage({ type: 'progress', filesProcessed: accumulated.fileCount });
|
|
parentPort.postMessage({ type: 'sub-batch-done' });
|
|
return;
|
|
}
|
|
if (msg && msg.type === 'flush') parentPort.postMessage({ type: 'result', data: accumulated });
|
|
});
|
|
`,
|
|
);
|
|
};
|
|
|
|
/**
|
|
* Like `writeResultWorker`, but each spawned instance writes its OWN marker
|
|
* keyed by `threadId`. The shared single-marker workers above can only prove
|
|
* "at least one worker started"; counting files in `markerDir` gives the actual
|
|
* pool size the parse phase asked `createWorkerPool` for, which is the only
|
|
* thing that distinguishes a clamped pool from an honored override.
|
|
*/
|
|
const writeSpawnCountingWorker = (workerPath: string, markerDir: string): void => {
|
|
fs.writeFileSync(
|
|
workerPath,
|
|
`
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { parentPort, threadId } = require('node:worker_threads');
|
|
fs.mkdirSync(${JSON.stringify(markerDir)}, { recursive: true });
|
|
fs.writeFileSync(path.join(${JSON.stringify(markerDir)}, 'worker-' + threadId), 'spawned');
|
|
parentPort.postMessage({ type: 'ready' });
|
|
const accumulated = {
|
|
nodes: [], relationships: [], symbols: [], imports: [], calls: [], assignments: [], heritage: [],
|
|
routes: [], fetchCalls: [], fetchWrapperDefs: [], decoratorRoutes: [], routerIncludes: [], routerImports: [], toolDefs: [], ormQueries: [], constructorBindings: [],
|
|
fileScopeBindings: [], parsedFiles: [], skippedLanguages: {}, fileCount: 0,
|
|
};
|
|
parentPort.on('message', (msg) => {
|
|
if (msg && msg.type === 'sub-batch') {
|
|
for (const file of msg.files) {
|
|
const filePath = file.path;
|
|
const name = filePath.split('/').pop().replace(/\.ts$/, '');
|
|
accumulated.nodes.push({
|
|
id: 'Function:' + filePath + ':' + name,
|
|
label: 'Function',
|
|
properties: { name, filePath, startLine: 1, endLine: 1, language: 'typescript' },
|
|
});
|
|
accumulated.fileCount++;
|
|
}
|
|
parentPort.postMessage({ type: 'progress', filesProcessed: accumulated.fileCount });
|
|
parentPort.postMessage({ type: 'sub-batch-done' });
|
|
return;
|
|
}
|
|
if (msg && msg.type === 'flush') parentPort.postMessage({ type: 'result', data: accumulated });
|
|
});
|
|
`,
|
|
);
|
|
};
|
|
|
|
const writeExitBeforeReadyWorker = (workerPath: string): void => {
|
|
fs.writeFileSync(workerPath, `process.exit(1);\n`);
|
|
};
|
|
|
|
describe('parse-impl worker pool lazy startup', () => {
|
|
let tempDir = '';
|
|
let repoDir = '';
|
|
|
|
beforeEach(() => {
|
|
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'parse-impl-worker-lazy-cache-'));
|
|
repoDir = path.join(tempDir, 'repo');
|
|
fs.mkdirSync(repoDir, { recursive: true });
|
|
});
|
|
|
|
afterEach(() => {
|
|
if (tempDir) fs.rmSync(tempDir, { recursive: true, force: true });
|
|
});
|
|
|
|
it('does not spawn a parse worker when every chunk is served from parse cache', async () => {
|
|
const rel = 'src/cached.ts';
|
|
const content = 'export function cached() { return 1; }\n';
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, content);
|
|
|
|
const chunkHash = computeChunkHash([{ filePath: rel, contentHash: fileContentHash(content) }]);
|
|
const parseCache = {
|
|
version: 'test',
|
|
entries: new Map<string, ParseWorkerResult[]>([
|
|
[chunkHash, [emptyWorkerResult(rel, 'cached')]],
|
|
]),
|
|
usedKeys: new Set<string>(),
|
|
};
|
|
|
|
const markerPath = path.join(tempDir, 'worker-spawned.marker');
|
|
const workerPath = path.join(tempDir, 'ready-worker.js');
|
|
writeReadyWorker(workerPath, markerPath);
|
|
|
|
const graph = createKnowledgeGraph();
|
|
await runChunkedParseAndResolve(
|
|
graph,
|
|
[{ path: rel, size: fs.statSync(full).size }],
|
|
[rel],
|
|
1,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
{
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
workerPoolSize: 1,
|
|
parseCache,
|
|
},
|
|
);
|
|
|
|
expect(fs.existsSync(markerPath)).toBe(false);
|
|
expect(parseCache.usedKeys.has(chunkHash)).toBe(true);
|
|
expect(Array.from(graph.nodes.values()).some((n) => n.properties.name === 'cached')).toBe(true);
|
|
});
|
|
|
|
it('spawns the parse worker lazily on the first cache miss and stores raw results', async () => {
|
|
const rel = 'src/miss.ts';
|
|
const content = 'export function miss() { return 1; }\n';
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, content);
|
|
|
|
const markerPath = path.join(tempDir, 'worker-spawned.marker');
|
|
const workerPath = path.join(tempDir, 'result-worker.js');
|
|
writeResultWorker(workerPath, markerPath);
|
|
|
|
const parseCache = {
|
|
version: 'test',
|
|
entries: new Map<string, ParseWorkerResult[]>(),
|
|
usedKeys: new Set<string>(),
|
|
};
|
|
const chunkHash = computeChunkHash([{ filePath: rel, contentHash: fileContentHash(content) }]);
|
|
|
|
const graph = createKnowledgeGraph();
|
|
await runChunkedParseAndResolve(
|
|
graph,
|
|
[{ path: rel, size: fs.statSync(full).size }],
|
|
[rel],
|
|
1,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
{
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
workerPoolSize: 1,
|
|
parseCache,
|
|
},
|
|
);
|
|
|
|
expect(fs.existsSync(markerPath)).toBe(true);
|
|
expect(parseCache.entries.has(chunkHash)).toBe(true);
|
|
expect(Array.from(graph.nodes.values()).some((n) => n.properties.name === 'miss')).toBe(true);
|
|
});
|
|
|
|
it('fails fast (no silent fallback) when the pool cannot start its workers (#1741)', async () => {
|
|
const rel = 'src/fatal.ts';
|
|
const content = 'export function fatal() { return 1; }\n';
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, content);
|
|
|
|
const workerPath = path.join(tempDir, 'exit-before-ready-fatal-worker.js');
|
|
writeExitBeforeReadyWorker(workerPath);
|
|
|
|
const parseCache = {
|
|
version: 'test',
|
|
entries: new Map<string, ParseWorkerResult[]>(),
|
|
usedKeys: new Set<string>(),
|
|
};
|
|
|
|
const graph = createKnowledgeGraph();
|
|
await expect(
|
|
runChunkedParseAndResolve(
|
|
graph,
|
|
[{ path: rel, size: fs.statSync(full).size }],
|
|
[rel],
|
|
1,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
{
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
workerPoolSize: 1,
|
|
// No flag: a total worker-startup failure always fails fast now.
|
|
parseCache,
|
|
},
|
|
),
|
|
).rejects.toThrow(/Worker pool failed to start/i);
|
|
|
|
// The fatal path did not silently parse sequentially behind the user's back.
|
|
expect(Array.from(graph.nodes.values()).some((n) => n.properties.name === 'fatal')).toBe(false);
|
|
});
|
|
|
|
it('honors GITNEXUS_WORKER_POOL_SIZE above the work-proportional cap', async () => {
|
|
// The auto pool size is bounded by source bytes so a tiny repo does not
|
|
// spawn a full idle pool. That bound must apply to the AUTO default only —
|
|
// it used to clamp the operator's env override too, so an operator asking
|
|
// for more workers silently got the byte-derived number while `--workers`
|
|
// was honored.
|
|
//
|
|
// This asserts the pool the PARSE PHASE actually builds, not the resolver in
|
|
// isolation: `resolveAutoPoolSize()` already honored the env var before the
|
|
// fix, so a test at that level stays green through a revert.
|
|
const saved = process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
process.env.GITNEXUS_WORKER_POOL_SIZE = '3';
|
|
try {
|
|
// Four tiny files: total bytes are far under one CHUNK_BYTES_PER_WORKER so
|
|
// the work-proportional cap is 1, while the parseable count stays above the
|
|
// requested 3 (the pool never exceeds the number of files to parse).
|
|
const rels = ['src/a.ts', 'src/b.ts', 'src/c.ts', 'src/d.ts'];
|
|
const scanned = rels.map((rel) => {
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, `export function ${path.basename(rel, '.ts')}() { return 1; }\n`);
|
|
return { path: rel, size: fs.statSync(full).size };
|
|
});
|
|
|
|
const markerDir = path.join(tempDir, 'pool-size-markers');
|
|
const workerPath = path.join(tempDir, 'pool-size-worker.js');
|
|
writeSpawnCountingWorker(workerPath, markerDir);
|
|
|
|
const result = await runChunkedParseAndResolve(
|
|
createKnowledgeGraph(),
|
|
scanned,
|
|
rels,
|
|
rels.length,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
// No `workerPoolSize`: the env var is the only override in play.
|
|
{ workerUrlForTest: pathToFileURL(workerPath) },
|
|
);
|
|
|
|
expect(result.usedWorkerPool).toBe(true);
|
|
// 3, not the byte-derived 1. Exactly this assertion fails on the clamped
|
|
// parent commit, which is what makes it a regression test for the fix.
|
|
expect(fs.readdirSync(markerDir)).toHaveLength(3);
|
|
} finally {
|
|
if (saved === undefined) delete process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
else process.env.GITNEXUS_WORKER_POOL_SIZE = saved;
|
|
}
|
|
});
|
|
|
|
it('throws when GITNEXUS_WORKER_POOL_SIZE=0 and no --workers flag (sequential parsing removed)', async () => {
|
|
const saved = process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
process.env.GITNEXUS_WORKER_POOL_SIZE = '0';
|
|
try {
|
|
const rel = 'src/env0.ts';
|
|
const content = 'export function env0() { return 1; }\n';
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, content);
|
|
|
|
// A ready-worker double with a spawn marker — it must NOT be spawned,
|
|
// because the disabled-channel validation throws before any pool is built.
|
|
const markerPath = path.join(tempDir, 'env0-worker.marker');
|
|
const workerPath = path.join(tempDir, 'env0-ready-worker.js');
|
|
writeReadyWorker(workerPath, markerPath);
|
|
|
|
const graph = createKnowledgeGraph();
|
|
await expect(
|
|
runChunkedParseAndResolve(
|
|
graph,
|
|
[{ path: rel, size: fs.statSync(full).size }],
|
|
[rel],
|
|
1,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
{
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
// No workerPoolSize option — the ambient env=0 is the only signal.
|
|
},
|
|
),
|
|
).rejects.toThrow(/GITNEXUS_WORKER_POOL_SIZE=0/);
|
|
|
|
// Sequential parsing was removed: env=0 is a hard error, not a silent
|
|
// sequential run. The validation throws before any pool is constructed.
|
|
expect(fs.existsSync(markerPath)).toBe(false);
|
|
} finally {
|
|
if (saved === undefined) delete process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
else process.env.GITNEXUS_WORKER_POOL_SIZE = saved;
|
|
}
|
|
});
|
|
|
|
it('an explicit --workers wins over an ambient GITNEXUS_WORKER_POOL_SIZE=0 (#1741)', async () => {
|
|
const saved = process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
process.env.GITNEXUS_WORKER_POOL_SIZE = '0';
|
|
try {
|
|
const rel = 'src/precedence.ts';
|
|
const content = 'export function precedence() { return 1; }\n';
|
|
const full = path.join(repoDir, rel);
|
|
fs.mkdirSync(path.dirname(full), { recursive: true });
|
|
fs.writeFileSync(full, content);
|
|
|
|
const markerPath = path.join(tempDir, 'precedence-worker.marker');
|
|
const workerPath = path.join(tempDir, 'precedence-result-worker.js');
|
|
writeResultWorker(workerPath, markerPath);
|
|
|
|
const graph = createKnowledgeGraph();
|
|
const result = await runChunkedParseAndResolve(
|
|
graph,
|
|
[{ path: rel, size: fs.statSync(full).size }],
|
|
[rel],
|
|
1,
|
|
repoDir,
|
|
Date.now(),
|
|
() => {},
|
|
{
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
workerPoolSize: 1, // explicit --workers 1 must win over ambient env=0
|
|
},
|
|
);
|
|
|
|
expect(result.usedWorkerPool).toBe(true); // explicit flag wins; env=0 ignored
|
|
expect(fs.existsSync(markerPath)).toBe(true); // worker was spawned
|
|
} finally {
|
|
if (saved === undefined) delete process.env.GITNEXUS_WORKER_POOL_SIZE;
|
|
else process.env.GITNEXUS_WORKER_POOL_SIZE = saved;
|
|
}
|
|
});
|
|
});
|