mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-12-01 23:57:21 +00:00
* fix(cache): reuse unchanged files across chunks Key parser facts and scopes per file while retaining batched workers and compressed pack storage. Preserve staged repairs and recovery. Fixes #3849 * ci: gate parse cache speed and memory Compare fresh baseline and candidate processes on both corpora. Require paired speed and RSS improvements, graph equality, and bounded phase regressions; retain measure.json and failed trials. * perf(cache): reduce result restore overhead Batch adjacent pack reads within bounded windows. Avoid duplicate validation and oversized decompression buffers while preserving binding, checksum, output-limit, and corruption checks. * ci: keep checks active for stacked cache PR Allow PRs targeting fix/3852-root-cause to run the test and performance gates while the cache fix is stacked. * fix(cache): address review feedback (#3856) Keep optional cache failures from aborting analysis and retain immutable packs to avoid copying every unchanged result during publication. Bind benchmark corpus hashes unambiguously and cover worker fallback paths. Validation: build, typechecks, focused suites, lint and smoke tests pass. The full run passed 32,878 tests; two failures observed an overlapping edit/build. Both complete failing files pass fresh reruns (64 tests). * fix(cache): bound index reads and reuse checks Check and read the same open index to prevent pathname replacement from bypassing the size bound. Reject growth and truncation. Require exactly one reparse in the Java edit benchmark and update the expected cache counts while retaining semantic and scaling checks. * perf(cache): share decoded fact strings Deduplicate paths, IDs, and labels within each decode batch to reduce retained heap and peak RSS. Preserve valid facts and cache hits if optional interning fails. Refs #3856 --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
228 lines
9.1 KiB
TypeScript
228 lines
9.1 KiB
TypeScript
import { afterEach, 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 { createWorkerPool } from '../../../src/core/ingestion/workers/worker-pool.js';
|
|
import type { ParseWorkerResult } from '../../../src/core/ingestion/workers/parse-worker.js';
|
|
import {
|
|
loadParseCache,
|
|
loadParseCacheFiles,
|
|
pruneCache,
|
|
saveParseCache,
|
|
type ParseCache,
|
|
} from '../../../src/storage/parse-cache.js';
|
|
import { clearParsedFileStore } from '../../../src/storage/parsedfile-store.js';
|
|
import { loadFileResultStore } from '../../../src/storage/file-result-store.js';
|
|
import { runtimeParseIdentity } from '../../helpers/runtime-parse-identity.js';
|
|
import { runPipelineFromRepo, writeFixtureRepo, type PipelineResult } from './helpers.js';
|
|
|
|
const realWorker = new URL('../../../dist/core/ingestion/workers/parse-worker.js', import.meta.url);
|
|
const codecModule = new URL('../../../dist/storage/file-result-codec.js', import.meta.url);
|
|
const providerModule = new URL(
|
|
'../../../dist/core/ingestion/languages/typescript.js',
|
|
import.meta.url,
|
|
);
|
|
const temporary: string[] = [];
|
|
const tempDirectory = () => {
|
|
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-wrapper-persistence-'));
|
|
temporary.push(directory);
|
|
return directory;
|
|
};
|
|
|
|
afterEach(() => {
|
|
for (const directory of temporary.splice(0))
|
|
fs.rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
|
});
|
|
|
|
function fetchEdges(result: PipelineResult): string[] {
|
|
return [...result.graph.iterRelationships()]
|
|
.filter((edge) => edge.type === 'FETCHES')
|
|
.map(
|
|
(edge) => `${result.graph.getNode(edge.sourceId)?.properties.filePath} -> ${edge.targetId}`,
|
|
)
|
|
.sort();
|
|
}
|
|
|
|
describe('fetch-wrapper facts across workers and persistent caches', () => {
|
|
it('reuses raw identity facts on warm runs and re-resolves changed project aliases', async () => {
|
|
const identity = await runtimeParseIdentity();
|
|
const directory = tempDirectory();
|
|
const repo = path.join(directory, 'repo');
|
|
const storage = path.join(directory, 'storage');
|
|
const marker = path.join(directory, 'worker.jsonl');
|
|
const workerPath = path.join(directory, 'observed-worker.mjs');
|
|
fs.writeFileSync(
|
|
workerPath,
|
|
`
|
|
import fs from 'node:fs';
|
|
import { parentPort } from 'node:worker_threads';
|
|
import { decodeFileResultSection } from ${JSON.stringify(codecModule.href)};
|
|
const send = parentPort.postMessage.bind(parentPort);
|
|
parentPort.postMessage = (message, ...rest) => {
|
|
if (message.type === 'result') {
|
|
const parts = message.data.fileResults?.map(part => part.encoded
|
|
? decodeFileResultSection(part.encoded.facts, part.key, part.path, 'facts').value
|
|
: part.raw) ?? [message.data];
|
|
fs.appendFileSync(${JSON.stringify(marker)}, JSON.stringify({
|
|
definitions: parts.flatMap(part => part.fetchWrapperDefs ?? []),
|
|
calls: parts.flatMap(part => part.fetchWrapperCalls ?? []),
|
|
}) + '\\n');
|
|
}
|
|
return send(message, ...rest);
|
|
};
|
|
await import(${JSON.stringify(realWorker.href)});
|
|
`,
|
|
);
|
|
const config = (target: string) =>
|
|
JSON.stringify({
|
|
compilerOptions: { baseUrl: '.', paths: { '@http': [target] } },
|
|
});
|
|
const files = {
|
|
'tsconfig.json': config('./lib/http.ts'),
|
|
'lib/http.ts':
|
|
'export function request(url, fetch = globalThis.fetch) { return fetch(url); }',
|
|
'lib/plain.ts': 'export function request(url) { return url; }',
|
|
'lib/forward.ts':
|
|
"import { request as send } from '@http'; export function forward(url) { return send(url); }",
|
|
'pages/client.ts':
|
|
"import { forward as send } from '../lib/forward'; send('/api/items'); export function blocked(send) { return send('/api/blocked'); }",
|
|
// A barrel on the warm path: its re-export facts come back from the cache.
|
|
'lib/index.ts': "export * from './forward';",
|
|
'pages/barrel.ts': "import { forward } from '../lib'; forward('/api/barrel');",
|
|
'app/api/items/route.ts': 'export function GET() { return new Response(); }',
|
|
'app/api/barrel/route.ts': 'export function GET() { return new Response(); }',
|
|
'app/api/blocked/route.ts': 'export function GET() { return new Response(); }',
|
|
};
|
|
writeFixtureRepo(repo, files);
|
|
const parsedCount = Object.keys(files).length - 1;
|
|
const run = (parseCache: ParseCache) =>
|
|
runPipelineFromRepo(repo, () => {}, {
|
|
workerPoolSize: 1,
|
|
skipGraphPhases: true,
|
|
workerUrlForTest: pathToFileURL(workerPath),
|
|
parseCache,
|
|
});
|
|
const persist = async (cache: ParseCache) => {
|
|
pruneCache(cache, cache.usedKeys);
|
|
await saveParseCache(storage, cache);
|
|
await clearParsedFileStore(storage);
|
|
};
|
|
const coldCache = await loadParseCache(storage, identity, storage);
|
|
const cold = await run(coldCache);
|
|
expect(cold.usedWorkerPool).toBe(true);
|
|
expect(cold.reparsedFileCount).toBe(parsedCount);
|
|
expect(fetchEdges(cold)).toEqual([
|
|
'pages/barrel.ts -> Route:/api/barrel',
|
|
'pages/client.ts -> Route:/api/items',
|
|
]);
|
|
const observed = fs
|
|
.readFileSync(marker, 'utf8')
|
|
.trim()
|
|
.split('\n')
|
|
.map(
|
|
(line) =>
|
|
JSON.parse(line) as {
|
|
definitions: ParseWorkerResult['fetchWrapperDefs'];
|
|
calls: ParseWorkerResult['fetchWrapperCalls'];
|
|
},
|
|
);
|
|
expect(observed.flatMap((part) => part.definitions)).toContainEqual(
|
|
expect.objectContaining({
|
|
filePath: 'lib/plain.ts',
|
|
functionName: 'request',
|
|
seed: false,
|
|
definitionId: expect.any(String),
|
|
bindingId: expect.any(String),
|
|
}),
|
|
);
|
|
expect(observed.flatMap((part) => part.calls)).toContainEqual(
|
|
expect.objectContaining({
|
|
filePath: 'pages/client.ts',
|
|
target: { kind: 'import', specifier: '../lib/forward', importedName: 'forward' },
|
|
}),
|
|
);
|
|
await persist(coldCache);
|
|
const durable = await loadFileResultStore(
|
|
path.join(storage, 'parse-cache', 'files'),
|
|
identity.base,
|
|
);
|
|
expect(durable.records.size).toBe(parsedCount);
|
|
|
|
const warmCache = await loadParseCache(storage, identity, storage);
|
|
expect(warmCache.entries.size).toBe(0);
|
|
const facts = await loadParseCacheFiles(warmCache, [...durable.records.values()], storage);
|
|
expect(facts.size).toBe(parsedCount);
|
|
const parts = [...facts.values()];
|
|
expect(parts.flatMap((part) => part.parsedFiles ?? [])).toEqual([]);
|
|
expect(parts.flatMap((part) => part.fetchWrapperDefs ?? [])).toContainEqual(
|
|
expect.objectContaining({
|
|
filePath: 'lib/forward.ts',
|
|
forwardsTo: expect.arrayContaining([
|
|
expect.objectContaining({
|
|
target: { kind: 'import', specifier: '@http', importedName: 'request' },
|
|
}),
|
|
]),
|
|
}),
|
|
);
|
|
fs.rmSync(marker);
|
|
const warm = await run(warmCache);
|
|
expect(warm.usedWorkerPool).toBe(false);
|
|
expect(warm.reparsedFileCount).toBe(0);
|
|
expect(warm.parseCacheHitFileCount).toBe(parsedCount);
|
|
expect(fs.existsSync(marker)).toBe(false);
|
|
expect(fetchEdges(warm)).toEqual(fetchEdges(cold));
|
|
await persist(warmCache);
|
|
|
|
writeFixtureRepo(repo, { 'tsconfig.json': config('./lib/plain.ts') });
|
|
const changed = await run(await loadParseCache(storage, identity, storage));
|
|
expect(fetchEdges(changed)).toEqual([]);
|
|
}, 180000);
|
|
|
|
it('omits scope-dependent HTTP facts when extraction fails but retains definitions and the failure receipt', async () => {
|
|
const directory = tempDirectory();
|
|
const workerPath = path.join(directory, 'failed-scope-worker.mjs');
|
|
fs.writeFileSync(
|
|
workerPath,
|
|
`
|
|
const { typescriptProvider } = await import(${JSON.stringify(providerModule.href)});
|
|
typescriptProvider.emitScopeCaptures = () => { throw new Error('deliberate scope extraction failure'); };
|
|
await import(${JSON.stringify(realWorker.href)});
|
|
`,
|
|
);
|
|
const pool = createWorkerPool(pathToFileURL(workerPath), 1);
|
|
try {
|
|
const results = await pool.dispatch<{ path: string; content: string }, ParseWorkerResult>([
|
|
{
|
|
path: 'failed.ts',
|
|
content: "export function request(url) { return fetch(url); } request('/api/items');",
|
|
},
|
|
]);
|
|
expect(results.flatMap((result) => result.scopeExtractionFailures ?? [])).toEqual([
|
|
'failed.ts',
|
|
]);
|
|
expect(results.flatMap((result) => result.nodes)).toContainEqual(
|
|
expect.objectContaining({
|
|
label: 'Function',
|
|
properties: expect.objectContaining({ name: 'request' }),
|
|
}),
|
|
);
|
|
// Without facts the function still names its export, so a name-only
|
|
// match elsewhere declines instead of becoming unique.
|
|
expect(results.flatMap((result) => result.fetchWrapperDefs)).toEqual([
|
|
expect.objectContaining({
|
|
filePath: 'failed.ts',
|
|
functionName: 'request',
|
|
moduleScope: true,
|
|
exportedNames: ['request'],
|
|
seed: false,
|
|
forwardsUrl: false,
|
|
forwardsTo: [],
|
|
}),
|
|
]);
|
|
expect(results.flatMap((result) => result.fetchWrapperCalls ?? [])).toEqual([]);
|
|
} finally {
|
|
await pool.terminate();
|
|
}
|
|
}, 180000);
|
|
});
|