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(heritage): anchor an inheritance edge to the child's real symbol id (#2414)

Raghav Chamadiya6007e6f1527f
diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
index 3a23c9a52..05c17bb11 100644
--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py
@@ -120,6 +120,13 @@ class HeritageResolver:
# Per-file class/interface/trait index: {file: {name: symbol_id}}
self._file_types: dict[str, dict[str, str]] = {}
+ # Type ids each file declares, for files carrying heritage relations.
+ # Used only to tell whether a composed child id already names a type.
+ self._file_type_ids: dict[str, set[str]] = {}
+
+ # Type names a file declares more than once, in whatever scopes.
+ self._file_ambiguous_types: dict[str, set[str]] = {}
+
# Global class/interface/trait index: {name: [symbol_ids]}
self._global_types: dict[str, list[str]] = defaultdict(list)
@@ -149,13 +156,25 @@ class HeritageResolver:
"""Build type-level lookup indices from parsed file data."""
for path, parsed in parsed_files.items():
file_types: dict[str, str] = {}
+ ambiguous: set[str] = set()
for sym in parsed.symbols:
if sym.kind in _PARENT_KINDS:
+ # Distinct ids, not repeat sightings: a type and the `impl`
+ # block on it are two symbols under one name and one id.
+ prior = file_types.get(sym.name)
+ if prior is not None and prior != sym.id:
+ ambiguous.add(sym.name)
file_types[sym.name] = sym.id
self._global_types[sym.name].append(sym.id)
self._file_types[path] = file_types
+ # Only the file that owns a relation asks these two, so a file
+ # declaring no heritage never needs them. _file_types stays global:
+ # tiers 2a, 2b and 3 read it for OTHER files.
+ if parsed.heritage:
+ self._file_type_ids[path] = set(file_types.values())
+ self._file_ambiguous_types[path] = ambiguous
def _merged_types_for(self, file_path: str) -> dict[str, str]:
"""Merged ``{type_name → symbol_id}`` across every imported file."""
@@ -185,12 +204,44 @@ class HeritageResolver:
def _resolve_one(self, file_path: str, rel: HeritageRelation) -> ResolvedHeritage | None:
"""Resolve a single HeritageRelation through three-tier fallback."""
- child_id = f"{file_path}::{rel.child_name}"
+ # Tier 1: same-file
+ file_types = self._file_types.get(file_path, {})
+
+ # The declaring file already knows what the child's symbol id is, and
+ # it is not always two segments: a type declared inside a `mod` carries
+ # the module in its id, so composing one from the file and the bare
+ # name anchors the edge to a node that was never emitted.
+ #
+ # A composed id that already names a real symbol is kept, and so is a
+ # name the file declares more than once. The type table is keyed by
+ # bare name and is last-wins, so for an ambiguous name it answers with
+ # whichever declaration came last: an associated `type X = ...` in an
+ # unrelated impl, or a same-named type from a different `mod`. That
+ # would swap an anchor that dangles for one that points confidently at
+ # the wrong node, which is the worse of the two. A child the table
+ # does not carry at all, such as a `where` bound whose child is a
+ # function, also keeps the composed form.
+ #
+ # The first test asks for a TYPE of that id, not any symbol: a file
+ # whose top-level function shares a nested type's bare name would
+ # otherwise capture the anchor and wire the edge to the function.
+ #
+ # Ceiling: it proves the composed id is not dangling, not that it is
+ # the right symbol. A file declaring `Speaker` at top level and another
+ # inside a `mod` anchors the mod's impl to the top-level one, as it did
+ # before this change. Telling those apart needs the relation to carry
+ # the scope it was declared in, which it does not.
+ composed = f"{file_path}::{rel.child_name}"
+ if (
+ composed in self._file_type_ids.get(file_path, ())
+ or rel.child_name in self._file_ambiguous_types.get(file_path, ())
+ ):
+ child_id = composed
+ else:
+ child_id = file_types.get(rel.child_name) or composed
parent_name = rel.parent_name
edge_type = _heritage_kind_to_edge_type(rel.kind)
- # Tier 1: same-file
- file_types = self._file_types.get(file_path, {})
if parent_name in file_types:
return ResolvedHeritage(
child_id=child_id,
diff --git a/tests/unit/ingestion/test_resolver_merged_index.py b/tests/unit/ingestion/test_resolver_merged_index.py
index ee206cd45..73ceda550 100644
--- a/tests/unit/ingestion/test_resolver_merged_index.py
+++ b/tests/unit/ingestion/test_resolver_merged_index.py
@@ -191,3 +191,103 @@ class TestHeritageTier2b:
results.extend(resolver.resolve_file(path, pf.heritage))
hits = [(r.child_id, r.parent_id, r.confidence) for r in results if r.confidence == 0.85]
assert hits == [("child.py::Child", "a_base.py::Base", 0.85)], hits
+
+
+class TestHeritageChildAnchor:
+ """The edge's source must name a symbol the file actually declares."""
+
+ def test_child_inside_a_mod_keeps_its_module_segment(self, tmp_path: Path) -> None:
+ files = {
+ "lib.rs": (
+ "rust",
+ "pub trait Greet {}\n"
+ "pub mod inner {\n"
+ " pub struct Speaker;\n"
+ " impl super::Greet for Speaker {}\n"
+ "}\n",
+ ),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(parsed, {"lib.rs": set()})
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ child_ids = [r.child_id for r in results]
+ declared = {s.id for pf in parsed.values() for s in pf.symbols}
+ assert "lib.rs::inner::Speaker" in child_ids, child_ids
+ # And the anchor is a node that exists, which is the point.
+ assert all(c in declared for c in child_ids), (child_ids, sorted(declared))
+
+ def test_ambiguous_name_keeps_the_composed_id(self, tmp_path: Path) -> None:
+ # Two `Speaker` types in different mods. The name-keyed table answers
+ # with whichever came last, so neither is trustworthy: an anchor that
+ # dangles beats one that points confidently at the wrong type.
+ files = {
+ "lib.rs": (
+ "rust",
+ "pub trait Greet {}\n"
+ "pub mod a {\n"
+ " pub struct Speaker;\n"
+ " impl super::Greet for Speaker {}\n"
+ "}\n"
+ "pub mod b {\n"
+ " pub struct Speaker;\n"
+ "}\n",
+ ),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(parsed, {"lib.rs": set()})
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ child_ids = [r.child_id for r in results]
+ assert "lib.rs::b::Speaker" not in child_ids, child_ids
+ assert "lib.rs::Speaker" in child_ids, child_ids
+
+ def test_composed_id_that_already_exists_is_kept(self, tmp_path: Path) -> None:
+ # `Speaker` is declared at file scope, so the composed id is already
+ # right. A same-named type inside a `mod` must not steal the anchor.
+ files = {
+ "lib.rs": (
+ "rust",
+ "pub trait Greet {}\n"
+ "pub struct Speaker;\n"
+ "impl Greet for Speaker {}\n"
+ "pub mod tests {\n"
+ " pub struct Speaker;\n"
+ "}\n",
+ ),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(parsed, {"lib.rs": set()})
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ child_ids = [r.child_id for r in results]
+ assert "lib.rs::Speaker" in child_ids, child_ids
+ assert "lib.rs::tests::Speaker" not in child_ids, child_ids
+
+ def test_a_function_of_the_same_name_does_not_capture_the_anchor(
+ self, tmp_path: Path
+ ) -> None:
+ # The composed id names a top-level FUNCTION here, not a type. The
+ # nested struct is the real child, so the function must not hold the
+ # anchor just by existing.
+ files = {
+ "lib.rs": (
+ "rust",
+ "pub trait Greet {}\n"
+ "pub fn Speaker() {}\n"
+ "pub mod inner {\n"
+ " pub struct Speaker;\n"
+ " impl super::Greet for Speaker {}\n"
+ "}\n",
+ ),
+ }
+ parsed = _parse_all(tmp_path, files)
+ resolver = HeritageResolver(parsed, {"lib.rs": set()})
+ results = []
+ for path, pf in parsed.items():
+ results.extend(resolver.resolve_file(path, pf.heritage))
+ child_ids = [r.child_id for r in results]
+ assert "lib.rs::inner::Speaker" in child_ids, child_ids