GitNexus/gitnexus/test/unit/scope-resolution/php/php-unresolved-receiver-fallback.test.ts
Abhinav Pandey ee81970bcd
perf(ingestion): remove unused worker records and repeated AST walks (#3920)
* 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>
2026-11-14 15:18:27 +00:00

178 lines
5.6 KiB
TypeScript

/**
* DART-11 — PHP's 0.6 unique-method-name fallback must respect a stopped
* receiver walk.
*
* `phpEmitUnresolvedReceiverEdges` guesses an edge when a receiver has no type
* and exactly one method in the workspace has the called name. "No type" used
* to be the only condition, so a receiver whose NEAREST binder declares it
* without a type — a binder that deliberately stopped the walk — still got a
* name-only guess. The fallback now reads that stop itself.
*
* PHP publishes no `Scope.lexicalNames` today, so no PHP fixture can reach the
* stop; this drives the emitter with a hand-built scope that does. The control
* proves the same site is guessed when the scope does not bind the name.
*/
import { describe, expect, it } from 'vitest';
import {
buildDefIndex,
buildMethodDispatchIndex,
buildModuleScopeIndex,
buildQualifiedNameIndex,
buildScopeTree,
createEagerImportVisibility,
type NodeLabel,
type ParsedFile,
type Range,
type ReferenceSite,
type Scope,
type SymbolDefinition,
} from 'gitnexus-shared';
import { createKnowledgeGraph } from '../../../../src/core/graph/graph.js';
import type { ScopeResolutionIndexes } from '../../../../src/core/ingestion/model/scope-resolution-indexes.js';
import type { SemanticModel } from '../../../../src/core/ingestion/model/semantic-model.js';
import { buildGraphNodeLookup } from '../../../../src/core/ingestion/scope-resolution/graph-bridge/node-lookup.js';
import { phpScopeResolver } from '../../../../src/core/ingestion/languages/php/scope-resolver.js';
const CALLER_FILE = 'caller.php';
const TARGET_FILE = 'models.php';
const range = (sl: number, sc: number, el = sl, ec = sc + 10): Range => ({
startLine: sl,
startCol: sc,
endLine: el,
endCol: ec,
});
const callerDef: SymbolDefinition = {
nodeId: 'def:only_fallback',
filePath: CALLER_FILE,
type: 'Function',
qualifiedName: 'only_fallback',
};
const targetDef: SymbolDefinition = {
nodeId: 'def:OnlyFormat.formatOnly',
filePath: TARGET_FILE,
type: 'Method',
qualifiedName: 'OnlyFormat.formatOnly',
ownerId: 'def:OnlyFormat',
parameterCount: 0,
requiredParameterCount: 0,
};
/** `$date->formatOnly()` inside `only_fallback($date)`. */
const site: ReferenceSite = {
name: 'formatOnly',
atRange: range(4, 2),
inScope: 'scope:fn',
kind: 'call',
callForm: 'member',
arity: 0,
explicitReceiver: { name: '$date' },
};
function run(fnExtra: Partial<Scope>) {
const moduleScope: Scope = {
id: 'scope:mod',
parent: null,
kind: 'Module',
range: range(1, 0, 20, 0),
filePath: CALLER_FILE,
bindings: new Map(),
ownedDefs: [],
imports: [],
typeBindings: new Map(),
};
const fnScope: Scope = {
id: 'scope:fn',
parent: 'scope:mod',
kind: 'Function',
range: range(3, 0, 5, 1),
filePath: CALLER_FILE,
bindings: new Map(),
ownedDefs: [callerDef],
imports: [],
typeBindings: new Map(),
...fnExtra,
};
const targetModule: Scope = { ...moduleScope, id: 'scope:target', filePath: TARGET_FILE };
const scopes = [moduleScope, fnScope, targetModule];
const defs = [callerDef, targetDef];
const parsed: ParsedFile = {
filePath: CALLER_FILE,
moduleScope: 'scope:mod',
scopes: [moduleScope, fnScope],
parsedImports: [],
localDefs: [callerDef],
referenceSites: [site],
};
const indexes = {
scopeTree: buildScopeTree(scopes),
defs: buildDefIndex(defs),
qualifiedNames: buildQualifiedNameIndex(defs),
moduleScopes: buildModuleScopeIndex([
{ filePath: CALLER_FILE, moduleScopeId: 'scope:mod' },
{ filePath: TARGET_FILE, moduleScopeId: 'scope:target' },
]),
methodDispatch: buildMethodDispatchIndex({
owners: [],
computeMro: () => [],
implementsOf: () => [],
}),
imports: createEagerImportVisibility(new Map()),
bindings: new Map(),
bindingAugmentations: new Map(),
workspaceTypeBindings: new Map(),
namespaceTypeBindings: new Map(),
accessibleNamespacesByScope: new Map(),
} as unknown as ScopeResolutionIndexes;
const graph = createKnowledgeGraph();
graph.addNode({
id: 'Function:caller.php:only_fallback',
label: 'Function' as NodeLabel,
properties: { name: 'only_fallback', filePath: CALLER_FILE, qualifiedName: 'only_fallback' },
});
graph.addNode({
id: 'Method:models.php:OnlyFormat.formatOnly',
label: 'Method' as NodeLabel,
properties: {
name: 'formatOnly',
filePath: TARGET_FILE,
qualifiedName: 'OnlyFormat.formatOnly',
},
});
const model = {
methods: {
lookupMethodByName: (name: string) => (name === 'formatOnly' ? [targetDef] : []),
},
} as unknown as SemanticModel;
const emit = phpScopeResolver.emitUnresolvedReceiverEdges;
if (emit === undefined) throw new Error('PHP lost its unresolved-receiver fallback');
const emitted = emit(
graph,
indexes,
[parsed],
buildGraphNodeLookup(graph),
new Set<string>(),
model,
);
return {
emitted,
calls: graph.relationships
.filter((r) => r.type === 'CALLS')
.map((r) => `${r.sourceId} -> ${r.targetId} ${r.confidence} ${r.reason}`),
};
}
describe('PHP unresolved-receiver fallback — respects an untyped binder stop', () => {
it('control: an unbound receiver with a workspace-unique method is guessed at 0.6', () => {
expect(run({})).toEqual({
emitted: 1,
calls: [
'Function:caller.php:only_fallback -> Method:models.php:OnlyFormat.formatOnly 0.6 php-unresolved-receiver-fallback',
],
});
});
it('a receiver whose nearest binder declares it without a type is not guessed', () => {
expect(run({ lexicalNames: new Set(['$date']) })).toEqual({ emitted: 0, calls: [] });
});
});