mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* fix(ingestion): stop reading the callee of an awaited generic member call tree-sitter-typescript parses `await svc.verify<T>(x)` as `call_expression(function: await_expression(member_expression))`, so the member's parent is the await, not the call. `shouldEmitReadMember` had no case for that shape, although its doc comment listed it: the call got its CALLS edge and also a read ACCESSES edge to the method. An awaited member that is not called (`await svc.pending`) stays a read. * test(bench): record the read edge the awaited-call fix removes The fix drops one wrong ACCESSES read from GitNexus's own source, `await workerPool.dispatchGroups<ParseWorkerInput, ParseWorkerResult>(…)` in parsing-processor.ts:398, so the benches that compare the main and PR graphs failed on that difference: - scope-capture: new typescript fingerprint. The one removed match is the `svc.verify` read in typescript-generic-calls/src/guest.ts, and disabling only the new await_expression case restores the old fingerprint. - parse cache, real corpus: graph expectations for this base and head, one edge fewer in every phase, nodes unchanged. - lexical lookup: the reference receipt can now pin removed rows as well as added ones, and only reference relationships may be removed. The manifest pins this single ACCESSES row for the current corpus trees. * test(bench): refresh parse-cache fingerprints after the source comment merge --------- Co-authored-by: Gergő Magyar <gergomagyar@icloud.com> Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
397 lines
16 KiB
TypeScript
397 lines
16 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
|
import v8 from 'node:v8';
|
|
import { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import path from 'node:path';
|
|
import { spawnSync } from 'node:child_process';
|
|
import { createHash } from 'node:crypto';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
|
const checker = new URL('../../bench/v8-sidecar/check.mjs', import.meta.url);
|
|
const { assessPairs, indexingMetrics, interningMetrics } = await import(checker.href);
|
|
|
|
const indexing = (lifecycle = 'fresh') => ({
|
|
lifecycle,
|
|
screen: false,
|
|
pairs: 9,
|
|
head: 'same-source',
|
|
node: process.version,
|
|
results: Array.from({ length: 10 }, (_, pair) =>
|
|
['baseline', 'candidate'].map((variant) => ({
|
|
name: variant + '-' + (pair || 'seed'),
|
|
variant,
|
|
ms: variant === 'baseline' ? 100 : 90,
|
|
cpuMs: variant === 'baseline' ? 100 : 90,
|
|
incremental: { writeMode: 'incremental', changedFiles: 1 },
|
|
rebuildReasons: [] as string[],
|
|
cachedFiles: 100,
|
|
graph: { nodes: { count: 3, sha256: 'nodes' }, edges: { count: 2, sha256: 'edges' } },
|
|
persistedTargets: [{ target: pair % 2 ? 'load' : 'save' }],
|
|
})),
|
|
).flat(),
|
|
});
|
|
|
|
const interning = () => ({
|
|
equivalent: true,
|
|
shards: 2,
|
|
bytes: 1000,
|
|
strings: 10,
|
|
warmupRounds: 2,
|
|
corpusHead: 'same-source',
|
|
node: process.version,
|
|
samples: Array.from({ length: 10 }, (_, round) =>
|
|
['baseline', 'candidate'].map((variant) => ({
|
|
round,
|
|
variant,
|
|
ms: 100,
|
|
cpuMs: 100,
|
|
hydrateCpuMs: 200,
|
|
})),
|
|
).flat(),
|
|
});
|
|
|
|
describe('cache interning performance gate', () => {
|
|
it('measures hydration CPU separately from interning CPU', async () => {
|
|
const sample = new URL('../../bench/v8-sidecar/intern-sample.mjs', import.meta.url);
|
|
const { measure } = await import(sample.href);
|
|
let cpu = 0;
|
|
vi.stubGlobal('gc', () => {});
|
|
vi.spyOn(process, 'cpuUsage').mockImplementation((previous) => ({
|
|
user: cpu - (previous?.user ?? 0),
|
|
system: 0,
|
|
}));
|
|
vi.spyOn(v8, 'deserialize').mockImplementation(() => {
|
|
cpu += 2000;
|
|
return {};
|
|
});
|
|
try {
|
|
const result = measure(
|
|
[Buffer.alloc(0), Buffer.alloc(0)],
|
|
() => {
|
|
cpu += 7000;
|
|
},
|
|
0,
|
|
);
|
|
expect(result.hydrateCpuMs).toBe(4);
|
|
expect(result.cpuMs).toBe(14);
|
|
} finally {
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
it.each([0.7, 1, 1.05, 1.051, 1.2])('enforces the paired 5%% budget (%s)', (ratio) => {
|
|
const pairs = Array.from({ length: 8 }, () => ({ baseline: 100, candidate: 100 * ratio }));
|
|
expect(assessPairs(pairs).verdict).toBe(ratio > 1.05 ? 'regression' : 'within-budget');
|
|
});
|
|
|
|
it.each([0, -1, NaN, Infinity, undefined])('rejects invalid timing (%s)', (value) => {
|
|
const pairs = Array.from({ length: 8 }, () => ({ baseline: 100, candidate: value }));
|
|
expect(() => assessPairs(pairs)).toThrow('timing');
|
|
});
|
|
|
|
it('rejects a slower overall median even when most paired ratios improve', () => {
|
|
const pairs = [100, 100, 100, 100, 200, 200, 200, 200].map((baseline, i) => ({
|
|
baseline,
|
|
candidate: baseline * (i < 3 ? 2 : 0.9),
|
|
}));
|
|
const result = assessPairs(pairs);
|
|
expect(result.pairedMedianRatio).toBeLessThan(1);
|
|
expect(result.medianRatio).toBeGreaterThan(1.05);
|
|
expect(result.verdict).toBe('regression');
|
|
});
|
|
|
|
it('excludes warm-up but keeps every measured pair', () => {
|
|
const report = indexing();
|
|
report.results[1].ms = 10000;
|
|
report.results[3].ms = 10000;
|
|
expect(indexingMetrics(report, 'fresh')[0].candidateMedian).toBe(90);
|
|
report.results
|
|
.filter((r) => r.variant === 'candidate')
|
|
.forEach((r) => {
|
|
r.cpuMs = 120;
|
|
});
|
|
expect(indexingMetrics(report, 'fresh')[1].verdict).toBe('regression');
|
|
});
|
|
|
|
it('accepts compact full writes for cached edits without relaxing the performance budget', () => {
|
|
const report = indexing();
|
|
for (const sample of report.results.filter((row) => row.variant === 'candidate')) {
|
|
sample.incremental.writeMode = 'full';
|
|
sample.rebuildReasons = ['escalated-full-write'];
|
|
sample.cpuMs = 120;
|
|
}
|
|
expect(indexingMetrics(report, 'fresh')[1].verdict).toBe('regression');
|
|
report.results[3].cachedFiles = 0;
|
|
expect(() => indexingMetrics(report, 'fresh')).toThrow('hydrate cached files');
|
|
});
|
|
|
|
it('rejects cache invalidations even alongside a compact full-write reason', () => {
|
|
const report = indexing();
|
|
report.results[3].incremental.writeMode = 'full';
|
|
report.results[3].rebuildReasons = ['escalated-full-write', 'runner-identity'];
|
|
expect(() => indexingMetrics(report, 'fresh')).toThrow('invalidate the parse cache');
|
|
});
|
|
|
|
it.each(['', 'unknown', undefined])('rejects an unrecognized write mode (%s)', (mode) => {
|
|
const report = indexing();
|
|
report.results[3].incremental = { ...report.results[3].incremental, writeMode: mode as string };
|
|
expect(() => indexingMetrics(report, 'fresh')).toThrow();
|
|
});
|
|
|
|
it.each(['missing', 'duplicate', 'screened', 'cold', 'wrong-target', 'graph', 'rebuild'])(
|
|
'rejects invalid indexing evidence (%s)',
|
|
(kind) => {
|
|
const report = indexing();
|
|
if (kind === 'missing') report.results.pop();
|
|
if (kind === 'duplicate') report.results[3] = report.results[2];
|
|
if (kind === 'screened') report.screen = true;
|
|
if (kind === 'cold') report.results[3].cachedFiles = 0;
|
|
if (kind === 'wrong-target') report.results[3].persistedTargets = [{ target: 'save' }];
|
|
if (kind === 'graph') report.results[3].graph.edges.sha256 = 'wrong';
|
|
if (kind === 'rebuild') report.results[3].rebuildReasons = ['cache-miss'];
|
|
expect(() => indexingMetrics(report, 'fresh')).toThrow();
|
|
},
|
|
);
|
|
|
|
it('requires pair-bound validated projection receipts when graph IDs migrate', () => {
|
|
const report = indexing();
|
|
const candidate = report.results.find((sample) => sample.name === 'candidate-1')!;
|
|
candidate.graph.edges.sha256 = 'full-span-edges';
|
|
expect(() => indexingMetrics(report, 'fresh')).toThrow(/without a parity receipt/);
|
|
const graphParity = Array.from({ length: 10 }, (_, i) => {
|
|
const suffix = i || 'seed';
|
|
const baseline = report.results.find((sample) => sample.name === `baseline-${suffix}`)!;
|
|
const after = report.results.find((sample) => sample.name === `candidate-${suffix}`)!;
|
|
return {
|
|
version: 1,
|
|
mode: i === 1 ? 'point-to-span' : 'exact',
|
|
baselineName: baseline.name,
|
|
candidateName: after.name,
|
|
baseline: structuredClone(baseline.graph),
|
|
candidate: structuredClone(after.graph),
|
|
comparison: structuredClone(baseline.graph),
|
|
};
|
|
});
|
|
expect(() => indexingMetrics({ ...report, graphParity }, 'fresh')).not.toThrow();
|
|
expect(() =>
|
|
indexingMetrics({ ...report, graphParity: graphParity.slice(1) }, 'fresh'),
|
|
).toThrow(/Incomplete graph parity/);
|
|
const modified = structuredClone(graphParity);
|
|
modified[1].comparison.edges.sha256 = 'invented';
|
|
expect(() => indexingMetrics({ ...report, graphParity: modified }, 'fresh')).toThrow(
|
|
/projection differs/,
|
|
);
|
|
const misbound = structuredClone(graphParity);
|
|
misbound[1].candidate.edges.sha256 = 'other';
|
|
expect(() => indexingMetrics({ ...report, graphParity: misbound }, 'fresh')).toThrow(
|
|
/candidate does not match/,
|
|
);
|
|
|
|
const expectedReferences = JSON.parse(
|
|
readFileSync(
|
|
new URL('../../bench/lib/expected-reference-additions.json', import.meta.url),
|
|
'utf8',
|
|
),
|
|
);
|
|
type Digest = { count: number; sha256: string };
|
|
const [head, { additions, typeOnlyImports }] = Object.entries(expectedReferences)[0] as [
|
|
string,
|
|
{ additions: Digest; typeOnlyImports: Digest },
|
|
];
|
|
const withAdditions = graphParity.map((receipt) => {
|
|
const sample = report.results.find((entry) => entry.name === receipt.candidateName);
|
|
if (!sample) throw new Error(`Missing sample ${receipt.candidateName}`);
|
|
sample.graph.edges.count += additions.count;
|
|
return {
|
|
...receipt,
|
|
mode: 'added-references',
|
|
candidate: structuredClone(sample.graph),
|
|
additions,
|
|
typeOnlyImports,
|
|
};
|
|
});
|
|
expect(() =>
|
|
indexingMetrics({ ...report, corpusTrees: head, graphParity: withAdditions }, 'fresh'),
|
|
).not.toThrow();
|
|
expect(() => indexingMetrics({ ...report, graphParity: withAdditions }, 'fresh')).toThrow(
|
|
'Unknown reference corpus',
|
|
);
|
|
const missingImports = withAdditions.map(
|
|
({ typeOnlyImports: _imports, ...receipt }) => receipt,
|
|
);
|
|
expect(() =>
|
|
indexingMetrics({ ...report, corpusTrees: head, graphParity: missingImports }, 'fresh'),
|
|
).toThrow('Unexpected type-only imports');
|
|
const tampered = withAdditions.map((receipt, i) =>
|
|
i === 1 ? { ...receipt, additions: { ...additions, sha256: 'invented' } } : receipt,
|
|
);
|
|
expect(() =>
|
|
indexingMetrics({ ...report, corpusTrees: head, graphParity: tampered }, 'fresh'),
|
|
).toThrow('Unexpected added reference receipt');
|
|
});
|
|
|
|
it('rejects exact parity when every pinned reference addition is absent', async () => {
|
|
const manifest = new URL('../../bench/lib/expected-reference-additions.json', import.meta.url);
|
|
const [head] = Object.keys(JSON.parse(readFileSync(manifest, 'utf8')));
|
|
const source = new URL('../../bench/lexical-lookup/reference-migration.mjs', import.meta.url);
|
|
const { assertGraphParity } = await import(source.href);
|
|
const report = indexing();
|
|
const { graph } = report.results[0];
|
|
expect(() => assertGraphParity({ graph }, { graph }, '.', head)).toThrow(
|
|
'Missing expected added reference receipt',
|
|
);
|
|
expect(() => indexingMetrics({ ...report, corpusTrees: head }, 'fresh')).toThrow(
|
|
'Missing expected added reference receipt',
|
|
);
|
|
});
|
|
|
|
it('accepts only the pinned reference removals', async () => {
|
|
type Digest = { count: number; sha256: string };
|
|
const manifest = JSON.parse(
|
|
readFileSync(
|
|
new URL('../../bench/lib/expected-reference-additions.json', import.meta.url),
|
|
'utf8',
|
|
),
|
|
) as Record<string, { removals?: Digest }>;
|
|
const pinned = Object.entries(manifest).find(([, entry]) => entry.removals);
|
|
if (!pinned?.[1].removals) throw new Error('No manifest entry pins a removal');
|
|
const [head, { removals }] = pinned;
|
|
// The read the awaited generic call `workerPool.dispatchGroups<…>()` no longer emits.
|
|
const removed = JSON.stringify({
|
|
confidence: 1,
|
|
id: 'rel:ACCESSES:Function:gitnexus/src/core/ingestion/parsing-processor.ts:dispatchChunkParseRound->Method:gitnexus/src/core/ingestion/workers/worker-pool.ts:WorkerPool.dispatchGroups#2:read:398:25:398:50',
|
|
reason: 'read',
|
|
sourceId: 'Function:gitnexus/src/core/ingestion/parsing-processor.ts:dispatchChunkParseRound',
|
|
targetId:
|
|
'Method:gitnexus/src/core/ingestion/workers/worker-pool.ts:WorkerPool.dispatchGroups#2',
|
|
type: 'ACCESSES',
|
|
});
|
|
const kept = JSON.stringify({
|
|
id: 'rel:CALLS:a->b:1:0',
|
|
sourceId: 'a',
|
|
targetId: 'b',
|
|
type: 'CALLS',
|
|
});
|
|
const imports = JSON.stringify({
|
|
id: 'rel:IMPORTS:a->b',
|
|
sourceId: 'a',
|
|
targetId: 'b',
|
|
type: 'IMPORTS',
|
|
});
|
|
const rowsDigest = (rows: string[]) => {
|
|
const hash = createHash('sha256');
|
|
for (const row of [...rows].sort()) hash.update(row).update('\n');
|
|
return { count: rows.length, sha256: hash.digest('hex') };
|
|
};
|
|
const directory = mkdtempSync(path.join(tmpdir(), 'reference-removals-'));
|
|
try {
|
|
let files = 0;
|
|
const sample = (edges: string[]) => {
|
|
const graphRowsPath = path.join(directory, `graph-${files++}.json`);
|
|
writeFileSync(graphRowsPath, JSON.stringify({ nodes: ['node'], edges }));
|
|
return { graph: { nodes: rowsDigest(['node']), edges: rowsDigest(edges) }, graphRowsPath };
|
|
};
|
|
const source = new URL('../../bench/lexical-lookup/reference-migration.mjs', import.meta.url);
|
|
const { assertGraphParity } = await import(source.href);
|
|
const receipt = assertGraphParity(sample([kept, removed]), sample([kept]), '.', head);
|
|
expect(receipt.mode).toBe('added-references');
|
|
expect(receipt.removals).toEqual(removals);
|
|
expect(() =>
|
|
assertGraphParity(sample([kept, removed]), sample([removed]), '.', head),
|
|
).toThrow('Unexpected removed reference receipt');
|
|
expect(() =>
|
|
assertGraphParity(sample([imports, kept, removed]), sample([kept]), '.', head),
|
|
).toThrow('Removed a non-reference relationship');
|
|
|
|
const report = indexing();
|
|
const graphParity = Array.from({ length: 10 }, (_, i) => {
|
|
const suffix = i || 'seed';
|
|
const baseline = report.results.find((entry) => entry.name === `baseline-${suffix}`);
|
|
const candidate = report.results.find((entry) => entry.name === `candidate-${suffix}`);
|
|
if (!baseline || !candidate) throw new Error(`Missing samples ${suffix}`);
|
|
candidate.graph.edges.count -= removals.count;
|
|
return {
|
|
version: 1,
|
|
mode: 'added-references',
|
|
baselineName: baseline.name,
|
|
candidateName: candidate.name,
|
|
baseline: structuredClone(baseline.graph),
|
|
candidate: structuredClone(candidate.graph),
|
|
comparison: structuredClone(baseline.graph),
|
|
additions: receipt.additions,
|
|
removals: receipt.removals,
|
|
typeOnlyImports: receipt.typeOnlyImports,
|
|
};
|
|
});
|
|
expect(() =>
|
|
indexingMetrics({ ...report, corpusTrees: head, graphParity }, 'fresh'),
|
|
).not.toThrow();
|
|
const unpinned = graphParity.map(({ removals: _removals, ...rest }) => rest);
|
|
expect(() =>
|
|
indexingMetrics({ ...report, corpusTrees: head, graphParity: unpinned }, 'fresh'),
|
|
).toThrow('Unexpected removed reference receipt');
|
|
} finally {
|
|
rmSync(directory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('loads timing assessment without the reference manifest', async () => {
|
|
const directory = mkdtempSync(path.join(tmpdir(), 'timing-check-'));
|
|
try {
|
|
const bench = new URL('../', checker);
|
|
for (const file of [
|
|
'v8-sidecar/check.mjs',
|
|
'mcp-query/statistics.mjs',
|
|
'lib/reference-additions.mjs',
|
|
]) {
|
|
const destination = path.join(directory, file);
|
|
mkdirSync(path.dirname(destination), { recursive: true });
|
|
copyFileSync(new URL(file, bench), destination);
|
|
}
|
|
const isolated = await import(
|
|
pathToFileURL(path.join(directory, 'v8-sidecar/check.mjs')).href
|
|
);
|
|
expect(isolated.assessPairs(Array(8).fill({ baseline: 1, candidate: 1 })).verdict).toBe(
|
|
'within-budget',
|
|
);
|
|
} finally {
|
|
rmSync(directory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('rejects missing, duplicate, or non-equivalent shard measurements', () => {
|
|
const report = interning();
|
|
expect(interningMetrics(report)).toHaveLength(3);
|
|
expect(() => interningMetrics({ ...report, equivalent: false })).toThrow('equivalence');
|
|
expect(() => interningMetrics({ ...report, samples: report.samples.slice(1) })).toThrow(
|
|
'Incomplete',
|
|
);
|
|
report.samples[1] = report.samples[0];
|
|
expect(() => interningMetrics(report)).toThrow('Duplicate');
|
|
});
|
|
|
|
it('fails the CLI on CPU regressions and retains the diagnostic report', () => {
|
|
const directory = mkdtempSync(path.join(tmpdir(), 'intern-gate-'));
|
|
try {
|
|
for (const lifecycle of ['fresh', 'persistent']) {
|
|
mkdirSync(path.join(directory, lifecycle));
|
|
const report = indexing(lifecycle);
|
|
if (lifecycle === 'fresh')
|
|
report.results
|
|
.filter((r) => r.variant === 'candidate')
|
|
.forEach((r) => {
|
|
r.cpuMs = 120;
|
|
});
|
|
writeFileSync(path.join(directory, lifecycle, 'results.json'), JSON.stringify(report));
|
|
}
|
|
writeFileSync(path.join(directory, 'interner.json'), JSON.stringify(interning()));
|
|
const result = spawnSync(process.execPath, [fileURLToPath(checker), directory], {
|
|
encoding: 'utf8',
|
|
});
|
|
expect(result.status, result.stderr).toBe(1);
|
|
expect(readFileSync(path.join(directory, 'report.md'), 'utf8')).toContain('regression');
|
|
} finally {
|
|
rmSync(directory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|