mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-12-01 23:57:21 +00:00
* test(conformance): compare TypeScript resolution with compiler declarations * test(typescript): compare fixture declarations and runtime dispatch * test(typescript): compare namespace and generic dispatch fixtures with tsc * fix(typescript): resolve qualified types and nested generic references * test(typescript): run CLI, embedding and workspace fixtures in conformance * fix(typescript): compare JSX member bindings and callable declarations * test(bench): pin compiler-verified property declaration positions * test(typescript): exercise parser cache and graph publication in conformance * test(typescript): run graph publication and recovery fixtures in conformance * fix(typescript): select member overloads from bound call results * bench(typescript): pin the verified overload resolver source tree * test(typescript): compare property accesses and migrate mixed fixtures * test(typescript): require FTS and correct conformance run instructions * fix(typescript): attribute constrained and aliased types to their declarations * test(bench): verify graph and capture changes for TypeScript aliases * test(typescript): move MCP and embedding fixtures into native conformance * test(typescript): check callback signatures and concrete targets against the compiler * test(conformance): verify callback types and migrate TypeScript product fixtures * fix(typescript): propagate the selected overload return to receiver calls * test(conformance): compare callback assignments and preserve class-expression coverage * test(bench): pin the verified overload resolver tree for parse reuse * test(conformance): compare overloaded callbacks and migrate rename and workspace fixtures * fix(typescript): preserve distinct local classes and chained overload return types * test(conformance): cover dirty snapshot reuse and graph rename in the native runner * test(conformance): release the database when fixture setup fails * test(conformance): run TypeScript watcher and shared-store fixtures natively * test(conformance): verify embedding identity and cache reuse in the native runner * test(conformance): move shared-store checkout fixtures into TypeScript jobs * test(bench): pin cold and resumed graphs for the local-class resolver * test(conformance): compare block-shadowed property reads with TypeScript * test(conformance): exercise TypeScript WAL recovery and Git directory handling natively * fix(ingestion): count receiver ownership suppressions once after replay * test(conformance): exercise TypeScript source edits during cold and cached resolution * test(conformance): stage only bundled dependencies for the installed CLI fixture * test(conformance): verify cold and incremental TypeScript file reuse in the native suite * test(conformance): exercise mixed-language embedding chunk reuse and source ranges * fix(typescript): qualify class graph identities by their namespace * test(conformance): move mixed worker persistence and filesystem fixtures to Node * test(cache): verify namespace owner identities across all reuse phases * test(conformance): exercise all 38 POSIX atomic publication cases in the native job * Move TypeScript graph, heap and scenario fixtures to native conformance * Resolve inherited TypeScript overloads and verify transitive interface methods * Compare TypeScript method keys and move wiki and embedding fixtures to conformance * Run TypeScript-backed rename, benchmark and scenario fixtures in native conformance * Compare class type parameters with TypeScript and preserve literal constraints * Fix conformance lint, formatting and rename fixture file handling * Pin both verified cache trials for literal type parameters * Run embedding recovery and control-flow fixtures in TypeScript conformance * Check TypeScript local function identities and repository fixtures in conformance * Compile shared TypeScript callable query patterns once per worker * Verify the Java wildcard graph includes the field declaration column * Pin verified file reuse results for the consolidated TypeScript query * Compare generator, closure and shadowing fixtures with the TypeScript compiler * Run incremental database fixtures in TypeScript conformance on their original platforms * Limit receiver replay to files with call-result consumers and resolve TypeScript overloads in declaration order * Bind TypeScript ambient declarations in their project and reject named imports from declaration scripts * Verify compiler capture, graph and file reuse baselines for the scoped resolver Two real-corpus runs agree across all five reuse phases. The TypeScript ingestion workload retains its call targets on all three sizes. Method-declaration graphs add only the source columns of the Dart and Kotlin properties. The migrated private-field fixture contributes the one additional array push reported by both runtimes. * Shard the Linux TypeScript product tests and require coverage from both runners * Run full-text opt-out lifecycle fixtures in native TypeScript conformance * Verify actual CLI exits, repeated skill output and shared-store analysis * Match TypeScript inheritance order, declared generic defaults and interface method identities * Trace callable arguments through TypeScript constructors and conditional expressions * Give anonymous TypeScript signatures their own generic scope * Move parser drain and analysis lifecycle fixtures into native conformance * Verify TypeScript reference and capture changes against frozen benchmark corpora * Move TypeScript incremental analysis and external config fixtures to conformance * Skip interface identity and callable-flow work for ordinary TypeScript values * Check TypeScript overload declarations and migrate fixture-backed product coverage * Resolve TypeScript script visibility, merged overloads, and immutable receivers * Record the verified TypeScript parse-cache benchmark graphs * Use TypeScript project file membership for global declarations * Match merged rest overloads and hoisted script declarations * Run TypeScript-backed indexing, worker, and rename fixtures in conformance * Move TypeScript gRPC and workspace-link fixtures to conformance * Keep runtime inference out of TypeScript compiler conformance * Keep TypeScript compiler conformance focused on static resolution * fix(typescript): preserve compiler-selected project and method bindings * test(typescript): compare callback sites with the resolved call range * test(typescript): let the compiler check namespace and ambient exports * style(test): format TypeScript conformance fixtures * test(typescript): align capture and receiver benchmarks with the compiler corpus Fingerprint all 174 capture inputs. Compared with main, these inputs add 25 call-result assignments, 19 type references and four scopes. Preserve the scaling budgets. The former duplicate Store fixture contributed one unresolved array push. Replaying both revisions on the current corpus yields exactly the same 20 TypeScript drop sites. Restore the original receiver counts. * perf(typescript): limit overload lookup to compiler-visible bindings * Compare TypeScript module ownership, defaults, and tuple bindings with the compiler Treat export flags as declaration metadata so identifier length cannot displace the declaration anchor. The benchmark corpus gains two reads and two calls to the two extractor helpers. All five cache scenarios keep their previous reparse counts. * Check published call locations and keep receiver replay scoped to call sites Resolve qualified heritage through its lexical namespace and honor TypeScript module detection for script globals. Index overload consumers by scope so 400 independent functions take 400 owner checks instead of 80,200. The published graph and all five real-corpus cache fingerprints remain stable. * Resolve script globals within their TypeScript projects and namespaces Follow compiler project references and source directives, share the global binding tables, and keep namespace values from resolving to unrelated types. Record the compiler-verified declaration positions in the lexical benchmark. * Resolve destructured script globals and preserve CommonJS loader targets Compare script bindings with TypeScript and forwarded CommonJS values with Node after compilation. Move capture ordering and worker parity checks to the native conformance job. Verify the iterable benchmark against the compiler-selected Value.save declaration. * Preserve TypeScript default factory exports across unrelated writes * Resolve standalone TypeScript projects and callable CommonJS exports * Match TypeScript compiler overloads, overrides, and narrowed calls * Resolve TypeScript CommonJS defaults using the project's module format * Check block-local handler bindings against the TypeScript compiler * Run TypeScript compiler conformance from one entry point * Match TypeScript on scoped enum members and tuple overloads * fix(typescript): address resolver and compiler conformance review Preserve shared overload implementation edges and exact literal member keys. Track reachable writes and namespace receiver types, honor inherited package mode, and scan shared overload bindings once. Extend compiler and graph controls for the outstanding literal, scope, and generic-parameter findings. * fix(typescript): verify module bindings and computed keys against runtime Restrict factory invalidation to reachable direct eval and preserve CommonJS wrapper binding order. Evaluate grouped numeric operands in property keys. Add runtime, compiler and scope controls. Update only the capture digests attributable to the awaited tuple marker. * fix(typescript): preserve native ESM exports around CommonJS references Use the module format to select explicit ESM exports in JavaScript and TypeScript. Check namespace keys and imported call targets against Node for .mjs, .mts, .js and .ts, with executable CommonJS controls. * fix(ingestion): preserve JavaScript and TypeScript binding identities Honor project nullability during overload selection and distinguish lexical loop callables. Preserve empty TypeScript method names and signatures through database publication. Track CommonJS wrapper identity across reassignment and grouping. Resolve JavaScript numeric property keys under the owning package format and refresh the affected index rows after a manifest change. * fix(ingestion): restore compiler-proven graph edges and CI parity Correct ESM package scope, CommonJS wrapper evaluation, strict class keys and TypeScript overload and field resolution. Share workspace discovery across providers in the same scan. Pin the verified graph changes to the exact benchmark inputs, preserve the measured performance limits, and cover the reported cases with compiler and runtime regressions. * fix(ingestion): validate package reads and TypeScript type evidence Read package manifests through the same validated descriptor. Preserve keyof precedence, cooked template overloads, and static computed method identities. Pin the compiler-confirmed graph changes to the frozen benchmark inputs. * fix(ingestion): resolve nullable inheritance and TypeScript overloads Preserve nullable generic override targets across C#, Kotlin and Dart. Match TypeScript overloads for loose object fields and inherited instance methods on union receivers. Share the verified parse-cache graph expectations across the two source revisions. * fix(ingestion): preserve narrowed call targets and generic overrides Carry prior instanceof exclusions through direct else-if chains and respect execution order for CommonJS wrapper writes. Match scoped C# reference and global-qualified generic signatures and Kotlin nullable generic arguments. Add compiler-backed regression cases and record the verified cache graph identity. * fix(ingestion): preserve constructed overrides and guard C++ defaults Retain the scoped identity and nested arguments of nullable C# and Dart overrides. Keep earlier C++ template parameters when parser recovery truncates a comparison in the last default. Add compiler-backed positive and negative controls. * fix(ingestion): resolve Map entries and qualified nullable overrides * ci: require both compiler checks for coverage reuse * test(bench): verify resolver graph on release corpus * fix(ingestion): preserve scoped call and override identities * fix(ingestion): preserve timer handles and inherited method targets Classify host timer registrations through lexical bindings. Preserve Vue inherited method selection and C++ digit-separated template arguments. Track Babel in the parse cache, skip unnecessary generic substitution work, and verify both frozen graph corpora. * fix(ingestion): preserve module exports and method return types Keep CommonJS wrapper-only exports out of native ES modules. Resolve TypeScript literal method returns by owner and preserve rooted nullable C# generic overrides. Record exact graph equivalence for both frozen corpora. * fix(ingestion): preserve receiver and override targets Separate TypeScript static and instance lookup and retain nullable C# and Kotlin override identity. Make conformance ordering and syntax scanning explicit. Both frozen cache corpora preserve all graph rows and duplicate counts. * test(java): load graph helpers in native Node Use the conformance comparator from a native ECMAScript module. The Java contract runner imports the TypeScript graph helper directly under Node 22. * fix(csharp): resolve named tuple overrides and repair CI checks Compare C# tuple element types and labels in declaration scope and select an eligible inherited method. Cover method arity, accessibility, return conversions and closed slots. Verify raw Git path bytes and preserve Node test registration. Both frozen graph corpora match on the new source trees. * fix(ingestion): preserve CLR override identities and C++ template defaults Resolve predefined C# types in their declaring scope and compare explicit ValueTuple and Nullable return types, including array variance and long tuples. Keep C++ comparison operators intact inside template parameter defaults. Preserve point and range coordinates in the lexical benchmark. Add compiler-backed regressions and record the verified graph equivalence. * fix(ingestion): resolve default classes and namespace aliases Preserve default-class ownership through parentheses and stop at nested anonymous classes. Keep existing CommonJS exports across unrelated property writes. Resolve ambient namespace aliases by public name and preserve type-only visibility. Document receiver filtering and add regression coverage. * fix(ingestion): preserve compiler-selected bindings Filter function-local namespace accesses. Preserve Node setImmediate handles and qualified verbatim C# names. Use each TypeScript project’s optional-property rules for overload selection and verify the resulting call and read edges against the compiler. * test(bench): record frozen graph equivalence Accept the verified source trees for the two existing frozen-corpus expectations. All 1,671,468 graph rows and their multiplicities matched across ten indexing runs; all 78 negative controls rejected altered evidence. * fix(ingestion): preserve template defaults and TypeScript call targets Recover complete C++ template defaults from verified parser spans and retain their source spelling. Resolve intrinsic Set tuple iteration and matching primitive method overloads across union receivers. Add compiler-backed positive and negative controls. * fix(ingestion): address SonarCloud findings in compiler conformance Simplify resolver and conformance code, preserve compiler-selected bindings, and distinguish C++ reference overloads in the graph lookup cache. Record graph equivalence for both frozen benchmark corpora. * refactor(ingestion): simplify four resolver functions Resolve the remaining four hosted SonarCloud complexity findings. Preserve class ownership, narrowing order, tsconfig file selection, and template parameter parsing. Record the matching graph fingerprints for both frozen corpora. --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
368 lines
14 KiB
JavaScript
368 lines
14 KiB
JavaScript
// Build both runtimes, then run with Node:
|
|
// measure.mjs BASE_RUNTIME CANDIDATE_RUNTIME BASE_CORPUS CANDIDATE_CORPUS OUTPUT [fresh|persistent] [PAIRS]
|
|
// Corpus checkouts must be clean/disposable and at the same commit. OUTPUT must not exist.
|
|
// For gate evidence, set GITNEXUS_LEXICAL_BENCH_SCREEN=0; PAIRS defaults to 9.
|
|
import assert from 'node:assert/strict';
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import os from 'node:os';
|
|
import { createHash } from 'node:crypto';
|
|
import { fork } from 'node:child_process';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { runBenchmarkTool } from '../lib/benchmark-tools.mjs';
|
|
import { checkoutFingerprint } from './corpus-fingerprint.mjs';
|
|
import { assertGraphParity } from './reference-migration.mjs';
|
|
const args = process.argv.slice(2);
|
|
assert(
|
|
args.length >= 5 && args.slice(0, 5).every((value) => value !== ''),
|
|
'Expected BASE_RUNTIME CANDIDATE_RUNTIME BASE_CORPUS CANDIDATE_CORPUS OUTPUT [fresh|persistent]',
|
|
);
|
|
const [baselineRuntime, candidateRuntime, baseline, candidate, output] = args
|
|
.slice(0, 5)
|
|
.map((value) => path.resolve(value));
|
|
const lifecycle = args[5] ?? 'fresh';
|
|
const pairs = Number(args[6] ?? 9);
|
|
assert(Number.isSafeInteger(pairs) && pairs > 0, 'Pairs must be a positive integer');
|
|
const workers = Number(process.env.GITNEXUS_LEXICAL_BENCH_WORKERS ?? 16);
|
|
const heapMiB = Number(process.env.GITNEXUS_LEXICAL_BENCH_HEAP_MIB ?? 8192);
|
|
const screenSetting = process.env.GITNEXUS_LEXICAL_BENCH_SCREEN ?? '1';
|
|
const baseFirstSetting = process.env.GITNEXUS_LEXICAL_BENCH_BASE_FIRST ?? '1';
|
|
assert(Number.isSafeInteger(workers) && workers > 0, 'Workers must be a positive integer');
|
|
assert(Number.isSafeInteger(heapMiB) && heapMiB > 0, 'Heap MiB must be a positive integer');
|
|
assert(['0', '1'].includes(screenSetting), 'Screen must be 0 or 1');
|
|
assert(['0', '1'].includes(baseFirstSetting), 'Base first must be 0 or 1');
|
|
const screen = screenSetting === '1';
|
|
const baseFirst = baseFirstSetting === '1';
|
|
assert(
|
|
['fresh', 'persistent'].includes(lifecycle),
|
|
`Lifecycle must be fresh or persistent; received ${JSON.stringify(lifecycle)}`,
|
|
);
|
|
assert.notEqual(baseline, candidate, 'BASE_CORPUS and CANDIDATE_CORPUS must differ');
|
|
const isWorker = process.env.GITNEXUS_LEXICAL_BENCH_WORKER === '1';
|
|
let runFullAnalysis, initLbug, executeQuery, closeLbug;
|
|
if (!isWorker) assert(!fs.existsSync(output), 'Output already exists');
|
|
const control = 'gitnexus/src/semantic-bench-control.ts';
|
|
const source =
|
|
'export class SemanticBenchStore { save(): void {} load(): void {} }\nexport function semanticBenchUse(s: SemanticBenchStore) { s.save(); }\n';
|
|
const head = (repo) =>
|
|
runBenchmarkTool('git', ['rev-parse', 'HEAD'], { cwd: repo, encoding: 'utf8' }).trim();
|
|
assert.equal(head(baseline), head(candidate));
|
|
for (const repo of isWorker ? [] : [baseline, candidate]) {
|
|
assert.equal(
|
|
runBenchmarkTool('git', ['status', '--porcelain'], { cwd: repo, encoding: 'utf8' }),
|
|
'',
|
|
'Checkout must be clean',
|
|
);
|
|
assert(!fs.existsSync(path.join(repo, control)));
|
|
}
|
|
// Keep the report field readable by existing performance checkers.
|
|
const corpusTrees = isWorker ? undefined : checkoutFingerprint(baseline);
|
|
if (!isWorker) {
|
|
assert.equal(checkoutFingerprint(candidate), corpusTrees, 'Materialized source corpora differ');
|
|
}
|
|
fs.mkdirSync(output, { recursive: true });
|
|
process.env.GITNEXUS_HOME = path.join(output, 'home');
|
|
process.env.GITNEXUS_STORAGE_ROOT = path.join(output, 'indexes');
|
|
delete process.env.GITNEXUS_STORAGE_PATH;
|
|
process.env.GITNEXUS_SHARED_STORE = 'off';
|
|
process.env.PROF_SCOPE_RESOLUTION = '1';
|
|
const records = [];
|
|
if (isWorker) {
|
|
const runtime = process.env.GITNEXUS_BENCH_RUNTIME;
|
|
({ runFullAnalysis } = await import(path.join(runtime, 'gitnexus/dist/core/run-analyze.js')));
|
|
({ initLbug, executeQuery, closeLbug } = await import(
|
|
path.join(runtime, 'gitnexus/dist/core/lbug/lbug-adapter.js')
|
|
));
|
|
const { configureLoggerSink } = await import(path.join(runtime, 'gitnexus/dist/core/logger.js'));
|
|
configureLoggerSink({
|
|
destination: {
|
|
write(line) {
|
|
try {
|
|
records.push(JSON.parse(line));
|
|
} catch {
|
|
/* non-JSON diagnostic */
|
|
}
|
|
process.stderr.write(line);
|
|
},
|
|
},
|
|
});
|
|
}
|
|
const results = [];
|
|
const graphParity = [];
|
|
function saveResults(repo) {
|
|
fs.writeFileSync(
|
|
path.join(output, 'results.json'),
|
|
JSON.stringify(
|
|
{
|
|
head: head(repo),
|
|
corpusTrees,
|
|
node: process.version,
|
|
lifecycle,
|
|
pairs,
|
|
workers,
|
|
heapMiB,
|
|
screen,
|
|
baseFirst,
|
|
baselineRuntime,
|
|
candidateRuntime,
|
|
results,
|
|
graphParity,
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
);
|
|
}
|
|
function verifyPair(before, after, repo) {
|
|
const receipt = assertGraphParity(before, after, repo, corpusTrees);
|
|
graphParity.push({ baselineName: before.name, candidateName: after.name, ...receipt });
|
|
saveResults(repo);
|
|
}
|
|
const canonical = (value) =>
|
|
Array.isArray(value)
|
|
? value.map(canonical)
|
|
: value && typeof value === 'object'
|
|
? Object.fromEntries(
|
|
Object.keys(value)
|
|
.sort()
|
|
.map((key) => [key, canonical(value[key])]),
|
|
)
|
|
: value;
|
|
const digest = (rows) => {
|
|
const hash = createHash('sha256');
|
|
for (const row of rows.sort()) hash.update(row).update('\n');
|
|
return { count: rows.length, sha256: hash.digest('hex') };
|
|
};
|
|
|
|
async function sample(repo, isCandidate, name) {
|
|
process.env.GITNEXUS_EXPERIMENTAL_SEMANTIC_CACHE = '0';
|
|
global.gc?.();
|
|
records.length = 0;
|
|
const logs = [];
|
|
const progress = [];
|
|
const loadBefore = os.loadavg();
|
|
const cpuBefore = process.cpuUsage();
|
|
const started = performance.now();
|
|
const result = await runFullAnalysis(
|
|
repo,
|
|
{
|
|
skipAgentsMd: true,
|
|
skipSkills: true,
|
|
workerPoolSize: workers,
|
|
verbose: true,
|
|
},
|
|
{
|
|
onProgress(phase, percent, message) {
|
|
if (progress.at(-1)?.phase !== phase)
|
|
progress.push({ ms: performance.now() - started, phase, percent, message });
|
|
},
|
|
onLog(message) {
|
|
logs.push(message);
|
|
},
|
|
},
|
|
);
|
|
const ms = performance.now() - started;
|
|
const cpu = process.cpuUsage(cpuBefore);
|
|
// Process-lifetime high-water mark captured before this sample's verification.
|
|
// In persistent mode earlier graph snapshot serialization can set it, so
|
|
// exclude persistent RSS from performance comparisons. It is not an interval
|
|
// peak or a memory delta.
|
|
const analysisPeakRssKiB = process.resourceUsage().maxRSS;
|
|
assert(!result.alreadyUpToDate, 'A no-op is not an edit benchmark');
|
|
assert(!result.graphWriteCollapsed);
|
|
assert(!result.ftsSkipped, 'This benchmark includes FTS');
|
|
const graph = result.pipelineResult.graph;
|
|
const nodes = [],
|
|
edges = [];
|
|
for (const node of graph.iterNodes()) {
|
|
// Derived clustering is stochastic; compare all source/semantic properties.
|
|
if (['Community', 'Process', 'Folder'].includes(node.label)) continue;
|
|
nodes.push(JSON.stringify(canonical(node)));
|
|
}
|
|
let controlCalls = 0;
|
|
for (const edge of graph.iterRelationships()) {
|
|
if (['MEMBER_OF', 'STEP_IN_PROCESS', 'CONTAINS'].includes(edge.type)) continue;
|
|
edges.push(JSON.stringify(canonical(edge)));
|
|
if (edge.type === 'CALLS' && edge.sourceId.includes('semanticBenchUse')) controlCalls++;
|
|
}
|
|
assert(controlCalls > 0, 'The changed call must resolve');
|
|
// The snapshot is collected after timing and overwritten for each variant.
|
|
// Digests remain the compact, stable benchmark receipt.
|
|
const graphRowsPath = path.join(
|
|
output,
|
|
isCandidate ? 'candidate-graph.json' : 'baseline-graph.json',
|
|
);
|
|
fs.writeFileSync(graphRowsPath, JSON.stringify({ nodes, edges }));
|
|
const expectedTarget = fs.readFileSync(path.join(repo, control), 'utf8').includes('s.load()')
|
|
? 'load'
|
|
: 'save';
|
|
let persistedTargets;
|
|
try {
|
|
await initLbug(path.join(result.storagePath, 'lbug'), { skipFts: true });
|
|
persistedTargets = await executeQuery(
|
|
"MATCH (a:Function)-[r:CodeRelation]->(b:Method) WHERE a.name = 'semanticBenchUse' AND r.type = 'CALLS' RETURN b.name AS target",
|
|
);
|
|
assert.deepEqual(
|
|
persistedTargets.map((row) => row.target),
|
|
[expectedTarget],
|
|
'Persisted call must follow the edit',
|
|
);
|
|
} finally {
|
|
await closeLbug();
|
|
}
|
|
const report = {
|
|
name,
|
|
variant: isCandidate ? 'candidate' : 'baseline',
|
|
ms,
|
|
cpuMs: (cpu.user + cpu.system) / 1000,
|
|
analysisPeakRssKiB,
|
|
rssInterpretation:
|
|
lifecycle === 'persistent'
|
|
? 'Process-lifetime peak can include earlier graph snapshot serialization; exclude from performance comparisons.'
|
|
: 'Process-lifetime peak before this sample graph verification.',
|
|
storagePath: result.storagePath,
|
|
loadBefore,
|
|
loadAfter: os.loadavg(),
|
|
maxRssKiB: process.resourceUsage().maxRSS,
|
|
stats: result.stats,
|
|
incremental: result.incrementalStats,
|
|
rebuildReasons: result.rebuildReasons,
|
|
reparsedFiles: result.pipelineResult.reparsedFileCount,
|
|
cachedFiles: result.pipelineResult.parseCacheHitFileCount,
|
|
graph: { nodes: digest(nodes), edges: digest(edges) },
|
|
graphRowsPath,
|
|
logs,
|
|
progress,
|
|
persistedTargets,
|
|
records: [...records],
|
|
};
|
|
console.log(
|
|
'LEXICAL_BENCH ' +
|
|
JSON.stringify({ name, ms, incremental: report.incremental, graph: report.graph }),
|
|
);
|
|
return report;
|
|
}
|
|
|
|
// Separate runtimes isolate implementation and JIT state. Fresh mode exits
|
|
// after every sample; persistent mode retains a process across real edits.
|
|
function worker(repo, isCandidate) {
|
|
let child, pending, exited;
|
|
const start = () => {
|
|
child = fork(fileURLToPath(import.meta.url), process.argv.slice(2), {
|
|
execArgv: [`--max-old-space-size=${heapMiB}`, '--expose-gc'],
|
|
env: {
|
|
...process.env,
|
|
GITNEXUS_LEXICAL_BENCH_WORKER: '1',
|
|
GITNEXUS_BENCH_RUNTIME: isCandidate ? candidateRuntime : baselineRuntime,
|
|
},
|
|
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
|
});
|
|
exited = new Promise((resolve) => child.once('exit', resolve));
|
|
child.on('message', (message) => {
|
|
const current = pending;
|
|
pending = undefined;
|
|
if (message.error) current?.reject(new Error(message.error));
|
|
else current?.resolve(message.report);
|
|
});
|
|
child.on('error', (error) => pending?.reject(error));
|
|
child.on('exit', (code) => pending?.reject(new Error(`Benchmark worker exited: ${code}`)));
|
|
};
|
|
const close = async () => {
|
|
if (!child) return;
|
|
if (child.connected) child.disconnect();
|
|
const code = await exited;
|
|
child = undefined;
|
|
assert.equal(code, 0, 'Worker must exit normally after analysis');
|
|
};
|
|
return {
|
|
async run(name) {
|
|
assert(!pending, 'Samples must run serially');
|
|
if (!child) start();
|
|
const report = await new Promise((resolve, reject) => {
|
|
pending = { resolve, reject };
|
|
child.send({ repo, reuse: isCandidate, name });
|
|
});
|
|
results.push(report);
|
|
saveResults(repo);
|
|
if (lifecycle === 'fresh') await close();
|
|
return report;
|
|
},
|
|
close,
|
|
};
|
|
}
|
|
|
|
if (isWorker) {
|
|
process.on('message', async ({ repo, reuse: isCandidate, name }) => {
|
|
try {
|
|
process.send({ report: await sample(repo, isCandidate, name) });
|
|
} catch (error) {
|
|
process.send({ error: error.stack ?? String(error) });
|
|
}
|
|
});
|
|
} else {
|
|
const beforeWorker = worker(baseline, false);
|
|
const afterWorker = worker(candidate, true);
|
|
try {
|
|
for (const repo of [baseline, candidate]) {
|
|
fs.mkdirSync(path.dirname(path.join(repo, control)), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, control), source);
|
|
}
|
|
let beforeSeed, afterSeed;
|
|
if (baseFirst) {
|
|
beforeSeed = await beforeWorker.run('baseline-seed');
|
|
afterSeed = await afterWorker.run('candidate-seed');
|
|
} else {
|
|
afterSeed = await afterWorker.run('candidate-seed');
|
|
beforeSeed = await beforeWorker.run('baseline-seed');
|
|
}
|
|
verifyPair(beforeSeed, afterSeed, candidate);
|
|
for (let pair = 1; pair <= pairs; pair++) {
|
|
const text = pair % 2 ? source.replace('s.save()', 's.load()') : source;
|
|
for (const repo of [baseline, candidate]) fs.writeFileSync(path.join(repo, control), text);
|
|
// Alternate ordering to reduce warm-up/load bias. Both indexes see a real edit.
|
|
let before, after;
|
|
if (Boolean(pair % 2) === baseFirst) {
|
|
before = await beforeWorker.run(`baseline-${pair}`);
|
|
after = await afterWorker.run(`candidate-${pair}`);
|
|
} else {
|
|
after = await afterWorker.run(`candidate-${pair}`);
|
|
before = await beforeWorker.run(`baseline-${pair}`);
|
|
}
|
|
verifyPair(before, after, candidate);
|
|
// The seed established a compact baseline; this tiny cached edit must
|
|
// exercise the selective path. Periodic compaction is covered separately.
|
|
if (pair === 1) {
|
|
assert.equal(
|
|
after.incremental?.writeMode,
|
|
'incremental',
|
|
'First cached edit must stay selective',
|
|
);
|
|
}
|
|
for (const entry of [before, after]) {
|
|
// Cached one-file edits may use row writes in an older baseline or a
|
|
// compact full COPY in a newer runtime (#3852). Both are timed in full.
|
|
assert(
|
|
['incremental', 'full'].includes(entry.incremental?.writeMode),
|
|
'Invalid physical write mode for a cached edit',
|
|
);
|
|
assert.equal(entry.incremental?.changedFiles, 1);
|
|
// A compact COPY is reported as a non-forcing write-plan change;
|
|
// cache/schema invalidations must still be absent from measured edits.
|
|
assert.deepEqual(
|
|
entry.rebuildReasons.filter(
|
|
(reason) => entry.incremental.writeMode !== 'full' || reason !== 'escalated-full-write',
|
|
),
|
|
[],
|
|
);
|
|
}
|
|
if (screen && pair === 1 && after.ms >= before.ms) {
|
|
console.log('SCREEN REJECTED: no end-to-end improvement; stopping after one pair.');
|
|
break;
|
|
}
|
|
}
|
|
} finally {
|
|
const closed = await Promise.allSettled([beforeWorker.close(), afterWorker.close()]);
|
|
for (const repo of [baseline, candidate]) fs.rmSync(path.join(repo, control), { force: true });
|
|
for (const result of closed) if (result.status === 'rejected') throw result.reason;
|
|
}
|
|
}
|