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): rescue Python symbols used only within their own file (#563)

Raghav Chamadiya4b4ff2426854
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 759958154..652fe6d20 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -838,6 +838,19 @@ class DeadCodeAnalyzer:
if local_type_uses and sym_name in local_type_uses:
continue
+ # Same-file reference rescue (Python): a top-level function
+ # or class consumed only within its own module in a non-call
+ # position carries no graph edge — passed as a first-class
+ # callable argument (``_score_dimension(.., weight_fn, ..)``),
+ # used purely as a type annotation (a Pydantic model that is
+ # only a FastAPI request-body param type), named in a
+ # decorator, or stored as a default/collection value. The
+ # parser stamps these intra-module references on the file node
+ # (see ``ingestion/python_local_refs.py``); treat them as live.
+ local_refs = node_data.get("local_refs")
+ if local_refs and sym_name in local_refs:
+ continue
+
is_deprecated = any(
sym_name.endswith(suffix) for suffix in ("_DEPRECATED", "_LEGACY", "_COMPAT")
)
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index 4d2922bd5..5cee37e25 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -169,6 +169,11 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
is_test=parsed.file_info.is_test,
is_entry_point=parsed.file_info.is_entry_point,
docstring=parsed.docstring,
+ # Same-file references (Python): names used intra-module in a
+ # non-call/non-import position. Rescues them in the unused-export
+ # pass. An immutable frozenset (never mutated post-stamp, unlike
+ # ``local_type_uses`` which the type-ref phase ``.update()``s).
+ local_refs=parsed.local_refs,
)
# --- Symbol nodes ---
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 74ad68443..7e148bcbb 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -301,6 +301,12 @@ class ParsedFile:
parse_errors: list[str] = field(default_factory=list) # non-fatal parser warnings/errors
content_hash: str = "" # SHA-256 hex of raw file bytes
type_refs: list[TypeReference] = field(default_factory=list)
+ # Top-level symbol names referenced elsewhere in this same file in a
+ # non-import, non-call position (callable passed as an argument, used as
+ # a type annotation, decorator target, default value, …). Populated for
+ # 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)
def compute_content_hash(source: bytes) -> str:
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index 00ee0c6e8..110061a4e 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -68,6 +68,7 @@ from .parser_helpers import (
_qualified_cpp_parent,
_run_query,
)
+from .python_local_refs import extract_python_local_refs
log = structlog.get_logger(__name__)
@@ -290,6 +291,16 @@ class ASTParser:
docstring = extract_module_docstring(root, src, lang)
type_refs = self._extract_type_refs(matches, src, lang)
+ # Same-file reference rescue (Python only): top-level symbols used
+ # elsewhere in their own module in a non-call / non-import position
+ # (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}
+ local_refs = extract_python_local_refs(src, top_level_names)
+
if len(symbols) > _SYMBOL_COUNT_WARN_THRESHOLD:
log.warning(
"parser.symbol_bloat",
@@ -309,6 +320,7 @@ class ASTParser:
docstring=docstring,
parse_errors=parse_errors,
type_refs=type_refs,
+ local_refs=local_refs,
)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/python_local_refs.py b/packages/core/src/repowise/core/ingestion/python_local_refs.py
new file mode 100644
index 000000000..2bd0b9543
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/python_local_refs.py
@@ -0,0 +1,162 @@
+"""Same-file symbol-reference extraction for Python.
+
+The dead-code analyzer's unused-export pass treats a public symbol as live
+when something imports it (cross-file ``imports`` edge naming it) or a
+``calls`` / ``type_use`` / heritage edge lands on it. Neither signal fires
+for a top-level function or class that is only *referenced within its own
+module* in a non-call position:
+
+* passed as a first-class callable argument to a higher-order helper
+ (``_score_dimension(results, maintainability_weight, ...)`` — the
+ function is never invoked by name, so no ``calls`` edge exists);
+* used as a default value, named in a decorator expression, or stored as a
+ dict/list value;
+* used purely as a **type annotation** — the canonical case being a
+ Pydantic ``BaseModel`` used only as a FastAPI request-body parameter
+ type, which FastAPI instantiates at runtime (no constructor call lands in
+ user code).
+
+Python can only reach a name from another module through an ``import``, so
+a *cross-file* reference almost always carries the name on an ``imports``
+edge and is handled — the one residual cross-file gap is a namespace import
+(``import mymod``) used only as a qualified annotation (``x: mymod.Thing``),
+where the edge names ``mymod`` rather than ``Thing``; that is out of scope
+here. The dominant blind spot, and the one this module closes, is
+*same-file* usage. This module computes, per Python file, the set of
+top-level symbol names that are referenced elsewhere in the same file,
+which the analyzer stamps on the file node (``local_refs``) and consults to
+rescue them.
+
+A symbol's *own body* does not count as a use — otherwise a function that
+is dead from the rest of the codebase would rescue itself through its own
+recursive call. Mutual recursion between two otherwise-dead top-level
+symbols is a known residual gap (each rescues the other); resolving it
+would need strongly-connected-component analysis and is deliberately not
+done — under-reporting a dead recursive cluster is the safe error for a
+dead-code tool, where the failure to avoid is a confident *false positive*.
+
+We use the stdlib :mod:`ast` rather than enumerating tree-sitter capture
+patterns: the host language is Python, ``ast`` already backs the
+Django/pytest dynamic hints, and it distinguishes ``Load`` from ``Store``
+context and walks annotation subtrees — including quoted forward-reference
+annotations — reliably.
+"""
+
+from __future__ import annotations
+
+import ast
+
+__all__ = ["extract_python_local_refs"]
+
+
+def extract_python_local_refs(
+ source: str,
+ defined_names: frozenset[str] | set[str],
+) -> frozenset[str]:
+ """Return the subset of *defined_names* referenced elsewhere in *source*.
+
+ A name counts as referenced when it appears in any ``Load`` position
+ (call argument, default value, decorator expression, collection value,
+ assignment RHS, type annotation, …) anywhere in the module — including
+ inside a quoted/postponed forward-reference annotation such as
+ ``Optional["Foo"]``.
+
+ *defined_names* should be the file's top-level symbol names (methods
+ excluded — they are reached through their class, never imported by
+ name). Restricting to defined names keeps the result a small rescue set
+ and bounds the walk's bookkeeping.
+
+ Returns an empty set when there are no candidate names or the source is
+ not parseable as Python 3 (Python 2 source, syntax tree-sitter
+ tolerated but ``ast`` rejects, etc.) — a missed rescue simply falls
+ back to the analyzer's prior behaviour, never a false negative on a
+ genuinely-dead symbol elsewhere.
+ """
+ if not defined_names:
+ return frozenset()
+ try:
+ tree = ast.parse(source)
+ except (SyntaxError, ValueError):
+ 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
+ # (``owner``) is excluded while walking that statement's subtree, so a
+ # recursive self-call is not mistaken for an external use.
+ for stmt in tree.body:
+ owner = _bound_name(stmt)
+ _collect_refs(stmt, defined_names, owner, referenced)
+
+ return frozenset(referenced)
+
+
+def _bound_name(stmt: ast.stmt) -> str | None:
+ """Return the symbol name a top-level def/class binds, else ``None``."""
+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return stmt.name
+ return None
+
+
+def _collect_refs(
+ node: ast.AST,
+ defined_names: frozenset[str] | set[str],
+ owner: str | None,
+ out: set[str],
+) -> None:
+ """Record defined-name references inside *node*, excluding ``owner`` itself."""
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Name):
+ # ``Store``/``Del`` Names are (re)definitions, not uses; only a
+ # ``Load`` of a defined name (other than the enclosing symbol's
+ # own name) is evidence the symbol is consumed elsewhere.
+ if (
+ isinstance(sub.ctx, ast.Load)
+ and sub.id != owner
+ and sub.id in defined_names
+ ):
+ out.add(sub.id)
+ continue
+
+ # Quoted / postponed forward-reference annotations are string
+ # constants in the AST; their inner names are invisible to the
+ # ``Name`` walk above. Re-parse each annotation's string literals
+ # and collect any defined name they reference.
+ annotation = _annotation_of(sub)
+ if annotation is not None:
+ _collect_forward_refs(annotation, defined_names, owner, out)
+
+
+def _annotation_of(node: ast.AST) -> ast.expr | None:
+ """Return the annotation expression carried by *node*, if any."""
+ if isinstance(node, (ast.AnnAssign, ast.arg)):
+ return node.annotation
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ return node.returns
+ return None
+
+
+def _collect_forward_refs(
+ annotation: ast.expr,
+ defined_names: frozenset[str] | set[str],
+ owner: str | None,
+ out: set[str],
+) -> None:
+ """Parse quoted forward refs inside *annotation* and record defined names.
+
+ Handles a quoted forward ref anywhere in the annotation —
+ ``"Foo"``, ``Optional["Foo"]``, ``dict[str, "Bar"]`` — by re-parsing
+ each string-constant leaf as a type expression. ``owner`` is excluded so
+ a self-referential annotation (``class Node: next: "Node"``) does not
+ rescue an otherwise-dead class.
+ """
+ for sub in ast.walk(annotation):
+ if not (isinstance(sub, ast.Constant) and isinstance(sub.value, str)):
+ continue
+ try:
+ inner = ast.parse(sub.value, mode="eval")
+ except (SyntaxError, ValueError):
+ continue
+ for ref in ast.walk(inner):
+ if isinstance(ref, ast.Name) and ref.id != owner and ref.id in defined_names:
+ out.add(ref.id)
diff --git a/tests/unit/ingestion/test_python_dead_code_fixes.py b/tests/unit/ingestion/test_python_dead_code_fixes.py
index 1d1273754..6e7f0cef0 100644
--- a/tests/unit/ingestion/test_python_dead_code_fixes.py
+++ b/tests/unit/ingestion/test_python_dead_code_fixes.py
@@ -258,6 +258,111 @@ def test_python_dynamic_hints_ignore_dotted_strings_without_loader(
assert all(e.source != "pkg/doc.py" for e in edges)
+# ---------------------------------------------------------------------------
+# 5. Same-file references in a non-call position (PR #531 false positives)
+# ---------------------------------------------------------------------------
+
+
+def test_callable_passed_as_argument_same_file_not_flagged() -> None:
+ """A function handed to a higher-order helper — never invoked by name —
+ is live. Mirrors ``maintainability_weight`` / ``performance_category``
+ passed into ``_score_dimension`` in ``health/scoring.py``."""
+ sources = {
+ "packages/core/src/myrepo/__init__.py": "",
+ "packages/core/src/myrepo/scoring.py": (
+ "def maintainability_weight(name):\n return 1.0\n\n\n"
+ "def maintainability_category(name):\n return 'x'\n\n\n"
+ "def _score_dimension(results, weight_fn, category_fn):\n"
+ " return weight_fn(results) + category_fn(results)\n\n\n"
+ "def score_file(results):\n"
+ " return _score_dimension(\n"
+ " results, maintainability_weight, maintainability_category\n"
+ " )\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ flagged = _unused_export_names(graph)
+ assert "maintainability_weight" not in flagged
+ assert "maintainability_category" not in flagged
+
+
+def test_class_used_only_as_type_annotation_same_file_not_flagged() -> None:
+ """A Pydantic-style model used only as a request-body parameter type is
+ live — FastAPI instantiates it at runtime, so no constructor call lands
+ in user code. Mirrors ``FindingStatusUpdate`` in ``routers/code_health.py``."""
+ sources = {
+ "packages/server/src/myrepo/__init__.py": "",
+ "packages/server/src/myrepo/server/__init__.py": "",
+ "packages/server/src/myrepo/server/routers/__init__.py": "",
+ "packages/server/src/myrepo/server/routers/code_health.py": (
+ "from pydantic import BaseModel\n\n\n"
+ "class FindingStatusUpdate(BaseModel):\n status: str\n\n\n"
+ "def update_status(finding_id, payload: FindingStatusUpdate):\n"
+ " return payload.status\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ assert "FindingStatusUpdate" not in _unused_export_names(graph)
+
+
+def test_forward_ref_annotation_same_file_not_flagged() -> None:
+ """A quoted forward-reference annotation (``payload: "Body"``) still
+ counts as a use — the parser re-parses string annotations."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/api.py": (
+ "class Body:\n x: int = 0\n\n\n"
+ "def handler(payload: 'Body'):\n return payload\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ assert "Body" not in _unused_export_names(graph)
+
+
+def test_genuinely_unused_same_file_symbol_still_flagged() -> None:
+ """The rescue must not blanket-hide dead code: a public symbol that is
+ never referenced anywhere (in-file or cross-file) is still reported."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/mod.py": (
+ "def used_helper():\n return 1\n\n\n"
+ "def caller():\n return used_helper()\n\n\n"
+ "def never_referenced():\n return 2\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ flagged = _unused_export_names(graph)
+ assert "never_referenced" in flagged
+
+
+def test_genuinely_unused_recursive_symbol_still_flagged() -> None:
+ """A symbol's own body must not rescue it: a recursive function that is
+ dead from the rest of the codebase is still reported (its only reference
+ is its own recursive call)."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/mod.py": (
+ "def dead_recursive(n):\n"
+ " if n <= 0:\n return 0\n"
+ " return dead_recursive(n - 1)\n"
+ ),
+ }
+ graph = _graph_from_sources(sources)
+ assert "dead_recursive" in _unused_export_names(graph)
+
+
+def test_name_only_in_all_string_is_not_rescued() -> None:
+ """A name appearing solely as an ``__all__`` string literal is not a
+ real reference (it is export bookkeeping, not a use) and must not be
+ rescued by the same-file machinery."""
+ sources = {
+ "pkg/__init__.py": "",
+ "pkg/mod.py": ("__all__ = ['orphan']\n\n\ndef orphan():\n return 1\n"),
+ }
+ graph = _graph_from_sources(sources)
+ assert "orphan" in _unused_export_names(graph)
+
+
def test_dynamic_use_edge_marks_target_file_live() -> None:
"""An incoming ``dynamic_uses`` edge keeps every public export of the
target file out of the unused-export results (analyzer contract that the