Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(graph): a java chain rooted at an external type is not a bare-name call (#1897)

Raghav Chamadiya08e493b8f932
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index ae01c0719..2bdba3178 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -31,7 +31,11 @@ from typing import Any
import structlog
-from .language_data import get_builtin_methods, get_external_receiver_types
+from .language_data import (
+ get_builtin_methods,
+ get_external_receiver_types,
+ get_external_return_types,
+)
from .languages.receiver_types import (
FRAMEWORK_DECORATOR_LANGUAGES,
IMPLICIT_FIELD_LANGUAGES,
@@ -45,6 +49,7 @@ from .languages.receiver_types import (
types_in_span,
)
from .models import (
+ CallReceiver,
CallSite,
CallSiteEdgeType,
NamedBinding,
@@ -905,7 +910,12 @@ class CallResolver:
language = self._language_of(file_path) or ""
receiver_call = call.receiver_call
- if receiver_call is not None and language in self._return_type_chain_languages:
+ # A language with an `external_return_types` table reaches the tier for
+ # that table alone; only the constant above admits the full lane.
+ if receiver_call is not None and (
+ language in self._return_type_chain_languages
+ or get_external_return_types(language)
+ ):
handled, resolved = self._resolve_return_typed_chain(
file_path, call, caller_id, language
)
@@ -936,45 +946,36 @@ class CallResolver:
inner = call.receiver_call
assert inner is not None
- inner_call = CallSite(
- target_name=inner.target_name,
- receiver_name=inner.receiver_name,
- caller_symbol_id=caller_id,
- line=call.line,
- argument_count=inner.argument_count,
- )
- resolved_inner = self._resolve_one(file_path, inner_call)
- if resolved_inner is None:
- return False, None
- symbol = self._symbols_by_id.get(resolved_inner.callee_id)
- if symbol is None:
+ tabled = self._external_chain_return_type(file_path, inner, language)
+ from_table = tabled is not None
+ if tabled is not None:
+ type_name = tabled
+ elif language not in self._return_type_chain_languages:
+ # Admitted by its table alone. Inferring the head's type from the
+ # declared return type of a repository symbol is a separate and much
+ # larger population, and it is unmeasured here.
return False, None
- if symbol.kind in _TYPE_KINDS:
- type_name = symbol.name
else:
- raw_return = declared_return_type(symbol.signature or "")
- type_name = normalize_return_type(raw_return, language) if raw_return else None
- symbol_path = self._symbol_paths_by_id.get(resolved_inner.callee_id)
- if symbol_path is None:
- return False, None
- overload_key = (
- symbol_path,
- symbol.parent_name,
- symbol.name,
- inner.argument_count,
+ inferred = self._inferred_chain_return_type(
+ file_path, call, inner, caller_id, language
)
- if len(self._overload_return_types.get(overload_key, ())) > 1:
+ if inferred is None:
return False, None
- if type_name is None:
- return False, None
+ type_name = inferred
found = self._typed_receiver_target(file_path, call, caller_id, type_name)
if language == "java":
# A simple type name is not repository-unique. Java package and
# import binding settle its identity; the global tier does not.
+ #
+ # When the name came from the table it is external *in this file*,
+ # and java has no extension methods, so the repository cannot
+ # declare that type's method either. That makes the bare-name
+ # answer disproved rather than merely unevidenced, which is the
+ # difference between refusing the site and falling through to it.
if found is None or found[1] == "global":
- return False, None
+ return from_table, None
elif language == "cpp":
# P17 admits only the measured Seastar debt family. Broader C++
# return-name matching remains probe evidence, not production
@@ -995,6 +996,87 @@ class CallResolver:
sym_id, tier = found
return True, self._return_typed_call(caller_id, sym_id, tier, call.line)
+ def _external_chain_return_type(
+ self,
+ file_path: str,
+ inner: CallReceiver,
+ language: str,
+ ) -> str | None:
+ """The table's return type for ``Type.method(..)`` at the head of a chain.
+
+ None when the head is not a table entry, and — the part the rust half of
+ this phase bought — when this file rebinds the name to something the
+ repository owns. Java imports resolve to repository files, so
+ ``_import_names`` answers that directly, where rust needs its raw import
+ text read against the workspace index.
+
+ The bound value has to be read, not merely tested: an unresolved import
+ is recorded as an ``external:`` marker, so a truthiness check exempts
+ ``import com.google.common.collect.Maps`` and silently drops 36 of
+ caffeine's 96 measured sites.
+
+ The import list alone is not enough, because java's same-package types
+ need no import. A repository declaring its own ``Duration`` anywhere is
+ exempted outright rather than same-package-checked: the table records
+ the *JDK's* return type, which is the wrong answer for a repository
+ type whose factory returns something else, and refusing on it would
+ drop a correct edge. Costs nothing measured - 0 of the 106 sites has a
+ repo-declared receiver name, by construction of the population.
+ """
+ receiver = inner.receiver_name
+ if not receiver:
+ return None
+ methods = get_external_return_types(language).get(receiver)
+ if methods is None:
+ return None
+ if receiver in self._known_type_names:
+ return None
+ bound = self._import_names.get(file_path, {}).get(receiver)
+ if bound and not bound.startswith("external:"):
+ return None
+ return methods.get(inner.target_name)
+
+ def _inferred_chain_return_type(
+ self,
+ file_path: str,
+ call: CallSite,
+ inner: CallReceiver,
+ caller_id: str,
+ language: str,
+ ) -> str | None:
+ """The head's type read off the repository symbol the inner call resolves to."""
+ inner_call = CallSite(
+ target_name=inner.target_name,
+ receiver_name=inner.receiver_name,
+ caller_symbol_id=caller_id,
+ line=call.line,
+ argument_count=inner.argument_count,
+ )
+ resolved_inner = self._resolve_one(file_path, inner_call)
+ if resolved_inner is None:
+ return None
+
+ symbol = self._symbols_by_id.get(resolved_inner.callee_id)
+ if symbol is None:
+ return None
+ if symbol.kind in _TYPE_KINDS:
+ return symbol.name
+
+ raw_return = declared_return_type(symbol.signature or "")
+ type_name = normalize_return_type(raw_return, language) if raw_return else None
+ symbol_path = self._symbol_paths_by_id.get(resolved_inner.callee_id)
+ if symbol_path is None:
+ return None
+ overload_key = (
+ symbol_path,
+ symbol.parent_name,
+ symbol.name,
+ inner.argument_count,
+ )
+ if len(self._overload_return_types.get(overload_key, ())) > 1:
+ return None
+ return type_name
+
def _return_typed_call(self, caller_id: str, sym_id: str, tier: str, line: int) -> ResolvedCall:
"""Stamp an edge whose receiver is the inner callee's return type."""
if tier == "same_file":
diff --git a/packages/core/src/repowise/core/ingestion/language_data.py b/packages/core/src/repowise/core/ingestion/language_data.py
index afe8005bf..41e8489c2 100644
--- a/packages/core/src/repowise/core/ingestion/language_data.py
+++ b/packages/core/src/repowise/core/ingestion/language_data.py
@@ -7,6 +7,8 @@ so existing consumers need no changes.
from __future__ import annotations
+from collections.abc import Mapping
+
from .languages.registry import REGISTRY
# ---------------------------------------------------------------------------
@@ -65,3 +67,9 @@ def get_external_receiver_types(language: str) -> frozenset[str]:
"""Return the type names the repo-wide receiver tier must not answer for."""
spec = REGISTRY.get(language)
return spec.external_receiver_types if spec else frozenset()
+
+
+def get_external_return_types(language: str) -> Mapping[str, Mapping[str, str]]:
+ """Return ``{external type: {static method: return type}}`` for chain heads."""
+ spec = REGISTRY.get(language)
+ return spec.external_return_types if spec else {}
diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.py
index 3e2d0b9a2..cd55a3f9b 100644
--- a/packages/core/src/repowise/core/ingestion/languages/spec.py
+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py
@@ -12,6 +12,7 @@ a leaf dependency — it imports nothing from the ingestion pipeline.
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass, field
@@ -165,6 +166,18 @@ class LanguageSpec:
# at a repo file - and is populated for nine languages. Keeping them apart
# is what makes this change a no-op on every language but the one measured.
external_receiver_types: frozenset[str] = field(default_factory=frozenset)
+ # ``{external type: {static method: the type name it returns}}``, for the
+ # head of a chained call: ``Duration.ofSeconds(3).toNanos()``. Read only by
+ # the chained-call tier in ``CallResolver``, which otherwise resolves the
+ # outer ``toNanos`` by bare name and hands it whatever same-named method the
+ # repository happens to declare.
+ #
+ # A return type rather than a refusal set, because the recorded type is what
+ # decides which of the two answers is right: a repository declaring its own
+ # type of that name gets a retarget, one that does not gets a refusal.
+ # Populated only where the return type is external for *every* repository,
+ # so a name a repository plausibly declares in its own right stays off it.
+ external_return_types: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
# -- Display ---------------------------------------------------------
color_hex: str = "#8b5cf6" # fallback purple ("other")
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/java.py b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
index 69a4260ad..bc3e3f8fc 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/java.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
@@ -2,6 +2,65 @@
from ..spec import LanguageSpec
+# ``{type: {static method: the type it returns}}`` for the head of a chained
+# call. Every entry is a JDK or Guava static factory whose return type is
+# external for *every* repository, which is what makes the outer link of the
+# chain disprovable: java has no extension methods, so an external receiver
+# type implies an external callee, unqualified.
+#
+# Selection rule, inherited from rust's: a name a repository plausibly declares
+# in its own right stays off. That is why ``List``, ``Map`` and ``Set`` are
+# absent despite eight measured sites, and why the Eclipse Collections,
+# JavaPoet and Guava-testlib tail of the measured population is absent too.
+# Sibling methods of an admitted type are listed with it -- ``ofMinutes``
+# beside ``ofSeconds`` costs nothing and removes an arbitrary edge in the data.
+_EXTERNAL_RETURN_TYPES: dict[str, dict[str, str]] = {
+ # java.time
+ "Duration": {
+ "between": "Duration", "ofDays": "Duration", "ofHours": "Duration",
+ "ofMillis": "Duration", "ofMinutes": "Duration", "ofNanos": "Duration",
+ "ofSeconds": "Duration",
+ },
+ # java.util.stream
+ "Stream": {"concat": "Stream", "of": "Stream"},
+ "IntStream": {
+ "generate": "IntStream", "of": "IntStream", "range": "IntStream",
+ "rangeClosed": "IntStream",
+ },
+ "LongStream": {
+ "generate": "LongStream", "of": "LongStream", "range": "LongStream",
+ "rangeClosed": "LongStream",
+ },
+ # java.util / java.math / java.lang / java.util.concurrent
+ # `Arrays.stream` is overloaded and returns IntStream/LongStream/DoubleStream
+ # for a primitive array. Recording `Stream` is a ceiling, not an oversight:
+ # the type is only used to ask whether the repository declares one of that
+ # name, all four are external, and the resolver exempts any name the
+ # repository does declare - so both readings refuse, and refusing is right.
+ "Arrays": {"asList": "List", "stream": "Stream"},
+ "BigInteger": {"valueOf": "BigInteger"},
+ "ThreadLocal": {"withInitial": "ThreadLocal"},
+ "CompletableFuture": {
+ "allOf": "CompletableFuture", "anyOf": "CompletableFuture",
+ "completedFuture": "CompletableFuture", "runAsync": "CompletableFuture",
+ "supplyAsync": "CompletableFuture",
+ },
+ # Guava
+ "Streams": {"concat": "Stream", "stream": "Stream"},
+ "Maps": {
+ "filterKeys": "Map", "filterValues": "Map", "newHashMap": "HashMap",
+ "transformValues": "Map",
+ },
+ "Sets": {"difference": "SetView", "intersection": "SetView", "union": "SetView"},
+ "MoreObjects": {"toStringHelper": "ToStringHelper"},
+ "FluentIterable": {"from": "FluentIterable"},
+ "Splitter": {"on": "Splitter"},
+ "ImmutableMap": {"copyOf": "ImmutableMap", "of": "ImmutableMap"},
+ "ImmutableSet": {"copyOf": "ImmutableSet", "of": "ImmutableSet"},
+ "LocalDate": {"now": "LocalDate", "of": "LocalDate", "parse": "LocalDate"},
+ "UUID": {"fromString": "UUID", "nameUUIDFromBytes": "UUID", "randomUUID": "UUID"},
+}
+
SPEC = LanguageSpec(
tag="java",
display_name="Java",
@@ -116,5 +175,6 @@ SPEC = LanguageSpec(
"IOException", "Serializable",
}
),
+ external_return_types=_EXTERNAL_RETURN_TYPES,
color_hex="#B07219",
)
diff --git a/tests/unit/ingestion/test_return_type_chain_resolution.py b/tests/unit/ingestion/test_return_type_chain_resolution.py
index 9d2909d1c..d6f4b8869 100644
--- a/tests/unit/ingestion/test_return_type_chain_resolution.py
+++ b/tests/unit/ingestion/test_return_type_chain_resolution.py
@@ -237,3 +237,118 @@ def test_module_level_chain_keeps_structural_receiver(tmp_path: Path) -> None:
assert result[0].caller_id == "example.ts::__module__"
assert result[0].callee_id.endswith("::Product::run")
+
+
+def _java_chain_call(parsed: dict[str, ParsedFile], path: str, outer: str):
+ return next(
+ c
+ for c in parsed[path].calls
+ if c.target_name == outer and getattr(c, "receiver_call", None)
+ )
+
+
+def test_java_external_chain_head_refuses_a_bare_name_fallback(tmp_path: Path) -> None:
+ """`Duration.ofSeconds(3).toNanos()` is not a call to whatever declares toNanos.
+
+ Java has no extension methods, so an external receiver type implies an
+ external callee. That makes the bare-name answer disproved rather than
+ merely unevidenced, which is what lets the tier refuse the site outright.
+ """
+ source = (
+ "import java.time.Duration;\n"
+ "class Expiry { long toNanos() { return 0; } }\n"
+ "class Use { long go() { return Duration.ofSeconds(3).toNanos(); } }\n"
+ )
+ parsed = _parse(tmp_path, "Example.java", "java", source)
+ call = _java_chain_call(parsed, "Example.java", "toNanos")
+
+ before = CallResolver(parsed, {}, repo_path=str(tmp_path)).resolve_file(
+ "Example.java", [call]
+ )
+ assert before == []
+
+
+def test_java_external_chain_head_is_exempt_when_the_file_rebinds_the_name(
+ tmp_path: Path,
+) -> None:
+ """A file importing the repository's own `Duration` means that one.
+
+ The same call in the same table entry, differing only in the import, which
+ is the claim stated as a test rather than as prose. Java imports resolve to
+ repository files, so the file's import list is what separates the two.
+ """
+ own = "package a;\npublic class Duration { public long toNanos() { return 0; } }\n"
+ use = (
+ "package b;\nimport a.Duration;\n"
+ "class Use { long go() { return Duration.ofSeconds(3).toNanos(); } }\n"
+ )
+ (tmp_path / "a").mkdir()
+ (tmp_path / "b").mkdir()
+ parsed = {}
+ parsed.update(_parse(tmp_path, "a/Duration.java", "java", own))
+ parsed.update(_parse(tmp_path, "b/Use.java", "java", use))
+ # Stands in for the import-resolution phase, which unit tests do not run.
+ for imp in parsed["b/Use.java"].imports:
+ imp.resolved_file = "a/Duration.java"
+ call = _java_chain_call(parsed, "b/Use.java", "toNanos")
+
+ resolved = CallResolver(
+ parsed, {"b/Use.java": {"a/Duration.java"}}, repo_path=str(tmp_path)
+ ).resolve_file("b/Use.java", [call])
+ assert len(resolved) == 1
+ assert resolved[0].callee_id.endswith("::Duration::toNanos")
+
+
+def test_a_table_admits_only_its_own_lane(tmp_path: Path) -> None:
+ """The table reaches the tier; it does not switch on the inferred lane too.
+
+ Without this, adding a table to a language would silently enable return-type
+ inference over every chained site it has, which is a different and much
+ larger population than the one measured.
+ """
+ source = (
+ "class Product { void run() {} }\nclass Wrong { void run() {} }\n"
+ "class Use {\n Product make() { return new Product(); }\n"
+ " void go() { make().run(); }\n}\n"
+ )
+ parsed = _parse(tmp_path, "Example.java", "java", source)
+ call = _java_chain_call(parsed, "Example.java", "run")
+
+ resolved = CallResolver(parsed, {}, repo_path=str(tmp_path)).resolve_file(
+ "Example.java", [call]
+ )
+ assert not any(edge.origin.startswith("return_type_") for edge in resolved)
+
+
+def test_java_is_the_only_language_carrying_a_chain_head_table() -> None:
+ """The no-op-elsewhere argument, enforced rather than remembered."""
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ populated = {
+ spec.tag for spec in REGISTRY.all_specs() if spec.external_return_types
+ }
+ assert populated == {"java"}
+
+
+def test_java_external_chain_head_is_exempt_when_the_repo_declares_the_name(
+ tmp_path: Path,
+) -> None:
+ """A same-package repository type needs no import, so the import list misses it.
+
+ The table records the JDK's return type, which is the wrong answer for a
+ repository type whose factory returns something else, so refusing on it
+ would drop a correct edge. Any repo-declared receiver name is exempted.
+ """
+ own = "package a;\nclass Duration { static Duration ofSeconds(int s) { return null; }\n long toNanos() { return 0; } }\n"
+ use = "package a;\nclass Use { long go() { return Duration.ofSeconds(3).toNanos(); } }\n"
+ (tmp_path / "a").mkdir()
+ parsed = {}
+ parsed.update(_parse(tmp_path, "a/Duration.java", "java", own))
+ parsed.update(_parse(tmp_path, "a/Use.java", "java", use))
+ call = _java_chain_call(parsed, "a/Use.java", "toNanos")
+
+ resolved = CallResolver(parsed, {}, repo_path=str(tmp_path)).resolve_file(
+ "a/Use.java", [call]
+ )
+ assert len(resolved) == 1
+ assert resolved[0].callee_id.endswith("::Duration::toNanos")