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(python): resolve super() calls through the MRO, not the file's last same name (#2773)
Raghav Chamadiyab59e1bd6653b
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.mdindex b8cdba7f1..b07f13e4b 100644--- a/docs/architecture/language-support.md+++ b/docs/architecture/language-support.md@@ -533,6 +533,9 @@ Two directions, deliberately separate:below the two same-class origins because the walk compares no signature andreads no visibility, so it can reach a method the language would not actuallydispatch to. Gated on `_INHERITED_LANGUAGES`.+ Python's `super().m()` walks the caller's C3 MRO instead and also emits+ `self_inherited`; a base the repository does not declare ends the walk+ unresolved, since it may declare `m` itself.- **Forward**: `dispatches_to`, a base method → an implementation that cananswer for it. Named for what it asserts rather than for a heritage relation:the pass matches by method name and compares no signature, so it is adiff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 5a430f737..9c10266ba 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -89,6 +89,10 @@ _LEXICAL_BARE_NAME_LANGUAGES = frozenset({"elixir", "fsharp"})# The sentinel an import that binds a whole module's public names carries._WILDCARD_IMPORTED_NAMES = ["*"]+# The graph's prefix for an import target outside the repository. Also marks a+# Python base class the repository does not declare, in an MRO walk.+_EXTERNAL_PREFIX = "external:"+# Ancestors within four hops: ``heritage_ancestors`` bounds expansion, not# reach, so 3 reaches 4._MAX_ANCESTOR_EXPAND_DEPTH = 3@@ -240,6 +244,7 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):else return_type_chain_languages)self._ancestors: dict[str, tuple[str, ...]] = {}+ self._mros: dict[str, tuple[str, ...] | None] = {}# Per-file symbol index: {file_path: {symbol_name: symbol_id}}self._file_symbols: dict[str, dict[str, str]] = {}@@ -764,6 +769,8 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):language = self._language_of(file_path) or ""receiver_call = call.receiver_call+ if language == "python" and _is_super_receiver(receiver_call):+ return self._with_props(self._super_call(call, caller_id), call)# 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 (@@ -1004,6 +1011,18 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):hit = self._bound_import_call(call, caller_id, binding)if hit is not None:return hit+ # A Python name imported from outside the repository is that module's,+ # not a same-named repo symbol a later tier would find. Python only:+ # Python resolves a repo's own absolute imports by dotted path, while+ # another language's import of the repo's own package by its published+ # name may still be marked external and mean repo code. Ceiling: an+ # in-repo ``except ImportError:`` fallback definition is not linked.+ if (+ binding is not None+ and (binding.source_file or "").startswith(_EXTERNAL_PREFIX)+ and self._language_of(file_path) == "python"+ ):+ return Noneif not declared:return Nonereturn (@@ -1385,6 +1404,83 @@ class CallResolver(LanguageStrategiesMixin, ReceiverTypingMixin):return Nonereturn ResolvedCall(caller_id, sym_id, 0.90, call.line, "self_inherited")+ def _super_call(self, call: CallSite, caller_id: str) -> ResolvedCall | None:+ """``super().m()``: the first class after the caller's own in its MRO to declare ``m``.++ Never handed to the bare-name tiers, which answered with whichever+ same-named method the file declared last. A base outside the+ repository ends the walk unresolved: it may declare ``m`` itself.++ Ceiling: ``super(C, self)`` is read as the caller's own class, since+ the call site keeps no argument text. A ``C`` naming another class+ starts the walk in the wrong place; reading the first argument would+ close it.+ """+ class_id = _extract_class_id(caller_id)+ mro = self._mro(class_id) if class_id is not None else None+ for ancestor in (mro or ())[1:]:+ if ancestor.startswith(_EXTERNAL_PREFIX):+ return None+ sym_id = self._declares(ancestor, call.target_name)+ if sym_id is not None:+ return ResolvedCall(caller_id, sym_id, 0.90, call.line, "self_inherited")+ return None++ def _mro(self, class_id: str, visiting: frozenset[str] = frozenset()) -> tuple[str, ...] | None:+ """Python's C3 linearization of *class_id*, or None when it cannot be built.++ A base outside the repository is kept as an opaque leaf, so the walk+ can tell where in the order it sits without knowing its own bases.+ """+ if class_id in self._mros:+ return self._mros[class_id]+ bases = self._declared_bases(class_id)+ mro: tuple[str, ...] | None = None+ if bases is not None and class_id not in visiting:+ inner = visiting | {class_id}+ chains: list[tuple[str, ...]] = []+ for base in bases:+ external = base.startswith(_EXTERNAL_PREFIX)+ chain = (base,) if external else self._mro(base, inner)+ if chain is None:+ break+ chains.append(chain)+ else:+ merged = _c3_merge([*chains, tuple(bases)])+ mro = None if merged is None else (class_id, *merged)+ self._mros[class_id] = mro+ return mro++ def _declared_bases(self, class_id: str) -> list[str] | None:+ """*class_id*'s bases in declaration order, each an in-repo class id or an external marker.++ The resolved heritage is an unordered id set, so each declared name is+ matched back to its id through the symbol's name, or the name an import+ alias stands for. None when a name matches two ids, or the file+ declares two classes of this name.+ """+ symbol = self._symbols_by_id.get(class_id)+ file_path = self._symbol_paths_by_id.get(class_id)+ parsed = self._parsed_files.get(file_path) if file_path else None+ if symbol is None or file_path is None or parsed is None:+ return None+ relations = [r for r in parsed.heritage if r.child_name == symbol.name]+ if len({r.line for r in relations}) > 1:+ return None+ parents = self._heritage_parents.get(class_id, ())+ bindings = self._import_bindings.get(file_path, {})+ bases: list[str] = []+ for relation in relations:+ binding = bindings.get(relation.parent_name)+ names = {relation.parent_name, binding.exported_name if binding else None}+ hits = [+ p for p in parents if (s := self._symbols_by_id.get(p)) is not None and s.name in names+ ]+ if len(hits) > 1:+ return None+ bases.append(hits[0] if hits else _EXTERNAL_PREFIX + relation.parent_name)+ return bases+def _language_of(self, file_path: str) -> str | None:parsed = self._parsed_files.get(file_path)return parsed.file_info.language if parsed else None@@ -1529,6 +1625,27 @@ def _rivals_a_class_method(symbol_id: str) -> bool:return len(parts) >= 3 and parts[-1] != parts[-2]+def _is_super_receiver(receiver: CallReceiver | None) -> bool:+ """Is this chained call's receiver Python's ``super(...)``?"""+ return receiver is not None and receiver.target_name == "super" and receiver.receiver_name is None+++def _c3_merge(sequences: list[tuple[str, ...]]) -> list[str] | None:+ """The C3 merge step of Python's MRO; None when no consistent order exists."""+ pending = [list(seq) for seq in sequences if seq]+ merged: list[str] = []+ while pending:+ head = next(+ (seq[0] for seq in pending if not any(seq[0] in other[1:] for other in pending)),+ None,+ )+ if head is None:+ return None+ merged.append(head)+ pending = [rest for seq in pending if (rest := seq[1:] if seq[0] == head else seq)]+ return merged++def _extract_class_id(symbol_id: str) -> str | None:"""``path::Cls::meth`` -> ``path::Cls``; None when no class encloses it.diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex a07bbc92d..a0448c699 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -490,7 +490,7 @@ ResolutionOrigin = Literal[# of its ancestors does. Below the two same-class origins because the walk# compares no signature and reads no visibility, so it can reach a method# the language would not actually dispatch to.- "self_inherited", # 0.90 — explicit self/this receiver+ "self_inherited", # 0.90 — explicit self/this receiver, or Python super()"enclosing_inherited", # 0.90 — implicit receiver, bare call]diff --git a/packages/core/src/repowise/core/ingestion/queries/python.scm b/packages/core/src/repowise/core/ingestion/queries/python.scmindex 4a928f737..81ffc2f35 100644--- a/packages/core/src/repowise/core/ingestion/queries/python.scm+++ b/packages/core/src/repowise/core/ingestion/queries/python.scm@@ -95,7 +95,7 @@; Chained method call: obj.method1().method2(args)(callfunction: (attribute- object: (call)+ object: (call) @call.receiver_callattribute: (identifier) @call.target)arguments: (argument_list) @call.argumentsdiff --git a/tests/unit/ingestion/test_dispatch_edges.py b/tests/unit/ingestion/test_dispatch_edges.pyindex 72a8fb8fc..e1f4269a5 100644--- a/tests/unit/ingestion/test_dispatch_edges.py+++ b/tests/unit/ingestion/test_dispatch_edges.py@@ -388,3 +388,129 @@ def test_a_csharp_overload_set_resolves_to_the_one_id_it_shares(tmp_path: Path)assert ("Test.cs::Test::Run", "Steps.cs::Steps::Given") in _calls_by_origin(graph, "enclosing_inherited")+++# ``super().m()`` walks the caller's MRO past its own class. It used to reach+# the bare-name tiers as ``m()``, which bound it to whichever same-named method+# the file declared last.+++def _calls_from(graph, caller: str) -> set[str]:+ return {+ v for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls" and u == caller+ }+++def test_super_call_resolves_to_the_base_not_the_file_last_same_name(tmp_path: Path) -> None:+ graph = _build(+ tmp_path,+ {+ "base.py": "class Base:\n def __init__(self, m):\n self.m = m\n",+ "impl.py": (+ "from base import Base\n\n\n"+ "class Child(Base):\n"+ " def __init__(self, m):\n"+ " super().__init__(m)\n\n\n"+ "class Unrelated:\n"+ " def __init__(self):\n"+ " pass\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "impl.py::Child::__init__") == {"base.py::Base::__init__"}+++def test_super_call_skips_a_base_that_does_not_declare_the_method(tmp_path: Path) -> None:+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Root:\n def run(self):\n return 0\n\n\n"+ "class Middle(Root):\n def other(self):\n return 1\n\n\n"+ "class Leaf(Middle):\n def run(self):\n return super().run()\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Leaf::run") == {"a.py::Root::run"}+++def test_super_call_follows_c3_order_through_a_diamond(tmp_path: Path) -> None:+ """C3 puts ``Right`` before the shared ``Top``; a depth-first walk would+ reach ``Top`` through ``Left`` first."""+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Top:\n def m(self):\n return 0\n\n\n"+ "class Left(Top):\n pass\n\n\n"+ "class Right(Top):\n def m(self):\n return 1\n\n\n"+ "class Bottom(Left, Right):\n def m(self):\n return super().m()\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Bottom::m") == {"a.py::Right::m"}+++def test_super_call_takes_the_first_declared_base_that_answers(tmp_path: Path) -> None:+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Mixin:\n def greet(self):\n return 2\n\n\n"+ "class Base:\n def greet(self):\n return 1\n\n\n"+ "class Both(Mixin, Base):\n"+ " def greet(self):\n return super(Both, self).greet()\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Both::greet") == {"a.py::Mixin::greet"}+++def test_super_call_on_an_external_base_resolves_to_nothing(tmp_path: Path) -> None:+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Failure(Exception):\n"+ " def __init__(self, message):\n"+ " super().__init__(message)\n\n\n"+ "class Unrelated:\n def __init__(self):\n pass\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Failure::__init__") == set()+++def test_super_call_stops_at_an_external_base_ahead_of_a_repo_one(tmp_path: Path) -> None:+ """``dict`` comes first in the MRO and declares ``get`` itself."""+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Store:\n def get(self, key):\n return None\n\n\n"+ "class Cache(dict, Store):\n"+ " def get(self, key):\n return super().get(key)\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Cache::get") == set()+++def test_super_call_in_a_class_without_bases_resolves_to_nothing(tmp_path: Path) -> None:+ graph = _build(+ tmp_path,+ {+ "a.py": (+ "class Plain:\n def __init__(self):\n super().__init__()\n\n\n"+ "class Other:\n def __init__(self):\n pass\n"+ ),+ },+ "python",+ )+ assert _calls_from(graph, "a.py::Plain::__init__") == set()diff --git a/tests/unit/ingestion/test_python_resolver_external.py b/tests/unit/ingestion/test_python_resolver_external.pyindex a67e21052..caa1c3bee 100644--- a/tests/unit/ingestion/test_python_resolver_external.py+++ b/tests/unit/ingestion/test_python_resolver_external.py@@ -333,3 +333,68 @@ def test_own_root_wins_over_a_same_dotted_name_in_another_root() -> None:assert resolve_python_import("tests.stubs", "libs/b/tests/test_x.py", ctx) == ("libs/b/tests/stubs.py")+++# A name imported from outside the repository is that module's, so a call to+# it must not fall through to a same-named repo symbol.+++def _call_edges(tmp_path, sources: dict[str, str]) -> set[tuple[str, str]]:+ from datetime import datetime++ from repowise.core.ingestion.graph import GraphBuilder+ from repowise.core.ingestion.models import FileInfo+ from repowise.core.ingestion.parser import ASTParser++ parser = ASTParser()+ builder = GraphBuilder(tmp_path)+ for rel, text in sources.items():+ abs_path = tmp_path / rel+ abs_path.parent.mkdir(parents=True, exist_ok=True)+ abs_path.write_text(text, encoding="utf-8")+ info = FileInfo(+ path=rel,+ abs_path=str(abs_path),+ language="python",+ size_bytes=len(text),+ git_hash="",+ last_modified=datetime.now(),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ builder.add_file(parser.parse_file(info, text.encode("utf-8")))+ graph = builder.build()+ return {(u, v) for u, v, d in graph.edges(data=True) if d.get("edge_type") == "calls"}+++_SHADOWED = {+ "pkg/__init__.py": "",+ "pkg/utils.py": "def unquote(s):\n return s\n\n\ndef other():\n return 1\n",+ "pkg/types.py": "class Path:\n pass\n",+}+++def test_an_imported_stdlib_name_does_not_bind_a_same_named_repo_symbol(tmp_path) -> None:+ edges = _call_edges(+ tmp_path,+ {+ **_SHADOWED,+ "pkg/urls.py": (+ "from urllib.parse import unquote\nfrom pkg.utils import other\n\n\n"+ "def parse(s):\n other()\n return unquote(s)\n"+ ),+ "pkg/paths.py": "from pathlib import Path\n\n\ndef mk(s):\n return Path(s)\n",+ },+ )+ assert ("pkg/urls.py::parse", "pkg/utils.py::other") in edges+ assert not {e for e in edges if e[1] in ("pkg/utils.py::unquote", "pkg/types.py::Path")}+++def test_an_unimported_name_still_reaches_the_repo_symbol(tmp_path) -> None:+ edges = _call_edges(+ tmp_path,+ {**_SHADOWED, "pkg/paths.py": "def mk(s):\n return Path(s)\n"},+ )+ assert ("pkg/paths.py::mk", "pkg/types.py::Path") in edges