mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* perf(ruby): classify every bare read of a file in one walk (RUBY-04)
`rubyBareNameIsLocalRead` climbed from each bare identifier through every
enclosing block to its method, so a nest where each of D levels reads
the method's parameter cost O(D^2) tree steps. At 128 methods x depth
64 the climb was about 60% of the Ruby capture pass.
The first call for a file now walks the tree once and carries, per name,
a stack of the earliest position the open scope chain binds it at; a
closed scope (method, class, module, program) starts a new chain. Each
read is one peek. The walk follows the connections the climb followed:
a closed scope's header expressions are visited in the enclosing chain,
and a heredoc body is visited at its opener, so the verdicts are
unchanged (the scope-capture Ruby fingerprint and every Ruby pin are
the same). The heredoc layout's body -> opener map is no longer used.
The new unit test counts SyntaxNode navigation steps while every read
of a depth-16 and a depth-64 nest is classified: 623 -> 7079 (x11.36)
on main, 484 -> 1876 (x3.88) here, for one name read at every level
and for a different unbound name at every level.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* fix(ruby): a call's callable-flow arguments are its own argument list
The shared callable-flow pass reads a call's arguments from its argument
list and, when the call has none, searched the call's whole subtree for
one. A Ruby call that takes only a block (`run_with do ... end`,
`items.each { ... }`) has no list of its own, so the search entered the
block and took the first nested call's list: `run_with do helper(cb)
end` recorded `cb` as `run_with`'s argument 0, and `[1].each do |i|
helper(cb) end` recorded it as `each`'s. The search also cost O(block
size) per call, O(depth^2) over a nest of blocks: with the bare-read
walk in place it was most of the remaining capture time at depth 64.
Ruby now supplies `extractCallArguments`: a call without an `arguments`
field passes nothing; one with it takes the generic path unchanged. The
scope-capture Ruby fingerprint is unchanged (no fixture had the shape).
Fails on main: `expected [ 'helper(0)=cb', 'run_with(0)=cb' ] to deeply
equal [ 'helper(0)=cb' ]`, and the whole-capture-pass step count over a
depth-16 vs depth-64 nest grows 4522 -> 50194 (x11.10) on main, 4383 ->
44991 (x10.26) with the bare-read walk alone, 1871 -> 7295 (x3.90) here.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* perf(ruby): pair heredoc bodies with their openers in one pass (RUBY-04)
The heredoc layout paired each body with its opener by walking the
body's run of sibling bodies both ways and searching the opener line for
`heredoc_beginning` nodes, once per body: O(H) per body, O(H^2) for a
line that opens H heredocs. It now builds the runs in one pass (each
body joins its previous sibling's run) and finds each run's openers in
the line's openers, grouped by row once, by binary search. The pairing
rule is unchanged: a run is paired only when the line has exactly as
many openers ending before it as the run has bodies.
The cost test's new case counts tree steps over the whole capture pass
for a line opening 32 and 128 heredocs: 12126 -> 72702 (x6.00) before,
10046 -> 39806 (x3.96) here.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* test(bench): ruby-bare-reads — fixed-width indent, input bytes per cell, depth gated over 4 -> 64
The scaling-bench review's three defects all applied here:
- the blocks generator indented each level two spaces deeper, so the
input grew 47x over depth 4 -> 64; every line now has a fixed-width
indent, and each shape pins its input_bytes beside its capture groups
and relationships;
- depth was gated over 4 -> 16, where the O(depth^2) per-read climb
measured 1.222 and passed (it was the shipped code). Capture is now
gated at 1.5 over the full range 4 -> 64 (the ratio divides by each
shape's own growth, 16x here). Restoring the per-read climb fails it at
3.872, and restoring the callable-flow subtree search fails it at
1.792, both with unchanged fingerprints;
- the heredoc pairing term is invisible to timing at CI sizes, so its
guard is the operation-count unit test.
Resolution along depth is reported, not gated: the captures are the
same as on main, and the in-process ratio over 4 -> 64 measured
0.94-1.54 over seven runs (a 16 ms denominator, plus the shared lexical
lookup climbing from each reference to its binder). baseline.json
`_depth_note` records the fresh-process sweep for both phases.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* perf(callable-flow): stop re-searching a function-literal argument for every call nested in it
`emitCallFacts` reads every call argument through `operandSyntax`. Dart's
`argument`, Kotlin's `value_argument`, C#'s `argument` and PHP's `argument`
wrap a function literal, so the operand is not a function node and the
search went on: `terminalIdentifier` walked the literal's body for its last
identifier and `hasMultipleIdentifierLeaves` walked it again for a second
one. The argument is then dropped, because a wrapped literal is no
designator. A call nested k levels deep searched the k levels below it, so a
nest cost O(depth^2): at depth 64 the search visited 31,728 more nodes than
at depth 16, against 1,704 more from depth 8 to 16.
Two changes, both on the default path (no language option involved):
- `terminalIdentifier` depends on a node's subtree alone, so on the argument
path it is memoized per file (node id -> identifier or null). An outer
argument's search answers every argument nested inside it.
- An argument whose node text holds a bracket can be a designator only when
that text is its terminal identifier's: a qualified designator has no
bracket, and a single name is its own text. When they differ, the argument
is returned as dropped before the second-leaf search. Indirection,
address-of and identifier-typed nodes keep the full computation.
Output is byte-identical: all 17 scope-capture fingerprints match their
baselines. Dropping the bracket condition from the early return (a wrong
early exit) drifts c, cpp, swift, java and typescript, so the fingerprint
gate catches that class of mistake.
A test hook counts the subtree nodes the operand search enters. The new test
asserts linear growth over nests of 8, 16 and 64 for Dart, Kotlin, C# and
PHP; on the old search it fails for all four:
expected 31728 to be less than or equal to 10224 (Dart)
expected 23856 to be less than or equal to 7728 (Kotlin, C#)
expected 24048 to be less than or equal to 7920 (PHP)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* perf(worker): climb to the enclosing function once per ancestor, with parents from an index
Two climbs in the parse worker run from every call or reference to its
enclosing named function and pass every anonymous closure on the way:
`findEnclosingFunctionId` (parse-worker, once per call) and
`findEnclosingScopeKey` (type-env, once per receiver lookup). Each step read
`parent`, which re-descends from the root in node-tree-sitter (about 150 ns
per AST level), so a lookup k levels deep cost k steps of depth each. In a
file of closures nested 48 deep they took 8.1 s each of the worker's 17.9 s
at 64 functions, and at 256 functions the worker exceeded the pool's idle
timeout and quarantined the file: no nodes, no edges, missing context for
every consumer.
Both now go through `climbAncestors` (utils/ancestor-climb.ts):
- parents come from one downward pass over the tree's named nodes, made the
first time a climb on that tree asks (`indexedParent`);
- the answer is recorded for every ancestor a climb examined, by node id, in
one map per question per file (`functionIdAtAncestor`, cleared with the
worker's other per-file caches; one map per `buildTypeEnv`). The answer at
an ancestor depends only on that ancestor and the ones above it, so the
next climb that reaches it stops there.
The per-ancestor rules are unchanged; parse-worker's loop body moved into
`enclosingFunctionIdAt` (whitespace-only re-indent apart from the returns).
Output is unchanged: all 17 scope-capture fingerprints match, and the
closure-binder bench's shape cells and fingerprints match through the worker.
A test hook counts climb steps and native parent reads. The new test drives
type-env's lookups through `buildTypeEnv(...).lookup` and the parse-worker's
stop rule through `climbAncestors` (parse-worker.ts posts to `parentPort` on
import, so a test cannot load it), and checks a memoised answer equals a
fresh climb for every call. With the helper set back to main's behaviour
(native parent reads, no memo) both depth tests fail:
`expected 19488 to be less than or equal to 6048`.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* perf(dart): complete closure scaling fixes
Index native tree navigation and cache empty-scope lookups during
read-only resolution passes. Retain the existing callable-flow memo
and bound added lookup-cache memory by scope count.
Guard function count and closure depth over geometric 16x sweeps,
with exact output checks and deterministic work limits that reject
repeated ancestor walks and full-scope scans.
Refs #3920, #3912, #3903
* refactor(bench): simplify scaling validation
Compare target multiplicities with frequency maps while preserving
missing and unexpected edge counts. Keep one prepared workload record
and rely on the existing per-measurement counter reset.
Refs #3920
* perf(dart): port remaining closure walk fixes
Reuse the tree index for enclosing types of named closures and cache
static-token checks per parent. Port the deep-worker regression and
count native AST navigation in the cost tests.
Refs #3917
Co-authored-by: Abhinav Pandey <abhinavpandey1230@gmail.com>
* fix: address scaling review feedback (#3920)
Native parent reads cost depth. Reuse indexed links and reject
names absent from value channels before walking scopes. Keep
operand search iterative and pin bound-closure work without
raising benchmark budgets.
* test: guard optional Kotlin grammar (#3920)
Correct the Ruby benchmark's restored depth-gate description.
Note: pre-existing failures not addressed by this PR:
- test/integration/setup-skills.test.ts
- test/unit/setup.test.ts
- test/unit/scenario-map/consolidation.test.ts
* fix(ci): allow serial benchmarks to finish
The PR #3920 runner spent 27 minutes on passing guards before the final benchmark suite started, exhausting the 30-minute job limit. A prior run completed in 22 minutes; unchanged guard timings grew about 50% on the slower runner.
Allow 45 minutes for the serial workload and its execution receipt. Keep every benchmark command, performance budget, and completeness gate unchanged.
* refactor: simplify ingestion and exact checks
Reuse Dart's enclosing-type index and flatten worker property routing.
Preserve regression coverage with exact counts and toBe assertions.
Refs #3920
* fix: address follow-up review of the scaling changes (#3920)
- ancestor climb: build the parent index on accumulated native reads only
when the node is deep, so a flat file of shallow climbs keeps native
parents; counters are opt-in for tests.
- type-env: restore the plain enclosing-scope loop. TypeEnv.lookup has no
production caller, so its memo and count tests guarded a test-only path.
- worker: drop the callExtractor truthiness guard and the uncalled
extractCallArgTypes helper.
- name-lookup cache: the class-skipping bypass lives in
cachedNameLookupStart, shared by both callers.
- tests: the reference pass must see a binding its recorder writes between
sites; pin the cache entry cap; replace branches in test bodies with
table data.
- Dart gate: count sibling getters and require them flat across the
closure sweep; measure a timing-only failure a second time before
failing; record the bound-shape figure in the normalization note.
- comments: Ruby call-argument hook scope, CI step text.
Refs #3920
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* fix(analyze): admit the default heap limit as a ceiling when the autopilot is off
With GITNEXUS_MEMORY=off and no --max-old-space-size, analyze passed V8's
own default heap limit (about 4144 MiB) to admission as an explicit main
heap. Admission reserves that amount for the main process and again for
each required worker, so the default command needed about
2 x 4144 + 3307 + supervisor MiB against a budget of 75% of RAM and
refused to start on any host below about 15.8 GiB:
Resource budget 11775 MiB cannot admit parser/model work; requires at
least 11820 MiB for these allocations.
Hosted CI runners that report 15,700 MiB hit this in the MCP query
benchmark, whose harness sets GITNEXUS_MEMORY=off; runners reporting
about 15,990 MiB passed.
A heap the operator pinned with --max-old-space-size is still an explicit
reservation and is still rejected when it does not fit. An unpinned
default limit is now a ceiling (mainHeapLimitMb): the automatic main heap
never exceeds it and may be admitted below it. Hosts where the limit
already fit get the same reservation as before.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* test(mcp): build the benchmark indexes with an explicit heap
The MCP query benchmark indexes its fixture with GITNEXUS_MEMORY=off and
no heap setting, so whether the index step starts depended on the runner:
a runtime that reserves V8's default heap limit refuses hosts reporting
under about 15.8 GiB. Hosted runners come in two sizes. Runs on Intel
Xeon 6975P-C machines (15,701.6 MiB) failed before any round ran; runs on
machines reporting 15,983 MiB passed with the same baseline commit.
The baseline runtime is built from the PR's base commit, so fixing the
runtime alone cannot make this job pass on the PR that carries the fix.
Indexing is setup, outside the timing window: pass --memory-budget 1024
to both runtimes so admission no longer depends on host RAM or on the
runtime's default heap policy. The measured MCP requests are unchanged.
Checked with an unfixed main build as baseline: the index command fails
on a simulated 15,700 MiB host without the flag and succeeds with it, and
the full --check run passes locally (8 process pairs x 5 rounds).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* perf(java): find assignment write targets in one search, not one parent read per member
emitJavaScopeCaptures asked every field_access for its native parent to
skip a member that an assignment writes. A native parent read costs the
node's depth, so a left-deep chain of N member reads paid N reads of
depth up to N. That is the java-deep-chain case of the scope-capture
gate, which measured 1.42 to 1.58 against its 1.5 budget on main and on
this branch.
Collect the ids of every assignment's left operand in one native
descendantsOfType search and look members up in that set. On the gate's
workload native parent reads drop from N + 17 to 17, the 800-operand
capture from 41.8 ms to 22.4 ms, and the scaling ratio to 0.97. All 17
capture fingerprints are unchanged.
Refs #3920
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
505 lines
19 KiB
JavaScript
505 lines
19 KiB
JavaScript
/**
|
|
* Ruby bare-read correctness and scaling gate (#3880, RUBY-04).
|
|
*
|
|
* A bare identifier that names a parameter or a local in scope is a read, not
|
|
* a call. The capture pass classifies every bare identifier of a file in one
|
|
* walk that carries the open scope chain's bindings down the tree
|
|
* (`rubyBoundReadIds`); a heredoc body is read at its opener, and bodies are
|
|
* paired with openers in one pass (`rubyHeredocOpeners`). This gate pins what
|
|
* that produces and gates capture and resolution growth in methods, block
|
|
* depth, heredocs per opener line and reads per heredoc body. Every normalized
|
|
* scaling ratio has a 1.5 budget in baseline.json.
|
|
*
|
|
* Workload: N files `lib/host<i>.rb`, each holding class `Host<i>` that
|
|
* declares `target`, `helper` and `other(*args)` plus the method under test.
|
|
* One class per file: on main, Ruby resolution is already super-linear in the
|
|
* number of classes or methods in ONE file, which would mask this change.
|
|
* `--shape crowded <methods> <depth>` (sweeps only, not gated) is the `blocks`
|
|
* form with every class in one file, to measure that term. Two forms:
|
|
* - `blocks`: `m(target)` calls `helper`, then nests K
|
|
* `[1].each do |x<j>|` blocks, each reading `target` bare. Every read sees
|
|
* the parameter: no edge. `helper` binds nothing and stays a call.
|
|
* - `heredocs`: `h(target)` opens H heredocs on one line,
|
|
* `other(<<~A0, <<~A1, …)`, each body holding R `#{[1].map do target end}`
|
|
* reads that see the parameter: no edge. A second method `e(x)` keeps the
|
|
* exact opener rule: `other(<<~EOS, target = 1)` binds `target` after the
|
|
* body, so the body's bare `target` is still a call.
|
|
* Each method's CALLS edges must equal the expected multiset exactly.
|
|
*
|
|
* Every line has a fixed-width indent, so a cell's source grows linearly in
|
|
* each size parameter (`input_bytes` is pinned per shape, beside the capture
|
|
* groups and relationships it produces).
|
|
*
|
|
* Shapes, with the dimension each one grows over `small`:
|
|
* - blocks: small 128 methods x depth 4; methods 512 x 4 (4x); depth
|
|
* 128 x 64 (16x: a per-read climb to the method costs O(depth), and a
|
|
* short depth range hides that behind per-file overhead).
|
|
* - heredocs: small 64 methods x 2 heredocs x 2 reads; methods 256 x 2 x 2;
|
|
* per_line 64 x 8 x 2; size 64 x 2 x 8 (4x each). Pairing bodies with
|
|
* openers was O(H^2) per line; at CI sizes that term is invisible to a
|
|
* timing ratio even over 16x, so the operation-count unit test
|
|
* (ruby-bare-read-cost.test.ts) is its guard.
|
|
* A scaling ratio is (t_shape / t_small) / growth: about 1 is linear.
|
|
* Two profiles. Default (CI, also with --check): one process prepares every
|
|
* workload, runs every accuracy gate, and times every workload interleaved
|
|
* (each round times each workload once, in rotating order), min of 5 after 1
|
|
* warmup. `--full`: one child times every workload, min of 15 after 2 warmups
|
|
* (the estimator of bench/ruby-gem-resolution), and each shape's accuracy
|
|
* cells and peak RSS come from a fresh child process (`--shape`). Phases:
|
|
* - capture_ms: emitRubyScopeCaptures over every file. Build-free.
|
|
* - resolve_ms: runScopeResolution over worker-extracted files. The corpus is
|
|
* parsed once through the real parse worker, so this needs dist/. Each
|
|
* timed pass replays a structured clone of the worker output through
|
|
* mergeChunkResults into a fresh graph and model, outside the timer.
|
|
*
|
|
* `--shape <form> <methods> <k> [<r>] --reps R --warmup W` also times that one
|
|
* workload in its own process, for size sweeps.
|
|
*
|
|
* node --import tsx bench/ruby-bare-reads/measure.mjs [--check] [--full]
|
|
*/
|
|
import assert from 'node:assert/strict';
|
|
import { spawnSync } from 'node:child_process';
|
|
import crypto from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { emitRubyScopeCaptures } from '../../src/core/ingestion/languages/ruby/index.ts';
|
|
import { rubyScopeResolver } from '../../src/core/ingestion/languages/ruby/scope-resolver.ts';
|
|
import { runScopeResolution } from '../../src/core/ingestion/scope-resolution/pipeline/run.ts';
|
|
import { mergeChunkResults, processParsing } from '../../src/core/ingestion/parsing-processor.ts';
|
|
import { createKnowledgeGraph } from '../../src/core/graph/graph.ts';
|
|
import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.ts';
|
|
import { generateId } from '../../src/lib/utils.ts';
|
|
import { createWorkerPool } from '../../src/core/ingestion/workers/worker-pool.ts';
|
|
import { DIST_WORKER_URL } from '../../test/helpers/worker-parse.ts';
|
|
|
|
const script = fileURLToPath(import.meta.url);
|
|
const baselinePath = fileURLToPath(new URL('./baseline.json', import.meta.url));
|
|
const CHECK = process.argv.includes('--check');
|
|
// Two profiles. The default (CI, also under --check) prepares every workload,
|
|
// runs every accuracy gate and times every workload, min of 5 after 1 warmup,
|
|
// in this one process. `--full` times them in one child, min of 15 after 2
|
|
// warmups, and takes each shape's accuracy cells and peak RSS from a fresh
|
|
// process per shape.
|
|
const FULL = process.argv.includes('--full');
|
|
const WARMUP = FULL ? 2 : 1;
|
|
const REPS = FULL ? 15 : 5;
|
|
const MARKER = 'RUBY_BARE_READ_RESULT ';
|
|
const FORMS = ['blocks', 'heredocs'];
|
|
/** Per form: shape name -> size parameters; every non-small shape grows one. */
|
|
const SHAPES = {
|
|
blocks: { small: [128, 4], methods: [512, 4], depth: [128, 64] },
|
|
heredocs: { small: [64, 2, 2], methods: [256, 2, 2], per_line: [64, 8, 2], size: [64, 2, 8] },
|
|
};
|
|
const roots = [];
|
|
/** One parse worker for every workload in this process. */
|
|
let pool;
|
|
|
|
/** Where class `Host<i>` lives: its own file, or one shared file (`crowded`). */
|
|
const hostFile = (form, i) => (form === 'crowded' ? 'lib/host.rb' : `lib/host${i}.rb`);
|
|
|
|
function corpus(form, methods, k, r = 0) {
|
|
const helpers = ' def target; end\n def helper; end\n def other(*args); end\n';
|
|
const files = new Map();
|
|
for (let i = 0; i < methods; i++) {
|
|
let source = `class Host${i}\n${helpers}`;
|
|
if (form !== 'heredocs') {
|
|
// Fixed-width indent: the source grows linearly in k, not in k^2.
|
|
source += '\n def m(target)\n helper\n';
|
|
for (let j = 0; j < k; j++) source += ` [1].each do |x${j}|\n target\n`;
|
|
for (let j = 0; j < k; j++) source += ' end\n';
|
|
source += ' end\n';
|
|
} else {
|
|
const read = ' #{[1].map do\n target\n end}\n';
|
|
const openers = Array.from({ length: k }, (_, j) => `<<~A${j}`).join(', ');
|
|
source += `\n def h(target)\n other(${openers})\n`;
|
|
for (let j = 0; j < k; j++) source += read.repeat(r) + ` A${j}\n`;
|
|
source += ' end\n';
|
|
source += `\n def e(x)\n other(<<~EOS, target = 1)\n${read} EOS\n end\n`;
|
|
}
|
|
source += 'end\n';
|
|
const file = hostFile(form, i);
|
|
files.set(file, files.has(file) ? `${files.get(file)}\n${source}` : source);
|
|
}
|
|
return [...files].map(([path, content]) => ({ path, content }));
|
|
}
|
|
|
|
/** The CALLS targets each tested method of class `Host<i>` must produce. */
|
|
function expectedTargets(form, i) {
|
|
// Arity suffixes (`#0`) are dropped: `other(*args)` carries none.
|
|
const at = (name) => `Method:${hostFile(form, i)}:Host${i}.${name}`;
|
|
if (form !== 'heredocs') return { m: [at('helper')] };
|
|
return { h: [at('other')], e: [at('other'), at('target')].sort() };
|
|
}
|
|
|
|
function addFileNodes(graph, files) {
|
|
// Structure processing creates these before parsing in the real pipeline.
|
|
for (const file of files) {
|
|
graph.addNode({
|
|
id: generateId('File', file.path),
|
|
label: 'File',
|
|
properties: { name: path.basename(file.path), filePath: file.path },
|
|
});
|
|
}
|
|
}
|
|
|
|
function resolve(files, config, parsed) {
|
|
const preExtractedParsedFiles = new Map(parsed.data.parsedFiles.map((f) => [f.filePath, f]));
|
|
const start = performance.now();
|
|
const stats = runScopeResolution(
|
|
{
|
|
graph: parsed.graph,
|
|
model: parsed.model,
|
|
files,
|
|
resolutionConfig: config,
|
|
preExtractedParsedFiles,
|
|
},
|
|
rubyScopeResolver,
|
|
);
|
|
return { ms: performance.now() - start, stats };
|
|
}
|
|
|
|
function replay(files, raw) {
|
|
const graph = createKnowledgeGraph();
|
|
const model = createSemanticModel();
|
|
const data = mergeChunkResults(graph, model.symbols, structuredClone(raw));
|
|
addFileNodes(graph, files);
|
|
return { graph, model, data };
|
|
}
|
|
|
|
/** Bytes of source in one workload: the input the size parameters grow. */
|
|
const inputBytes = (files) => files.reduce((n, f) => n + Buffer.byteLength(f.content), 0);
|
|
|
|
function correctness(form, files, sizes, graph, stats, captureGroups) {
|
|
const methods = sizes[0];
|
|
const edges = [];
|
|
const callsBySource = new Map();
|
|
let calls = 0;
|
|
for (const edge of graph.iterRelationships()) {
|
|
edges.push(
|
|
JSON.stringify([edge.sourceId, edge.targetId, edge.type, edge.confidence, edge.reason]),
|
|
);
|
|
const method = /^Method:lib\/host\d*\.rb:Host(\d+)\.([meh])#/.exec(edge.sourceId);
|
|
if (edge.type !== 'CALLS' || method === null) continue;
|
|
calls++;
|
|
const key = `${method[2]}${method[1]}`;
|
|
const list = callsBySource.get(key) ?? [];
|
|
list.push(edge.targetId.replace(/#\d+$/, ''));
|
|
callsBySource.set(key, list);
|
|
}
|
|
let missing = 0;
|
|
let unexpected = 0;
|
|
for (let i = 0; i < methods; i++) {
|
|
for (const [prefix, expected] of Object.entries(expectedTargets(form, i))) {
|
|
const remaining = new Map();
|
|
for (const target of expected) {
|
|
remaining.set(target, (remaining.get(target) ?? 0) + 1);
|
|
}
|
|
missing += expected.length;
|
|
for (const target of callsBySource.get(`${prefix}${i}`) ?? []) {
|
|
const count = remaining.get(target) ?? 0;
|
|
if (count === 0) unexpected++;
|
|
else {
|
|
remaining.set(target, count - 1);
|
|
missing--;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
const declines = {};
|
|
const outcomes = [];
|
|
for (const outcome of stats.resolutionOutcomes) {
|
|
if (outcome.kind === 'resolved') continue;
|
|
const key = outcome.declineDetail
|
|
? `${outcome.reason}/${outcome.declineDetail}`
|
|
: outcome.reason;
|
|
declines[key] = (declines[key] ?? 0) + 1;
|
|
const r = outcome.range;
|
|
outcomes.push(`${key}|${outcome.filePath}|${outcome.name}|${r.startLine}:${r.startCol}`);
|
|
}
|
|
return {
|
|
methods,
|
|
sizes,
|
|
input_bytes: inputBytes(files),
|
|
capture_groups: captureGroups,
|
|
relationships: graph.relationshipCount,
|
|
calls,
|
|
declines,
|
|
expected_missing: missing,
|
|
unexpected_edges: unexpected,
|
|
fingerprint: crypto
|
|
.createHash('sha256')
|
|
.update([...edges.sort(), ...outcomes.sort()].join('\n'))
|
|
.digest('hex'),
|
|
};
|
|
}
|
|
|
|
/** Write, parse once through the worker, and resolve once. */
|
|
async function prepare(form, sizes) {
|
|
const files = corpus(form, ...sizes);
|
|
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-ruby-bare-read-bench-'));
|
|
roots.push(root);
|
|
for (const file of files) {
|
|
fs.mkdirSync(path.dirname(path.join(root, file.path)), { recursive: true });
|
|
fs.writeFileSync(path.join(root, file.path), file.content);
|
|
}
|
|
// The real manifest loader, once; it is not what is timed.
|
|
const config = await rubyScopeResolver.loadResolutionConfig(root);
|
|
const raw = [];
|
|
const parsed = await parse(files, raw);
|
|
addFileNodes(parsed.graph, files);
|
|
const first = resolve(files, config, parsed);
|
|
return { files, config, raw, parsed, first };
|
|
}
|
|
|
|
/** Worker parse through the process's one pool (the real parse worker, dist/). */
|
|
async function parse(files, raw) {
|
|
pool ??= createWorkerPool(DIST_WORKER_URL, 1);
|
|
const graph = createKnowledgeGraph();
|
|
const model = createSemanticModel();
|
|
const data = await processParsing(graph, files, model.symbols, pool, undefined, raw);
|
|
return { graph, model, data };
|
|
}
|
|
|
|
function captureGroups(files) {
|
|
let groups = 0;
|
|
for (const file of files) groups += emitRubyScopeCaptures(file.content, file.path).length;
|
|
return groups;
|
|
}
|
|
|
|
/** Times capture and resolution of each input, interleaved; min of `reps`. */
|
|
function timeInputs(inputs, warmup, reps) {
|
|
const names = Object.keys(inputs);
|
|
for (const input of Object.values(inputs)) {
|
|
input.capture = [];
|
|
input.resolution = [];
|
|
}
|
|
for (let run = 0; run < warmup + reps; run++) {
|
|
for (let k = 0; k < names.length; k++) {
|
|
const input = inputs[names[(k + run) % names.length]];
|
|
const start = performance.now();
|
|
const groups = captureGroups(input.files);
|
|
const captureMs = performance.now() - start;
|
|
input.groups ??= groups;
|
|
assert.equal(groups, input.groups, 'capture pass must be the same work');
|
|
const pass = replay(input.files, input.raw);
|
|
const { ms } = resolve(input.files, input.config, pass);
|
|
assert.equal(
|
|
pass.graph.relationshipCount,
|
|
input.relationships,
|
|
'timed pass must do the validated work',
|
|
);
|
|
if (run >= warmup) {
|
|
input.capture.push(captureMs);
|
|
input.resolution.push(ms);
|
|
}
|
|
}
|
|
}
|
|
const timings = {};
|
|
for (const name of names) {
|
|
// Like the neighbouring resolver gates: min-of-N limits scheduler/GC noise.
|
|
timings[name] = {
|
|
capture_ms: Math.min(...inputs[name].capture),
|
|
resolve_ms: Math.min(...inputs[name].resolution),
|
|
relationships: inputs[name].relationships,
|
|
};
|
|
}
|
|
return timings;
|
|
}
|
|
|
|
/** One workload in a fresh process: the accuracy cells and its own peak RSS. */
|
|
async function measureShape(form, sizes, reps, warmup) {
|
|
const input = await prepare(form, sizes);
|
|
// Through one worker parse (thread included) and one resolution.
|
|
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
|
const groups = captureGroups(input.files);
|
|
const shape = correctness(
|
|
form,
|
|
input.files,
|
|
sizes,
|
|
input.parsed.graph,
|
|
input.first.stats,
|
|
groups,
|
|
);
|
|
const result = { shape, peak_rss_mib: peakRssMiB };
|
|
if (reps > 0) {
|
|
const timing = timeInputs(
|
|
{ one: { ...input, groups, relationships: input.parsed.graph.relationshipCount } },
|
|
warmup,
|
|
reps,
|
|
).one;
|
|
delete timing.relationships;
|
|
result.timing = { ...timing, peak_rss_mib: peakRssMiB };
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/** Every workload in ONE process, interleaved in rotating order. */
|
|
async function measureTimings() {
|
|
const inputs = {};
|
|
for (const form of FORMS) {
|
|
for (const [name, sizes] of Object.entries(SHAPES[form])) {
|
|
const { files, config, raw, parsed } = await prepare(form, sizes);
|
|
inputs[`${form}_${name}`] = {
|
|
files,
|
|
config,
|
|
raw,
|
|
groups: captureGroups(files),
|
|
relationships: parsed.graph.relationshipCount,
|
|
};
|
|
}
|
|
}
|
|
return timeInputs(inputs, WARMUP, REPS);
|
|
}
|
|
|
|
function child(args) {
|
|
const run = spawnSync(process.execPath, ['--import', 'tsx', script, ...args], {
|
|
encoding: 'utf8',
|
|
maxBuffer: 16 * 1024 * 1024,
|
|
env: { ...process.env, GITNEXUS_LOG_LEVEL: 'error' },
|
|
});
|
|
const line = run.stdout?.split('\n').find((l) => l.startsWith(MARKER));
|
|
assert.ok(
|
|
run.status === 0 && line !== undefined,
|
|
`${args.join(' ')}: ${run.error?.message || run.stderr || `exit ${run.status}`}`,
|
|
);
|
|
return JSON.parse(line.slice(MARKER.length));
|
|
}
|
|
|
|
function option(flag, fallback) {
|
|
const at = process.argv.indexOf(flag);
|
|
return at < 0 ? fallback : Number(process.argv[at + 1]);
|
|
}
|
|
|
|
const shapeArg = process.argv.indexOf('--shape');
|
|
try {
|
|
if (shapeArg >= 0) {
|
|
const form = process.argv[shapeArg + 1];
|
|
assert.ok([...FORMS, 'crowded'].includes(form), `unknown form ${form}`);
|
|
const sizes = [];
|
|
for (const arg of process.argv.slice(shapeArg + 2)) {
|
|
if (!/^\d+$/.test(arg)) break;
|
|
sizes.push(Number(arg));
|
|
}
|
|
const result = await measureShape(form, sizes, option('--reps', 0), option('--warmup', 0));
|
|
console.log(MARKER + JSON.stringify(result));
|
|
} else if (process.argv.includes('--timings')) {
|
|
console.log(MARKER + JSON.stringify(await measureTimings()));
|
|
} else {
|
|
await report();
|
|
}
|
|
} finally {
|
|
await pool?.terminate();
|
|
for (const root of roots) fs.rmSync(root, { recursive: true, force: true });
|
|
}
|
|
|
|
async function report() {
|
|
const shapes = {};
|
|
let timings;
|
|
if (FULL) {
|
|
timings = child(['--timings', '--full']);
|
|
for (const form of FORMS) {
|
|
for (const [name, sizes] of Object.entries(SHAPES[form])) {
|
|
const key = `${form}_${name}`;
|
|
const result = child(['--shape', form, ...sizes.map(String)]);
|
|
shapes[key] = result.shape;
|
|
timings[key].peak_rss_mib = result.peak_rss_mib;
|
|
}
|
|
}
|
|
} else {
|
|
const inputs = {};
|
|
for (const form of FORMS) {
|
|
for (const [name, sizes] of Object.entries(SHAPES[form])) {
|
|
const key = `${form}_${name}`;
|
|
const input = await prepare(form, sizes);
|
|
inputs[key] = {
|
|
...input,
|
|
relationships: input.parsed.graph.relationshipCount,
|
|
};
|
|
}
|
|
}
|
|
// Capture-group counts come from the first timed pass, not an extra one.
|
|
timings = timeInputs(inputs, WARMUP, REPS);
|
|
for (const form of FORMS) {
|
|
for (const [name, sizes] of Object.entries(SHAPES[form])) {
|
|
const key = `${form}_${name}`;
|
|
const input = inputs[key];
|
|
shapes[key] = correctness(
|
|
form,
|
|
input.files,
|
|
sizes,
|
|
input.parsed.graph,
|
|
input.first.stats,
|
|
input.groups,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
for (const [key, timing] of Object.entries(timings)) {
|
|
assert.equal(
|
|
timing.relationships,
|
|
shapes[key].relationships,
|
|
`${key}: the timed workload is not the validated one`,
|
|
);
|
|
delete timing.relationships;
|
|
}
|
|
const metrics = {};
|
|
for (const form of FORMS) {
|
|
const small = SHAPES[form].small;
|
|
for (const [name, sizes] of Object.entries(SHAPES[form])) {
|
|
if (name === 'small') continue;
|
|
const grown = sizes.map((n, i) => n / small[i]).filter((growth) => growth !== 1);
|
|
assert.ok(
|
|
grown.length === 1 && Number.isInteger(grown[0]) && grown[0] >= 4,
|
|
`${form}_${name} must grow exactly one dimension, at least 4x`,
|
|
);
|
|
for (const phase of ['capture', 'resolve']) {
|
|
const key = `${phase}_ms`;
|
|
metrics[`${form}_${phase}_${name}_scaling_ratio`] =
|
|
timings[`${form}_${name}`][key] / timings[`${form}_small`][key] / grown[0];
|
|
}
|
|
}
|
|
}
|
|
const out = {
|
|
shapes,
|
|
timings,
|
|
metrics,
|
|
estimator: {
|
|
profile: FULL ? 'full' : 'ci',
|
|
warmup: WARMUP,
|
|
samples: REPS,
|
|
statistic: 'minimum',
|
|
interleaved: true,
|
|
},
|
|
};
|
|
console.log(JSON.stringify(out, null, 2));
|
|
// Correctness holds on every run, not only under --check: each method's
|
|
// CALLS edges are exactly the expected multiset.
|
|
for (const [name, shape] of Object.entries(shapes)) {
|
|
assert.equal(shape.expected_missing, 0, `${name}: expected edges missing`);
|
|
assert.equal(shape.unexpected_edges, 0, `${name}: edges the source never makes`);
|
|
}
|
|
if (CHECK) {
|
|
const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
|
|
assert.deepEqual(shapes, baseline.shapes, 'Ruby bare-read workload/fingerprint drift');
|
|
assert.deepEqual(
|
|
Object.keys(baseline.budgets).sort(),
|
|
Object.keys(metrics).sort(),
|
|
'every metric needs a budget; deleting a budget must not disable a guard',
|
|
);
|
|
const failures = [];
|
|
for (const [name, budget] of Object.entries(baseline.budgets)) {
|
|
if (
|
|
!Number.isFinite(budget) ||
|
|
budget <= 0 ||
|
|
!Number.isFinite(metrics[name]) ||
|
|
metrics[name] > budget
|
|
) {
|
|
failures.push(`${name}: ${metrics[name]} > ${budget}`);
|
|
}
|
|
}
|
|
assert.equal(failures.length, 0, failures.join('\n'));
|
|
console.log('[ruby-bare-reads --check] PASS');
|
|
}
|
|
}
|