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): treat a function stored by its own decorator as used (#3490)

Raghav Chamadiya7cf2366da6e4
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 9f66d0609..c8f8e2cdf 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -26,6 +26,7 @@ import structlog
from ...code_origin import is_build_file
from ...entry_candidacy import is_reachability_root
+from ...ingestion.decorator_names import decorator_base as _decorator_base
from ...ingestion.models import REACHABILITY_USE_EDGE_TYPES
from ...ingestion.package_roots import package_manifest_names
from ...ingestion.symbol_identity import base_symbol_id, overload_sets
@@ -175,29 +176,6 @@ def _declared_deliberately_unused(decorators: Iterable[str]) -> bool:
return False
-def _decorator_base(raw: str) -> str:
- """Return the normalised base name of a single decorator/annotation token.
-
- Strips a leading ``@``, trims whitespace, and drops any call-argument
- ``(…)`` tail. For multi-word tokens (e.g. a Java modifier blob fragment
- ``"Deprecated\n public"``) only the first whitespace-delimited word is
- kept, so visibility keywords that trail the annotation name are discarded.
-
- This function handles ONE token. Callers that receive multi-annotation
- blobs (Java/Kotlin ``modifiers`` node) must split on ``@`` first.
- """
- base = raw.lstrip("@").strip()
- paren = base.find("(")
- if paren >= 0:
- base = base[:paren].strip()
- else:
- # Handle trailing visibility keywords in modifier blobs:
- # "Deprecated\n public" → "Deprecated"
- parts = base.split()
- base = parts[0] if parts else base
- return base
-
-
def _is_framework_registered(decorators: list[str]) -> bool:
"""Whether any decorator wires the symbol into a framework dispatcher.
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 383533d1c..7e15830eb 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -806,6 +806,9 @@ _FRAMEWORK_DECORATORS: tuple[str, ...] = (
"app.task",
"celery.task",
"shared_task",
+ # SQLAlchemy, imported bare: stored in the dialect compiler / event registry.
+ "compiles",
+ "listens_for",
# Click CLI commands — registered with the parent group/command.
"click.command",
"click.group",
diff --git a/packages/core/src/repowise/core/analysis/execution_roles.py b/packages/core/src/repowise/core/analysis/execution_roles.py
index 43c23376d..4080586cf 100644
--- a/packages/core/src/repowise/core/analysis/execution_roles.py
+++ b/packages/core/src/repowise/core/analysis/execution_roles.py
@@ -24,6 +24,7 @@ from typing import Any, Literal, get_args
from repowise.core.code_origin import path_origin
from repowise.core.ingestion.framework_routes import flask_routes, next_app_router_file
+from repowise.core.ingestion.models import REGISTRATION_HINT
from repowise.core.test_paths import is_test_path
from .execution_graph import ExecutionGraphIndex, file_of_symbol
@@ -215,7 +216,8 @@ def _scan(graph: Any) -> _Scan:
scan.url_targets.add(target)
elif edge_type == "framework_binds":
scan.binds.append((source, target))
- elif edge_type == "references":
+ # A registry holding the function says nothing about how it runs.
+ elif edge_type == "references" and (data or {}).get("hint_source") != REGISTRATION_HINT:
scan.references.append((source, target))
scan.referenced.add(target)
return scan
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 7854c1e51..eb26fee51 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -40,6 +40,7 @@ from .call_receiver_typing import (
ReceiverTypingMixin,
_store_capped,
)
+from .decorator_names import decorator_base
from .language_data import (
get_builtin_methods,
get_builtin_types,
@@ -132,7 +133,7 @@ _PROPERTY_ACCESSOR_SUFFIXES = (".setter", ".getter", ".deleter")
def _is_property_accessor(sym: Any) -> bool:
for decorator in getattr(sym, "decorators", ()) or ():
- tail = decorator.lstrip("@").strip()
+ tail = decorator_base(decorator)
if tail in _PROPERTY_DECORATORS or tail.endswith(_PROPERTY_ACCESSOR_SUFFIXES):
return True
return False
diff --git a/packages/core/src/repowise/core/ingestion/decorator_names.py b/packages/core/src/repowise/core/ingestion/decorator_names.py
new file mode 100644
index 000000000..56437611b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/decorator_names.py
@@ -0,0 +1,19 @@
+"""The base name of one decorator or annotation token, shared by every reader."""
+
+from __future__ import annotations
+
+
+def decorator_base(raw: str) -> str:
+ """``@app.route("/x")`` -> ``app.route``; ``"Deprecated\n public"`` -> ``Deprecated``.
+
+ Strips a leading ``@`` and any call-argument tail. Without a tail only the
+ first word is kept, so visibility keywords trailing a Java/Kotlin modifier
+ blob fragment are dropped. Handles ONE token: callers holding a
+ multi-annotation blob split on ``@`` first.
+ """
+ base = raw.lstrip("@").strip()
+ paren = base.find("(")
+ if paren >= 0:
+ return base[:paren].strip()
+ parts = base.split()
+ return parts[0] if parts else base
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 3bd10f835..9e9638d45 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -11,7 +11,9 @@ from typing import Any
import structlog
+from ..decorator_names import decorator_base
from ..languages.specs.cpp import INCLUDE_FRAGMENT_EXTENSIONS
+from ..models import REGISTRATION_HINT, CallSite, ParsedFile
log = structlog.get_logger(__name__)
@@ -713,6 +715,7 @@ class ResolveMixin:
)
self._add_reference_edges(resolver)
+ self._add_registration_edges(resolver)
def _add_reference_edges(self, resolver: Any) -> None:
"""Emit ``references`` edges for functions named but never called.
@@ -767,14 +770,82 @@ class ResolveMixin:
continue
if self._graph.nodes[rc.callee_id].get("kind") not in allowed_kinds:
continue
- if self._graph.has_edge(rc.caller_id, rc.callee_id):
- continue
- self._graph.add_edge(
- rc.caller_id,
- rc.callee_id,
+ total += self._add_reference_edge(rc.caller_id, rc.callee_id, rc)
+ log.info("Reference edges resolved", total=total)
+
+ def _add_reference_edge(
+ self, source: str, target: str, rc: Any, hint_source: str | None = None
+ ) -> int:
+ """Add a ``references`` edge between two graph nodes unless the pair has one."""
+ if source not in self._graph or target not in self._graph:
+ return 0
+ if self._graph.has_edge(source, target):
+ return 0
+ self._graph.add_edge(
+ source,
+ target,
+ edge_type="references",
+ confidence=rc.confidence,
+ resolution_origin=rc.origin,
+ **({"hint_source": hint_source} if hint_source else {}),
+ )
+ return 1
+
+ def _add_registration_edges(self, resolver: Any) -> None:
+ """Link each registering decorator to the functions it decorates.
+
+ The decorated function is reached through the registry, never by name.
+ A mention, not a call: running the decorator does not run the function.
+ """
+ registrar_ids = {
+ f"{path}::{name}"
+ for path, parsed in self._parsed_files.items()
+ for name in parsed.registrars
+ }
+ if not registrar_ids:
+ return
+ names = {node_id.rsplit("::", 1)[1] for node_id in registrar_ids}
+ total = 0
+ for path, parsed in self._parsed_files.items():
+ sites = _decorator_sites(parsed, names)
+ if not sites:
+ continue
+ for rc in resolver.resolve_file(path, sites):
+ if rc.confidence < _MIN_REFERENCE_CONFIDENCE or rc.callee_id not in registrar_ids:
+ continue
+ total += self._add_reference_edge(
+ rc.callee_id, rc.caller_id, rc, hint_source=REGISTRATION_HINT
+ )
+ log.info("Registration edges resolved", total=total)
+
+
+def _decorator_sites(parsed: ParsedFile, registrar_names: set[str]) -> list[CallSite]:
+ """One site per Python decorator that may name a registrar, called from the decorated symbol.
+
+ A name imported under an alias (``import rule as r``) is matched by its alias;
+ the resolver then binds it back through the same import.
+ """
+ if parsed.file_info.language != "python":
+ return []
+ names = registrar_names | {
+ b.local_name
+ for imp in parsed.imports
+ for b in imp.bindings
+ if b.exported_name in registrar_names
+ }
+ sites: list[CallSite] = []
+ for sym in parsed.symbols:
+ for text in sym.decorators:
+ receiver, _, name = decorator_base(text).rpartition(".")
+ if name in names:
+ sites.append(
+ CallSite(
+ target_name=name,
+ receiver_name=receiver or None,
+ caller_symbol_id=sym.id,
+ line=sym.start_line,
+ argument_count=None,
edge_type="references",
- confidence=rc.confidence,
- resolution_origin=rc.origin,
)
- total += 1
- log.info("Reference edges resolved", total=total)
+ )
+ return sites
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index e6ce1a396..c5cac721d 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -630,6 +630,15 @@ EXECUTION_EDGE_TYPES: frozenset[str] = SYMBOL_USE_EDGE_TYPES - {"references"}
REACHABILITY_USE_EDGE_TYPES: frozenset[str] = SYMBOL_USE_EDGE_TYPES | {"type_use"}
+# ``hint_source`` of a ``references`` edge from a registering decorator to a
+# function it decorates (see ``python_registrars``). The fact sits on the
+# decorated (target) side, so incremental persistence rewrites these edges by
+# target file, and role seeding skips them: a registry says nothing about how
+# the function runs.
+REGISTRATION_HINT = "decorator_registration"
+TARGET_OWNED_HINTS: frozenset[str] = frozenset({REGISTRATION_HINT})
+
+
def is_dynamic_edge(edge_type: str | None) -> bool:
"""Whether *edge_type* is a dynamic-dispatch hint.
@@ -711,6 +720,9 @@ class ParsedFile:
# Python only; lets the dead-code unused-export pass rescue symbols whose
# only use is intra-module. See ``python_local_refs``.
local_refs: frozenset[str] = field(default_factory=frozenset)
+ # Top-level functions that store and return the function they decorate
+ # (Python only); see ``python_registrars``.
+ registrars: frozenset[str] = field(default_factory=frozenset)
# C/C++ sites that name a function without calling it: a dispatch table
# entry, a callback field, an argument to a registration macro. Reuses
# ``CallSite`` because resolving one is the identical problem — a name, the
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index f61d444ef..f89a97ff8 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -123,8 +123,9 @@ from .parser_helpers import (
_ts_nested_object_method_owner,
import_load_kind,
)
-from .python_local_refs import extract_python_local_refs
+from .python_local_refs import local_refs_from_tree, parse_python_module
from .python_overload import is_python_overload as _is_python_overload
+from .python_registrars import registering_functions
from .python_tasks import is_fire_and_forget
from .sfc_source import component_call_sites, prepare_source
from .special_handlers import SPECIAL_HANDLER_LANGUAGES, parse_special
@@ -1521,13 +1522,9 @@ class ASTParser:
# (callable passed as an arg, type annotation, decorator, default)
# carry no graph edge, so the dead-code unused-export pass would flag
# them. Stamp the referenced names so the analyzer can rescue them.
- local_refs: frozenset[str] = frozenset()
- if lang == "python":
- top_level_names = {s.name for s in symbols if s.name and not s.parent_name}
- nested_classes = {
- (s.parent_name, s.name) for s in symbols if s.kind == "class" and s.parent_name
- }
- local_refs = extract_python_local_refs(src, top_level_names, nested_classes)
+ local_refs, registrars = (
+ _python_module_facts(src, symbols) if lang == "python" else (frozenset(), frozenset())
+ )
if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
log.warning(
@@ -1551,6 +1548,7 @@ class ASTParser:
content_hash=content_hash,
type_refs=type_refs,
local_refs=local_refs,
+ registrars=registrars,
references=references,
)
@@ -2262,6 +2260,26 @@ class ASTParser:
_DEFAULT_PARSER: ASTParser | None = None
+def _python_module_facts(
+ src: str, symbols: list[Symbol]
+) -> tuple[frozenset[str], frozenset[str]]:
+ """``(local_refs, registrars)`` for a Python module, from one ``ast`` parse.
+
+ See ``python_local_refs`` and ``python_registrars``.
+ """
+ top_level_names = {s.name for s in symbols if s.name and not s.parent_name}
+ tree = parse_python_module(src) if top_level_names else None
+ if tree is None:
+ return frozenset(), frozenset()
+ nested_classes = {
+ (s.parent_name, s.name) for s in symbols if s.kind == "class" and s.parent_name
+ }
+ return (
+ local_refs_from_tree(tree, top_level_names, nested_classes),
+ registering_functions(tree),
+ )
+
+
def parse_file(file_info: FileInfo, source: bytes) -> ParsedFile:
"""Module-level convenience: parse a file using the default ASTParser."""
global _DEFAULT_PARSER
diff --git a/packages/core/src/repowise/core/ingestion/python_local_refs.py b/packages/core/src/repowise/core/ingestion/python_local_refs.py
index a89f5ab6a..06288a089 100644
--- a/packages/core/src/repowise/core/ingestion/python_local_refs.py
+++ b/packages/core/src/repowise/core/ingestion/python_local_refs.py
@@ -48,7 +48,7 @@ import ast
from collections.abc import Iterator
from collections.abc import Set as AbstractSet
-__all__ = ["extract_python_local_refs"]
+__all__ = ["extract_python_local_refs", "local_refs_from_tree", "parse_python_module"]
def extract_python_local_refs(
@@ -79,13 +79,28 @@ def extract_python_local_refs(
back to the analyzer's prior behaviour, never a false negative on a
genuinely-dead symbol elsewhere.
"""
- if not defined_names:
+ tree = parse_python_module(source) if defined_names else None
+ if tree is None:
return frozenset()
+ return local_refs_from_tree(tree, defined_names, nested_classes)
+
+
+def parse_python_module(source: str) -> ast.Module | None:
+ """*source* as an ``ast`` module, or ``None`` when Python 3 cannot parse it."""
try:
- tree = ast.parse(source)
+ return ast.parse(source)
except (SyntaxError, ValueError):
- return frozenset()
+ return None
+
+def local_refs_from_tree(
+ tree: ast.Module,
+ defined_names: frozenset[str] | set[str],
+ nested_classes: AbstractSet[tuple[str, str]] = frozenset(),
+) -> frozenset[str]:
+ """:func:`extract_python_local_refs` over a tree the caller already parsed."""
+ if not defined_names:
+ return frozenset()
referenced: set[str] = set()
# Walk each top-level statement separately so a definition can be told
# apart from its own body: the name a top-level ``def``/``class`` binds
diff --git a/packages/core/src/repowise/core/ingestion/python_registrars.py b/packages/core/src/repowise/core/ingestion/python_registrars.py
new file mode 100644
index 000000000..c1a6be549
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/python_registrars.py
@@ -0,0 +1,120 @@
+"""Python functions that store the function they decorate in module state.
+
+``def rule(fn): _RULES.append(fn); return fn`` makes every ``@rule`` function
+reachable through ``_RULES`` and through no name. Read from the parser's
+existing ``ast`` tree, each function's own statements only.
+
+Ceiling: a method used as a decorator (``@registry.on``) is not read, and a
+store under a condition does not count. A wrapper never matches: the argument
+itself must be both stored and returned.
+"""
+
+from __future__ import annotations
+
+import ast
+
+__all__ = ["registering_functions"]
+
+# Calls that put their argument into a container or a registry.
+_STORE_METHODS = frozenset({"append", "appendleft", "add", "insert", "setdefault", "register"})
+
+
+def registering_functions(tree: ast.Module) -> frozenset[str]:
+ """Top-level functions that register their argument, directly or via a factory."""
+ module_names = _module_names(tree)
+ return frozenset(
+ stmt.name
+ for stmt in tree.body
+ if isinstance(stmt, ast.FunctionDef)
+ and (_registers_argument(stmt, module_names) or _returns_registrar(stmt, module_names))
+ )
+
+
+def _module_names(tree: ast.Module) -> frozenset[str]:
+ """Names bound at module level by an assignment or an import."""
+ names: set[str] = set()
+ for stmt in tree.body:
+ if isinstance(stmt, ast.Assign):
+ names.update(t.id for t in stmt.targets if isinstance(t, ast.Name))
+ elif isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
+ names.add(stmt.target.id)
+ elif isinstance(stmt, (ast.Import, ast.ImportFrom)):
+ names.update((a.asname or a.name).split(".", 1)[0] for a in stmt.names)
+ return frozenset(names)
+
+
+def _registers_argument(fn: ast.FunctionDef, module_names: frozenset[str]) -> bool:
+ """Whether *fn* stores its only positional parameter in module state and returns it."""
+ params = [*fn.args.posonlyargs, *fn.args.args]
+ if len(params) != 1 or not fn.body:
+ return False
+ name = params[0].arg
+ if not _returns_name(fn.body[-1], name):
+ return False
+ module_state = module_names - _local_names(fn)
+ return any(_stores_name(stmt, name, module_state) for stmt in fn.body[:-1])
+
+
+def _returns_registrar(fn: ast.FunctionDef, module_names: frozenset[str]) -> bool:
+ """Whether *fn* is a factory returning a nested registering decorator."""
+ return any(
+ isinstance(stmt, ast.FunctionDef)
+ and _registers_argument(stmt, module_names)
+ and _returns_name(fn.body[-1], stmt.name)
+ for stmt in fn.body
+ )
+
+
+def _local_names(fn: ast.FunctionDef) -> set[str]:
+ """Names *fn* binds itself, which shadow module state of the same name."""
+ params = {a.arg for a in (*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs)}
+ return params | {
+ t.id
+ for stmt in fn.body
+ if isinstance(stmt, ast.Assign)
+ for t in stmt.targets
+ if isinstance(t, ast.Name)
+ }
+
+
+def _returns_name(stmt: ast.stmt, name: str) -> bool:
+ return (
+ isinstance(stmt, ast.Return) and isinstance(stmt.value, ast.Name) and stmt.value.id == name
+ )
+
+
+def _stores_name(stmt: ast.stmt, name: str, module_state: frozenset[str]) -> bool:
+ if isinstance(stmt, ast.Assign):
+ return _assigns_into_state(stmt, name, module_state)
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
+ return _calls_store(stmt.value, name, module_state)
+ return False
+
+
+def _assigns_into_state(stmt: ast.Assign, name: str, module_state: frozenset[str]) -> bool:
+ """``STATE[k] = name``."""
+ return (
+ isinstance(stmt.value, ast.Name)
+ and stmt.value.id == name
+ and any(
+ isinstance(t, ast.Subscript) and _root_name(t.value) in module_state
+ for t in stmt.targets
+ )
+ )
+
+
+def _calls_store(call: ast.Call, name: str, module_state: frozenset[str]) -> bool:
+ """``STATE.append(name)``, ``STATE.setdefault(k, []).append(name)`` and the like."""
+ return (
+ isinstance(call.func, ast.Attribute)
+ and call.func.attr in _STORE_METHODS
+ and _root_name(call.func.value) in module_state
+ and any(isinstance(arg, ast.Name) and arg.id == name for arg in call.args)
+ )
+
+
+def _root_name(node: ast.expr) -> str | None:
+ """The name an attribute / subscript / call chain starts from."""
+ while isinstance(node, (ast.Attribute, ast.Subscript, ast.Call)):
+ node = node.func if isinstance(node, ast.Call) else node.value
+ return node.id if isinstance(node, ast.Name) else None
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index 29f8a2262..7013a95c3 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -242,10 +242,14 @@ async def reconcile_edges_for_files(
symbols the change deleted whose node rows the incremental path never prunes
— then inserts the fresh set. Edges *into* a changed file from an unchanged
one are owned by that other file and left untouched, the same file-scoping
- the symbol reconciler uses; a full reindex reconciles those.
+ the symbol reconciler uses; a full reindex reconciles those. The exception
+ is an edge whose fact sits at its target (``TARGET_OWNED_HINTS``), which
+ the target's file owns too.
Returns the number of deleted rows.
"""
+ from repowise.core.ingestion.models import TARGET_OWNED_HINTS
+
scoped = [p for p in dict.fromkeys(source_file_paths) if p]
if not scoped:
return 0
@@ -290,7 +294,13 @@ async def reconcile_edges_for_files(
res = await session.execute(
delete(GraphEdge).where(
GraphEdge.repository_id == repository_id,
- GraphEdge.source_node_id.in_(batch),
+ or_(
+ GraphEdge.source_node_id.in_(batch),
+ and_(
+ GraphEdge.hint_source.in_(TARGET_OWNED_HINTS),
+ GraphEdge.target_node_id.in_(batch),
+ ),
+ ),
)
)
deleted += res.rowcount or 0
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index bb5a65ce4..0e4e7a6af 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -635,11 +635,15 @@ def _changed_file_edges(
"""``(reconcile_paths, edges)`` for edges emanating from changed+parsed files.
An edge is attributed to the file that owns its *source* node: a file node
- is the path itself; a symbol node carries ``file_path``. Restricting to
+ is the path itself; a symbol node carries ``file_path``. An edge whose fact
+ sits at its target (``TARGET_OWNED_HINTS``) belongs to the target's file
+ as well, so editing the decorated file rewrites it. Restricting to
files that both changed and parsed this run mirrors ``_changed_file_symbols``
— a changed file that failed to parse keeps its existing edges rather than
having them wrongly wiped on a transient failure.
"""
+ from repowise.core.ingestion.models import TARGET_OWNED_HINTS
+
changed = set(changed_paths or [])
parsed = {pf.file_info.path for pf in parsed_files or []}
reconcile = changed & parsed
@@ -656,9 +660,10 @@ def _changed_file_edges(
edges: list[dict] = []
for u, v, data in graph.edges(data=True):
- if owner.get(u) not in reconcile:
- continue
- edges.append(_edge_row(u, v, data))
+ if owner.get(u) in reconcile or (
+ data.get("hint_source") in TARGET_OWNED_HINTS and owner.get(v) in reconcile
+ ):
+ edges.append(_edge_row(u, v, data))
return sorted(reconcile), edges
diff --git a/tests/unit/dead_code/test_registering_decorators.py b/tests/unit/dead_code/test_registering_decorators.py
new file mode 100644
index 000000000..06cecd4a1
--- /dev/null
+++ b/tests/unit/dead_code/test_registering_decorators.py
@@ -0,0 +1,229 @@
+"""A function a registering decorator stores is reached through the registry.
+
+``@rule`` where ``rule`` appends its argument to a module list and returns it:
+the decorated function is called by whoever walks the list, never by name.
+A decorator that only wraps, or stores something other than the function, is
+not a registration and keeps its targets flagged.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.models import REGISTRATION_HINT
+from repowise.core.ingestion.python_registrars import registering_functions
+
+_REGISTRY = """\
+import functools
+
+_RULES = []
+_BY_NAME = {}
+_SEEN = set()
+
+
+def rule(fn):
+ _RULES.append(fn)
+ return fn
+
+
+def named(key):
+ def deco(fn):
+ _BY_NAME[key] = fn
+ return fn
+ return deco
+
+
+def timed(fn):
+ @functools.wraps(fn)
+ def wrapper(*args):
+ return fn(*args)
+ return wrapper
+
+
+def remember(fn):
+ _SEEN.add(fn.__name__)
+ return fn
+
+
+def run(value):
+ for check in _RULES:
+ check(value)
+ return [f(value) for f in _BY_NAME.values()]
+"""
+
+_SAME_FILE = """\
+_HOOKS = []
+
+
+def hook(fn):
+ _HOOKS.append(fn)
+ return fn
+
+
+@hook
+def _local_hook():
+ return 1
+
+
+def fire():
+ return [h() for h in _HOOKS]
+"""
+
+_RULES = """\
+from pkg.registry import named, remember, rule, timed
+
+
+@rule
+def _imported_rule(value):
+ return value
+
+
+@named("x")
+def _factory_rule(value):
+ return value
+
+
+@timed
+def _wrapped_only(value):
+ return value
+
+
+@remember
+def _name_only(value):
+ return value
+
+
+def _undecorated(value):
+ return value
+"""
+
+_ALIASED = """\
+from pkg import registry
+from pkg.registry import rule as r
+
+
+@r
+def _aliased_rule(value):
+ return value
+
+
+def _dotted_rule(value):
+ return value
+"""
+
+_SQL = """\
+from sqlalchemy.ext.compiler import compiles
+from sqlalchemy.sql.functions import FunctionElement
+
+
+class json_text(FunctionElement):
+ pass
+
+
+@compiles(json_text)
+def _json_text_sqlite(element, compiler, **kw):
+ return "x"
+"""
+
+
+def _build(root: Path) -> tuple[nx.DiGraph, dict[str, bytes]]:
+ traverser, parser, builder = FileTraverser(root), ASTParser(), GraphBuilder(repo_path=root)
+ source_map = {}
+ for fi in traverser.traverse():
+ source_map[fi.path] = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, source_map[fi.path]))
+ return builder.build(), source_map
+
+
+def _unused_internals(root: Path) -> set[str]:
+ graph, source_map = _build(root)
+ report = DeadCodeAnalyzer(graph, source_map=source_map).analyze({"min_confidence": 0.0})
+ return {f.symbol_name for f in report.findings if f.kind is DeadCodeKind.UNUSED_INTERNAL}
+
+
+def _write(root: Path, files: dict[str, str]) -> Path:
+ for rel, text in files.items():
+ path = root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return root
+
+
+def test_registered_functions_are_used_and_wrapped_ones_are_not(tmp_path):
+ root = _write(
+ tmp_path,
+ {
+ "pkg/__init__.py": "",
+ "pkg/registry.py": _REGISTRY,
+ "pkg/hooks.py": _SAME_FILE,
+ "pkg/rules.py": _RULES,
+ "pkg/aliased.py": _ALIASED,
+ },
+ )
+ flagged = _unused_internals(root)
+ used = {"_local_hook", "_imported_rule", "_factory_rule", "_aliased_rule", "_dotted_rule"}
+ assert not flagged & used
+ assert {"_wrapped_only", "_name_only", "_undecorated"} <= flagged
+
+
+def test_sqlalchemy_compiles_registers_the_function(tmp_path):
+ root = _write(tmp_path, {"pkg/__init__.py": "", "pkg/sql.py": _SQL})
+ assert "_json_text_sqlite" not in _unused_internals(root)
+
+
+def test_registrar_shapes():
+ found = registering_functions(ast.parse(_REGISTRY))
+ assert found == {"rule", "named"}
+ # A stored argument that is not returned, or returned but never stored.
+ assert not registering_functions(
+ ast.parse("def a(fn):\n L.append(fn)\n\ndef b(fn):\n return fn\n")
+ )
+
+
+def test_a_store_into_local_or_conditional_state_is_not_a_registration():
+ source = """\
+_RULES = []
+
+
+def local_only(fn):
+ seen = []
+ seen.append(fn)
+ return fn
+
+
+def shadowed(fn):
+ _RULES = []
+ _RULES.append(fn)
+ return fn
+
+
+def conditional(fn):
+ if fn.__doc__:
+ _RULES.append(fn)
+ return fn
+"""
+ assert not registering_functions(ast.parse(source))
+
+
+def test_the_edge_is_a_registration_reference_and_reaches_a_class(tmp_path):
+ root = _write(
+ tmp_path,
+ {
+ "pkg/__init__.py": "",
+ "pkg/hooks.py": _SAME_FILE + "\n\n@hook\nclass _Plugin:\n pass\n",
+ # ``ast`` rejects this file; its decorator must not break the pass.
+ "pkg/broken.py": "from pkg.hooks import hook\n\n\n@hook\ndef _f(:\n",
+ },
+ )
+ graph, _ = _build(root)
+ for target in ("pkg/hooks.py::_local_hook", "pkg/hooks.py::_Plugin"):
+ edge = graph.get_edge_data("pkg/hooks.py::hook", target)
+ assert edge is not None, target
+ assert edge["edge_type"] == "references"
+ assert edge["hint_source"] == REGISTRATION_HINT
diff --git a/tests/unit/health/test_execution_roles.py b/tests/unit/health/test_execution_roles.py
index 8c038d20e..321f53b21 100644
--- a/tests/unit/health/test_execution_roles.py
+++ b/tests/unit/health/test_execution_roles.py
@@ -20,6 +20,7 @@ from repowise.core.analysis.health.queue.eligibility import (
perf_queue_verdict,
queue_proof,
)
+from repowise.core.ingestion.models import REGISTRATION_HINT
def _graph(*symbols: tuple[str, str, list[str]], start: int = 10) -> nx.DiGraph:
@@ -162,6 +163,19 @@ def test_a_scheduler_import_seeds_only_registered_functions() -> None:
assert {"tool/cli.py::main", "tool/cli.py::cmd_sync"} <= seeds.by_role["cli"]
+def test_a_decorator_registry_seeds_no_role() -> None:
+ """``@rule`` storing a function says nothing about how it runs, even beside argparse."""
+ graph = _graph(("tool/rules.py::rule", "python", []), ("tool/rules.py::poll_once", "python", ["@rule"]))
+ _imports(graph, "tool/rules.py", "argparse")
+ graph.add_edge(
+ "tool/rules.py::rule",
+ "tool/rules.py::poll_once",
+ edge_type="references",
+ hint_source=REGISTRATION_HINT,
+ )
+ assert _seed_of(graph, "tool/rules.py::poll_once") is None
+
+
def test_vscode_activate_is_startup_and_registered_commands_are_cli() -> None:
graph = _graph(("src/extension.ts::activate", "typescript", []), ("src/extension.ts::refresh", "typescript", []))
_imports(graph, "src/extension.ts", "vscode")
diff --git a/tests/unit/persistence/test_incremental_edge_persist.py b/tests/unit/persistence/test_incremental_edge_persist.py
index 9f44f310e..8ea8e06a6 100644
--- a/tests/unit/persistence/test_incremental_edge_persist.py
+++ b/tests/unit/persistence/test_incremental_edge_persist.py
@@ -326,3 +326,26 @@ async def test_full_reindex_does_not_suppress_the_widen(async_session, tmp_path)
await persist_incremental_edges(async_session, repo.id, gb, parsed, ["b.py"])
await async_session.commit()
assert ("c.py", "a.py", "imports") not in await _db_edge_set(async_session, repo.id)
+
+
+async def test_a_registration_edge_follows_the_decorated_file(async_session, tmp_path):
+ """``@rule`` lives in the decorated file, so editing only that file adds and drops the edge."""
+ repo = await insert_repo(async_session)
+ registry = "_RULES = []\n\n\ndef rule(fn):\n _RULES.append(fn)\n return fn\n"
+ plain = "from reg import rule\n\n\ndef _check():\n return 1\n"
+ (tmp_path / "reg.py").write_text(registry)
+ (tmp_path / "b.py").write_text(plain)
+ gb1, _ = _build_graph(tmp_path)
+ await _seed_full(async_session, repo.id, gb1)
+ await async_session.commit()
+ edge = ("reg.py::rule", "b.py::_check", "references")
+ assert edge not in await _db_edge_set(async_session, repo.id)
+
+ for text, expected in ((plain.replace("def _check", "@rule\ndef _check"), True), (plain, False)):
+ (tmp_path / "b.py").write_text(text)
+ gb, parsed = _build_graph(tmp_path)
+ await persist_graph_nodes(async_session, repo.id, gb)
+ await persist_incremental_edges(async_session, repo.id, gb, parsed, ["b.py"])
+ await async_session.commit()
+ assert (edge in await _db_edge_set(async_session, repo.id)) is expected
+