GitNexus/gitnexus/bench/python-scope
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
..
baseline-fingerprint.txt fix(python): find dependents of constants and passed functions (#3957) 2026-11-16 16:42:30 +00:00
baseline-import-target-fingerprint.txt refactor(ingestion): colocate import resolution rules (#3670) 2026-10-22 03:49:35 +00:00
import-target-fingerprint.mjs perf(ingestion): linearize scope-capture across all languages + Python import resolution (O(n²)→O(n)) (#1918) 2026-05-30 19:44:22 +01:00
measure.mjs fix(python): find dependents of constants and passed functions (#3957) 2026-11-16 16:42:30 +00:00
README.md fix(python): find dependents of constants and passed functions (#3957) 2026-11-16 16:42:30 +00:00
value-references-baseline.json fix(python): find dependents of constants and passed functions (#3957) 2026-11-16 16:42:30 +00:00
value-references.mjs perf(python): remove quadratic import-claim reconciliation and deep-syntax hazards (#3964) 2026-11-18 15:04:43 +00:00

Python capture and value-reference benchmarks

Run from gitnexus/ after npm run build:

node --import tsx bench/python-scope/measure.mjs --check
node --import tsx bench/python-scope/import-target-fingerprint.mjs --check

The existing CI Python benchmark step runs both commands. The first retains the DAO capture scaling and fixture fingerprint checks and also runs the value-reference benchmark for #3942 and #3943. Its JSON includes the full value_references report. The value-reference resolver arm requires the compiled parse worker; the original capture arm imports source directly.

To run only the new benchmark and save its samples:

node --import tsx bench/python-scope/value-references.mjs --check --output /tmp/python-value-references.json

Two generated Python files contain growing sets of constants, helper functions, and reader classes. Capture extraction uses 128, 256 and 512 entities; resolution continues through 1,024 and 2,048, spanning 16× input growth. Each class exercises bare imported reads despite a class member with the same name, explicit self access, keyword callbacks, direct calls, Depends defaults, Annotated metadata, parameter shadowing and a plain type annotation. Definitions and references both grow with the entity count.

  • Captures: measures parsing and emitPythonScopeCaptures on the reader file. Exact counts require two bare constant reads and three helper value captures per entity, including the shadowed capture whose resolution must subsequently fail.
  • Resolution: parses both files once with a real worker, then measures the production scope-resolution pass. Each invocation starts with a fresh graph, semantic model and deep copy of the parsed files. Completion checks assert that the resolver used those exact worker results instead of silently reparsing. Preparation is outside timing; no resolved state or lookup cache is reused between invocations. Exact edge identities require four accesses, two value uses and two calls per entity. These include the existing access edge accompanying a callable value use. Metadata uses belong to the class definition scope; Depends defaults retain the analyzer's existing method-owned synthetic call. Shadowed callbacks and plain type annotations must not reach the imported helper, and callback uses must not become calls.

Both arms check semantics before timing and again afterward, and require identical results from fresh invocations. Committed fingerprints cover all captures and the complete graph, including relationship identities, endpoints, confidence and reason. A faster run that drops facts cannot pass. Review intentional semantic changes before updating value-references-baseline.json; the check never records baselines.

The measurement protocol follows lexical-binding-provenance's duration-calibrated-v2: double the invocation count until three consecutive pilot batches each contain at least 500 ms of measured work, then keep that count for five warmup and fifteen measured batches. All pilot, warmup and measured samples are reported. Nothing is discarded or retried to obtain a passing result.

For both the minimum and median batch-average time, comparisons with the smallest input use (larger time / smaller time) / (larger entities / smaller entities). Each must be finite and at most the predeclared 1.8 budget. Adjacent 2× steps also must stay at or below 1.5. Near 1 means linear measured growth; a dominant quadratic term approaches the input-size multiplier. The 16× resolution span helps expose a quadratic term that is small at the starting size. This is a regression gate on these workloads, not a proof of an asymptotic bound for every Python program. Run on an otherwise idle host; the report records Node, CPU, load, revision, dirty status and hashes of the relevant source, compiled Python modules, compiled shared lookup and built worker.

--verify checks semantics without timing. --sizes 256,512,1024 selects both arms' sizes for a diagnostic sweep; --check requires the committed default sizes and real timing. The output includes errors for diagnostic sweeps as well, but only --check enforces a nonzero exit for timing or fingerprint failures.

An expanded run on Node 22.23.3, Linux x64, Intel i9-12900K produced the following batch medians. The shared host had other jobs running (initial one-minute load 14.49). All eight semantic checks and both timing gates passed; the graph grew from 1,538 nodes / 2,561 edges to 24,578 nodes / 40,961 edges. Times are per invocation; scaling is normalized to 128 entities. The gate uses both the median shown here and the minimum, with all samples and standard deviations in the JSON.

Entities Capture median (ms) Capture scaling Resolution median (ms) Resolution scaling
128 333.21 — 55.54 —
256 799.85 1.200 128.95 1.161
512 1,578.85 1.185 244.50 1.101
1,024 — — 609.19 1.371
2,048 — — 1,218.39 1.371

The subsequent combined CI command also passed every fingerprint and timing gate. Its full-span normalized median ratios were 1.071 for captures and 1.622 for resolution (minimum ratios 1.129 and 1.674). Its largest adjacent ratio was 1.275. These results bound measured growth on this corpus; they do not establish strict linear or sublinear complexity for the entire ingestion pipeline.

The largest input used the worker's built-in preparation retry after its initial 30-second timeout. An earlier expanded attempt aborted during worker replacement under severe host contention (load above 100); it produced no complete timing report. Worker preparation is outside the resolution measurement. Neither run changed timeouts or scaling budgets.

Fault-injection checks rejected dropped value captures, missing baselines and fallback reparsing. Injected quadratic work preserved the output fingerprints but failed the timing gate (normalized capture median 2.295, limit 1.8).