Repository navigation
feat(java): dispatch interface method calls to their implementers (#5319) - #5323
livingforelvis wants to merge 4 commits into
Conversation
|
Thanks for the pull request, @livingforelvis. 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.11 and 3.13, and that the change keeps extraction deterministic. |
|
I ran a small test set against this branch (27e6b42). One case gives a wrong edge: an interface method named like the implementing class gets linked to that class's constructor. // F.java
public interface F { void Widget(); }
// Widget.java
public class Widget implements F { public Widget() {} }On this branch the graph gets Here's why. The fix is two lines in elif config.ts_module == "tree_sitter_java" and t == "method_declaration":
method_metadata = {**java_sig_meta, "signature": java_sig}
+ elif config.ts_module == "tree_sitter_java" and t == "constructor_declaration":
+ method_metadata = {"kind": "constructor"}It changes cached Java nodes, so With the tag in place, the case gives no edge. All Java and dispatch tests on v8 still pass (239). The test I used: def test_constructor_named_like_interface_method_is_not_a_target(tmp_path):
d, r = _extract(tmp_path, {
"F.java": "public interface F { void Widget(); }",
"Widget.java": "public class Widget implements F { public Widget() {} }"})
assert d == []
ctor = _id(r, ".Widget()", "Widget.java")
assert next(n for n in r["nodes"] if n["id"] == ctor)["metadata"]["kind"] == "constructor"The commit is 1040335e on my fork if you'd like to cherry-pick it. Otherwise feel free to fold it in however suits the PR. A separate thing I noticed (not this PR): a Java constructor |
There was a problem hiding this comment.
Graphify code review 
Review completed · e85852c51246
Warning
Merge confidence: 3/5 · Review before merging · 🟠 High impact
2 P2 bugs · 5 possible issues not confirmed
1 not re-checked
The change registers a Java resolver that links interface methods to implementing methods.
Full summary
The change registers a Java resolver that links interface methods to implementing methods. It also marks Java constructors so they are excluded from those links.
Bugs (2)
P2 · Disable arity-only fallback in resolve_java_interface_dispatch: an abstract implementer can leave an interface method unimplemented, but the matcher may link it to a different-signature overload. Inspect source
Detailed review · checked against the code
Java overloads with matching parameter counts can get false dispatch edges
An abstract Java class can be linked to an overload that does not implement the interface method.
Expected: No dispatch edge connects overloads with different signatures.
Actually: After exact matches are taken, the matcher can pair remaining overloads by arity alone, producing a false dispatch edge.
For Java, the resolver enables match_arity=True. In the shared matcher, multi-method overload sets are matched by signature first, then unmatched interface methods fall back to arity. Thus send(String) can pair with send(String), after which an unmatched send(Integer) can pair by arity with the remaining send(Long). That creates a dispatch edge between methods with different signatures. The Java resolver is registered in the extraction pipeline, and an abstract implementer may legally leave an interface method unimplemented.
-
Independent source review: The tests cover matching same-arity signatures and an unmatched interface overload when the implementer has only one method, but do not cover distinct same-arity overloads on both sides. The matching implementation confirms the false edge can occur in that multi-overload case.
-
Some lookups asked for files or lines that do not exist; the review was told and carried on.
P2 · Restrict _overload_pairs to matching parameter signatures for Java dispatch: its arity fallback can link interface overloads to implementation methods with different parameter types. Inspect source
Detailed review · checked against the code
Java overloads can dispatch to methods with the wrong parameter types
When both sides have multiple same-name overloads, Java interface methods can be linked to implementation methods with different parameter types.
Expected: Dispatch edges should only pair overloads that implement the interface method’s parameter signature.
Actually: The matcher falls back from signature matching to arity and can infer an edge to the mismatched overload.
For overloaded methods, _overload_pairs first tries signatures and then falls back to arity. With multiple overloads on each side, a declared method can therefore pair with the sole unused candidate of its arity even when their parameter types differ. For example, interface overloads send(String) and send(int, int) and implementer overloads send(Integer) and send(long, long) produce unique arity matches but no signature matches. The Java wrapper passes match_arity=True, but that flag only checks the one-method-on-each-side case; Java dispatch can consequently include these mismatched pairs. Java’s resolver is registered in extraction, so this path is reachable for Java interface-dispatch graphs.
-
Independent source review: The tests cover matching overload signatures, an interface overload with multiple nonmatching candidates (which yields no edge), and a one-method-per-side same-arity mismatch (which is intentionally linked). They do not cover multiple overloads on each side with unique arity matches but mismatched signatures. The candidate’s wording that all overloads must share one arity is narrower than necessary: distinct arities can each have a unique mismatching candidate.
-
The false pairing requires multiple overloads of the same name and arity on both sides; other overload shapes may be rejected or matched by signature.
Not confirmed (5 possible issues)
Leads worth a look; we didn't double-check these. They don't change the score.
Not confirmed · Same-arity overload test expects an interface send(String) to link to an unrelated send(int) overload Inspect source
Detailed review · not confirmed
The test at line 222 asserts that the interface's send(String) is dispatched to MailSender.send(int). Those are different parameter types, so a real call would run the inherited Base.send(String) instead. The test locks in a wrong edge.
Lines 199 and 214 define Base.send(String), which MailSender inherits. Line 217 declares send(int) on MailSender, which is an overload with a different parameter type and does not override the String method. The comment at lines 210-211 calls the match a known limit of erased signatures, which would make it a missed precision case. But line 222 asserts a concrete edge to the wrong method, not a missing one. The sibling test at lines 194-206 correctly refuses to link a non-matching overload, which shows the intended rule is to match the signature and not only the arity. The expected value here contradicts that rule.
-
Only the one-method-per-side case with a single inherited method is shown; the resolver code that compares erased signatures is not in this file.
-
Found by the per-file sweep; not double-checked.
Not confirmed · With match_arity on, two methods that record no parameter count are paired, although the docstring requires both to record the same count Inspect source
Detailed review · not confirmed
When match_arity is set, a lone interface method is paired with a lone implementer method even when neither records a parameter count. The docstring says the pair needs both to record the same count, so an unknown count should block the pair.
At lines 247-251, _overload_pairs takes the lone-pair branch and runs if match_arity and _meta(source).get("arity") != _meta(target).get("arity"): return []. _meta returns {} when there is no metadata, so .get("arity") returns None for both nodes and the comparison passes. The docstrings at lines 107-109 say match_arity makes the pair happen "only when both record the same parameter count", and lines 240-241 say "the one-of-each pair also needs the same recorded parameter count". Neither condition holds when neither side records a count. The overload branch at lines 253-262 avoids this because it only matches on keys that are not None (want is None is skipped at line 258).
-
Whether the Java extractor records an
arityvalue in method metadata is not visible in this file. -
Whether the Java wrapper passes match_arity=True is not visible in this diff, so the effect on real Java output is unconfirmed.
-
The case where only one side records an arity is handled by the
!=comparison and was not traced further.
Not confirmed · The Java no-dispatch test calls only the C# resolver, so it cannot fail if Java dispatch is wrong Inspect source
Detailed review · not confirmed
test_java_interface_and_implementation_are_untouched now calls only resolve_csharp_interface_dispatch on Java nodes and checks that no dispatches_to edge appears. The C# resolver skips non-.cs files, so this assertion passes whatever the Java pass does. The earlier end-to-end check through _extract was removed, so nothing in this file checks the Java pipeline for a Java-only corpus.
Lines 196-212 build Java-labelled nodes and edges, then call resolve_csharp_interface_dispatch([], nodes, edges). The removed version went through _extract with Java files, so it exercised the full extraction path. The new version exercises only the C# resolver, which returns early for .java source files, so the assertion on line 212 is always true. The mixed-corpus test at line 316 covers Java linking only when a C# pair is also present, so a Java-only regression has no assertion at all.
-
Whether a Java-only
_extracttest exists elsewhere in the repository was not inspected -
Only this file's diff was available, so the Java pass implementation was not read
-
Found by the per-file sweep; not double-checked.
Not confirmed · The PR title says it dispatches interface calls to implementers, but the changed lines only tag Java constructors with a kind marker Inspect source
Detailed review · not confirmed
The changed lines at 9976-9977 add a {"kind": "constructor"} metadata branch for Java constructor declarations. The PR title describes interface method dispatch, and the description is empty, so nothing in the code shown connects this change to that goal.
Before this change, Java constructor nodes received method_metadata = ruby_method_metadata, which is None for Java. Lines 9976-9977 now replace that with {"kind": "constructor"}. No line in the changed hunk touches interface resolution, implementer lookup, or call edges, and the PR description is blank. So the code and the stated intent do not match.
-
The rest of the PR diff, its commit history, and any tests were not provided, so the dispatch logic may live in other files.
-
The consumers of the node metadata key
kindwere not in the excerpt, so their handling of the new value is unknown. -
Found by the per-file sweep; not double-checked.
Not confirmed · Java constructor nodes gain a generic kind metadata key that differs from the namespaced Ruby key and may collide with other readers Inspect source
Detailed review · not confirmed
Constructor nodes now store kind as a top-level metadata key. The neighbouring Ruby logic uses the namespaced ruby_method_kind key, and Java methods store signature metadata under other keys. A reader that looks for a kind key expecting another meaning could misclassify these nodes.
Line 9977 assigns method_metadata = {"kind": "constructor"}. Ruby metadata at line 9963 uses ruby_method_kind, and the sanitize_metadata call at line 9970 is applied only to existing Ruby nodes. The shape of the Java constructor metadata therefore differs from the other method metadata in this function, and this change adds no namespacing for it.
-
The metadata consumers and the sanitize_metadata implementation were not visible, so whether a collision happens is unconfirmed.
-
The function that computes func_nid for Java constructor_declaration nodes was not in the excerpt, so the node identity of constructors could not be checked.
-
Found by the per-file sweep; not double-checked.
What this review covered
- Some lookups asked for files or lines that do not exist; the review was told and carried on.
- 10 of 10 changed files inspected. This is scope, not a correctness guarantee.
Code graph and static checks · 6038 functions depend on this change
Impact & health
Impact — 6038 functions depend on the 1079 functions this change touches.
Health — this change adds coupling hotspots:
- worse:
extract()— 1305 callers, 78 callees - worse:
resolve_interface_dispatch()— 8 callers, 4 callees
Formal checks — 6038 functions this change can affect weren't formally checked in this review. Formal checks are informational only.
Gate & verification
✅ PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.
Advisory (not blocking):
- verification_scope: 5331 function(s) in the blast radius were not formally verified this run
Test selection
602 of 602 test file(s) selected (100%) via static blast radius.
Escalated to a full run for safety (
uncovered-code) — the selection is not trustworthy on its own (see below). CI should run the whole suite.
tests/pi.test.ts— full-run-safetytests/test_4874_jvm_resolution.py— impact, full-run-safetytests/test_4909_reference_binding_scale.py— full-run-safetytests/test_4978_reconcile_cost.py— impact, full-run-safetytests/test_4992_ts_import_types.py— impact, full-run-safetytests/test_5072_splittable_under_cap_retry.py— full-run-safetytests/test_affected_cli.py— full-run-safetytests/test_affected_defines.py— full-run-safetytests/test_affected_member_seed.py— full-run-safetytests/test_affected_overrides.py— impact, full-run-safetytests/test_affected_path_file_node.py— full-run-safetytests/test_affected_seed_reference_forms.py— full-run-safetytests/test_agents_platform.py— full-run-safetytests/test_alias_folding.py— impact, full-run-safetytests/test_analyze.py— impact, full-run-safetytests/test_anthropic_custom_endpoint.py— full-run-safetytests/test_antigravity_install.py— full-run-safetytests/test_apm_fallback_version.py— full-run-safetytests/test_architecture_doc.py— full-run-safetytests/test_astro_extraction.py— impact, full-run-safetytests/test_astro_import_ids.py— impact, full-run-safetytests/test_atomic_canvas_export.py— full-run-safetytests/test_atomic_version_stamp.py— full-run-safetytests/test_atomic_writes.py— full-run-safetytests/test_backend_env_isolation.py— full-run-safetytests/test_backend_extras.py— full-run-safetytests/test_backend_opt_in.py— full-run-safetytests/test_benchmark.py— full-run-safetytests/test_benchmark_raw_graph.py— full-run-safetytests/test_benchmark_real_query.py— full-run-safetytests/test_binary_media_words.py— impact, full-run-safetytests/test_blade_extractor.py— impact, full-run-safetytests/test_build.py— impact, full-run-safetytests/test_build_located_semantic_identity.py— impact, full-run-safetytests/test_build_merge_dedup_scope.py— impact, full-run-safetytests/test_build_merge_ghost_fold_4955.py— impact, full-run-safetytests/test_build_merge_hyperedges_and_prune.py— impact, full-run-safetytests/test_build_merge_shrink_guard.py— impact, full-run-safetytests/test_builtin_global_type_refs.py— impact, full-run-safetytests/test_c_include_resolution.py— impact, full-run-safetytests/test_cache.py— impact, full-run-safetytests/test_cache_long_paths.py— impact, full-run-safetytests/test_cache_stale_import_target.py— impact, full-run-safetytests/test_cache_windows_case_4925.py— impact, full-run-safetytests/test_callflow_html.py— full-run-safetytests/test_cargo_introspect.py— full-run-safetytests/test_cargo_missing_manifest.py— full-run-safetytests/test_carried_hyperedge_remap.py— impact, full-run-safetytests/test_case_only_decl_ids_4904.py— impact, full-run-safetytests/test_case_sensitive_resolution.py— impact, full-run-safety- … and 552 more
⚠️ changed code file(s) with no mapped test (tests/fixtures/java_interface_dispatch/EmailWorker.java,tests/fixtures/java_interface_dispatch/Job.java,tests/fixtures/java_interface_dispatch/Worker.java) — a coverage gap or a missing link — running the full suite rather than only the selected tests
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.
Every flagged function
extract()ingraphify/extract.py:11751· 1305 callers, 78 callees: fans out to 78 callees (efferent coupling); 1305 callers depend on it (afferent coupling)resolve_interface_dispatch()ingraphify/interface_dispatch.py:94· 8 callers, 4 callees: 8 callers depend on it (afferent coupling)
|
Thanks @Deepjyoti-Sarmah, good catch, and confirmed: on
+1 on filing the constructor / same-named method id collision separately; it's outside this PR. |
…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 <noreply@anthropic.com>
A Java constructor node carried no metadata, so nothing told it apart from a method of the same name. The C# extractor already tags its constructors this way, and the shared interface-dispatch resolver relies on it to skip them. Bumps the AST cache schema to 49 so cached Java extractions re-run. (cherry picked from commit 1040335)
…spatch target (Graphify-Labs#5319) Pins the constructor tag from the previous commit: an interface method named after the implementing class gets no dispatches_to edge, and the Java constructor node carries kind "constructor". Co-Authored-By: Claude <noreply@anthropic.com>
…od's arity (Graphify-Labs#5319) With one interface method and one implementer method of a name, the shared resolver paired them without comparing signatures, so send(int, int) on a class that inherits send(String) from its base got a dispatches_to edge. Java signatures are erased (a type variable becomes its bound), so types cannot be compared without dropping generic pairs; the parameter count survives erasure. resolve_interface_dispatch takes a keyword-only match_arity, off by default so C# and Swift are unchanged, and the Java pass turns it on. Co-Authored-By: Claude <noreply@anthropic.com>
9c5ea67 to
e85852c
Compare
What does this PR do?
Closes #5319.
this.worker.run()) lands on the interface method; nothing joined it to the implementer, so a directed walk stopped at the interface.dispatches_tofor this;.javahad no pass.graphify/java_dispatch.py: a.javagate overresolve_interface_dispatch, the same shape asswift_dispatch.py.extract.pyasjava_interface_dispatch, after the Go dispatch pass.implementsand the interface'smethodedges. One extractor change: a Java constructor node now carrieskind: "constructor"(as C# does), so the shared resolver's constructor skip applies andinterface F { void Widget(); }is never linked toWidget's constructor._AST_CACHE_SCHEMA48 -> 49 so cached Java extractions re-run. Fix by @Deepjyoti-Sarmah, cherry-picked with authorship kept..java, thecallsedge to the interface method kept.signature/aritymetadata, so the shared pairing links each interface overload to the implementer overload of the same signature (arity as fallback), and nothing when the match is not unique.resolve_interface_dispatchtakes a keyword-onlymatch_arity(default off, so C# and Swift are unchanged); the Java pass turns it on, so a lone implementer method pairs only at the interface method's parameter count. Without it,send(int, int)on a class inheritingsend(String)got an edge.interface_dispatch.pymodule docstring now names Swift, Go and Java beside C# (it still described C# as the only wrapper).test_java_interface_and_implementation_are_untouchednow calls the C# pass directly on a Java pair (same pattern as the Swift test for a C# pair).test_mixed_corpus_links_only_the_csharp_pairis nowtest_mixed_corpus_links_each_pair_within_its_own_languageand expects the C# and Java pairs, never a cross-language one.Known limits, documented in the module docstring and pinned by tests:
extends(abstract class or superclass override) is not read; a base method may be the real target.interface Task extends Worker) are not walked, as for C#.defaultmethod nobody overrides gets no edge; the call really lands on the default body.run(T)onWorker<T>recordsObject,T extends NumberrecordsNumber), so a type check would drop real generic pairs.send(int)beside an inheritedsend(String)is still linked;send(int, int)is not.implements a.Workerwritten fully qualified, with no import, binds to a sourceless stub and gets no edge (fails closed, no edge to a same-namedb.Worker); the imported form links.Type of change
Verification & Invariants
Invariant: a
dispatches_toedge only joins an interface method to a same-named method of a type the extractor says implements it, both declared in.java; anything else gets no edge.Cross-language name collisions stay unlinked both ways (Kotlin
Worker/ Java implementer, JavaWorker/ C# implementer), and the C# pass still ignores Java pairs.Persisted state: AST cache schema 48 -> 49, so a cached Java file without the constructor tag is re-extracted.
Read the CONTRIBUTING.md guide.
Reproduced the issue and identified the invariant.
Made the smallest fix necessary.
Added isolated boundary tests.
Kept the PR description synchronized with the final implementation.
Documented any limitations / unsupported cases explicitly.
How was this tested?
Environment: macOS arm64, Python 3.13.16, uv 0.13.1,
uv sync --all-extras, basev8at340268a(0.9.112). Before = cleanv8with the new test file copied in; after = this branch.New tests: before vs after
uv run pytest tests/test_java_interface_dispatch.py -q -rA --tb=linetest_call_through_an_interface_field_reaches_the_implementer:69: AssertionError: assert set() == {('worker_wor...lworker_run')}test_dispatch_edge_shape_and_the_call_is_kept:77: StopIteration(nodispatches_toedge)test_two_implementers_both_get_an_edge_at_lower_confidence:92: AssertionError: assert set() == {('worker_wor...sworker_run')}test_three_implementers_floor_at_the_weak_inference_tier:105: assert 0 == 3test_overload_links_only_the_matching_signature:125: AssertionError: assert set() == {('sender_sen...sender_send')}test_overloads_on_both_sides_pair_one_to_one:147: AssertionError: assert set() == {('sender_sen...send_12f1a1')}test_same_arity_overloads_pair_by_parameter_type:165: AssertionError: assert set() == {('sender_sen...send_46f8ab')}test_an_interface_overload_with_no_implementation_gets_no_edge:178: AssertionError: assert set() == {('sender_sen...sender_send')}test_two_candidates_neither_matching_get_no_edgetest_a_lone_method_with_another_parameter_count_is_not_linkedAssertionError: assert {('sender_sen...sender_send')} == set()test_a_lone_method_with_the_same_parameter_count_is_linked:222: AssertionError: assert set() == {('sender_sen...sender_send')}test_constructor_is_not_a_dispatch_target:223: AssertionError: assert set() == {('worker_wor...lworker_run')}test_a_constructor_named_like_the_interface_method_is_not_a_target:248: KeyError: 'metadata'(constructor node untagged)AssertionError: assert {('starter_st...gine_engine')} == set()test_no_matching_member_produces_no_edgetest_abstract_base_class_is_out_of_scopetest_interface_hierarchy_is_not_walked_transitivelytest_an_unoverridden_default_method_is_not_dispatched:261: AssertionError: assert set() == {('worker_wor...worker_stop')}test_enum_record_and_generic_implementers_link:271: AssertionError: assert set() == {('worker_wor...ce_once_run')}test_a_same_named_interface_in_another_language_is_not_linkedtest_a_same_named_kotlin_interface_is_not_linkedtest_a_csharp_implementer_of_a_java_interface_is_not_linkedtest_same_simple_name_in_two_packages_links_only_the_imported_one:316: AssertionError: assert set() == {('a_worker_w...lworker_run')}test_a_qualified_implements_clause_is_a_known_limittest_a_csharp_pair_is_untouched_by_the_java_pass:331: ModuleNotFoundError: No module named 'graphify.java_dispatch'test_java_pass_is_registered_with_the_other_dispatch_passes:353: AssertionError: assert 'java_interface_dispatch' in ['terraform_modules', ...]16 failed, 9 passed, 1 warning in 2.42s25 passed, 1 warning in 0.42sFixture graph: before vs after
Fixture:
tests/fixtures/java_interface_dispatch/(Worker.java,EmailWorker.java,Job.java),GRAPHIFY_BACKEND=none graphify extract <copy> --code-only --out <dir>, no API keys.extractsummary11 nodes, 13 edges, 3 communities11 nodes, 14 edges, 3 communitiesdispatches_toedgesconfidence_score0.85)graphify path "Job.execute" "EmailWorker.run"No directed path found between 'Job.execute' and 'EmailWorker.run'. Re-run with --undirected to search ignoring edge direction.Shortest path (2 hops):/.execute() --calls [INFERRED 0.85]--> .run() --dispatches_to [INFERRED 0.85]--> .run()Full checks
uv run pyteston the C#, Go and Swift dispatch test files (+ Java on this branch)45 passed70 passeduv run pytest tests -q -n 6(pytest-xdist)22 failed, 11549 passed, 165 skipped, 1 xfailed(run before review, with the 23-test Java file)7 failed, 11566 passed, 165 skipped, 1 xfaileduv run ruff check .All checks passed!All checks passed!uv run pyright761 errors760 errors(0 injava_dispatch.pyand the Java test file)uv run python -m tools.skillgen --checkcheck OK: 134 artifact(s)check OK: 134 artifact(s)test_terraform_modules.py::test_copied_ast_cache_preserves_terraform_ids[parallel-*].test_workers_by_work_size.py::test_extract_honours_max_workers_argument.test_language_override_lifecycle.py::test_watch_declared_code_updates_graph_on_observer_thread.pytest tests/test_language_override_lifecycle.py tests/test_terraform_modules.pygives69 passed;tests/test_install.py tests/test_terraform_modules.py tests/test_workers_by_work_size.pygave209 passedon both trees.Graphify-specific checklist
uv run python -m tools.skillgen --bless) when changing their source fragments. (No skill fragments changed;--checkpasses.)