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(dead-code): stop reporting symbols a framework or a container reaches (#1673)
Raghav Chamadiya6b17c4983357
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 9278108c6..0b1c8ae48 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport fnmatchimport re+from collections.abc import Iterablefrom collections.abc import Set as AbstractSetfrom datetime import UTC, datetimefrom pathlib import Path@@ -22,7 +23,9 @@ import structlogfrom ...ingestion.models import REACHABILITY_USE_EDGE_TYPESfrom .constants import (+ _CONTAINER_USE_LANGUAGES,_DEFAULT_DYNAMIC_PATTERNS,+ _DELIBERATELY_UNUSED_ANNOTATIONS,_FRAMEWORK_DECORATOR_SUFFIXES,_FRAMEWORK_DECORATORS,_NEVER_PACKAGE_DIRS,@@ -110,6 +113,31 @@ _DEPRECATED_DECORATOR_BASES: frozenset[str] = frozenset(_QUOTED_STR_RE: re.Pattern[str] = re.compile(r'"[^"]*"')+def _declared_deliberately_unused(decorators: Iterable[str]) -> bool:+ """True when the author has written that the symbol is deliberately uncalled.++ Distinct from the framework lists, which infer a caller we cannot see. Here+ there may be no caller at all and the annotation says so, which is a+ stronger signal than any heuristic. Read from the raw token because the+ base name is shared with every other use of the same annotation.+ """+ for blob in decorators:+ # A Java/Kotlin modifiers node delivers every annotation concatenated,+ # so the blob is split the way ``_is_symbol_deprecated`` splits it —+ # without this, ``@Named("unused-legacy-bean")`` beside an unrelated+ # ``@SuppressWarnings`` reads as the author's statement.+ for token in str(blob).split("@"):+ if not token.strip():+ continue+ base = _decorator_base(token)+ if any(+ base == name and argument in token+ for name, argument in _DELIBERATELY_UNUSED_ANNOTATIONS+ ):+ return True+ return False++def _decorator_base(raw: str) -> str:"""Return the normalised base name of a single decorator/annotation token.@@ -958,6 +986,42 @@ class DeadCodeAnalyzer:risk_factors=list(risk_factors),)+ def _member_is_used(self, sym_id: str, language: str | None) -> bool:+ """True when this container declares a method something else uses.++ Reads the ``has_method`` edges the graph already holds, so this adds no+ pass and no extraction.++ Two narrowings, and both were forced by review rather than chosen:++ **The use must come from outside the container.** A class's own methods+ are predecessors of each other, so counting them would make any class+ with two methods where one calls the other rescue itself — evidence+ about the inside of a container is not evidence that anything reaches+ it.++ **Only a call counts, not the wider reachability set.** Transferring+ member-level evidence to the container is only sound when something+ actually invokes the member; an ``implements`` or ``method_implements``+ edge says the member satisfies a contract, which is a fact about the+ member's shape and not about anyone reaching the class.+ """+ if language not in _CONTAINER_USE_LANGUAGES or not self.graph.has_node(sym_id):+ return False+ members = {+ method_id+ for _, method_id, data in self.graph.out_edges(sym_id, data=True)+ if data.get("edge_type") == "has_method"+ }+ within = members | {sym_id}+ for method_id in members:+ if any(+ pred not in within and self.graph[pred][method_id].get("edge_type") == "calls"+ for pred in self.graph.predecessors(method_id)+ ):+ return True+ return False+def _detect_unused_exports(self,dynamic_patterns: tuple[str, ...],@@ -1182,6 +1246,8 @@ class DeadCodeAnalyzer:for suffix in _FRAMEWORK_DECORATOR_SUFFIXES):continue+ if _declared_deliberately_unused(decorators):+ continueif self._name_matches_dynamic(sym_name, dynamic_patterns):continue@@ -1262,6 +1328,21 @@ class DeadCodeAnalyzer:):continue+ # A container whose member is used is itself used, and no+ # search for the container's own name can see it. A C# static+ # holder class is only ever named at its declaration --+ # ``Guard.Against.EmptyBasket(...)`` writes the method, never+ # ``BasketGuards`` -- so the name really is absent and the name+ # is the wrong thing to look for. Asked after the direct check+ # so it can only rescue, never displace.+ #+ # Gated to C# because that is where the idiom lives. The+ # argument generalises -- deleting any class whose method has a+ # caller breaks that caller -- but ungating it removes findings+ # in every language at once, which is its own measured change.+ if self._member_is_used(sym_id, sym.get("language")):+ continue+if is_deprecated:confidence = 0.3elif file_has_importers:@@ -1418,6 +1499,8 @@ class DeadCodeAnalyzer:for suffix in _FRAMEWORK_DECORATOR_SUFFIXES):continue+ if _declared_deliberately_unused(decorators):+ continue# Any inbound use, not only a call. A base class that is subclassed# rather than instantiated, a collaborator the container constructs,diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.pyindex 2e0b9e859..7554d316a 100644--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py@@ -897,6 +897,12 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = ("OnClose","OnMessage","OnError",+ # OSGi declarative-services lifecycle. The container calls these by+ # reflection off the component descriptor, so they are private and have no+ # caller in source by design.+ "Activate",+ "Deactivate",+ "Modified","PactTestFor","Pact",# ---- JVM: test method markers -----------------------------------@@ -989,6 +995,30 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (".exception_handler",# Celery apps under a non-``app``/``celery`` local name (``@worker.task``).".task",+ # Django template tags and filters. ``@register.tag(name="result_list")``+ # registers the function under a string key; the template then invokes it+ # as ``{% result_list cl %}``, so no Python source ever names it. The+ # registry object is conventionally ``register`` but is file-local, which+ # is why this matches the suffix rather than the receiver.+ ".tag",+ ".filter",+ ".simple_tag",+ ".inclusion_tag",+)++# Languages whose idiom is a static holder class: a container the source never+# names at a call site, because the call names only the member. C# extension+# methods are the shape (``Guard.Against.EmptyBasket(...)`` against a+# ``static class BasketGuards``). Kept as a set rather than inlined so widening+# it is a deliberate, measurable act.+_CONTAINER_USE_LANGUAGES: frozenset[str] = frozenset({"csharp"})++# Annotations whose *argument* is the signal, so the base name alone cannot be+# matched: ``@SuppressWarnings`` says nothing on its own, and only the+# ``"unused"`` argument is the author stating that the symbol is deliberately+# uncalled. Matched against the raw decorator text rather than its base.+_DELIBERATELY_UNUSED_ANNOTATIONS: tuple[tuple[str, str], ...] = (+ ("SuppressWarnings", "unused"),)diff --git a/tests/unit/dead_code/test_framework_registration_rescues.py b/tests/unit/dead_code/test_framework_registration_rescues.pynew file mode 100644index 000000000..520814c69--- /dev/null+++ b/tests/unit/dead_code/test_framework_registration_rescues.py@@ -0,0 +1,230 @@+"""Rescues for symbols a framework or a container reaches, not a caller.++Each case here is a symbol the repository really uses and whose name a search+would correctly report as absent, because the name is the wrong thing to look+for: a template invokes a tag by its registered string, and a C# call site+writes an extension method's name and never its holder class's.+"""++from __future__ import annotations++import networkx as nx++from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind+from tests.unit.dead_code._helpers import _build_graph+++def _unused_export_names(graph: nx.DiGraph) -> list[str]:+ report = DeadCodeAnalyzer(graph, git_meta_map={}).analyze(+ {"detect_unreachable_files": False, "detect_zombie_packages": False}+ )+ return [f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT]+++def _django_tag_graph(decorator: str) -> nx.DiGraph:+ return _build_graph(+ nodes={+ "app/templatetags/admin_list.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "result_list_tag",+ "kind": "function",+ "visibility": "public",+ "decorators": [decorator],+ "start_line": 1,+ "end_line": 10,+ "complexity_estimate": 1,+ },+ ],+ },+ },+ )+++def test_django_template_tag_is_not_flagged():+ """``{% result_list cl %}`` is the only caller and it is not Python."""+ for decorator in (+ '@register.tag(name="result_list")',+ "@register.simple_tag",+ "@register.inclusion_tag('admin/list.html')",+ "@register.filter",+ ):+ assert "result_list_tag" not in _unused_export_names(_django_tag_graph(decorator))+++def test_an_undecorated_sibling_is_still_flagged():+ """The rescue is the decorator, not the directory."""+ graph = _django_tag_graph("@staticmethod")+ assert "result_list_tag" in _unused_export_names(graph)+++def test_suppresswarnings_unused_is_read_as_an_author_statement():+ """``@SuppressWarnings("unused")`` says outright that nothing calls this."""+ graph = _build_graph(+ nodes={+ "src/Provider.java": {+ "language": "java",+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "activate",+ "kind": "function",+ "visibility": "public",+ "decorators": ['@SuppressWarnings("unused")'],+ "start_line": 1,+ "end_line": 5,+ "complexity_estimate": 1,+ "language": "java",+ },+ ],+ },+ },+ )+ assert "activate" not in _unused_export_names(graph)+++def test_a_bare_suppresswarnings_still_flags():+ """The argument is the signal; the annotation alone is worn by everything."""+ graph = _build_graph(+ nodes={+ "src/Provider.java": {+ "language": "java",+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "activate",+ "kind": "function",+ "visibility": "public",+ "decorators": ['@SuppressWarnings("rawtypes")'],+ "start_line": 1,+ "end_line": 5,+ "complexity_estimate": 1,+ "language": "java",+ },+ ],+ },+ },+ )+ assert "activate" in _unused_export_names(graph)+++def _holder_graph(language: str, wire_call: bool) -> nx.DiGraph:+ graph = _build_graph(+ nodes={+ "src/GuardExtensions.cs": {+ "language": language,+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "BasketGuards",+ "kind": "class",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 20,+ "complexity_estimate": 2,+ "language": language,+ },+ ],+ },+ "src/Checkout.cs": {+ "language": language,+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "Checkout",+ "kind": "function",+ "visibility": "public",+ "decorators": [],+ "start_line": 1,+ "end_line": 9,+ "complexity_estimate": 1,+ "language": language,+ },+ ],+ },+ },+ )+ holder = "src/GuardExtensions.cs::BasketGuards"+ member = "src/GuardExtensions.cs::BasketGuards::EmptyBasketOnCheckout"+ graph.add_node(member, node_type="symbol", file_path="src/GuardExtensions.cs", language=language)+ graph.add_edge(holder, member, edge_type="has_method")+ if wire_call:+ graph.add_edge("src/Checkout.cs::Checkout", member, edge_type="calls")+ return graph+++def test_csharp_holder_class_is_rescued_by_its_used_member():+ """A call site writes the extension method's name, never the holder's."""+ assert "BasketGuards" not in _unused_export_names(_holder_graph("csharp", wire_call=True))+++def test_a_holder_whose_member_is_also_unused_is_still_flagged():+ """The rescue is a used member, not the presence of members."""+ assert "BasketGuards" in _unused_export_names(_holder_graph("csharp", wire_call=False))+++def test_the_container_rescue_is_language_gated():+ """A static holder class is C#'s idiom; ungating it is its own change."""+ assert "BasketGuards" in _unused_export_names(_holder_graph("java", wire_call=True))+++def test_a_container_cannot_rescue_itself_from_the_inside():+ """One of its own methods calling another is not a use of the container.++ Without this, any class holding two methods where one calls the other is+ unreportable, because a class's own methods are predecessors of each other.+ """+ graph = _holder_graph("csharp", wire_call=False)+ holder = "src/GuardExtensions.cs::BasketGuards"+ sibling = "src/GuardExtensions.cs::BasketGuards::Round"+ member = "src/GuardExtensions.cs::BasketGuards::EmptyBasketOnCheckout"+ graph.add_node(sibling, node_type="symbol", file_path="src/GuardExtensions.cs", language="csharp")+ graph.add_edge(holder, sibling, edge_type="has_method")+ graph.add_edge(sibling, member, edge_type="calls")++ assert "BasketGuards" in _unused_export_names(graph)+++def test_an_annotation_beside_suppresswarnings_does_not_leak_its_argument():+ """``@Named("unused-legacy-bean")`` is not the author declaring anything."""+ graph = _build_graph(+ nodes={+ "src/Provider.java": {+ "language": "java",+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [+ {+ "name": "activate",+ "kind": "function",+ "visibility": "public",+ "decorators": ['@SuppressWarnings("rawtypes")\n@Named("unused-legacy-bean")'],+ "start_line": 1,+ "end_line": 5,+ "complexity_estimate": 1,+ "language": "java",+ },+ ],+ },+ },+ )+ assert "activate" in _unused_export_names(graph)