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(contracts): key symbol_index by symbol id, not bare name (#3176)
xiao11525522d117e0287c
diff --git a/packages/core/src/repowise/core/analysis/change_contracts.py b/packages/core/src/repowise/core/analysis/change_contracts.pyindex aeffbf0ca..fea0cf63a 100644--- a/packages/core/src/repowise/core/analysis/change_contracts.py+++ b/packages/core/src/repowise/core/analysis/change_contracts.py@@ -164,13 +164,20 @@ def _containing_file(symbol_id: str) -> str:def symbol_index(parsed: Any, changed_set: set[str] | None = None) -> dict[str, dict[str, SymbolFacts]]:- """``{file_path: {symbol_name: SymbolFacts}}`` from either shape of parse.+ """``{file_path: {symbol_id: SymbolFacts}}`` from either shape of parse.Accepts both live ``ParsedFile``-shaped objects and the plain dicts in a``parsed_files.json`` artifact, so the same index builder serves the headparse, the base parse, and a snapshot fallback. Unknown or malformed rowsare skipped rather than raised on: this feeds advisory evidence, and one badrow must not cost the whole analysis.++ Keyed by ``symbol_id`` rather than the bare name: a file commonly holds+ several classes with like-named methods (``login``, ``validate``, ``to_dict``),+ and a name key silently keeps only the last one, hiding every change to the+ earlier ones. The id is also what :func:`caller_index` and+ :func:`_with_callers` use, so base and head now pair on the same key the+ call graph does."""out: dict[str, dict[str, SymbolFacts]] = {}for pf in parsed or []:@@ -187,7 +194,11 @@ def symbol_index(for sym in symbols or []:facts = _facts(sym, path)if facts is not None:- bucket[facts.name] = facts+ # Same-arity overloads in one class share an id -- Java and C#+ # register a parameter-count discriminator, so ``foo(int)`` and+ # ``foo(String)`` stay one node -- and the last one still wins+ # for them. Keying those apart is a separate change.+ bucket[facts.symbol_id] = factsif bucket:out[path] = bucketreturn out@@ -283,8 +294,11 @@ def analyze_contract_impact(continueranges = added_ranges_by_file.get(path, [])- for name, facts in sorted(head_syms.items()):- prior = base_syms.get(name)+ # Head and base pair by symbol id (see :func:`symbol_index`), so a method+ # moved between classes reads as removed + added rather than as an edit+ # to whichever same-named method sits in that class.+ for symbol_id, facts in sorted(head_syms.items()):+ prior = base_syms.get(symbol_id)effect = Noneif prior is not None and prior.signature != facts.signature:effect = classify_signature_change(@@ -312,8 +326,8 @@ def analyze_contract_impact(_with_callers(path, facts, change, callers, changed_set, callers_per_symbol, effect))- for name, facts in sorted(base_syms.items()):- if name not in head_syms:+ for symbol_id, facts in sorted(base_syms.items()):+ if symbol_id not in head_syms:changes.append(_with_callers(path, facts, CHANGE_REMOVED, callers, changed_set, callers_per_symboldiff --git a/tests/unit/analysis/test_change_contracts.py b/tests/unit/analysis/test_change_contracts.pyindex 88b8a2861..0f5ff7a67 100644--- a/tests/unit/analysis/test_change_contracts.py+++ b/tests/unit/analysis/test_change_contracts.py@@ -28,6 +28,18 @@ def _sym(name: str, *, path: str, sig: str, start: int = 10, end: int = 20, kind}+def _method(cls: str, name: str, *, path: str, sig: str, start: int = 10, end: int = 20):+ """A method, whose id carries its class: ``<path>::<Class>::<method>``."""+ return {+ "id": f"{path}::{cls}::{name}",+ "name": name,+ "kind": "method",+ "signature": sig,+ "start_line": start,+ "end_line": end,+ }++def _file(path: str, symbols: list[dict]) -> dict:return {"file_info": {"path": path}, "symbols": symbols}@@ -66,8 +78,8 @@ def _compute(base, head, *, calls=(), changed=("app/a.py",), ranges=None, **kwardef test_symbol_index_accepts_both_artifact_and_live_shapes():rows = [_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]live = [_live_file("app/a.py", [_sym("run", path="app/a.py", sig="run(x)")])]- assert symbol_index(rows)["app/a.py"]["run"].signature == "run(x)"- assert symbol_index(live)["app/a.py"]["run"].signature == "run(x)"+ assert symbol_index(rows)["app/a.py"]["app/a.py::run"].signature == "run(x)"+ assert symbol_index(live)["app/a.py"]["app/a.py::run"].signature == "run(x)"def test_symbol_index_drops_uninteresting_kinds():@@ -80,7 +92,25 @@ def test_symbol_index_drops_uninteresting_kinds():],)]- assert set(symbol_index(rows)["app/a.py"]) == {"run"}+ assert set(symbol_index(rows)["app/a.py"]) == {"app/a.py::run"}+++def test_symbol_index_keeps_every_same_named_method():+ # Keying by bare name would keep only the last `login`, so a change to the+ # first one could never be seen.+ rows = [+ _file(+ "service.py",+ [+ _method("AuthService", "login", path="service.py", sig="def login(user, pw)"),+ _method("SSOService", "login", path="service.py", sig="def login(token)"),+ ],+ )+ ]+ indexed = symbol_index(rows)["service.py"]+ assert set(indexed) == {"service.py::AuthService::login", "service.py::SSOService::login"}+ assert indexed["service.py::AuthService::login"].signature == "def login(user, pw)"+ assert indexed["service.py::SSOService::login"].signature == "def login(token)"def test_caller_index_reads_calls_edges_only():@@ -151,6 +181,80 @@ def test_removed_symbol_with_outside_caller_is_breaking():assert [c.name for c in impact.breaking] == ["gone"]+def test_signature_change_reports_the_same_named_method_it_belongs_to():+ # Two classes, both with `login`. Only AuthService's changes, so only that+ # id may be reported -- and against its own callers.+ auth = _method("AuthService", "login", path="service.py", sig="def login(user, pw)")+ sso = _method(+ "SSOService", "login", path="service.py", sig="def login(token)", start=30, end=40+ )+ edited = _method("AuthService", "login", path="service.py", sig="def login(user, pw, mfa)")+ base = [_file("service.py", [auth, sso])]+ head = [_file("service.py", [edited, sso])]++ impact = _compute(+ base,+ head,+ changed=("service.py",),+ calls=[("app/b.py::main", "service.py::AuthService::login")],+ )++ assert [c.change for c in impact.changes] == ["signature"]+ change = impact.changes[0]+ assert change.symbol_id == "service.py::AuthService::login"+ assert change.name == "login"+ assert change.outside_callers == ["app/b.py::main"]+ assert [c.symbol_id for c in impact.breaking] == ["service.py::AuthService::login"]+++def test_removing_one_same_named_method_leaves_the_other_alone():+ # Deleting SSOService.login must not diff AuthService.login against it: the+ # surviving method is unchanged, so nothing at all is reported for it.+ auth = _method("AuthService", "login", path="service.py", sig="def login(user, pw)")+ sso = _method(+ "SSOService", "login", path="service.py", sig="def login(token)", start=30, end=40+ )+ base = [_file("service.py", [auth, sso])]+ head = [_file("service.py", [auth])]++ impact = _compute(+ base,+ head,+ changed=("service.py",),+ calls=[("app/b.py::main", "service.py::SSOService::login")],+ )++ assert [(c.symbol_id, c.change) for c in impact.changes] == [+ ("service.py::SSOService::login", "removed")+ ]+ assert impact.changes[0].name == "login"+ assert [c.symbol_id for c in impact.breaking] == ["service.py::SSOService::login"]+++def test_a_method_moved_between_classes_reads_removed_and_added():+ # Its callers point at the old id, so a move is a removal plus an addition+ # rather than an edit to whichever method now answers to the bare name.+ base = [+ _file(+ "service.py",+ [_method("AuthService", "login", path="service.py", sig="def login(user, pw)")],+ )+ ]+ head = [+ _file(+ "service.py",+ [_method("SSOService", "login", path="service.py", sig="def login(user, pw)")],+ )+ ]++ impact = _compute(base, head, changed=("service.py",))++ assert [(c.symbol_id, c.change) for c in impact.changes] == [+ ("service.py::AuthService::login", "removed"),+ ("service.py::SSOService::login", "added"),+ ]++def test_body_change_needs_an_added_line_and_never_breaks():# Same signature. Without an overlapping added-line range the symbol is not# reported at all: the base side may be an out-of-date snapshot, and