Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
perf(graph): give each language a call-strategy seam and reject unresolvable names first (#1632)
Raghav Chamadiya58ed639b2902
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 606356829..22d190a2d 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -40,6 +40,42 @@ log = structlog.get_logger(__name__)_IMPLICIT_RECEIVER_LANGUAGES = frozenset({"java", "csharp", "cpp", "kotlin"})+@dataclass(frozen=True, slots=True)+class _LanguageCallStrategies:+ """What a language resolves that the language-neutral tiers cannot.++ ``free`` runs after the same-file tier and before the import tiers;+ ``member`` runs before every receiver strategy. Both stop at the first hit.+ Strategies are named rather than bound so a probe can substitute one.+ """++ free: tuple[str, ...] = ()+ member: tuple[str, ...] = ()+++_NO_LANGUAGE_STRATEGIES = _LanguageCallStrategies()++_JVM_STRATEGIES = _LanguageCallStrategies(+ free=("_resolve_jvm_same_package",),+ member=("_resolve_jvm_receiver_same_package",),+)++_CPP_STRATEGIES = _LanguageCallStrategies(free=("_resolve_cpp_same_target",))++# Rust's crate-root strategy is deliberately absent: it runs for every language+# today, and gating it here would drop crate-name receivers in mixed repos.+_LANGUAGE_CALL_STRATEGIES: dict[str, _LanguageCallStrategies] = {+ "go": _LanguageCallStrategies(+ free=("_resolve_go_same_package",),+ member=("_resolve_go_package_call",),+ ),+ "java": _JVM_STRATEGIES,+ "kotlin": _JVM_STRATEGIES,+ "cpp": _CPP_STRATEGIES,+ "c": _CPP_STRATEGIES,+}++def _file_language(parsed_files: dict[str, ParsedFile], symbol_id: str) -> str | None:"""Extract language from a symbol ID's file via the parsed files map."""file_path = symbol_id.split("::")[0] if "::" in symbol_id else symbol_id@@ -145,6 +181,8 @@ class CallResolver:self._cpp_index: Any = Noneself._cpp_index_built = False+ self._strategies_by_file: dict[str, _LanguageCallStrategies] = {}+self._build_indices(parsed_files)self._follow_barrel_exports()@@ -248,17 +286,11 @@ class CallResolver:self._go_index = build_go_package_index(_Ctx(self._repo_path, self._parsed_files))return self._go_index- def _is_go(self, file_path: str) -> bool:- parsed = self._parsed_files.get(file_path)- return bool(parsed and parsed.file_info.language == "go")-- def _is_jvm(self, file_path: str) -> bool:+ def _strategies_for(self, file_path: str) -> _LanguageCallStrategies:+ """The extra strategies this file's language gets."""parsed = self._parsed_files.get(file_path)- return bool(parsed and parsed.file_info.language in ("java", "kotlin"))-- def _is_cpp_family(self, file_path: str) -> bool:- parsed = self._parsed_files.get(file_path)- return bool(parsed and parsed.file_info.language in ("cpp", "c"))+ language = parsed.file_info.language if parsed else ""+ return _LANGUAGE_CALL_STRATEGIES.get(language, _NO_LANGUAGE_STRATEGIES)def _get_cpp_index(self) -> Any:"""Lazily build a CppWorkspaceIndex via a minimal stand-in context."""@@ -349,6 +381,29 @@ class CallResolver:return ResolvedCall(caller_id, sym_id, 0.90, call.line, "same_package")return None+ def _resolve_jvm_receiver_same_package(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ ) -> ResolvedCall | None:+ """Resolve ``Receiver.method()`` where the receiver is a package sibling.++ JVM files in the same package see each other's types with no import,+ so the receiver may name a class declared in any sibling file.+ """+ key = (call.receiver_name or "", call.target_name)+ if key not in self._global_methods:+ return None+ index = self._get_jvm_index()+ if index is None:+ return None+ for sibling in index.same_package_files(file_path):+ sym_id = self._file_methods.get(sibling, {}).get(key)+ if sym_id is not None:+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "receiver_same_package")+ return None+def _resolve_go_package_call(self,file_path: str,@@ -631,6 +686,9 @@ class CallResolver:) -> ResolvedCall | None:"""Resolve a free function call (no receiver)."""target_name = call.target_name+ # Every tier keys on the target name, so a name the repo declares+ # nowhere can only be matched under an import alias (2a below).+ declared = target_name in self._global_symbols# Tier 1: same-filefile_syms = self._file_symbols.get(file_path, {})@@ -645,28 +703,14 @@ class CallResolver:if callee_id != caller_id: # no self-recursion edges for nowreturn ResolvedCall(caller_id, callee_id, 0.95, call.line, "same_file")- # Go: a bare call may target a function defined in a sibling file of- # the same package (shared namespace, no import). Resolve against the- # package before the weaker import/global tiers.- if self._is_go(file_path):- go_same_pkg = self._resolve_go_same_package(file_path, call, caller_id)- if go_same_pkg is not None:- return go_same_pkg-- # JVM: same-package implicit access — classes in the same package- # reference each other with no import statement.- if self._is_jvm(file_path):- jvm_same_pkg = self._resolve_jvm_same_package(file_path, call, caller_id)- if jvm_same_pkg is not None:- return jvm_same_pkg-- # C/C++: same-target unqualified access — a bare call may target a- # function declared in a header consumed by the importer's CMake/- # Bazel target and defined in any sibling TU of that target.- if self._is_cpp_family(file_path):- cpp_same_target = self._resolve_cpp_same_target(file_path, call, caller_id)- if cpp_same_target is not None:- return cpp_same_target+ # The caller's language may see names no import statement mentions —+ # a Go or JVM package sibling, a C/C++ translation unit in the same+ # build target — and those beat the weaker import/global tiers.+ if declared:+ for strategy in self._strategies_for(file_path).free:+ hit = getattr(self, strategy)(file_path, call, caller_id)+ if hit is not None:+ return hit# Tier 2: import-scoped# 2a: Check specific imported name → source file (binding-aware)@@ -684,6 +728,9 @@ class CallResolver:caller_id, source_syms[lookup_name], 0.90, call.line, "import_scoped")+ if not declared:+ return None+# 2a fallback: plain _import_names (for imports without binding data)name_to_file = self._import_names.get(file_path, {})if target_name in name_to_file and not binding:@@ -726,27 +773,19 @@ class CallResolver:method_name = call.target_nameassert receiver_name is not None- # Go: ``pkg.Func()`` where ``pkg`` is an import alias resolves to the- # function in *any* file of that package, not just the single- # representative the import resolved to. Try this first for Go so a- # multi-file package's exported funcs are reached correctly.- if self._is_go(file_path):- go_pkg_call = self._resolve_go_package_call(file_path, call, caller_id)- if go_pkg_call is not None:- return go_pkg_call-- # JVM: receiver may be a class in the same package (no import needed)- if self._is_jvm(file_path):- index = self._get_jvm_index()- if index is not None:- siblings = index.same_package_files(file_path)- for sibling in siblings:- methods = self._file_methods.get(sibling, {})- key = (receiver_name, method_name)- if key in methods:- return ResolvedCall(- caller_id, methods[key], 0.90, call.line, "receiver_same_package"- )+ # Every strategy below ends in a lookup keyed on the method name, so a+ # name the repo declares nowhere cannot resolve. That is most member+ # calls — the callee is usually external — and this is the whole of+ # what those call sites now cost.+ if method_name not in self._global_symbols:+ return None++ # A language may reach a receiver no import statement mentions: a Go+ # package alias spanning several files, a JVM class in the same package.+ for strategy in self._strategies_for(file_path).member:+ hit = getattr(self, strategy)(file_path, call, caller_id)+ if hit is not None:+ return hit# Strategy 1: receiver is a module alias (e.g. "import models" → "models.User()")module_file = self._module_aliases.get(file_path, {}).get(receiver_name)@@ -779,31 +818,32 @@ class CallResolver:caller_id, root_syms[method_name], 0.88, call.line, "crate_root")- # Strategy 2: receiver is a known class name → look for method on that class- # Check same-file classes first- file_methods = self._file_methods.get(file_path, {})+ # Strategies 2 and 2b: the receiver names a class that declares the+ # method — in this file, in an imported one, or anywhere at all. No+ # class declares the pair unless the global method index holds it, and+ # that check also keeps the merged-import view from being built for a+ # pair that cannot be in it.key = (receiver_name, method_name)- if key in file_methods:- return ResolvedCall(- caller_id, file_methods[key], 0.93, call.line, "receiver_same_file"- )+ if key in self._global_methods:+ file_methods = self._file_methods.get(file_path, {})+ if key in file_methods:+ return ResolvedCall(+ caller_id, file_methods[key], 0.93, call.line, "receiver_same_file"+ )- # Check imported files for (class, method) pairs (pre-merged lookup)- merged_methods = self._merged_methods_for(file_path)- if key in merged_methods:- return ResolvedCall(- caller_id, merged_methods[key], 0.88, call.line, "receiver_import"- )+ merged_methods = self._merged_methods_for(file_path)+ if key in merged_methods:+ return ResolvedCall(+ caller_id, merged_methods[key], 0.88, call.line, "receiver_import"+ )- # Strategy 2b: trait method dispatch — receiver is a type that- # implements a trait; the method may be defined on the trait's- # impl block in another file. The global index preserves the old- # file-insertion match order; entries from the caller's own file- # are skipped exactly as before.- for _path, sym_id in self._global_methods.get(key, ()):- if _path == file_path:- continue- return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")+ # Trait method dispatch — the method may be defined on a trait's+ # impl block in another file. The global index preserves+ # file-insertion match order; the caller's own file is skipped.+ for _path, sym_id in self._global_methods[key]:+ if _path == file_path:+ continue+ return ResolvedCall(caller_id, sym_id, 0.75, call.line, "receiver_global")# Strategy 3: receiver is "self" or "this" — look in same class.# Only the caller's own file can hold the match, so index straight@@ -811,15 +851,9 @@ class CallResolver:if receiver_name in ("self", "this"):caller_class = _extract_class_from_symbol_id(caller_id)if caller_class:- for (cls_name, meth_name), sym_id in self._file_methods.get(- file_path, {}- ).items():- if (- meth_name == method_name- and sym_id != caller_id- and cls_name == caller_class- ):- return ResolvedCall(caller_id, sym_id, 0.95, call.line, "self_scope")+ sym_id = self._file_methods.get(file_path, {}).get((caller_class, method_name))+ if sym_id is not None and sym_id != caller_id:+ return ResolvedCall(caller_id, sym_id, 0.95, call.line, "self_scope")# No further fallback: any (class, method) pair present in any file's# method index was already resolved by strategy 2 (same file) or 2bdiff --git a/tests/unit/ingestion/test_call_resolver_strategies.py b/tests/unit/ingestion/test_call_resolver_strategies.pynew file mode 100644index 000000000..740ac311f--- /dev/null+++ b/tests/unit/ingestion/test_call_resolver_strategies.py@@ -0,0 +1,336 @@+"""Characterisation tests for the call-resolution cascade.++Every strategy in ``CallResolver`` is reachable only through one long chain, and+six of them had no test that triggered them at all. These pin the observable+contract — which strategy fires, at which confidence, under which origin, and+which languages consult a language-specific strategy — so a refactor of the+chain is a refactor and not a rewrite.++The dispatch tests use spies rather than fixtures because the alternative is a+CMake or Cargo workspace per assertion; what is under test is which strategies a+language reaches and in what order, and a spy states that directly.+"""++from __future__ import annotations++from datetime import datetime+from pathlib import Path++import pytest++from repowise.core.ingestion.call_resolver import CallResolver+from repowise.core.ingestion.models import FileInfo, ParsedFile+from repowise.core.ingestion.parser import parse_file+++def _file_info(rel: str, abs_: Path, lang: str) -> FileInfo:+ return FileInfo(+ path=rel,+ abs_path=str(abs_),+ language=lang, # type: ignore[arg-type]+ size_bytes=abs_.stat().st_size,+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+++def _parse_all(tmp_path: Path, files: dict[str, tuple[str, str]]) -> dict[str, ParsedFile]:+ out: dict[str, ParsedFile] = {}+ for rel, (lang, content) in files.items():+ abs_ = tmp_path / rel+ abs_.parent.mkdir(parents=True, exist_ok=True)+ abs_.write_text(content)+ out[rel] = parse_file(_file_info(rel, abs_, lang), content.encode("utf-8"))+ return out+++def _link_imports(parsed: dict[str, ParsedFile], links: dict[str, dict[str, str]]) -> None:+ """Stand in for the import-resolution phase, which unit tests do not run."""+ for path, module_to_file in links.items():+ for imp in parsed[path].imports:+ target = module_to_file.get(imp.module_path)+ if target is not None:+ imp.resolved_file = target+++def _edges(+ parsed: dict[str, ParsedFile],+ tmp_path: Path,+ import_targets: dict[str, set[str]] | None = None,+) -> list[tuple[str, str, float, str]]:+ resolver = CallResolver(+ parsed,+ import_targets if import_targets is not None else {p: set() for p in parsed},+ repo_path=str(tmp_path),+ )+ return [+ (rc.caller_id, rc.callee_id, rc.confidence, rc.origin)+ for path, pf in parsed.items()+ for rc in resolver.resolve_file(path, pf.calls)+ ]+++class TestUnpinnedStrategies:+ """One test per strategy that no existing test triggered."""++ def test_receiver_names_a_class_in_the_same_file(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "app.py": (+ "python",+ "class User:\n"+ " def save(self):\n"+ " return 1\n"+ "\n"+ "def run():\n"+ " return User.save()\n",+ )+ },+ )+ assert (+ "app.py::run",+ "app.py::User::save",+ 0.93,+ "receiver_same_file",+ ) in _edges(parsed, tmp_path)++ def test_a_repo_wide_unique_name_resolves_as_a_guess(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "lib.py": ("python", "def only_one_of_these():\n return 1\n"),+ "caller.py": ("python", "def run():\n return only_one_of_these()\n"),+ },+ )+ assert (+ "caller.py::run",+ "lib.py::only_one_of_these",+ 0.50,+ "global_unique",+ ) in _edges(parsed, tmp_path)++ def test_a_repo_wide_ambiguous_name_resolves_to_nothing(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "a.py": ("python", "def shared():\n return 1\n"),+ "b.py": ("python", "def shared():\n return 2\n"),+ "caller.py": ("python", "def run():\n return shared()\n"),+ },+ )+ assert _edges(parsed, tmp_path) == []++ def test_receiver_is_a_module_alias(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "models.py": ("python", "def build():\n return 1\n"),+ "caller.py": ("python", "import models\n\ndef run():\n return models.build()\n"),+ },+ )+ _link_imports(parsed, {"caller.py": {"models": "models.py"}})+ assert (+ "caller.py::run",+ "models.py::build",+ 0.88,+ "module_alias",+ ) in _edges(parsed, tmp_path)++ def test_jvm_bare_call_reaches_a_same_package_sibling(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "src/com/example/Helper.java": (+ "java",+ "package com.example;\n\npublic class Helper {\n Helper() {}\n}\n",+ ),+ "src/com/example/Main.java": (+ "java",+ "package com.example;\n\n"+ "public class Main {\n"+ " void run() {\n"+ " new Helper();\n"+ " }\n"+ "}\n",+ ),+ },+ )+ hits = [e for e in _edges(parsed, tmp_path) if e[3] == "same_package"]+ # The sibling's flat symbol index is last-wins, so the constructor and+ # not the class is what ``Helper`` names by the time the tier reads it.+ assert hits == [+ (+ "src/com/example/Main.java::Main::run",+ "src/com/example/Helper.java::Helper::Helper",+ 0.90,+ "same_package",+ )+ ]++ def test_a_target_name_declared_nowhere_resolves_to_nothing(self, tmp_path: Path) -> None:+ """The population the cascade spends most of its budget on."""+ parsed = _parse_all(+ tmp_path,+ {+ "caller.py": (+ "python",+ "def run(obj):\n obj.never_declared_anywhere()\n "+ "also_never_declared()\n",+ )+ },+ )+ assert _edges(parsed, tmp_path) == []+++class _Spy:+ """Records that a strategy was consulted, and declines to resolve."""++ def __init__(self) -> None:+ self.calls: list[str] = []++ def wrap(self, monkeypatch: pytest.MonkeyPatch, name: str) -> None:+ original = getattr(CallResolver, name)++ def spy(inner_self, *args, **kwargs):+ self.calls.append(name)+ return original(inner_self, *args, **kwargs)++ monkeypatch.setattr(CallResolver, name, spy)+++_LANGUAGE_STRATEGIES = (+ "_resolve_go_same_package",+ "_resolve_go_package_call",+ "_resolve_jvm_same_package",+ "_resolve_jvm_receiver_same_package",+ "_resolve_cpp_same_target",+)++# Declares the called names elsewhere, so a dispatch test measures dispatch and+# not the reject-early gate. Kotlin so nothing else in these repos can match it.+_DECOY = (+ "kotlin",+ "class Decoy {\n fun elsewhere() {}\n fun Elsewhere() {}\n}\n",+)+++def spy(monkeypatch: pytest.MonkeyPatch) -> _Spy:+ recorder = _Spy()+ for name in _LANGUAGE_STRATEGIES:+ recorder.wrap(monkeypatch, name)+ return recorder+++class TestLanguageDispatch:+ """Which language-specific strategies a file reaches, and which it does not."""++ def test_every_registered_strategy_exists(self) -> None:+ from repowise.core.ingestion.call_resolver import _LANGUAGE_CALL_STRATEGIES++ for strategies in _LANGUAGE_CALL_STRATEGIES.values():+ for name in strategies.free + strategies.member:+ assert callable(getattr(CallResolver, name, None)), name++ @pytest.mark.parametrize(+ ("rel", "lang", "source", "expected"),+ [+ (+ "main.go",+ "go",+ "package main\n\nfunc run() {\n\telsewhere()\n}\n",+ ["_resolve_go_same_package"],+ ),+ (+ "Main.java",+ "java",+ "class Main {\n void run() {\n elsewhere();\n }\n}\n",+ ["_resolve_jvm_same_package"],+ ),+ (+ "main.cc",+ "cpp",+ "void run() {\n elsewhere();\n}\n",+ ["_resolve_cpp_same_target"],+ ),+ ("main.py", "python", "def run():\n elsewhere()\n", []),+ ("main.rs", "rust", "fn run() {\n elsewhere();\n}\n", []),+ ],+ )+ def test_a_bare_call_consults_only_its_own_languages_strategies(+ self,+ tmp_path: Path,+ spy: _Spy,+ rel: str,+ lang: str,+ source: str,+ expected: list[str],+ ) -> None:+ parsed = _parse_all(tmp_path, {rel: (lang, source), "Decoy.kt": _DECOY})+ _edges(parsed, tmp_path)+ assert spy.calls == expected++ def test_a_member_call_consults_only_its_own_languages_strategies(+ self, tmp_path: Path, spy: _Spy+ ) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "main.go": ("go", "package main\n\nfunc run() {\n\tpkg.Elsewhere()\n}\n"),+ "main.py": ("python", "def run(pkg):\n pkg.elsewhere()\n"),+ "Decoy.kt": _DECOY,+ },+ )+ _edges(parsed, tmp_path)+ assert spy.calls == ["_resolve_go_package_call"]++ def test_an_undeclared_name_reaches_no_strategy_at_all(+ self, tmp_path: Path, spy: _Spy+ ) -> None:+ """The reject-early gate: nothing declares it, so nothing can match it."""+ parsed = _parse_all(+ tmp_path,+ {+ "main.go": (+ "go",+ "package main\n\nfunc run() {\n\tnowhere()\n\tpkg.Nowhere()\n}\n",+ )+ },+ )+ assert _edges(parsed, tmp_path) == []+ assert spy.calls == []++ def test_a_language_strategy_runs_before_the_import_tiers(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Go's package tier owns a name an import tier would also answer."""+ order: list[str] = []+ for name in ("_resolve_go_same_package", "_merged_symbols_for"):+ original = getattr(CallResolver, name)++ def spy(inner_self, *args, _name=name, _original=original, **kwargs):+ order.append(_name)+ return _original(inner_self, *args, **kwargs)++ monkeypatch.setattr(CallResolver, name, spy)++ parsed = _parse_all(+ tmp_path,+ {+ "pkg/helper.go": ("go", "package pkg\n\nfunc Helper() int {\n\treturn 1\n}\n"),+ "pkg/main.go": ("go", "package pkg\n\nfunc run() int {\n\treturn Helper()\n}\n"),+ },+ )+ edges = _edges(parsed, tmp_path, {"pkg/main.go": {"pkg/helper.go"}, "pkg/helper.go": set()})+ assert (+ "pkg/main.go::run",+ "pkg/helper.go::Helper",+ 0.90,+ "same_package",+ ) in edges+ assert order == ["_resolve_go_same_package"]