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(dead-code): stop reporting symbols a registration decorator wires in (#1681)

Raghav Chamadiya9c339fe7384d
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index f451f233d..82f6683b2 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -161,6 +161,38 @@ def _decorator_base(raw: str) -> str:
return base
+def _is_framework_registered(decorators: list[str]) -> bool:
+ """Whether any decorator wires the symbol into a framework dispatcher.
+
+ Both dead-code passes ask this question, and both asked it with the same
+ lines copy-pasted. It lives here once because a registration rule that
+ drifts between the export pass and the internals pass is a bug nobody goes
+ looking for.
+
+ Three spellings of one fact:
+
+ * a known base name or dotted prefix (``@Component``, ``@app.route``);
+ * a known trailing attribute, for a receiver the prefix list cannot
+ anticipate because it is named locally (``@my_group.command``);
+ * a registration verb in the final path segment. Every suffix entry begins
+ with a dot, so that list can only ever see a *dotted* decorator, and
+ celery's ``@register_drainer('eventlet')`` is bare — invisible to all of
+ them. Reading the final segment covers both spellings at once:
+ ``@register``, ``@register_drainer``, ``@Field.register_lookup``. Held to
+ ``register`` exactly or a ``register_`` stem so that a past participle
+ guarding a handler (``@registered_only``) is not read as one.
+ """
+ bases = [_decorator_base(d) for d in decorators]
+ if any(b.startswith(_FRAMEWORK_DECORATORS) for b in bases):
+ return True
+ if any(b.endswith(_FRAMEWORK_DECORATOR_SUFFIXES) for b in bases):
+ return True
+ return any(
+ segment == "register" or segment.startswith("register_")
+ for segment in (b.rsplit(".", 1)[-1] for b in bases)
+ )
+
+
def _is_symbol_deprecated(sym_name: str, decorators: list[str]) -> bool:
"""Return True when the symbol is marked deprecated by name suffix or annotation.
@@ -1236,25 +1268,9 @@ class DeadCodeAnalyzer:
):
continue
- # Decorators are stored with the leading "@" (e.g. "@app.route").
- # _FRAMEWORK_DECORATORS entries are bare prefixes; suffixes
- # like ``.command`` match locally-named Click groups
- # (``@my_group.command("add")``). Compare against the
- # stripped form, and strip any call ``(...)`` tail so the
- # suffix check sees the attribute path itself.
decorators = sym.get("decorators", [])
- if any(
- _decorator_base(d).startswith(prefix)
- for d in decorators
- for prefix in _FRAMEWORK_DECORATORS
- ):
- continue
- if any(
- _decorator_base(d).endswith(suffix)
- for d in decorators
- for suffix in _FRAMEWORK_DECORATOR_SUFFIXES
- ):
+ if _is_framework_registered(decorators):
continue
if _declared_deliberately_unused(decorators):
continue
@@ -1495,22 +1511,11 @@ class DeadCodeAnalyzer:
# private ``@PostConstruct``/``@EventListener``/``@Scheduled``
# method is invoked by the container, not by a source call.
decorators = node_data.get("decorators") or []
- if decorators:
- if any(
- _decorator_base(d).startswith(prefix)
- for d in decorators
- for prefix in _FRAMEWORK_DECORATORS
- ):
- continue
- if any(
- _decorator_base(d).endswith(suffix)
- for d in decorators
- for suffix in _FRAMEWORK_DECORATOR_SUFFIXES
- ):
- continue
- if _declared_deliberately_unused(decorators):
- continue
+ if _is_framework_registered(decorators):
+ 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.py
index 7554d316a..06009e2d4 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -971,12 +971,11 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (
".command",
".group",
".callback",
- # Registry registration: ``@filter_registry.register`` / ``@hooks.register``
- # wires the symbol in by side effect; consumers look it up by string key,
- # so the name never appears in an import. Any decorator whose attribute
- # path ends in ``.register`` is a registration, whatever the registry
- # object is called.
- ".register",
+ # Registry registration (``@filter_registry.register``) is deliberately not
+ # here. It is one spelling of a rule that must also reach the bare
+ # ``@register_drainer`` form, which no dotted suffix can ever match, so
+ # ``_is_framework_registered`` carries both rather than this list carrying
+ # half.
# FastAPI / Flask / Sanic route decorators on a receiver the prefix list
# doesn't anticipate (``api = FastAPI()``, ``_repo_health_router =
# APIRouter()``). A decorator ending in an HTTP verb or routing method is
@@ -993,6 +992,10 @@ _FRAMEWORK_DECORATOR_SUFFIXES: tuple[str, ...] = (
".websocket",
".middleware",
".exception_handler",
+ # Startup/shutdown lifecycle hooks (``@app.on_event("shutdown")``). The
+ # framework calls them and nothing imports them, exactly as for the route
+ # decorators above; the list simply never carried the hook form.
+ ".on_event",
# Celery apps under a non-``app``/``celery`` local name (``@worker.task``).
".task",
# Django template tags and filters. ``@register.tag(name="result_list")``
diff --git a/tests/unit/dead_code/test_decorators_dynamic.py b/tests/unit/dead_code/test_decorators_dynamic.py
index ea292a48e..a2f47098e 100644
--- a/tests/unit/dead_code/test_decorators_dynamic.py
+++ b/tests/unit/dead_code/test_decorators_dynamic.py
@@ -344,6 +344,17 @@ def test_unrelated_dot_command_function_still_flagged():
'@filter_registry.register("git_status")',
# ``from pytest import fixture`` leaves a bare, undotted decorator.
"@fixture",
+ # A *bare* registration decorator. No dotted suffix can reach this
+ # form, so it was invisible to every list until the final path
+ # segment became the thing matched.
+ "@register_drainer('eventlet')",
+ "@register",
+ # The dotted spellings of the same rule, which must keep working
+ # after the ``.register`` suffix entry was retired into it.
+ "@Field.register_lookup",
+ "@atexit.register",
+ # Lifecycle hooks: the framework calls them, nothing imports them.
+ '@app.on_event("shutdown")',
],
)
def test_renamed_receiver_and_registry_decorators_excluded(decorator):
@@ -372,3 +383,90 @@ def test_renamed_receiver_and_registry_decorators_excluded(decorator):
report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
assert "wired_symbol" not in names
+
+
+ "decorator",
+ [
+ # A past participle guarding a handler is not a registration, and it
+ # is the one word a ``register`` prefix would swallow — hence the rule
+ # matches ``register`` exactly or a ``register_`` stem, nothing else.
+ "@registered_only",
+ "@registry_cache",
+ # The receiver being called ``register`` says nothing about the
+ # decorator, which is what the final path segment is read for.
+ "@register.unwrap",
+ ],
+)
+def test_register_lookalike_decorators_still_flagged(decorator):
+ g = _build_graph(
+ nodes={
+ "pkg/guarded.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "guarded_symbol",
+ "kind": "function",
+ "visibility": "public",
+ "decorators": [decorator],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ edges=[],
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze({"detect_unreachable_files": False, "detect_zombie_packages": False})
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_EXPORT}
+ assert "guarded_symbol" in names
+
+
+ "decorator",
+ ["@register_drainer('gevent')", '@app.on_event("startup")', "@shared_task"],
+)
+def test_framework_registration_also_skips_the_internals_pass(decorator):
+ """The unused-internal pass must apply the same rule as the export pass.
+
+ It carried its own copy of it, so the two could diverge without any test
+ noticing — a private ``@register_drainer`` helper is registered by exactly
+ the same side effect as a public one.
+ """
+ g = _build_graph(
+ nodes={
+ "pkg/wired.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_wired_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [decorator],
+ "start_line": 1,
+ "end_line": 10,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+ names = {f.symbol_name for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL}
+ assert "_wired_helper" not in names