GitNexus/gitnexus/bench/python-scope/value-references.mjs
Gergő Magyar 7c312cffa6
perf(python): remove quadratic import-claim reconciliation and deep-syntax hazards (#3964)
* perf(python): remove quadratic import-claim reconciliation

* test(python): count identity and import-claim reads separately

The repeated-import scaling case counted `claim` getter reads under the
name `identityReads`, so a regression that re-read every import's
identity per claim could still pass. Instrument both properties: claim
reads must equal the import count (the old nested membership scan read
n(n+1)/2), and identity reads must stay within 2n.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(python): walk lexical bindings iteratively; find annotations by span

Syntax depth is input-controlled. The recursive lexical walk (visit,
bind, pattern) overflowed V8's stack near depth 2,000, e.g. a generated
2,000-term `a + b + ...` chain or 2,000 nested list literals, dropping
the whole file's scope extraction. All three walks now use an explicit
stack. Steps that the recursive walk interleaved between child visits
(parameter and comprehension-target binding) run as deferred tasks, so
events, environments and range marks keep their pre-order.

isPythonTypeAnnotation climbed `.parent` from every bare read and
attribute. tree-sitter keeps no parent pointers, so each `.parent`
re-walks from the root: n(n+1)/2 parent reads and O(n^3) time for an
n-term chain (10 s at 1,000 terms). It now collects `type` node byte
spans once per tree with a query, memoized per tree like
javaTypeIdentityMemo, and binary-searches them. Expressions never
contain a block, so span containment equals the old "type ancestor
below the nearest block" walk.

Captures are byte-identical to the merge base over 340 repository
.py fixtures plus synthetic edge cases. The only difference is a
1,000-level annotation the base walk could not process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(python): check annotations with one hash lookup per node

The span binary search cost log2(spans) iterations per read, so capture
work grew n log n: exact V8 block-execution growth on the value-reference
corpus rose to 1.0012 per doubling (gate: <= 1.0). Collect identifier and
attribute nodes under each outermost `type` node once per tree with the
native descendantsOfType, and answer each check with a Set lookup.
Nested `type` nodes are skipped, so deeply nested generics stay linear.

Capture block growth is back to 0.9990, the same as before the deep-syntax
change. Resolution block counts match the pre-change head exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(python): cover deep pattern and tuple-target walks

The explicit-stack `pattern` and `bind` walks had no deep regression
case, and the nested-literal case only checked that nothing threw. The
deep cases now assert the module claims of a 2,000-level class pattern
(`q`), a 2,000-level nested tuple target (`a`) and the nested-literal
assignment (`x`); all three throw RangeError on the merge base's
recursive walk.

The value-references benchmark identity now hashes
attribute-references.ts/.js, which sits on the measured capture path,
and the local-import scoping doc points at import-claims.ts for the
conflicting-import policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(python): classify attribute accesses with one query pass per tree

pythonAttributeAccessKinds read .parent three times per attribute to find
its target context, and node-tree-sitter re-walks from the root for each
read, so member and call chains cost O(n^2). Annotation membership and
access kinds now come from one query pass per tree: the existing (type)
pattern plus nine context patterns that capture the node in target
position and descend through tuple, list and parenthesized wrappers. Both
exports become one map lookup by node.id, and the file reads no .parent.

Every context pattern ends at its capture. A two-step pattern such as
(assignment left: (_) @write right: (_)) keeps its match open across the
target, and tree-sitter buffers every capture inside it: quadratic, and
past 65,535 buffered captures the 16-bit capture ids wrap and the process
segfaults. The annotation-only target gets its own capture and wins over
the plain assignment capture in JS instead.

Also drops the unreachable tree === undefined fallback and its cast.

Captures are identical in emission order to the previous head on the
repository fixtures, the CPython 3.13 stdlib and 23,464 generated and
mutated files. Parent-bound rows cover member reads, member chains and
call chains; a 70,000-argument assignment target pins the buffering
hazard. The parent-read wrapper is shared by both bound tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ingestion): walk named trees and binding targets without recursion

Syntax depth is input-controlled. Two shared helpers recursed once per
level and overflowed V8's stack on deep code in every language that uses
them:

- walkNamedTree (about 30 capture call sites across Go, Objective-C, Rust,
  Swift, PHP, Ruby, C#, Python and Dart) threw near depth 8,000. It now
  keeps an explicit stack of (node, next child index) frames and makes the
  same namedChildCount / namedChild(i) calls, in the same order, as the
  recursion. That order matters: namedChild(i) steps inside a visible
  anonymous node such as Python's `not in` while namedChildren does not,
  and the exact navigation-count tests for Dart and Ruby pin the calls.

- bindingIdentifier threw on 8,000 nested tuple targets. It searched each
  binding field and then every named child, and a field is usually also a
  named child, so a subtree that failed was searched again: O(2^depth) on
  a left-nested chain without an identifier (4,194,303 visits at depth 20,
  83 now). It now uses an explicit stack whose entries each make one lazy
  read in the recursion's order, and a seen set skips subtrees that
  already failed.

Results are unchanged. A node-level differential over the fixtures of 17
grammars (as written, truncated and corrupted) and the CPython stdlib
found 0 differences in visit sequence, navigation calls or returned node.
Scope-capture fingerprints pass for all 17 languages, and no node makes
more navigation calls than before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(python): keep scope-query matches and flow lookups linear on deep chains

- Anchor the eight scope-query rules that stayed open across a nested
  child (member call, member read, binary and boolean operands, call
  arguments) at the node they end on. expandPythonScopeMatches()
  rebuilds the original capture lists in the same order. Open matches on
  a chain drop from one per level to at most 11; matches() on a
  4,000-link call chain goes from 1,100 ms to 9 ms.
- Run the scope query and the attribute context query with
  maxStartDepth 0xffff. tree-sitter keeps a match's start depth in
  16 bits, and past depth 65,535 a wrapped match stays open: 90,000
  `or` operands took 35.7 s in the context query, now 0.3 s.
- Memoize nearestFunctionOwner, nearestLexicalRegion, terminalIdentifier
  and hasMultipleIdentifierLeaves per file in
  synthesizeCallableFlowCaptures, and read a call's text once for all of
  its arguments. Nested walrus at 600 levels: 12.2 s to 37 ms; assignment
  chains at 600 targets: 2.6 s to 49 ms; call-only chains at 2,000 calls:
  10.2 s to 52 ms.

Captures are identical in emission order on the repo (340 files),
stdlib (598) and generated (23,464) corpora, and the 15 languages that
share the flow helper show no differences.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(parse): read node text from the source string after a chunked parse

node-tree-sitter rebuilds `node.text` of a callback-parsed tree (sources
over DIRECT_PARSE_LIMIT_CHARS) by calling the input callback again on
every read: a fresh copy of the node's source each time. Point the tree
at the source string, as node-tree-sitter already does for a string
parse, so a read is one substring.

Long Python chains become linear in time and memory (a 16,000-target
assignment chain: 3.6 s and 1.7 GB before, 1.5 s and 184 MB after), and
a call with 40,000 arguments or an expression with 40,000 `or` operands
no longer exhausts a 4 GB heap. Peak RSS of analyze on the stdlib and on
gitnexus/src is unchanged (within 0.5%), with identical graphs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(python): keep the scope-query match helper out of the grammar gate

The grammar-literal gate calls every `*ScopeQuery` export of a language's
query.ts with no arguments to compile its query. matchPythonScopeQuery(root)
matched that name and threw on the missing root. Rename it to
pythonScopeQueryMatches and note the constraint at its definition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 15:04:43 +00:00

402 lines
15 KiB
JavaScript

/** Capture and resolution scaling for Python value references (#3942, #3943). */
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
import { SupportedLanguages } from 'gitnexus-shared';
import { emitPythonScopeCaptures } from '../../src/core/ingestion/languages/python/captures.ts';
import { createKnowledgeGraph } from '../../src/core/graph/graph.ts';
import { createSemanticModel } from '../../src/core/ingestion/model/semantic-model.ts';
import { SCOPE_RESOLVERS } from '../../src/core/ingestion/scope-resolution/pipeline/registry.ts';
import { runScopeResolution } from '../../src/core/ingestion/scope-resolution/pipeline/run.ts';
import { parseFilesWithWorkers } from '../../test/helpers/worker-parse.ts';
import { fingerprintIds } from '../lib/route-constant-guard.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const SIZES = [128, 256, 512];
const RESOLUTION_SIZES = [128, 256, 512, 1024, 2048];
// Protocol: ../lexical-binding-provenance/README.md.
const PROTOCOL = {
name: 'duration-calibrated-v2',
targetIterationMs: 500,
pilotConfirmationBatches: 3,
maxPilotIterations: 64,
maxInvocationsPerIteration: 1048576,
warmup: 5,
repetitions: 15,
scalingBudget: 1.8,
adjacentScalingBudget: 1.5,
};
function corpus(entities) {
const definitions = [];
const lines = ['from fastapi import Depends', 'from typing import Annotated'];
for (let i = 0; i < entities; i++) {
definitions.push(`TIMEOUT${i} = 30`, `def helper${i}(value):`, ' return value');
lines.push(
`from values import TIMEOUT${i}, helper${i}`,
`class Reader${i}:`,
` TIMEOUT${i} = 1`,
' def read(self):',
` return TIMEOUT${i} + TIMEOUT${i}`,
' def member(self):',
` return self.TIMEOUT${i}`,
' def register(self, items):',
` return sorted(items, key=helper${i})`,
' def direct(self):',
` return helper${i}(1)`,
` def injected(self, dep=Depends(helper${i})):`,
' return dep',
` def annotation(self, dep: Annotated[int, Depends(helper${i})]):`,
' return dep',
` def shadow(self, helper${i}):`,
` return sorted([], key=helper${i})`,
` def type_only(self, value: helper${i} | None):`,
' return value',
);
}
return [
{ path: 'values.py', content: definitions.join('\n') + '\n' },
{ path: 'readers.py', content: lines.join('\n') + '\n' },
];
}
function captureFacts(matches, entities) {
const reads = matches.filter((m) => /^TIMEOUT\d+$/.test(m['@reference.read.identifier']?.text));
const values = matches.filter((m) => /^helper\d+$/.test(m['@reference.value-ref']?.text));
assert.equal(reads.length, entities * 2, 'Missing bare constant reads');
assert.equal(values.length, entities * 3, 'Callback, metadata and shadow captures changed');
const identities = matches.map((match) =>
JSON.stringify(
Object.keys(match)
.sort()
.map((tag) => [tag, match[tag].text, match[tag].range]),
),
);
return {
groups: matches.length,
bareReads: reads.length,
valueRefs: values.length,
fingerprint: fingerprintIds(identities),
};
}
function graphFacts(graph, entities) {
const actual = [];
const nodes = [...graph.iterNodes()];
const edges = [...graph.iterRelationships()];
for (const edge of edges) {
if (!['ACCESSES', 'USES', 'CALLS'].includes(edge.type)) continue;
const target = graph.getNode(edge.targetId);
if (!/^(TIMEOUT|helper)\d+$/.test(target?.properties.name)) continue;
const source = graph.getNode(edge.sourceId);
assert.ok(source && target, 'Dangling reference');
actual.push(`${source.id}|${edge.type}|${target.id}`);
}
const expected = [];
for (let i = 0; i < entities; i++) {
expected.push(
`Method:readers.py:Reader${i}.read#0|ACCESSES|Variable:values.py:TIMEOUT${i}`,
`Method:readers.py:Reader${i}.read#0|ACCESSES|Variable:values.py:TIMEOUT${i}`,
`Method:readers.py:Reader${i}.member#0|ACCESSES|Variable:readers.py:TIMEOUT${i}`,
`Method:readers.py:Reader${i}.register#1|ACCESSES|Function:values.py:helper${i}`,
`Method:readers.py:Reader${i}.register#1|USES|Function:values.py:helper${i}`,
`Class:readers.py:Reader${i}|USES|Function:values.py:helper${i}`,
`Method:readers.py:Reader${i}.direct#0|CALLS|Function:values.py:helper${i}`,
`Method:readers.py:Reader${i}.injected#1|CALLS|Function:values.py:helper${i}`,
);
}
assert.deepEqual(
actual.sort(),
expected.sort(),
'Value edges, owners or negative controls changed',
);
return {
nodes: nodes.length,
edges: edges.length,
accesses: entities * 4,
uses: entities * 2,
calls: entities * 2,
fingerprint: fingerprintIds([
...nodes.map((node) => JSON.stringify([node.id, node.label, node.properties])),
...edges.map((edge) =>
JSON.stringify([
edge.id,
edge.sourceId,
edge.targetId,
edge.type,
edge.confidence,
edge.reason,
]),
),
]),
};
}
async function resolutionOperation(files) {
const raw = [];
const parsed = await parseFilesWithWorkers(files, { poolSize: 1, outRawResults: raw });
assert.equal(parsed.data.parsedFiles.length, files.length, 'Scope extraction omitted a file');
const nodes = [...parsed.graph.iterNodes()];
const edges = [...parsed.graph.iterRelationships()];
const symbols = raw.flatMap((chunk) => chunk.symbols);
const resolver = SCOPE_RESOLVERS.get(SupportedLanguages.Python);
assert.ok(resolver);
return {
prepare() {
// Resolution mutates graph, model and ParsedFiles. Never reuse resolved state.
const graph = createKnowledgeGraph();
for (const node of structuredClone(nodes)) graph.addNode(node);
for (const edge of structuredClone(edges)) graph.addRelationship(edge);
for (const file of files)
graph.addNode({
id: `File:${file.path}`,
label: 'File',
properties: { name: file.path, filePath: file.path },
});
const model = createSemanticModel();
for (const symbol of structuredClone(symbols)) {
model.symbols.add(symbol.filePath, symbol.name, symbol.nodeId, symbol.type, symbol);
}
const preExtractedParsedFiles = new Map(
structuredClone(parsed.data.parsedFiles).map((file) => [file.filePath, file]),
);
return {
graph,
model,
files,
preExtractedParsedFiles,
onResolved: ({ parsedFiles }) => {
assert.equal(parsedFiles.length, files.length, 'Resolution omitted files');
for (const file of parsedFiles) {
assert.equal(
file,
preExtractedParsedFiles.get(file.filePath),
'Resolution reparsed a worker result',
);
}
},
};
},
run(input) {
runScopeResolution(input, resolver);
return input.graph;
},
};
}
function measure({ prepare, run }, verify, verifyOnly) {
const initial = verify(run(prepare()));
if (verifyOnly) return { facts: initial };
let last;
const iteration = (invocations) => {
let workMs = 0;
const wallStart = performance.now();
for (let i = 0; i < invocations; i++) {
const input = prepare();
const start = performance.now();
last = run(input);
workMs += performance.now() - start;
}
return { invocations, workMs, wallMs: performance.now() - wallStart };
};
const pilotIterations = [];
let invocations = 1;
let confirmations = 0;
for (let i = 0; i < PROTOCOL.maxPilotIterations; i++) {
const pilot = iteration(invocations);
const qualified = pilot.workMs >= PROTOCOL.targetIterationMs;
pilotIterations.push({ ...pilot, qualified });
if (qualified) {
if (++confirmations === PROTOCOL.pilotConfirmationBatches) break;
} else {
confirmations = 0;
if (invocations >= PROTOCOL.maxInvocationsPerIteration) break;
invocations *= 2;
}
}
assert.equal(confirmations, PROTOCOL.pilotConfirmationBatches, 'Pilot calibration exhausted');
const warmupIterations = Array.from({ length: PROTOCOL.warmup }, () => iteration(invocations));
const measuredIterations = Array.from({ length: PROTOCOL.repetitions }, () =>
iteration(invocations),
);
const samplesMs = measuredIterations.map(({ workMs }) => workMs / invocations);
const sorted = [...samplesMs].sort((a, b) => a - b);
const meanMs = samplesMs.reduce((a, b) => a + b, 0) / samplesMs.length;
const facts = verify(last);
assert.deepEqual(facts, initial, 'Fresh invocations produced different outputs');
return {
facts,
timing: {
invocationsPerIteration: invocations,
pilotIterations,
warmupIterations,
measuredIterations,
samplesMs,
minMs: sorted[0],
medianMs: sorted[Math.floor(sorted.length / 2)],
meanMs,
standardDeviationMs: Math.sqrt(
samplesMs.reduce((sum, ms) => sum + (ms - meanMs) ** 2, 0) / (samplesMs.length - 1),
),
},
};
}
export async function measurePythonValueReferences({
check = false,
verifyOnly = false,
captureSizes = SIZES,
resolutionSizes = RESOLUTION_SIZES,
} = {}) {
for (const sizes of [captureSizes, resolutionSizes]) {
assert.ok(
sizes.length >= 3 &&
sizes.every((n, i) => Number.isSafeInteger(n) && n > 0 && (i === 0 || n > sizes[i - 1])),
'Use at least three increasing positive integer sizes',
);
}
if (check) {
assert.deepEqual(captureSizes, SIZES, '--check requires the capture baseline workload');
assert.deepEqual(
resolutionSizes,
RESOLUTION_SIZES,
'--check requires the resolution baseline workload',
);
}
assert.ok(!(check && verifyOnly), '--check requires timing');
const report = {
protocol: PROTOCOL,
environment: {
node: process.version,
platform: process.platform,
arch: process.arch,
cpu: os.cpus()[0]?.model,
loadAverage: os.loadavg(),
},
revision: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: HERE, encoding: 'utf8' }).trim(),
dirty:
execFileSync('git', ['status', '--porcelain'], { cwd: HERE, encoding: 'utf8' }).trim()
.length > 0,
sourceHashes: Object.fromEntries(
[
'../../src/core/ingestion/languages/python/captures.ts',
'../../src/core/ingestion/languages/python/query.ts',
'../../src/core/ingestion/languages/python/import-target.ts',
'../../src/core/ingestion/languages/python/lexical-bindings.ts',
'../../src/core/ingestion/languages/python/import-claims.ts',
'../../src/core/ingestion/languages/python/attribute-references.ts',
'../../../gitnexus-shared/src/scope-resolution/registries/lookup-core.ts',
'../../dist/core/ingestion/workers/parse-worker.js',
'../../dist/core/ingestion/languages/python/captures.js',
'../../dist/core/ingestion/languages/python/query.js',
'../../dist/core/ingestion/languages/python/import-target.js',
'../../dist/core/ingestion/languages/python/lexical-bindings.js',
'../../dist/core/ingestion/languages/python/import-claims.js',
'../../dist/core/ingestion/languages/python/attribute-references.js',
'../../../gitnexus-shared/dist/scope-resolution/registries/lookup-core.js',
].map((file) => [
file,
createHash('sha256')
.update(readFileSync(resolve(HERE, file)))
.digest('hex'),
]),
),
sizes: { captures: captureSizes, resolution: resolutionSizes },
arms: { captures: [], resolution: [] },
errors: [],
};
const baseline = check
? JSON.parse(readFileSync(resolve(HERE, 'value-references-baseline.json'), 'utf8'))
: {};
for (const entities of [...new Set([...captureSizes, ...resolutionSizes])].sort(
(a, b) => a - b,
)) {
const files = corpus(entities);
const inputBytes = files.reduce((sum, file) => sum + Buffer.byteLength(file.content), 0);
if (captureSizes.includes(entities))
report.arms.captures.push({
entities,
inputBytes,
...measure(
{
prepare: () => undefined,
run: () => emitPythonScopeCaptures(files[1].content, files[1].path),
},
(matches) => captureFacts(matches, entities),
verifyOnly,
),
});
if (resolutionSizes.includes(entities)) {
const operation = await resolutionOperation(files);
report.arms.resolution.push({
entities,
inputBytes,
...measure(operation, (graph) => graphFacts(graph, entities), verifyOnly),
});
}
process.stderr.write(
`[python value references] ${entities} entities verified${verifyOnly ? '' : ' and measured'}\n`,
);
}
for (const [arm, rows] of Object.entries(report.arms)) {
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (check && row.facts.fingerprint !== baseline[arm]?.[row.entities])
report.errors.push(`${arm}/${row.entities}: fingerprint drift`);
if (verifyOnly || i === 0) continue;
const small = rows[0];
row.scaling = Object.fromEntries(
['minMs', 'medianMs'].map((key) => [
key,
row.timing[key] / small.timing[key] / (row.entities / small.entities),
]),
);
for (const [stat, ratio] of Object.entries(row.scaling)) {
if (!Number.isFinite(ratio) || ratio > PROTOCOL.scalingBudget)
report.errors.push(
`${arm}/${row.entities}/${stat}: scaling ${ratio} exceeds ${PROTOCOL.scalingBudget}`,
);
}
const previous = rows[i - 1];
row.adjacentScaling = Object.fromEntries(
['minMs', 'medianMs'].map((key) => [
key,
row.timing[key] / previous.timing[key] / (row.entities / previous.entities),
]),
);
for (const [stat, ratio] of Object.entries(row.adjacentScaling)) {
if (!Number.isFinite(ratio) || ratio > PROTOCOL.adjacentScalingBudget)
report.errors.push(
`${arm}/${row.entities}/${stat}: adjacent scaling ${ratio} exceeds ${PROTOCOL.adjacentScalingBudget}`,
);
}
}
}
return report;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const { values } = parseArgs({
options: {
check: { type: 'boolean' },
verify: { type: 'boolean' },
sizes: { type: 'string' },
output: { type: 'string' },
},
});
const report = await measurePythonValueReferences({
check: values.check,
verifyOnly: values.verify,
captureSizes: values.sizes?.split(',').map(Number),
resolutionSizes: values.sizes?.split(',').map(Number),
});
const json = JSON.stringify(report, null, 2) + '\n';
if (values.output) writeFileSync(values.output, json);
process.stdout.write(json);
if (values.check && report.errors.length) process.exitCode = 1;
}