Skip to content

feat(go): dispatch interface method calls to implicit implementers - #4934

Closed
nothariharan wants to merge 1 commit into
Graphify-Labs:v8from
nothariharan:feat/go-implicit-interface-dispatch
Closed

nothariharan wants to merge 1 commit into
Graphify-Labs:v8from
nothariharan:feat/go-implicit-interface-dispatch

Conversation

@nothariharan

Copy link
Copy Markdown
Contributor

What does this PR do?

A Go call through an interface-typed field lands on the interface's method node, which is correct. But nothing links that interface method to the concrete types that implement it. So the concrete method loses every caller that goes through the interface, and a directed walk stops at the interface.

Repro on v8 (f5155bad, 0.9.100). go.mod is module example.com/app.

// plugincontext/provider.go
package plugincontext

type Provider struct{}

func (p *Provider) GetWithDataSource(uid string) error { return nil }
// expr/nodes.go
package expr

type pluginContextProvider interface {
	GetWithDataSource(uid string) error
}

type DSNode struct {
	provider pluginContextProvider
}

func (d *DSNode) Execute() error {
	return d.provider.GetWithDataSource("x")
}

v8 emits calls .Execute() -> expr_plugincontextprovider_getwithdatasource (the interface method). Nothing reaches plugincontext_provider_getwithdatasource, before or after build_from_json. Grafana has the same shape: pkg/expr/nodes.go calls GetWithDataSource through pkg/expr's local pluginContextProvider, and plugincontext.Provider.GetWithDataSource loses those callers.

Why. graphify.interface_dispatch (#3003, shared with the Swift pass) already links interface_method --dispatches_to--> implementing_method. It is driven by implements edges. Go satisfies interfaces implicitly, so the Go extractor emits no implements edges and the mechanism never runs.

Change.

  • graphify/extractors/go.py stamps each interface type node with metadata: {"language": "go", "kind": "interface"}. Without it the output cannot tell an interface's method requirements from a struct's methods, because both hang off their owner by a method edge. language and kind are already among the metadata keys that the incremental update/watch context forwards for unchanged nodes, so the stamp survives an incremental rebuild.
  • New graphify/go_dispatch.py, registered next to the C# and Swift passes. It infers implementers from method sets: named type T implements interface I when T's methods include every method name I requires, counting I's own methods and the methods of interfaces it embeds. T can be a struct or any other named type with methods. Value and pointer receivers both count, because the extractor hangs both off T's node. The pass hands those pairs to resolve_interface_dispatch and keeps only the dispatches_to edges that come back. The inferred implements pairs are not added to the graph.
  • _AST_CACHE_SCHEMA 33 -> 34, so cached Go extractions re-run and pick up the stamp.

The C# and Swift edges keep their shape and tiers: INFERRED, context: "call", 0.85 for one implementer, 0.75 for two, 0.65 floor, and the per-implementer single-owner guard. The edge is additive, so the calls edge to the interface method stays.

Matching rule and guards

  • Matching is by name only. Method nodes carry no parameter list, and Go has no overloads to tell apart. Adding arity would mean new metadata on every Go method node, so I left it out.
  • Both ends must be declared in a .go file. This is the same suffix gate as the C# and Swift passes.
  • An interface with no methods (interface{}, any) is skipped. Every type satisfies it.
  • A type-set interface (~int | ~string, which the extractor marks as a type_constraint reference) is skipped. It is a generics constraint, not something a call goes through.
  • When an interface embeds another, the embedded interface's methods are required too. If an embedded interface is not declared in the corpus (io.Reader), the method set is unknown, so the interface is skipped. Matching on part of the method set would admit types that do not implement it.
  • An unexported requirement (run()) can only be implemented in the interface's own package. When the interface requires one, only types in the same directory count.
  • Cap. The shared mechanism has no fan-out cap, because declared implements cannot explode. Name-only structural matching can. An interface matched by more than 10 types (_MAX_IMPLICIT_IMPLEMENTERS) is skipped entirely. It is not truncated, because which ten to keep would be arbitrary. On Grafana pkg/ (5715 Go files, 1056 interfaces), 160 interfaces go over the cap. The largest are Runnable/BackgroundService/Elector-style interfaces, with 436 matching types each, and Validator-style ones, with 333 each. Without the cap they would add thousands of 0.65 edges that say little.
  • Common names (Error, String). These get no special case. The builtin error and fmt.Stringer are not corpus nodes, so they never match. A local redeclaration (type stringer interface{ String() string }) is a real interface that calls go through. It gets edges like any other interface, and the cap covers the case where the name is everywhere.

Effect on Grafana pkg/: 6637 dispatches_to edges (680 at 0.85, 1502 at 0.75, 4455 at 0.65). expr.pluginContextProvider.GetWithDataSource now dispatches to plugincontext.Provider.GetWithDataSource and to the in-package test fake, at 0.75. The pass took about 3 s on that corpus with the cap disabled.

Limitations

  • Struct embedding is not followed. If a type gets a method from an embedded field, the type does not own that method node, so it is not matched.
  • Name-only matching can pair a type whose method has the same name but a different signature. Confidence tiers and the cap limit this; they do not remove it.
  • Test fakes and mocks implement interfaces too, so they count as implementers and lower the tier for the production type. That is structurally correct, but it is noisier than C#, where a mock usually comes from a framework rather than from source.
  • Interfaces declared outside the corpus (stdlib, dependencies) get no edges, because they have no method nodes.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariant: a dispatches_to edge joins a Go interface method only to a same-named method of a Go type that has every method the interface requires. The edge is additive (the calls edge to the interface stays), carries an INFERRED tier, and is never emitted for an interface whose method set is unknown or empty.

Persisted state: the AST cache schema is bumped, so stale Go cache entries without the stamp re-extract. The only other change to graph output is the new metadata on Go interface nodes.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

How was this tested?

New tests/test_go_interface_dispatch.py has 10 tests:

  • the repro, with the implementer in another package (edge shape, calls edge kept, chain reachable into the concrete method's callee, no implements leaked)
  • value and pointer receivers
  • a type missing one method (no edge)
  • two implementers (both get an edge, at 0.75)
  • empty interface ignored
  • embedded interface methods required
  • external embedded interface skipped
  • unexported method matched in the same package only
  • over-cap interface skipped
  • non-Go end ignored

Each guard was also turned off one at a time, and its test failed.

# without the change (source changes stashed, go_dispatch.py moved out)
uv run --frozen pytest -q tests/test_go_interface_dispatch.py -p no:cacheprovider
7 failed, 3 passed     # the 3 passes are the negative cases

# with the change
uv run --frozen pytest -q tests/test_go_interface_dispatch.py -p no:cacheprovider
10 passed

uv run --frozen pytest -q tests/ -k "go_ or dispatch" -p no:cacheprovider
296 passed, 10 skipped, 8980 deselected

uv run --frozen ruff check graphify/go_dispatch.py tests/test_go_interface_dispatch.py graphify/extract.py graphify/extractors/go.py
All checks passed!

uv run --frozen python -m tools.skillgen --check
check OK: 134 artifact(s) match committed output and expected/.

# full suite, Linux (WSL), uv sync --all-extras --frozen, isolated HOME, AWS env nulled
uv run --frozen pytest tests/ -q --tb=short -p no:cacheprovider
9372 passed, 28 skipped, 1 xfailed in 839s   (commit 97ccefff)

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (Not applicable: no skill fragments changed; --check passes.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables).
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages.

A call through an interface-typed field lands on the interface's method
node, and nothing joins it to the concrete method, because Go types
satisfy interfaces implicitly and the shared interface_dispatch pass
only reads `implements` edges. So the concrete method loses every caller
that goes through the interface.

The Go extractor now stamps interface type nodes with
metadata {"language": "go", "kind": "interface"}, and a new
graphify.go_dispatch pass infers implementers from method sets (every
method name the interface requires, own and embedded) and feeds those
pairs to resolve_interface_dispatch. Empty interfaces, type-set
constraints, interfaces embedding an interface outside the corpus, and
interfaces with more than ten structural implementers are skipped; an
unexported requirement only matches types in the same package. The AST
cache schema is bumped so cached Go extractions pick up the stamp.
@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Nov 1, 2026
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown

Thanks for the pull request, @nothariharan. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.

Not checked: tests were not run; formal verification proved 0 of 1 changed function(s) (1 sampled, not proven).

Formal verification. PR-changed functions: 1/1 verified (0 proven, 1 may-equivalent, 0 distinguished) · 0 not verified.


Graphify review — findings

Adds Go interface dispatch: calls through an interface now reach the types that implicitly implement it, and resolve_go_interface_dispatch leaves non-Go interfaces untouched. Go interface type nodes now carry metadata.kind == "interface" so the resolver can identify them, and the _AST_CACHE_SCHEMA bump to 34 forces cached Go extractions to re-run and pick up that tag. Which types count as implementers depends on the interface's method set, so how methods gained through embedded interfaces are counted decides which interfaces get dispatched at all.

Worth a look

  • Interfaces whose methods all come from embedded interfaces are never dispatched — graphify/go_dispatch.py:107 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 3967 functions depend on the 488 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: extract() — 1091 callers, 64 callees
  • new: resolve_go_interface_dispatch() — 3 callers, 5 callees

Verification — 3967 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 3694 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

261 of 488 test file(s) selected (53%) via static blast radius.

  • tests/test_4874_jvm_resolution.py — impact
  • tests/test_affected_overrides.py — impact
  • tests/test_astro_extraction.py — impact
  • tests/test_astro_import_ids.py — impact
  • tests/test_binary_media_words.py — impact
  • tests/test_blade_extractor.py — impact
  • tests/test_build.py — impact
  • tests/test_builtin_global_type_refs.py — impact
  • tests/test_c_include_resolution.py — impact
  • tests/test_cache.py — impact
  • tests/test_cache_long_paths.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_case_only_decl_ids_4904.py — impact
  • tests/test_case_sensitive_resolution.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_cobol_extractor.py — impact
  • tests/test_confidence_score_output.py — impact
  • tests/test_cpp_method_declarations.py — impact
  • tests/test_cpp_nested_and_cli.py — impact
  • tests/test_cpp_objc_cross_file_calls.py — impact
  • tests/test_cpp_template_type_params.py — impact
  • tests/test_cpp_type_alias.py — impact
  • tests/test_cross_extension_reexport_self_cycle.py — impact
  • tests/test_cross_language_call_resolution.py — impact
  • tests/test_cross_repo_external_call_guards.py — impact
  • tests/test_cross_repo_member_calls.py — impact
  • tests/test_csharp_call_site_generic_args.py — impact
  • tests/test_csharp_delegate_declarations.py — impact
  • tests/test_csharp_enum_members.py — impact
  • tests/test_csharp_field_generic_args.py — impact
  • tests/test_csharp_foreach_loop_variable.py — impact
  • tests/test_csharp_generic_callsites.py — impact
  • tests/test_csharp_interface_dispatch.py — impact
  • tests/test_csharp_member_calls.py — impact
  • tests/test_csharp_member_chain_calls.py — impact
  • tests/test_csharp_member_nodes.py — impact
  • tests/test_csharp_method_owner_labels.py — impact
  • tests/test_csharp_object_creation.py — impact
  • tests/test_csharp_overloads.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_csharp_tuple_type_refs.py — impact
  • tests/test_csharp_type_resolution.py — impact
  • tests/test_csharp_underscore_collisions.py — impact
  • tests/test_csharp_var_call_return_type.py — impact
  • tests/test_csharp_verbatim_interpolation.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • tests/test_dotnet.py — impact
  • … and 211 more

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Docs that may be stale (advisory)

Formal verification

No difference found (not proven): No behavior difference found in extract\_go (not a proof).

The verifier ran both versions of extract\_go on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

· 1 grounded finding(s) anchored inline below; 1 more finding(s) on lines outside this diff (see the check run).

Comment thread graphify/go_dispatch.py
return isinstance(meta, dict) and meta.get("language") == "go" and meta.get("kind") == "interface"


def resolve_go_interface_dispatch(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — resolve_go_interface_dispatch()

high coupling complexity (Ca·Ce = 15).

Grounded coupling-delta finding (deterministic), not an LLM guess.

safishamsi added a commit that referenced this pull request Nov 3, 2026
… extractor fixes

#4985, #4972, #4956 (#4935) and the Go cluster #4966/#4853/#4934 each change
per-file extractor output; fold them into one schema-37 entry (#4956 shipped
without its own bump) so warm caches re-run the affected extractions.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.102 (published to PyPI), cherry-picked with your authorship preserved. Thanks @nothariharan.

@safishamsi safishamsi closed this Nov 3, 2026
livingforelvis added a commit to livingforelvis/graphify that referenced this pull request Nov 20, 2026
…aphify-Labs#5319)

A call through an interface-typed field (`this.worker.run()` where
`worker` is a `Worker`) lands on the interface's method node, and nothing
joins it to `EmailWorker.run()`, so a directed walk stops at the
interface. C# (Graphify-Labs#3003), Swift (Graphify-Labs#4035) and Go (Graphify-Labs#4934) already close this
gap with `dispatches_to`; no pass was registered for `.java`.

The Java extractor already emits `implements` and the interface's
`method` edges, so graphify.java_dispatch is a thin `.java` gate over
resolve_interface_dispatch, registered after the Go pass. Same rules as
the other languages: additive INFERRED edges at 0.85 / 0.75 / 0.65 by
implementer count, both ends declared in `.java`. Each Java overload is
its own node, so the shared pairing links overloads by signature, then
arity. No extractor change, so no AST cache schema bump (as for Swift).

Known limits, pinned by tests: `extends` (abstract classes) is not
read, interface hierarchies are not walked, an unoverridden `default`
method gets no edge, a lone same-named method pairs without a signature
check, and a fully qualified `implements a.Worker` with no import binds
to a sourceless stub and gets no edge (the imported form links).

Two C# tests asserted that a Java corpus gains no dispatch edge; they now
call the C# pass directly, and the mixed-corpus test expects each pair
within its own language.

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants