GitNexus/gitnexus/bench/ruby-block-param-stop/scaling.mjs
Abhinav Pandey 704ec678b9
fix(ruby): a block parameter stops the receiver type walk — it no longer takes a same-named outer local's type (RUBY-03) (#3905)
* fix(ruby): a block parameter stops the receiver type walk — it no longer takes a same-named outer local's type (RUBY-03)

The shared receiver walk stops at the nearest scope that owns the
receiver's name, and a scope owns a name it holds no type for only through
Scope.lexicalNames. Ruby published none, so an untyped parameter was
invisible to the walk, which climbed past it to a same-named outer binding:
`user = User.new; items.each { |user| user.save }` resolved the block's
`user.save` to User#save.

- emitRubyScopeCaptures attaches @scope.lexical-names to every scope that
  declares parameters: a do/end or brace block (its |...| names, block
  locals included; this covers lambda { |x| }, proc { |x| } and
  Proc.new { |x| }), the body block of a stabby lambda (its parameter list
  is a sibling of the body), and a method or singleton method. Blocks
  already had scopes; none is added. Numbered and `it` parameters are not
  declared names and are not listed.
- The YARD @param decline (RUBY-01) no longer fires for a block, lambda or
  nested-def parameter of the tagged name: the shadow now stops the walk on
  its own scope, so the tagged use beside it keeps its type. A stabby lambda
  whose parameter default reads the name still declines, because the
  parameter list sits outside the lambda body.

Fixed shapes, each pinned against exact owner IDs with a decoy: block and
lambda/proc parameters shadowing a typed local or a YARD-typed parameter,
nested blocks, every block-parameter form, an untyped method parameter named
like a typed reader, an attr_reader @return type or a top-level local, a
nested def parameter under a tagged method, and a bare read of a parameter
(a read, not a call). Recall cost: an explicit target() / target(1) /
target 1 beside a same-named block parameter now resolves to nothing, as it
already did beside a same-named method parameter.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(bench): gate Ruby block-parameter stop correctness and scaling (RUBY-03)

Block, lambda and method parameters are published as lexical names on the
scope that declares them, so the receiver walk stops at a block parameter
instead of taking a same-named outer local's type.
bench/ruby-block-param-stop pins what that produces and checks how its
cost grows, in the format of bench/ruby-gem-resolution.

Each file holds class Svc<i> with m(items): `user = User.new`, K blocks
rotating `|x| user.run` (the nearest `user`), `|user| user.save` and
`|user, i| user.save` (no edge), side by side or nested, then `user.save`.
Each method's CALLS must equal the expected multiset; main gives the
rebinding blocks wrong User#save edges. One class per file, because Ruby
resolution on main is already super-linear in the classes of ONE file
(measured with `--shape crowded`, not gated).

--check runs a CI profile (about 15 s locally); --full keeps min of 15
after 2 warmups and a fresh process per shape. Every budget is 1.5.
Re-running the scope query over the method for every block scope fails
the nested block gate (2.242 > 1.5).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* test(bench): ruby-block-param-stop — fixed-width indent, input bytes per cell, 16x side-by-side blocks

Three defects the scaling-bench review found in the other benches apply
here too:
- the nested generator indented each level two spaces deeper, so the
  input grew 6.1x for 4x depth; every line now has a fixed-width indent
  and each shape pins its input_bytes beside its groups and edges;
- the gate could not see a known O(blocks^2) edit: walking the enclosing
  method once per block scope measured 1.410 on the 4x side-by-side
  range and passed. Side-by-side blocks now grow 16x (6 -> 96), where
  the same edit fails sibling_capture_block_scaling_ratio 3.596 > 1.5
  (nested 1.778) with unchanged fingerprints;
- the ratio divides by each shape's own growth factor.

Nesting depth stays 4x: over 6 -> 96 it measures 2.57 (capture) and 2.46
(resolution) from two terms that predate #3905 (the shared callable-flow
fallback that searches a block-taking call's subtree for an argument
list, and the shared lexical lookup climbing from each reference to its
binder); baseline.json `_nested_depth_note` records both. Three CI-profile
runs and one --full run pass, every ratio at most 1.202.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(ruby): resolve PR #3905 feedback

Preserve outer YARD types across lambda defaults and explicit self calls beside parameters. Add parameter-order regressions and a four-size scaling sweep.

Note: pre-existing failure in scenario-map/consolidation.test.ts (jscpd 5.4.2 installed; 5.4.3 expected) not addressed by this PR.

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-13 17:47:07 +00:00

208 lines
7.1 KiB
JavaScript

/**
* Four-size scaling sweep for RUBY-03, including the review fixes in #3905.
* Run after npm run build:
* node --import tsx bench/ruby-block-param-stop/scaling.mjs [--check]
*
* Resolution uses measure.mjs's real worker output and exact edge oracle.
* Each size runs in a fresh process. Capture-only workloads exercise many
* lambda defaults and explicit calls beside parameters in a single file.
* Report timings, work counts, normalized growth and a fitted log-log slope;
* a finite sweep is evidence over these sizes, not an asymptotic proof.
*/
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import os from 'node:os';
import { fileURLToPath } from 'node:url';
import { emitRubyScopeCaptures } from '../../src/core/ingestion/languages/ruby/index.ts';
const REPS = 7;
const WARMUP = 2;
const check = process.argv.includes('--check');
const script = fileURLToPath(import.meta.url);
const measure = fileURLToPath(new URL('./measure.mjs', import.meta.url));
const marker = 'RUBY_BLOCK_PARAM_RESULT ';
function child(file, args) {
const result = spawnSync(process.execPath, ['--import', 'tsx', file, ...args], {
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
env: { ...process.env, GITNEXUS_LOG_LEVEL: 'error' },
});
assert.equal(result.status, 0, result.error?.message ?? result.stderr);
const line = result.stdout.split('\n').find((line) => line.startsWith(marker));
assert.ok(line, `missing result: ${result.stdout}`);
return JSON.parse(line.slice(marker.length));
}
function captureWorkload(kind, size) {
if (kind === 'wide-explicit') {
const params = Array.from({ length: size }, (_, i) => `p${i}`);
return (
`class Host\ndef target; end\ndef run(${params.join(', ')}, target)\n` +
'target()\n'.repeat(size) +
'end\nend\n'
);
}
if (kind === 'defaults') {
// Every default reads one earlier parameter. Listing ALL earlier names
// on every default would make the emitted metadata quadratic.
const params = Array.from({ length: size }, (_, i) => `p${i} = user.save`);
return (
`class Host\n# @param user [User]\ndef run(user)\n` +
`f = ->(user, ${params.join(', ')}) { user.save }\nuser.save\nend\nend\n`
);
}
return (
`class Host\ndef target(*args); end\n` +
Array.from(
{ length: size },
(_, i) =>
`def run${i}(target)\n[1].each do |target|\ntarget()\ntarget(1)\ntarget 1\nend\nend\n`,
).join('') +
'end\n'
);
}
function measureCapture(kind, size) {
const source = captureWorkload(kind, size);
const samples = [];
let matches;
for (let i = 0; i < WARMUP + REPS; i++) {
const start = performance.now();
matches = emitRubyScopeCaptures(source, 'scaling.rb');
const ms = performance.now() - start;
if (i >= WARMUP) samples.push(ms);
}
const lexicalNames = matches.flatMap((match) =>
JSON.parse(match['@scope.lexical-names']?.text ?? '[]'),
);
if (kind === 'defaults') {
assert.equal(matches.filter((m) => m['@type-binding.parameter']).length, 1);
assert.equal(matches.filter((m) => m['@scope.block']).length, size + 1);
assert.equal(lexicalNames.length, size * 2 + 2, 'default metadata must grow linearly');
} else {
assert.equal(
matches.filter(
(m) =>
m['@reference.call.member'] &&
m['@reference.name']?.text === 'target' &&
m['@reference.receiver']?.text === 'self',
).length,
kind === 'wide-explicit' ? size : size * 3,
);
assert.equal(
matches.filter((m) => m['@callable-flow.invocation-kind']?.text === 'indirect').length,
0,
);
}
return {
size,
bytes: Buffer.byteLength(source),
capture_groups: matches.length,
lexical_names: lexicalNames.length,
samples_ms: samples,
capture_ms: Math.min(...samples),
};
}
function growth(rows, phase) {
const xs = rows.map((r) => Math.log(r.size));
const ys = rows.map((r) => Math.log(r[phase]));
assert.ok(ys.every(Number.isFinite), `${phase}: non-finite timing`);
const mean = (values) => values.reduce((sum, n) => sum + n, 0) / values.length;
const mx = mean(xs);
const my = mean(ys);
const exponent =
xs.reduce((sum, x, i) => sum + (x - mx) * (ys[i] - my), 0) /
xs.reduce((sum, x) => sum + (x - mx) ** 2, 0);
const first = rows[0];
const last = rows.at(-1);
return {
exponent,
normalized_growth: last[phase] / first[phase] / (last.size / first.size),
adjacent_normalized_growth: rows
.slice(1)
.map((row, i) => row[phase] / rows[i][phase] / (row.size / rows[i].size)),
};
}
if (process.argv.includes('--capture')) {
const at = process.argv.indexOf('--capture');
const kind = process.argv[at + 1];
assert.ok(['defaults', 'explicit', 'wide-explicit'].includes(kind));
const size = Number(process.argv[at + 2]);
assert.ok(Number.isSafeInteger(size) && size > 0);
console.log(marker + JSON.stringify(measureCapture(kind, size)));
} else {
const series = {};
for (const form of ['sibling', 'nested']) {
for (const axis of ['methods', 'blocks']) {
const sizes = axis === 'methods' ? [64, 128, 256, 512] : [3, 6, 12, 24];
const rows = [];
for (const size of sizes) {
const methods = axis === 'methods' ? size : 64;
const blocks = axis === 'blocks' ? size : 6;
const result = child(measure, [
'--shape',
form,
String(methods),
String(blocks),
'--reps',
String(REPS),
'--warmup',
String(WARMUP),
]);
assert.equal(result.shape.expected_missing, 0);
assert.equal(result.shape.unexpected_edges, 0);
rows.push({ size, ...result.shape, ...result.timing });
}
series[`${form}_${axis}`] = {
rows,
capture: growth(rows, 'capture_ms'),
resolve: growth(rows, 'resolve_ms'),
};
}
}
for (const kind of ['defaults', 'explicit', 'wide-explicit']) {
const rows = [64, 128, 256, 512].map((size) =>
child(script, ['--capture', kind, String(size)]),
);
series[kind] = { rows, capture: growth(rows, 'capture_ms') };
}
console.log(
JSON.stringify(
{
environment: {
node: process.version,
platform: process.platform,
arch: process.arch,
cpu: os.cpus()[0]?.model,
},
estimator: {
samples: REPS,
warmup: WARMUP,
statistic: 'minimum',
fresh_process_per_size: true,
},
// Slack for scheduling/GC noise; a quadratic 8x sweep grows 64x and fails.
budgets: { exponent: 1.2, normalized_growth: 1.5 },
series,
},
null,
2,
),
);
if (check) {
for (const [name, result] of Object.entries(series)) {
for (const phase of ['capture', 'resolve']) {
const metric = result[phase];
if (!metric) continue;
assert.ok(
metric.exponent <= 1.2 && metric.normalized_growth <= 1.5,
`${name}/${phase}: superlinear growth ${JSON.stringify(metric)}`,
);
}
}
console.log('[ruby-block-param-stop scaling --check] PASS');
}
}