GitNexus/docs/languages/ruby-ingestion-gaps.md
Gergő Magyar 111fa82ea1
fix(ingestion): close resolver, import and benchmark review gaps (#3945)
* fix(ingestion): close merged review gaps

Complete lexical ownership, import visibility and canonical worker
merges; guard repeated work with purpose-named benchmarks.

Refs #3915

* fix(hooks): read rg and grep options per tool so valid searches keep their query

The unknown-option decline added in this PR returned null for valid command
lines that the merge base augmented: `rg --color=never X`, `rg --no-heading X`,
`rg --json X`, `rg -nC3 X`, `grep -rn --exclude-dir=node_modules X .` and
others. extractPattern now classifies every option of ripgrep 14.1.1 and GNU
grep 3.11 in one table per tool (value in the next token, boolean, pattern,
pattern file, informational):

- `--name=value` carries its own value and never declines the command;
- a long option that takes a value consumes the next token (`--color always`,
  `--max-depth 3`, `--exclude-dir node_modules`, ...);
- a short bundle is read letter by letter, so the last letter may take an
  attached value or the next token (`-nC3`, `-rnA 2`, `-inm5`);
- letters and names the tools read differently are kept apart (`-r`, `-E`,
  `-T`, `-d`, `-h`, digits, `--color`, GNU long-name abbreviations, ripgrep's
  `-e=X`).

An option the tool does not have, written without `=`, still declines, as do
pattern files and options that print without searching.

Against the installed binaries as the oracle on 93 command lines: the base
build names a token the tool does not search for in 39, the PR head declines
71 searchable commands, this build does neither.

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

* test(ingestion): install the ownerless-read probe before reconciliation runs

The wrapper called the real reconcileOwnership before wrapping
lookupAllByOwner on model.fields and model.types, so the registry reads made
by the first reconciliation call on a model (its own duplicate checks) were
never counted. The lang-resolution fixture reconciles once per language on one
model, so a reader reintroduced for the first language passed with
`probe.reads === 0`.

The probe is now installed first. With the ownerless skip of the field branch
re-opened for the first reconciled language only, the previous test passes and
this one fails with 99 reads; removing either skip outright fails it with 833
(fields) and 1541 (nested types) reads.

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

* test(java): pin that on-demand imports are not re-exported, per import form

The test "does not expose imported members as members of the importing class"
used `import b.*;` in Util.java, a type-import-on-demand, so it never put a
static member of `b.Tools` in Util's scope and passed on the merge base. Util
now uses `import static b.Tools.*;`, and the importer names both a static
method and a static member type through `a.Util` (illegal under JLS 7.5.3).

A second test covers the package form: a type that Util.java imports with
`import c.*;` must not be reachable through `import b.Util.Lib;` (JLS 7.5.1)
nor through `import b.*;` (JLS 7.5.2). A same-named type in another package
keeps the workspace-unique-name fallback out of the result.

Removing `reexportsName: false` from the package on-demand branch of
interpretJavaImport (interpret.ts:41) fails the second test with
`named -> src/c/Lib.java:Lib` and `:make`; removing it from the static
on-demand branch (:66) fails the first with `wrong -> src/b/Tools.java:in`.
Both fail in the grouped and the one-edge-per-file storage forms.

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

* refactor(ingestion): make ScopeResolutionIndexes.namespaceExportsByFile readonly

`namespaceExportsByFile` was the only writable member of the bundle that
SemanticModel.attachScopeIndexes freezes, so
`model.scopes.namespaceExportsByFile = ...` compiled and then threw at run
time. The member is now `readonly`.

runScopeResolution no longer assigns it after building the bundle: the
workspace index is built from `finalized.scopeTree` (the same tree the bundle
carries), and the bundle is then created in one spread together with the
populated method dispatch, the way that late member was already installed.
The readers are unchanged.

A write to the member through `ScopeResolutionIndexes` is now TS2540; the
same file compiled on the previous head.

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

* test(ingestion): read the associative-merge opt-in from the Dart and Ruby providers

bench/scope-processing/measure.mjs and finalize-binding-scaling.test.ts built
their own finalize hooks with `mergeBindingsAreAssociative: true`, so deleting
the opt-in from dartScopeResolver or rubyScopeResolver left the gate at exit 0
and the test green while the pipeline went back to one merge per incoming
binding.

Both now take `mergeBindings` and `mergeBindingsAreAssociative` from the
provider objects. Sizes, budgets and the counted quantity (binding refs handed
to the merge hook) are unchanged.

With the opt-in removed from either provider the unit test fails
(`expected 136 to be 16`) and `measure.mjs --check` exits 1 at
`<lang>-bindings/16` (`8256 !== 128`, each binding enters its merge once).

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

* test(dart): pin show and hide on prefixed imports for every filtered consumer

No test had a prefixed import with `show`, so inverting the `show` branch of
namespaceImportAllowsMember (walkers.ts:2543) survived the suite: with
`import 'x.dart' as p show User;`, `p.Other` resolved to the hidden class.

The new suite imports one library under a prefix with no combinator, with
`show`, with `hide`, through a re-exporting library, through three imports
sharing one prefix with different `show` lists, and deferred with `show`. Each
form reaches a visible and a filtered-out class through construction
(inline, bound to a local, chained), a static member, a qualified callee, a
qualified parameter type and an awaited `Future<p.T>`; every class declares
the same member names, so a leak lands on another owner.

Mutants of the filter killed by this file alone: show inverted, hide
inverted, `some` -> `every`, the per-target-file conjunct, `?? true` ->
`?? false`, and the filter call dropped at walkers.ts:1071,
imported-return-types.ts:235 and :293 (and :281 together with :293),
receiver-bound-calls.ts:1001, :2428 and :2774.

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

* test(dart): skip the new Dart suites when the parser cannot be initialised

dart-branch-bindings, dart-inferred-result-scopes, dart-review-followups and
review-followups-cache guarded only with isLanguageAvailable, which reports
that the grammar module loaded, not that Parser.setLanguage accepts it. They
now probe loadParser() and loadLanguage(Dart) in a try/catch, as dart.test.ts
does, so a grammar that loads but fails at parser initialisation skips the
suites instead of failing them in useFixture.

With loadLanguage made to throw for Dart, the four suites and
dart-prefixed-show-hide report 5 files / 31 tests skipped; with the previous
guards the four suites still ran.

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

* fix(dart): read the SDK lower bound of any pub constraint and bound every manifest

The package language version is the major.minor of the pubspec SDK lower
bound. The previous pattern accepted only a leading `^X.Y.Z`, `>=X.Y.Z` or
bare version followed by whitespace, so `>3.6.0`, `>=2.12.0-0 <3.0.0`,
`^3.6.0-0`, `>=3.0.0-417.0.dev <4.0.0`, `>=3.0.0<4.0.0` and
`<4.0.0 >=3.0.0` produced no version and the package silently got the
3.7 wildcard rules for `_`.

`dartSdkLowerBoundLanguageVersion` now tokenizes the whole constraint:
caret, `>=`, `>` and exact versions give a lower bound in any order, with
or without whitespace, with pre-release and build suffixes; an exclusive
`>X.Y.Z` uses X.Y; the greatest lower bound wins. `any`, an empty string,
upper bounds only, or text that is not a constraint give null.

`captureDartPackageConfig` now records the language-version boundary for
every readable manifest before the package-name check. A nested pubspec
whose `name` is missing or rejected used to register nothing, so its
files inherited the enclosing package's version.

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

* fix(dart): re-capture only files whose capture depends on the package language version

A package's language version comes from metadata that can change while
every source file stays cached, so the parse worker always captures with
the default (3.7+) rules and the resolver re-captures on the main thread
for a pre-3.7 package. That re-capture ran for every file of such a
package on every run, cold and warm: with `sdk: '>=3.0.0 <4.0.0'` and 800
cached files without any `_`, all 800 were re-read and re-captured.

The only difference between the two language modes is how a parameter or
local named `_` binds, and every such decision goes through
`dartUsesWildcardVariables`. Its first question for a tree now records
whether the answer came from the caller's version (no leading
`// @dart=` override). The Dart provider publishes that as
`ParsedFile.captureSideChannel` (`{ kind: 'dart',
packageLanguageVersionSensitive: true }`, absent for every other file),
which already survives the worker boundary, the ParsedFile store and the
durable parse cache.

`ScopeResolver.requiresPostExtractSourceText` receives the reused
`ParsedFile` as a third argument (undefined when the caller has none,
answered conservatively), so the predicate stays free of file I/O.
`requiresDartPackageSource` is true only for a sensitive file inside a
pre-3.7 package, and `applyDartPackageLanguageVersions` extracts only
those files again. On N cached files of which K have a `_` parameter or
local, a run reads K sources and makes K main-thread captures.

The new integration test drives the durable cache through SDK bound
flips across 3.7, pubspec removal and addition, nested pubspec
added / renamed / removed, and `// @dart=` overrides added / removed,
comparing the complete warm graph with a cold graph of the same tree and
counting re-captured files and materialized sources at each step.

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

* fix(dart): keep the reused capture when a legacy file cannot be captured again

`applyDartPackageLanguageVersions` threw "Dart language version requires
source" / "Dart language-version extraction failed" when a file of a
pre-3.7 package could not be extracted again. The phase passes `''` for a
reused file whose source it could not read (deleted, renamed or
unreadable between the scan and scope resolution), `extractParsedFile`
returns undefined for empty text, and the throw then failed scope
resolution for every language in the repository.

A file whose source is missing, empty or whitespace-only, or whose
extraction yields nothing, now keeps its reused `ParsedFile` (the default
3.7 capture). Each cause is reported in one warning per pass, with the
exact count and at most five paths, through the logger the neighbouring
package-config module uses.

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

* fix(dart): walk the capture tree on an explicit stack

walkDartTree recursed once per syntax node, and its frame grew in this
branch (one more parameter and the branch / loop token locals), so the
nesting depth it tolerated fell below the merge base's: 500 nested
argument closures overflowed the stack under vitest
(callable-flow-stack-depth.test.ts), and outside vitest the limit moved
from about 700 closures to about 600.

The walk now keeps its pending nodes in explicit arrays and visits them
in the same pre-order with the same owner and outer-owner values, so the
call stack no longer bounds the depth. The ordered capture stream is
byte-identical before and after for 423 Dart sources (every .dart file
under test/ and bench/ plus the review fixtures).

The stack-depth test gains a 2000-closure case.

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

* test(dart): expect the block-local binding in the scope-openers case

`void block(Address x) { { final x = make(); use(x); } x.save(); }` now
yields two bindings for `x`: the block's own local, typed by `make()`'s
result on the Block scope (call-result inference counts declarations per
lexical scope since this branch), and the parameter annotation on the
Function scope. The graph is right at both sites (inner `x.save()` ->
User.save, outer -> Address.save); only this capture-level expectation
was stale. The other cases of the test are unchanged.

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

* fix(dart): keep a local function's return type in its declaring scope

Local functions are routed through @declaration.function, so Pass A
publishes their @type-binding.return, and dartBindingScopeFor hoisted
every return binding to the Module scope. A local `Other fetch()` inside
one function then retyped the result of every other `fetch()` in the
file: the top-level or imported `User fetch()` called from another
function, a method of the same name, and, through the exporting file,
call sites in importing files.

The hook now keeps the return binding of a callable declared inside a
body or a statement scope in that scope, which is where the function's
name binds. A call result of the local function still resolves inside
the declaring scope (nested closures and blocks included); sites
outside it read the top-level, imported or member return type again,
and two local functions of one name in different functions no longer
overwrite each other.

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

* fix(dart): step over comments in a cascade

tree-sitter keeps a comment as a named sibling. In a commented cascade
the node before a section was the comment, so its text became the
receiver of that section and of every later one, and those calls were
dropped with no outcome row. A comment inside a section, between a
selector and the next selector or its arguments, ended the section's
chain.

emitCascadeReference now skips line, block and documentation comments
before a section and inside one, so each section reads the cascade's
real receiver.

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

* refactor(dart): name the return-binding exemption for what it withholds

The local `accessor` in Pass A also covered @dart.callable-body
(operators and factory constructors), which are not accessors. It is
now `withholdsReturnBinding`, and the comment gives the reason for both:
a factory constructor declares no return type, and an operator's
binding would be named `operator *` (what the signature reader calls
it), which no receiver or callee can spell, so no lookup reads it.

No behaviour change. The merge base emitted no declaration capture for
either, hence no return binding; a capture-level test pins that an
operator and a factory publish none and that their bodies open a scope.

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

* fix(dart): refuse a name guess to a local callable outside its scope

With local functions declared as Function nodes, the global-name
fallback could bind a bare call to a local function of another function
or of another file whenever the name was unique in the workspace (the
merge base already did this for a closure bound to a local variable).
A local callable's name is visible only in the body or block that
declares it, so that call is impossible, not merely unproven.

dartIsGlobalNameFallbackPlausible now refuses a candidate whose name is
bound in a Function or Block scope when the call site lies outside that
scope; the site is recorded as fallback-refused. A site inside the
declaring scope keeps its candidate, and a site with no known scope is
allowed as before.

The unit-test ParsedFile stub gains the `scopes` array the type
requires.

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

* fix(ruby): keep local claims from hiding calls, constructor facts and heredoc order

The ordered local-name claims of this PR stop an untyped local from
borrowing an accessor's or an enclosing scope's type. Four side effects of
that mechanism are fixed here; what it achieved is unchanged
(ruby-review-followups, ruby-bare-read-shadows-method and
ruby-yard-param-scope pass as before).

A constructor fact reaches every read its assignment governs. A scope keeps
one type fact per name, and the shared lookup drops it for a read whose
claim is not the claim in force where the fact was written. Two claims for
`repo = Repo.new` in the two arms of an `if` therefore left every read under
the first one untyped. Consecutive writes that leave the local holding an
instance of the same class (`x = K.new` again, or `x ||= …` over an
instance) now share one claim. A write of another class still starts a new
claim, so a read before it gets no edge rather than the later class.

A local never stops a call of the same name. `name(args)`, `name()` and a
bare name that is not a local read are method calls in Ruby whatever locals
exist. `NameClaim.neverCallee` marks a declaration that a call expression
can never invoke, and `NameLookupOptions.callee` marks a lookup made for a
receiver-less callee (the free-call pass and the call registry set it); such
a lookup does not see such a claim. Every Ruby local claim carries the mark,
so call resolution outside a class is what it was before the claims existed,
also for a local of the program or of a block. Inside a class the call still
dispatches on `self`; when no ancestor defines the method,
`resolveRubyReceiverMember` now reaches a top-level `def` of the file or of
a required file (a method of Object) instead of reporting an ambiguity.

A claim belongs to the scope node that declares the local. Claims were keyed
by the start position of the scope, which `program` shares with a `def` or
`class` that is the first token of the file, so the Module scope received
that scope's claims and a later call was resolved past the file's own
method. Claims are now keyed by scope node id and attached to the match of
that node.

A heredoc body is ordered where Ruby parses it: at its opener, before the
rest of the opener's line. A declaration inside a body is therefore visible
on the rest of each enclosing opener's line, and a declaration written after
an opener is not visible in the bodies opened before it. Positions of sites
stay physical; a claim whose visibility is not a suffix of the scope states
it through `NameClaim.availableSpans`, and `NameClaim.order` ranks two such
claims in parse order. Only declarations displaced by a heredoc carry them.

Baselines: the Ruby capture golden and the scope-capture fingerprint change
by `"neverCallee":true` on the claims of 19 fixture files and nothing else
(76 files and the synthetic source are identical). The ruby-bare-reads
fingerprints are unchanged.

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

* fix(scope-resolution): apply an import's name filters in wildcard expansion

`ParsedImport.nameFilters` (an ordered list of show / hide filters) was
copied onto the import edge, but the wildcard expansion that produces one
edge per exported name never read it, so a provider that pairs a wildcard
import with filters would bind every name of the target.

`expandWildcard` now keeps only the names the statement's filters admit.
When they admit none, the original file-level edge is kept, as it already
is for a target that publishes no name, so the file dependency survives.
The predicate is exported as `importNameFiltersAllow` for providers that
produce an import's names themselves.

No provider reaches this path with filters today; the Dart provider stops
using wildcard expansion in the next commit and applies the same predicate
where it builds its import namespaces.

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

* fix(dart): publish each imported library's names once, one import per directive

A plain `import` was rewritten into one named import per public name of
the target's export closure, so imports, edge drafts, edges and bindings
all grew with importers x exported names, and an import whose expansion
was empty vanished together with its file-level IMPORTS edge.

A plain import now stays ONE wildcard import and one import edge per
directive. What it makes visible is published once per (library,
combinator list) as a table in the shared per-namespace binding channel
(`namespaceFqnBindings`), and each importing file lists the tables it
sees. `show` / `hide` are applied where a table is built. Per importing
file the lookup order is: its own override table (names it declares
itself, and names two imports bring in as different declarations), then
each imported namespace in directive order, so one declaration reached
through a barrel and directly binds once.

The tables are installed by a new optional `ScopeResolver` hook,
`populateImportNamespaces`, called right after finalize: inheritance
resolution reads bindings before `populateNamespaceSiblings` runs, and a
superclass named through a barrel has to resolve there.

Also in this change:

- The export closure delivers a name along an `export` directive only
  when its state changes (absent, one declaration, ambiguous), so the
  work is bounded by the directives times the names they carry on chains
  and cycles alike, in any file order. A chain of 1,000 files that each
  declare one name took 166,666,500 name visits and now takes 499,500,
  the number of exported entries it produces.
- The facts of a library (export closure, plain imports) travel on the
  ParsedFile under a module-private symbol instead of in WeakMaps keyed
  by the object, so the export-only veto on the name fallback holds when
  disk scope mode replaces every ParsedFile by a scope-stripped copy.
- An unresolved `package:` import that names a candidate's own file keeps
  that candidate plausible for the name fallback even when the importing
  file also exports the library.

Behaviour that differs from the previous rewrite: a call result is no
longer typed through a function two imports declare differently (the
first import's declaration used to win there); such a name stays
ambiguous for that lookup.

800 importers of a 1,600-name barrel, whole pipeline, one machine, two
runs each: 1,452,988 / 1,450,240 kB peak RSS and 14.5 / 13.4 s before,
307,656 / 290,656 kB and 1.8 / 1.8 s now (merge base: 295,336 / 297,728
kB, 1.8 / 1.8 s), with identical CALLS edges.

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

* test(dart): pin export closure rules; probe the parser before enabling the suite

Three rules of the export closure had no assertion that fails when the
rule is removed: a private name is never exported (the only private name
in the suite was also dropped by a `show`), a name travels several export
hops and around a cycle, and a library's own declaration wins over an
exported one of the same name. The new fixture gives `save`, `make` and
`open` two owners each and reaches every name through a prefix, so each
edge is decided by one library's export namespace.

The suite's skip guard only asked whether the Dart grammar module loaded.
It now probes `loadParser()` and `loadLanguage(Dart)` like dart.test.ts,
so a grammar that loads but fails in `setLanguage` skips the suite instead
of failing it. The existing describe block is re-indented by the formatter
because its header now fits on one line; its assertions are unchanged.

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

* fix(dart): keep the local-callable refusal when scopes are sealed to disk

The name fallback refuses a bare call to another function's local callable
by reading an index of the candidate file's scopes. That index was built
lazily, keyed by ParsedFile identity. Disk scope mode replaces every file by
a `{ ...file, scopes: [] }` copy before the fallback runs, so the index came
back empty there and the refusal was lost: `g -> f.helper` and
`h -> f.helper` reappeared for `void f() { void helper() {} helper(); }`.

The index is now built in the workspace-reference hook, while scopes are
resident, and carried on the file under a module-private symbol, which a
spread keeps. Direct callers that never ran the hook still index lazily.

dart-import-edges.test.ts runs the shape in both modes; the disk-sealed case
fails without the hook call.

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

* test(dart): pin that an ambiguous export stays refused downstream; correct stale comments

An export closure name has three states: absent, one declaration, ambiguous.
Ambiguity travels along `export` directives like a declaration does, so a
library that re-exports an ambiguous name refuses it too, even when another
of its exports carries a single declaration of that name. Dart rejects the
upstream library (one name exported as two declarations), so picking the
remaining declaration would resolve calls through a namespace the compiler
never builds. The closure's doc comment now states this, and
dart-library-exports.test.ts pins it ("Dart ambiguous exports travel"); the
test fails when upstream ambiguity is ignored.

Comment and title corrections, no behaviour change:
- signature-bindings.ts: the sentence about a local function's return type
  had lost its subject.
- dart-awaited-receiver-owner.test.ts: the UNRESOLVED comment still listed
  `prefixedQualifiedFactory`, which is resolved and has its own test.
- ruby-yard-param-scope.test.ts: the header and the suite title still called
  a first-statement `@return` above `attr_reader` unattached; it is attached.

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

* refactor(ingestion): remove duplicated predicates and an eager per-file index

No behaviour change.

- dart/name-fallback-visibility: `recordDartLocalCallables` attaches its
  index only to a file that declares a local callable. A file without one
  answers the same from the lazy index, with or without its scopes, so it is
  no longer copied or given a retained scope-parent map.
- scope/walkers: `namespaceImportAllowsMember` uses the shared
  `importNameFiltersAllow` instead of a second copy of the show/hide rule.
- dart/language-version: one `dartVersionHasWildcardVariables(version)` for
  the `major.minor` parse that two modules repeated.
- ruby/captures: one `rubyLocalScopeOf` for the scope-tag lookup that was
  written once for the node map and once for the match.
- dart/captures: two comments state the invariant instead of the history.
- hooks/claude: the option-table helper is named `optionNames`.

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

* fix(hooks): decline a GNU grep long-option prefix that names several options

GNU grep accepts a prefix of a long option only when it names one option:
`grep --no query` exits 2 with "option '--no' is ambiguous". The hook
accepted such a prefix whenever every matching option had the same kind, so
it read `query` as the search pattern of a command that searched nothing.

A prefix is now accepted only when all the names it matches are one option,
where the two spellings `--color` / `--colour` count as one (`--col` stays
valid, as in grep). Checked against GNU grep 3.11: `--no`, `--line`, `--nu`
and `--co` are rejected; `--no-m`, `--line-n` and `--col` are accepted.

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

* test(ingestion): pin four reviewed behaviours and tighten one assertion

No source change.

- finalize-algorithm.test.ts: the private-wildcard test asserted
  `imports?.[0]?.targetDefId` is undefined, which also holds when the
  caller's import edge is gone. It now requires exactly one edge:
  `['helper', 'unresolved', undefined]`.
- dart-package-language-version.test.ts: a `||` constraint reads as no
  language version. pub has no disjunction: `VersionConstraint.parse`
  rejects it as unknown text.
- ruby-local-claims.test.ts: a call beside a same-named local or parameter
  reaches a top-level method whose `require` is written inside the method
  body or the class body.
- ts-object-literal-namespace-import.test.ts (new): a method and an arrow
  property of an object literal reach a namespace import although a
  property of the literal has the import's name. Passes on the merge base
  as well.
- ruby-yard-param-scope.test.ts: the header no longer claims a local-shadow
  case that suite does not contain.

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

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 17:06:51 +00:00

105 lines
25 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Ruby Ingestion Gaps
Audited on 2026-10-23 with freshly built production sources at `c35806d24` and
the accompanying benchmark changes. See the [measurement audit](receiver-resolution-audit.md)
for commands, target checks, exclusions and test limits. Historical reports below
remain separate from freshly measured receiver cases; broader ingestion is not
exhaustively assessed.
## Receiver shape snapshot
States below come from [baseline.json](../../gitnexus/bench/receiver-resolution/baseline.json).
The [harness](../../gitnexus/bench/receiver-resolution/measure.mjs) defines each
spelling and its N/A reason. RESOLVES requires the exact expected declaration ID
and no same-named call to a different owner. WRONG-TARGET records incorrect edges.
| Shape | Recorded state | Expression or exclusion |
| ----------------------- | -------------- | ----------------------------------------------------------------------------------- |
| `plainChain` | RESOLVES | `plain_svc.get_user.save` |
| `untypedChain` | VISIBLE-GAP | `untyped_svc.get_user.save` (intentional untyped control) |
| `plainDeepChain` | VISIBLE-GAP | `deep_svc.get_user.address.save` |
| `optionalChain` | RESOLVES | `opt_svc&.get_user.save` |
| `nonNullAssert` | N/A | Ruby has no non-null assertion operator. |
| `awaitParen` | N/A | Ruby has no await expression in the core language. |
| `explicitTypeArgs` | N/A | Ruby has no type-argument syntax. |
| `indexElement` | VISIBLE-GAP | `idx_repos[0].save` |
| `fieldReceiverCall` | RESOLVES | `@repo.save` |
| `decoratedReceiverBase` | N/A | Ruby method receivers carry no type decoration. |
| `decoratedFieldType` | N/A | Ruby instance variables carry no declared type, so there is no decoration to strip. |
The typed plain and safe-navigation chains resolve. Before RUBY-01 was fixed, the baseline recorded YARD parameter bindings landing on Module scope: a typed sibling could lend its type to an untyped parameter with the same name, in either declaration order, and fresh probes using the same `svc` parameter reproduced the wrong `User.save` edge from the untyped sibling in both orders (see the audit receipt). `rubyBindingScopeFor` now keeps `@type-binding.parameter` on the declaring method; [ruby-yard-param-scope.test.ts](../../gitnexus/test/integration/resolvers/ruby-yard-param-scope.test.ts) pins typed/untyped siblings in both declaration orders against the exact owner ID with a decoy `save`, and carries the review corpus below as pin-only expectations. The benchmark keeps its distinct parameter names so each cell measures its own spelling.
### Boundaries chosen for precision (missing beats wrong)
- A YARD `@param` types only a name that is one of the method's formal parameters and that the body never REBINDS — binding-target semantics: the name itself, or the name reached through a destructuring list / splat (`a, user = …`, `(a, user), b = …`, `a, *user = …`), `||=`/`+=`, `for`, `rescue =>`, a `case … in` / `=>` / `in` pattern (array/find/hash/as/splat patterns and the hash shorthand `{user:}`). A write INTO the parameter (`user.name = x`, `post.user = user`, `self.user = user`, `user[0] = 1`, `@cache[user.id] = user`, `user.count += 1`, `user&.name = x`, `user.a, user.b = …`), a block-parameter default reading it (`|x, y = user|`), a pinned `^user` or `^(user)`, and a read inside a nested block or lambda do NOT decline the tag (an assignment nested inside a pinned expression is a corner accepted unseen). In the method scope the tag's fact (strength 2) outranks a local's constructor-inferred type (strength 1), so without this a `# @param user [AuditLog]` would retype `user = User.new; user.save` as `AuditLog#save` (before the pin the local won by scope order) and a doc-drifted tag would type a name it never described. A declined tag types nothing. A block `|user|`, a block local `|x; user|`, a lambda `->(user)` or a nested `def inner(user)` no longer declines the outer tag (RUBY-03): each lists its parameters on its own scope, where the receiver walk stops, so an untyped `user` inside it stays untyped and the tagged `user` beside it keeps `User#save`. A stabby-lambda default has a separate scope for referenced parameters declared before that expression, including its own parameter. Later parameters do not shadow earlier defaults. These scopes keep an untyped lambda parameter from borrowing the outer tag without declining the tag itself.
- Not guarded (documented gaps, the tag stays): a regex named capture `/(?<user>…)/ =~ s`, `binding.local_variable_set(:user, …)`, `eval`.
- With the tag declined, a rebound parameter resolves exactly as its untagged twin (and main) does: `user = AuditLog.new; user.save` → `AuditLog#save`, `user = UserDecorator.new(user); user.full_name` → `UserDecorator#full_name`, `opts = Options.new(opts); opts.save` → `Options#save`, `user = user.account; user.save` → no edge. A call before the rebinding (`user.save; user = AuditLog.new`) keeps the pre-existing flow-insensitive answer, the local's type (`AuditLog#save`, as on main and for the untagged twin); letting the tag win would get that order right but every reassign-then-use idiom above wrong.
- A YARD `@param` types the parameter and nothing else. `@user = user` in `initialize` does NOT type `@user`, so `@user.save` in a sibling method stays unresolved (as on main), and the `attr_reader :user` forms no longer resolve: `holder.user.save`, and inside the class the bare `user.save` and `self.user.save`. Main resolved those only through the leaked class-scope `user` binding that also produced the wrong sibling edges. A YARD `@return` on a hand-written reader still types its chain, and so does one on an `attr_reader`, including when the annotated `attr_reader` is the first statement of the class body. `@user = User.new` still binds the field through the constructor pattern.
- Explicit `target()`, `target(1)` and `target 1` calls beside a same-named parameter dispatch through the enclosing class's `self` binding. The Ruby provider preserves call arity and removes the generic receiver-less callable-cell invocation: Ruby invokes a callable local through `.call` or `.()`. This also closes the previous same-named method-parameter gap. Bare `target` reads are filtered during capture by [Bare identifier reads](#bare-identifier-reads-ruby-04-fixed) (RUBY-04); the lexical name also prevents free-call fallback from treating the parameter as a method.
- Ordered local-name claims stop untyped locals from borrowing an accessor or enclosing type. The claim activates at the declaration, so earlier accessor reads still resolve. A block assignment to an existing outer local updates that outer cell; an explicit block-local declaration stays separate. A later write invalidates the earlier inferred fact, unless it leaves the local holding an instance of the same class (`repo = Repo.new` again, or `repo ||= …` over an instance): those writes share one claim, so every read among them keeps the type. A claim belongs to the scope node that declares the local, and a declaration in or beside a heredoc is visible where Ruby parses it (the body at its opener, before the rest of the opener's line). `ruby-review-followups.test.ts` and `ruby-local-claims.test.ts` pin these cases.
- Pre-existing, unchanged: `user ||= User.new` is an `operator_assignment`, which the constructor pattern does not bind, so `user.save` after it is unresolved; a declined `@param` tag on that name must not fill the gap (it would type it wrongly), so the edge stays missing.
- Pre-existing, unchanged: `@user = Const.new` in one method binds `@user → Const` on the class even when another method writes something else to it.
- Pre-existing, unchanged: a tag above `private def m(user)` or a `sig`-prefixed def is not attached (`findFollowingMethod` accepts only a `method` / `singleton_method` sibling), so its call is a missing edge; main typed it only when a sibling's same-named tag leaked onto the class.
- A YARD `@return` on an `attr_reader` publishes the accessor’s type on the class scope. Both untyped parameters and ordered untyped locals stop before that fact. This permits first-statement accessor annotations without extending the former local-name leak.
### Future: field typing from typed parameters (parked design, not in this PR)
Inferring `@ivar → T` from `@ivar = param` with `# @param param [T]` was prototyped and withdrawn: per-file capture synthesis cannot see every write to the field, so the published type can be wrong, and a wrong field type reaches every reader of the ivar. Any future attempt must start from this hazard list and decline whenever one applies:
1. Writes the per-file collector cannot classify must veto, not be skipped: writes under a block body (`[..].each { |log| @user = log }`), `@user, x = …` multiple assignment, `@user ||= …` / `@user += …`, any non-parameter, non-`Const.new` value (`nil`, call results).
2. Ownership is the Ruby object, not the syntactic class body: reopened classes (same file or another file) and mixins (`module Storage` included into the class) all write the same ivar, so agreement must be established across every body that can write it — which a per-file capture layer cannot do.
3. Generated writers are writes: `attr_accessor :user` / `attr_writer :user` let `h.user = AuditLog.new` change the field without any `@user =` in the class.
4. `normalizeYardType` turns `Array<User>` into `User`; a container-typed parameter must never publish its element type as the field's scalar type.
5. Parameter rebinding before the ivar write must veto: plain and multiple assignment, `||=`/`+=`, `for x in`, `rescue => x`, block/lambda/nested-def parameters, `case … in` patterns, rightward `expr => x` / `expr in x` (node positions enumerated from the tree-sitter-ruby grammar).
6. Conflicting typed writes (`initialize(user)` `[User]` vs `replace(log)` `[AuditLog]`) must type nothing; agreeing writes must type once; a hand-written reader's own `@return` must win over any inferred accessor type.
7. The accessor name must never be published on the class scope (`user → T`): it is readable from every sibling method's same-named untyped local. Parameters and ordered local-name claims now stop the walk, but field inference must still account for all writes.
## Parameters stop the receiver walk (RUBY-03, fixed)
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 and took the type of a same-named binding further out: `user = User.new; items.each { |user| user.save }` resolved the block's `user.save` to `User#save`. `emitRubyScopeCaptures` now attaches `@scope.lexical-names` to every scope that declares parameters, and each binder lands on the scope that declares it:
- a `do … end` / `{ … }` block: its `|…|` names, including destructured, splat, keyword, optional and `&block` parameters and block locals (`|x; user|`); this covers `lambda { |x| }`, `proc { |x| }` and `Proc.new { |x| }`;
- a stabby lambda (`->(x) { }`, `->(x) do … end`, `-> x { }`): its parameter list is a sibling of the body block, so the names are listed on the body, which is the scope;
- a method or singleton method: its parameters, so an untyped parameter no longer borrows a same-named top-level local, a class-level reader type or an enclosing method's YARD tag (a `def` nested in a method).
Blocks retain their existing scopes. Lambda default expressions outside the body get a scope only when they reference a parameter already declared in that lambda. Each scope lists only referenced names, so many defaults do not duplicate every earlier parameter. A block or method that declares nothing carries no capture. Numbered (`_1`) and `it` parameters are not listed: the grammar parses them as plain identifiers, `_1` cannot name an outer local, and `it` reads an outer local of that name when one exists. Locals are not listed (see the boundaries above). A closure that does not bind the name still reads the captured outer local (`items.each { |item| user.save }` keeps `User#save`), and a block parameter reassigned to a constructor inside the block takes that type. A block over a YARD-typed collection (`# @param users [Array<User>]`, `users.each { |u| u.save }`) stays unresolved, as before; `for v in users` keeps its element type. The stopped site records `receiver-type-unresolved` with `declineDetail: untyped-binder` and its binder scope, using the recorder added by DART-11 (#3903). [ruby-block-param-lexical-stop.test.ts](../../gitnexus/test/integration/resolvers/ruby-block-param-lexical-stop.test.ts) pins each shape against exact owner IDs with a decoy `save`, and [ruby-lexical-names.test.ts](../../gitnexus/test/unit/scope-resolution/ruby/ruby-lexical-names.test.ts) pins what each scope lists.
## Bare identifier reads (RUBY-04, fixed)
A receiver-less, paren-less identifier that is a statement of its own is captured as a zero-arity call (`(body_statement (identifier)) @reference.call.free`). Ruby decides that question lexically: the name is a variable read once a formal parameter, a block parameter or an assignment seen earlier in the enclosing scope has bound it, and a method call otherwise. Before the fix `class Host; def target; end; def run(target); target; end; end` produced a wrong `run → Host#target` CALLS edge. `emitRubyScopeCaptures` now drops the capture when the name is bound; [ruby-bare-read-shadows-method.test.ts](../../gitnexus/test/integration/resolvers/ruby-bare-read-shadows-method.test.ts) pins the cases below against the exact `Host#target` ID with a decoy `Other#target`, and [ruby-bare-read-order.test.ts](../../gitnexus/test/unit/scope-resolution/ruby/ruby-bare-read-order.test.ts) pins the helper directly on parsed trees, including shapes the statement pattern never captures.
- Bindings that make the bare name a read (no edge): the enclosing `def` / lambda's formal parameters (positional, optional, keyword, splat, hash-splat, `&block`, destructured), a `|x|` block parameter or `|x; y|` block local of an enclosing block, and a local bound earlier in the same scope by assignment (plain, multiple, `||=`), `for`, `rescue =>`, or a `case … in` / `=>` / `in` pattern (including the hash shorthand `{target:}` and its quoted form `{"target":}`). A block sees the names of every enclosing block and the method; a nested `def` starts a fresh scope and sees none of them.
- Kept as calls: `target()`, `self.target`, `target arg`, a bare name with no binding in scope, a read BEFORE the assignment (`target; target = 1` — Ruby registers a local when the parser passes its assignment), a bare name after a block whose parameter or local had that name (block bindings do not leak), and a nested `def` body reading a name only its enclosing method binds.
- Where a name binds: at the offset where it is WRITTEN, which is the rule Ruby's parser follows. A parameter binds at its name node, so a default expression sees the parameters declared before it and the parameter it belongs to, never a later one: `def run(x = [1].each do |a| target end, target: nil)` calls the method, `def run(target = nil, x = [1].each do |a| target end)` reads the parameter, and `def run(target = [1].each do |a| target end)` reads the nil local (a circular reference); the same holds for block and lambda parameter lists (checked on CRuby 2.6). An assignment target or pattern variable binds at its own identifier, so a read inside the value of a rightward `value => target` / `value in target` or inside an earlier multiple-assignment target's subscript (`arr[[1].map do |x| target end], target = [], 1`) is still a call.
- Header expressions: a singleton method's receiver (`def (target = Object.new).run`), a class's or module's name expression (`class (target = Object)::Inner`), a class's superclass and a `class << value` value are evaluated in the ENCLOSING scope. They bind there, never in the body, so the body's bare `target` keeps its call; a read inside such a header (reachable through a `do` block or lambda body) is answered by the enclosing scope. A bare header name (`class << make_base`) is not a binding site.
- `BEGIN { … }` / `END { … }` bodies share the locals of the scope around them (Ruby's own `BEGIN` / `END` example shares one local with the program): an assignment inside one binds the enclosing scope (`def run; END { target = 1 }; target; end` reads the local), and a read inside one sees the enclosing scope's names. `BEGIN` is valid only at the top level.
- Patterns bind only in binding positions: pattern containers (array, find, hash, alternative, parenthesized) and an identifier, keyword pattern, as-pattern, splat or hash-splat. A string / regex / symbol / subshell `interpolation`, a `lambda` pattern's parameters, a `^pin`, a constant and a range bind nothing, so `in "x#{target}"` keeps the later call. tree-sitter-ruby parses a hash argument whose key starts with a unary operator (`s.put !x => target`, `put :a, -x => target`, `[!x => target]`) as a pattern match under `unary`; inside an argument list, array literal or subscript it is a hash pair and binds nothing, while the statement `!x => target` still binds.
- Not captured either way (pre-existing): a bare name inside a brace block body (`block_body`), a `begin … end` body, an `if` / `case` / `rescue` branch (`then`) or a `for` / `while` body (`do`), which the statement pattern never matched.
- Heredoc bodies are parsed at their opener: Ruby lexes a body when it reaches its `<<~EOS` token, before the rest of that line. The guard links each body to its opener and uses that scope and parse order for both bindings and reads. A body sees earlier parameters and locals, but not an assignment later on the opener line; a read later on that line sees bindings made in the body. The opener's scope still owns the body when a method or block closes on that line: its parameters remain visible, nested method boundaries still apply, and its assignments do not leak into the physical body's surrounding scope. Bodies opened on one line are paired with openers in token order. If their counts disagree, the unmatched body cannot establish a local read or a binding.
- Not guarded (the capture stays, a wrong edge where a same-named method exists, as before the fix): a regex named capture `/(?<target>…)/ =~ s`, `binding.local_variable_set`, `eval`, and the implicit block parameters `it` and `_1` … `_9` in a block without explicit parameters.
- Explicit `target()` calls beside same-named parameters or locals dispatch through `self` inside class methods; when no ancestor defines the method, `self` reaches a top-level `def` of the file or of a file it requires (a method of Object). A local never names what a call invokes, so its claim is marked `neverCallee` and no callee lookup sees it: outside a class, and for a local of the program or a class body, the call resolves as if the local were not there. Bare reads remain reads, and callable locals retain `.call` invocation.
- With RUBY-03's parameter lexical names, a bare name that the positional read check proves is a call can still collide with a later parameter or an outer method's parameter. Inside a class/module method, capture routes that call through the existing `self` binding. This preserves calls in nested methods, parameter defaults and heredoc bodies without letting a local read become a call or changing the explicit-call gaps above.
- Performance: one file walk records which bare identifier nodes read a bound name; each later classification is a set lookup. Files with heredocs also build a parse-order index once; ordinary files use source offsets. Visible names, self receivers and logical heredoc callers are indexed during that walk. Surviving free calls use those indexes without repeating ancestor climbs. These caches expire with the capture pass. The `scope-processing` benchmark gates this work at four sizes in fresh processes (#3915).
- Follow-up: the RUBY-01 rebinding guard (`rubyParameterNames` / `lhsBinds` / `patternBinds`) walks the same binding positions with its own helpers. Folding it onto these collectors is not mechanical: its pattern walker errs toward declining on unknown pattern kinds (a missing edge is its safe side), while this collector errs toward keeping the call, so the merge would change RUBY-01's decline set and needs its own pins.
## Planning candidates
| ID | Evidence | Gap or boundary | Next planning step and acceptance |
| ------- | ------------ | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| RUBY-01 | Fixed | YARD parameter types leaked between sibling functions: the method-anchored binding was auto-hoisted. | Fixed: `rubyBindingScopeFor` binds `@type-binding.parameter` to the declaring method; the tag binds only a formal parameter the body never rebinds (binding-target semantics — writes into the parameter and reads keep it; never `self`), and nothing else is inferred from it. Regression test covers typed/untyped siblings in both orders; the rebinding forms it guards — plain/multiple/splat assignment, `\|\|=`/`+=`, `for`, `rescue =>`, block/lambda/nested-def parameters and block locals, `case … in` / `=>` / `in` patterns incl. the hash shorthand `{user:}` — each `[]` with the guard and a wrong `User#save` without; the kept write-into/read forms (ten lost on the mention-based guard, `^(user)` lost after it); and the construct coverage. Not guarded: regex named captures, `binding.local_variable_set`, `eval`; the pin-only ivar boundaries and explicit-call parameter cases are pinned separately. Known unguarded rebindings listed above. |
| RUBY-02 | Measured gap | `plainDeepChain` reaches an attr_reader property whose type is unavailable. | Reproduce the property-type loss before choosing a propagation rule. Preserve accessor dispatch and same-name owner boundaries. |
| RUBY-03 | Fixed | An untyped block, lambda or method parameter climbed past itself to a same-named outer binding's type (`user = User.new; items.each { \|user\| user.save }` → `User#save`). | Fixed: `emitRubyScopeCaptures` lists each scope's parameters as `@scope.lexical-names` (block parameters and locals on the block, stabby-lambda parameters on the lambda body, method parameters on the method), so the shared walk stops there. The YARD `@param` decline no longer fires for parameter shadows, including lambda defaults. Defaults respect parameter declaration order. Explicit calls beside same-named parameters retain the enclosing class method target. |
| RUBY-04 | Fixed | A bare read of a name that is both a method on the enclosing class and a parameter or local resolved to the method (a local read misread as a call). | Fixed: `emitRubyScopeCaptures` drops the bare-identifier call capture when the enclosing scope binds the name (see "Bare identifier reads" above). Explicit calls beside a same-named parameter dispatch on the enclosing class's `self` binding. |
| RUBY-05 | Measured gap | `indexElement` is visible after the walker learned element_reference, but there is no elementTypeOf hook. Listed as RUBY-03 before that ID went to the fix above. | Carry YARD Array<User> element evidence into a provider route. Keep unsupported arrays and the intentional untypedChain control unresolved. |
## Code and regression entry points
- [Language provider directory](../../gitnexus/src/core/ingestion/languages/ruby/).
- [Scope resolver](../../gitnexus/src/core/ingestion/languages/ruby/scope-resolver.ts).
- [ruby-accessor-dispatch.test.ts](../../gitnexus/test/integration/resolvers/ruby-accessor-dispatch.test.ts).
- [ruby-scope.test.ts](../../gitnexus/test/integration/resolvers/ruby-scope.test.ts).
- [ruby-block-param-lexical-stop.test.ts](../../gitnexus/test/integration/resolvers/ruby-block-param-lexical-stop.test.ts).
- [ruby-captures-golden.test.ts](../../gitnexus/test/unit/scope-resolution/ruby/ruby-captures-golden.test.ts).
Evidence details: [receiver baseline notes](../../gitnexus/bench/receiver-resolution/BASELINE.md) and
[current roadmap](../../type-resolution-roadmap.md#current-backlog).