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
fix(ingestion): resolve a call to an overload set instead of refusing it (#1923)
Raghav Chamadiyaf97ced7a4c7b
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 86c5f13fa..2eaaca5ff 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -118,7 +118,7 @@ _TYPE_KINDS = frozenset({"class", "struct", "interface", "enum", "trait", "impl"_FUNCTION_KINDS = frozenset({"function", "method"})# Kinds that can never be the callee of a call, used to keep the bare-name-# Tier 3 index from offering a data member as a function (bug 90).+# Tier 3 index from offering a data member as a function.## This is deliberately NOT the complement of ``_FUNCTION_KINDS``. Measured over# the corpus, plenty of non-function kinds are legitimately called: ``class``@@ -135,6 +135,19 @@ _FUNCTION_KINDS = frozenset({"function", "method"})# field is indistinguishable from a callable value by kind alone._NON_CALLABLE_KINDS = frozenset({"property"})+# A getter and its setter are two declarations under one id, which reads as an+# overload set and is not one: the name is an attribute, not a callable.+_PROPERTY_DECORATORS = frozenset({"property", "cached_property"})+_PROPERTY_ACCESSOR_SUFFIXES = (".setter", ".getter", ".deleter")+++def _is_property_accessor(sym: Any) -> bool:+ for decorator in getattr(sym, "decorators", ()) or ():+ tail = decorator.lstrip("@").strip()+ if tail in _PROPERTY_DECORATORS or tail.endswith(_PROPERTY_ACCESSOR_SUFFIXES):+ return True+ return False+_JVM_STRATEGIES = _LanguageCallStrategies(free=("_resolve_jvm_same_package",),member=("_resolve_jvm_receiver_same_package",),@@ -294,9 +307,10 @@ class CallResolver:)# Symbols in the index above that are data members, not callables- # (bug 90). Held as an id set rather than a full id→kind map because- # it is the only kind question asked of it and the set is small.+ # Held as an id set rather than a full id->kind map: it is the only+ # kind question asked of it and the set is small.self._non_callable_ids: set[str] = set()+ self._property_accessor_ids: set[str] = set()# C/C++ forward declaration → the definition it declares. Populated by# ``_build_indices``; applied to every resolved call so the edge lands@@ -837,6 +851,8 @@ class CallResolver:# Global indicesif sym.kind in _NON_CALLABLE_KINDS:self._non_callable_ids.add(sym.id)+ if _is_property_accessor(sym):+ self._property_accessor_ids.add(sym.id)# Same rule as the per-file index above, for the global-unique# tier.if not (sym.is_declaration and sym.parent_name is not None):@@ -1295,7 +1311,7 @@ class CallResolver:# Tier 3: global unique match — only within the same language.# A data member is not callable, so it must not be the unique answer- # that mints an edge (bug 90). Filtered here rather than at index build+ # that mints an edge. Filtered here rather than at index build# so the `declared` gate above and the member gate in# ``_resolve_member_call`` keep seeing the whole repo.# Uniqueness is judged on the unfiltered list on purpose. Filtering the@@ -1310,28 +1326,9 @@ class CallResolver:# site named. `Ok(())` and a chained `.unwrap()` are the shape.candidates = self._global_symbols.get(target_name, [])if len(candidates) == 1 and candidates[0] != caller_id:- if target_name in get_builtin_methods(self._language_of(file_path) or ""):- return None- if candidates[0] in self._non_callable_ids:- # Refused here rather than by falling through, so "this tier- # can lose an edge but never gain one" is true of the control- # flow and not only of the corpus. Falling through would reach- # the implicit-receiver tier below, which the old code could- # not reach on this input.- #- # That tier is provably empty here anyway: it ends in- # ``_inherited_method``, which reads ``_file_methods`` — filled- # by the same loop that unconditionally fills- # ``_global_symbols``. So any method it could return would be a- # second entry under this name, and ``len(candidates)`` would- # not be 1. Returning is what stops that argument having to be- # re-derived if either index changes.- return None- caller_lang = symbol_id_language(self._parsed_files, caller_id)- callee_lang = symbol_id_language(self._parsed_files, candidates[0])- if caller_lang and callee_lang and caller_lang != callee_lang:- return None # reject cross-language Tier 3 match- return ResolvedCall(caller_id, candidates[0], 0.50, call.line, "global_unique")+ return self._global_unique_match(+ file_path, call, caller_id, target_name, candidates[0]+ )# Last, so it can only add an edge. The member-shaped refusal is the# one ``_enclosing_class_method`` already applies: several grammars@@ -1347,8 +1344,43 @@ class CallResolver:if sym_id is not None:return ResolvedCall(caller_id, sym_id, 0.90, call.line, "enclosing_inherited")+ # An overload set is several declarations under one id, which the row+ # count reads as an ambiguity that is not there. Not the filtering+ # refused above: a field and a method sharing a name stay two ids.+ # Last on purpose - ahead of the tier above it restated 1,027 edges+ # the caller's own hierarchy already answered, at half the confidence.+ collapsed = self._collapse_declarations(candidates)+ if len(candidates) > 1 and len(collapsed) == 1:+ only = next(iter(collapsed))+ if only != caller_id and only not in self._property_accessor_ids:+ return self._global_unique_match(+ file_path, call, caller_id, target_name, only+ )+return None+ def _global_unique_match(+ self,+ file_path: str,+ call: CallSite,+ caller_id: str,+ target_name: str,+ candidate: str,+ ) -> ResolvedCall | None:+ """Tier 3's gates, applied to the one symbol the name resolves to."""+ if target_name in get_builtin_methods(self._language_of(file_path) or ""):+ return None+ if candidate in self._non_callable_ids:+ # Refused here rather than by falling through, so "this tier can+ # lose an edge but never gain one" is true of the control flow and+ # not only of the corpus.+ return None+ caller_lang = symbol_id_language(self._parsed_files, caller_id)+ callee_lang = symbol_id_language(self._parsed_files, candidate)+ if caller_lang and callee_lang and caller_lang != callee_lang:+ return None # reject cross-language Tier 3 match+ return ResolvedCall(caller_id, candidate, 0.50, call.line, "global_unique")+def _resolve_member_call(self,file_path: str,diff --git a/tests/unit/ingestion/test_overload_set_uniqueness.py b/tests/unit/ingestion/test_overload_set_uniqueness.pynew file mode 100644index 000000000..82364ae6f--- /dev/null+++ b/tests/unit/ingestion/test_overload_set_uniqueness.py@@ -0,0 +1,238 @@+"""Behaviour pins for tier 3 counting symbols rather than declaration rows.++``_global_symbols`` holds one entry per declaration, so an overload set is+several rows under one id and ``len(candidates) == 1`` read it as an ambiguity+that does not exist. C#'s ``AddRetry`` is two rows and one symbol; the tier+refused it and the call reached nothing.++The controls are what make the collapse safe, and each is a shape that reads+like the same defect and is not: a name two DIFFERENT symbols declare stays two+ids and stays refused; a getter and its setter are one attribute, not an+overload set; the caller's own hierarchy still answers first; and a non-callable+symbol is still refused.+"""++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 _edges(+ parsed: dict[str, ParsedFile],+ tmp_path: Path,+ heritage: dict[str, set[str]] | None = None,+) -> list[tuple[str, str, float, str]]:+ resolver = CallResolver(parsed, {}, repo_path=str(tmp_path), heritage_parents=heritage)+ 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)+ ]+++# Two declarations, one symbol id: the shape the row count read as ambiguous.+CS_OVERLOADS = """+namespace App;++public static class Helpers+{+ public static int Widen(int a) => a;+ public static int Widen(int a, int b) => a + b;+}+"""++CS_CALLER = """+namespace App;++public class Caller+{+ public int Run() => Widen(1, 2);+}+"""++# `Widen` is a method on one class and a property on another: two ids, and the+# tier must keep refusing it.+CS_RIVAL_KINDS = """+namespace App;++public class Other+{+ public int Widen { get; set; }+}+"""++# The caller inherits `Step`, so its own hierarchy answers - and must keep+# answering, at its own confidence, rather than being taken over by the+# collapsed global name.+CS_BASE = """+public class Base+{+ public int Step(int a) => a;+ public int Step(int a, int b) => a + b;+}+"""++CS_DERIVED = """+public class Derived : Base+{+ public int Run() => Step(1, 2);+}+"""++# A field is not callable, so it must not become the unique answer.+CS_FIELD_ONLY = """+namespace App;++public class Holder+{+ public int Amount;+}+"""++CS_FIELD_CALLER = """+namespace App;++public class FieldCaller+{+ public int Run() => Amount();+}+"""+++# A getter and its setter are two declarations under one id. That reads as an+# overload set and is not one: the name is an attribute, not a callable.+PY_PROPERTY_PAIR = """+class Amqp:+ @cached_property+ def router(self):+ return 1++ @router.setter+ def router(self, value):+ return value+"""++PY_PROPERTY_CALLER = """+def query(router):+ return router(1, 2)+"""+++class TestOverloadSetIsOneSymbol:+ def test_an_overload_set_resolves_instead_of_reading_as_ambiguous(+ self, tmp_path: Path+ ) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "src/Helpers.cs": ("csharp", CS_OVERLOADS),+ "src/Caller.cs": ("csharp", CS_CALLER),+ },+ )+ edges = _edges(parsed, tmp_path)+ hits = [e for e in edges if e[0].endswith("::Caller::Run")]+ assert [e[1].split("::")[-2:] for e in hits] == [["Helpers", "Widen"]], (+ f"Widen's two declarations are one symbol and must resolve; edges: {edges}"+ )++ def test_two_different_symbols_of_one_name_stay_refused(self, tmp_path: Path) -> None:+ """The control the collapse has to fail: this is filtering, not deduping."""+ parsed = _parse_all(+ tmp_path,+ {+ "src/Helpers.cs": ("csharp", CS_OVERLOADS),+ "src/Other.cs": ("csharp", CS_RIVAL_KINDS),+ "src/Caller.cs": ("csharp", CS_CALLER),+ },+ )+ edges = _edges(parsed, tmp_path)+ assert not [e for e in edges if e[0].endswith("::Caller::Run")], (+ f"a name a method and a property both declare must stay ambiguous; edges: {edges}"+ )++ def test_the_callers_own_hierarchy_still_answers_first(self, tmp_path: Path) -> None:+ """Ahead of the inherited tier this rung restated 1,027 Ocelot edges worse."""+ parsed = _parse_all(+ tmp_path,+ {+ "src/Base.cs": ("csharp", CS_BASE),+ "src/Derived.cs": ("csharp", CS_DERIVED),+ },+ )+ edges = _edges(+ parsed,+ tmp_path,+ heritage={"src/Derived.cs::Derived": {"src/Base.cs::Base"}},+ )+ hits = [e for e in edges if e[0].endswith("::Derived::Run")]+ assert hits, f"Step() must resolve through the caller's own base; edges: {edges}"+ assert hits[0][3] == "enclosing_inherited", (+ f"the inherited tier must keep this site, not the global rung; edges: {edges}"+ )++ @pytest.mark.xfail(+ reason="_NON_CALLABLE_KINDS is {'property'} while C# extracts a field "+ "or property as kind 'variable', so the data-member refusal never "+ "reaches C#. Pre-existing, and unchanged by this collapse.",+ strict=True,+ )+ def test_a_non_callable_symbol_is_still_refused(self, tmp_path: Path) -> None:+ parsed = _parse_all(+ tmp_path,+ {+ "src/Holder.cs": ("csharp", CS_FIELD_ONLY),+ "src/FieldCaller.cs": ("csharp", CS_FIELD_CALLER),+ },+ )+ edges = _edges(parsed, tmp_path)+ assert not [e for e in edges if e[0].endswith("::FieldCaller::Run")], (+ f"a data member must not be the unique answer; edges: {edges}"+ )++ def test_a_property_getter_and_setter_are_not_an_overload_set(+ self, tmp_path: Path+ ) -> None:+ """Collapsing made an attribute look like a unique callable."""+ parsed = _parse_all(+ tmp_path,+ {+ "src/amqp.py": ("python", PY_PROPERTY_PAIR),+ "src/routes.py": ("python", PY_PROPERTY_CALLER),+ },+ )+ edges = _edges(parsed, tmp_path)+ assert not [e for e in edges if e[0].endswith("routes.py::query")], (+ f"router(...) is a local parameter, not Amqp.router; edges: {edges}"+ )