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): mark an unused export deletion-ready only when a use would have shown (#2903)

Raghav Chamadiya3b859b566e84
diff --git a/docs/layers/DEAD_CODE.md b/docs/layers/DEAD_CODE.md
index 89944d4c7..9ebce47a3 100644
--- a/docs/layers/DEAD_CODE.md
+++ b/docs/layers/DEAD_CODE.md
@@ -43,7 +43,7 @@ get_dead_code(kind="unused_export", group_by="owner")
| Kind | What it means | How it is computed | Base confidence |
|------|---------------|--------------------|-----------------|
| `unreachable_file` | No file in the repo imports this one. | File-node in-degree of 0 on the dependency graph, after entry points and the never-flag allowlist are removed. | Scored from git age (below) |
-| `unused_export` | A public symbol nothing imports. | No `imports` edge names the symbol (or `*`, or a TypeScript `export { local as alias }` rename), and no `calls` / `extends` / `implements` / `method_implements` / `dispatches_to` / `framework_binds` / `reads` / `references` / `type_use` edge reaches it. Member kinds (`method`, `field`, `property`, `enum_member`) are excluded from this pass across all languages since they are accessed through their container, not imported by name. Top-level `export const` primitives, objects, and arrays in TypeScript and JavaScript are fully evaluated (they are always importable by name). | `1.00` when the containing file *does* have importers (so the file is alive and only this symbol is not), `0.70` when it does not, `0.30` when the name ends in `_DEPRECATED` / `_LEGACY` / `_COMPAT` — then capped as described below |
+| `unused_export` | A public symbol nothing imports. | No `imports` edge names the symbol (or `*`, or a TypeScript `export { local as alias }` rename), and no `calls` / `extends` / `implements` / `method_implements` / `dispatches_to` / `framework_binds` / `reads` / `references` / `type_use` edge reaches it. Member kinds (`method`, `field`, `property`, `enum_member`) are excluded from this pass across all languages since they are accessed through their container, not imported by name. Top-level `export const` primitives, objects, and arrays in TypeScript and JavaScript are fully evaluated (they are always importable by name). | `1.00` when an importer of the containing file names one of its symbols (so the file is alive and its importers list what they take, but not this symbol); `0.60`, never safe to delete, when no importer names a symbol of the file (no importer at all, a C `#include`, a C# `using`), for every C, C++ and Objective-C symbol (the preprocessor reaches symbols through macros and typedef aliases no edge records), and for a C# class holding extension methods (called as `x.Method()` without naming the class); `0.30` when the name ends in `_DEPRECATED` / `_LEGACY` / `_COMPAT` — then capped as described below |
| `unused_internal` | A private or underscore-prefixed symbol nothing calls. | No `calls` edge, and no cross-file importer pulls the name (which would mean a dispatch-table lookup). Off by default. | `0.65` |
| `zombie_package` | A whole top-level package no other package imports. | No inter-package import edges into it. Never marked safe to delete. | `0.50` |
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 d92f275bb..9fda15be0 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -33,6 +33,7 @@ from .constants import (
_FRAMEWORK_DECORATOR_SUFFIXES,
_FRAMEWORK_DECORATORS,
_NEVER_PACKAGE_DIRS,
+ _PREPROCESSED_LANGUAGES,
_PURE_WRAPPER_DECORATOR_ATTRS,
_PURE_WRAPPER_DECORATOR_MODULES,
_is_fixture_path,
@@ -62,6 +63,7 @@ from .risk_factors import (
NO_GIT_SIGNAL_CONFIDENCE,
RISK_CAP_CONFIDENCE,
SAFE_CONFIDENCE_THRESHOLD,
+ UNPROVEN_EXPORT_CONFIDENCE,
path_risk_factors,
risk_evidence,
)
@@ -703,7 +705,13 @@ class _ExportFile:
node: Any
node_data: dict
symbol_pairs: list[tuple[str, dict]]
- file_has_importers: bool
+ # An importer names a symbol this file defines, so a name missing from
+ # every importer means something. A C ``#include`` names nothing and a C#
+ # ``using`` names a namespace, so neither says anything about a symbol.
+ importers_name_symbols: bool
+ # Classes holding C# extension methods, called as ``x.Method()`` without
+ # naming the class, so no importer would name them either.
+ extension_containers: frozenset[str]
imported_as_namespace: bool
enclosing_ranges: list[tuple[int, int]]
@@ -1019,7 +1027,9 @@ class DeadCodeAnalyzer:
if not tokens:
return findings
- skipped_names = ", ".join(path for path, _ in self._unindexed_source_files[:3])
+ # Sorted so the same skipped set always yields the same evidence text.
+ skipped = sorted(path for path, _ in self._unindexed_source_files)
+ skipped_names = ", ".join(skipped[:3])
if len(self._unindexed_source_files) > 3:
skipped_names += f" (+{len(self._unindexed_source_files) - 3} more)"
@@ -1265,7 +1275,8 @@ class DeadCodeAnalyzer:
node=node,
node_data=node_data,
symbol_pairs=symbol_pairs,
- file_has_importers=self.graph.in_degree(node) > 0,
+ importers_name_symbols=self._importers_name_symbols(node, symbols),
+ extension_containers=self._extension_containers(node_data, symbol_pairs),
imported_as_namespace=self._imported_as_namespace(node, node_data),
# Function bodies, so nested defs (closures) can be skipped.
enclosing_ranges=[
@@ -1276,6 +1287,26 @@ class DeadCodeAnalyzer:
],
)
+ def _importers_name_symbols(self, node: Any, symbols: list[dict]) -> bool:
+ """Whether any edge into *node* names a symbol the file defines."""
+ defined = {sym.get("name") for sym in symbols}
+ return any(
+ not defined.isdisjoint(imported)
+ for imported in self._imported_names_by_edge(node, edge_types=None)
+ )
+
+ def _extension_containers(
+ self, node_data: dict, symbol_pairs: list[tuple[str, dict]]
+ ) -> frozenset[str]:
+ """Names of the classes in this file that declare a C# extension method."""
+ if node_data.get("language") not in _CONTAINER_USE_LANGUAGES:
+ return frozenset()
+ return frozenset(
+ sym.get("name", "")
+ for sym_id, sym in symbol_pairs
+ if self._declares_extension_method(sym_id)
+ )
+
def _imported_as_namespace(self, node: Any, node_data: dict) -> bool:
"""Whether an importer pulled this file by its module name.
@@ -1291,11 +1322,13 @@ class DeadCodeAnalyzer:
return False
return any(file_stem in imported for imported in self._imported_names_by_edge(node))
- def _imported_names_by_edge(self, node: Any) -> Iterator[list[str]]:
- """``imported_names`` of every ``imports`` edge into *node*."""
+ def _imported_names_by_edge(
+ self, node: Any, edge_types: tuple[str, ...] | None = ("imports",)
+ ) -> Iterator[list[str]]:
+ """``imported_names`` of every edge of *edge_types* into *node* (any type if None)."""
for pred in self.graph.predecessors(node):
edge = self.graph.get_edge_data(pred, node, {})
- if edge.get("edge_type") != "imports":
+ if edge_types is not None and edge.get("edge_type") not in edge_types:
continue
yield edge.get("imported_names", [])
@@ -1464,6 +1497,28 @@ class DeadCodeAnalyzer:
**self._git_fields(str(node)),
)
+ @staticmethod
+ def _import_absence_is_evidence(file_ctx: _ExportFile, sym: dict) -> bool:
+ """Whether a use of *sym* would have shown up as an importer naming it.
+
+ Not when no importer names this file's symbols; not where the
+ preprocessor reaches a symbol through macros, typedef aliases and token
+ pasting; not for a class holding C# extension methods.
+ """
+ return (
+ file_ctx.importers_name_symbols
+ and sym.get("language") not in _PREPROCESSED_LANGUAGES
+ and sym.get("name") not in file_ctx.extension_containers
+ )
+
+ def _declares_extension_method(self, sym_id: str) -> bool:
+ """Whether this container declares a C# extension method (``this T x``)."""
+ return any(
+ data.get("edge_type") == "has_method"
+ and "(this " in (self.graph.nodes[method_id].get("signature") or "")
+ for _, method_id, data in self.graph.out_edges(sym_id, data=True)
+ )
+
def _unused_export_confidence(
self, file_ctx: _ExportFile, sym: dict, risk_factors: Any
) -> float:
@@ -1472,10 +1527,11 @@ class DeadCodeAnalyzer:
sym_name = sym.get("name", "")
if _is_symbol_deprecated(sym_name, sym.get("decorators") or []):
confidence = 0.3
- elif file_ctx.file_has_importers:
+ elif self._import_absence_is_evidence(file_ctx, sym):
confidence = 1.0
else:
- confidence = 0.7
+ # Ranked, never deletion-ready.
+ confidence = UNPROVEN_EXPORT_CONFIDENCE
if sym.get("kind") == "interface" and not self._file_has_implementors(node):
confidence = min(confidence, RISK_CAP_CONFIDENCE)
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 2387bdd34..80aa32aac 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/constants.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -964,6 +964,11 @@ _PURE_WRAPPER_DECORATOR_ATTRS: frozenset[str] = frozenset(
# is a deliberate act.
_CONTAINER_USE_LANGUAGES: frozenset[str] = frozenset({"csharp"})
+# Languages whose symbols the preprocessor reaches without naming them: a
+# ``typedef struct _X {...} X`` tag used only through ``X``, a function called
+# through a ``#define`` alias or a ``##``-pasted name, an icall table entry.
+_PREPROCESSED_LANGUAGES: frozenset[str] = frozenset({"c", "cpp", "objectivec"})
+
# Annotations whose *argument* is the signal (``@SuppressWarnings("unused")``),
# matched against the raw decorator text rather than its base name.
_DELIBERATELY_UNUSED_ANNOTATIONS: tuple[tuple[str, str], ...] = (
diff --git a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
index 2f1994469..553c72be8 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
@@ -45,6 +45,12 @@ SAFE_CONFIDENCE_THRESHOLD: float = 0.7
# below the deletion-ready threshold so no verdict is issued on it.
NO_GIT_SIGNAL_CONFIDENCE: float = 0.5
+# Confidence for an unused export whose absence nothing could have shown: no
+# importer of its file names the symbols it takes (a C ``#include``, a C#
+# ``using``, or no importer at all). Below the deletion-ready threshold, above
+# the review cap: still ranked, never issued as a deletion.
+UNPROVEN_EXPORT_CONFIDENCE: float = 0.6
+
# Confidence ceiling applied to a finding that carries a runtime-load risk
# factor. 0.4 is the default ``min_confidence`` floor across CLI, REST router,
# and MCP tools (which import this value as their single source of truth), so the
diff --git a/tests/unit/analysis/test_dead_code_unindexed_importers.py b/tests/unit/analysis/test_dead_code_unindexed_importers.py
index fbd9955cc..cb51daefb 100644
--- a/tests/unit/analysis/test_dead_code_unindexed_importers.py
+++ b/tests/unit/analysis/test_dead_code_unindexed_importers.py
@@ -77,6 +77,15 @@ class TestUnindexedImporterClamp:
_analyzer(repo, [("App.tsx", "over_max_size")])._clamp_for_unindexed_importers([finding])
assert finding.confidence >= 0.4
+ def test_evidence_names_skipped_files_in_a_stable_order(self, repo: Path) -> None:
+ # The skipped list arrives in traversal order, which varies run to run.
+ for name in ("d.tsx", "c.tsx", "b.tsx"):
+ (repo / name).write_text("Widget\n", encoding="utf-8")
+ skipped = [(n, "over_max_size") for n in ("d.tsx", "App.tsx", "c.tsx", "b.tsx")]
+ finding = _finding(symbol_name="Widget")
+ _analyzer(repo, skipped)._clamp_for_unindexed_importers([finding])
+ assert "(App.tsx, b.tsx, c.tsx (+1 more))" in finding.evidence[-1]
+
def test_symbol_absent_from_unindexed_file_is_untouched(self, repo: Path) -> None:
finding = _finding(symbol_name="Orphan")
_analyzer(repo, [("App.tsx", "over_max_size")])._clamp_for_unindexed_importers([finding])
diff --git a/tests/unit/dead_code/test_dynamic_use_uncertainty.py b/tests/unit/dead_code/test_dynamic_use_uncertainty.py
index 787eeba5b..b9cb99275 100644
--- a/tests/unit/dead_code/test_dynamic_use_uncertainty.py
+++ b/tests/unit/dead_code/test_dynamic_use_uncertainty.py
@@ -35,7 +35,10 @@ from repowise.core.analysis.dead_code import (
DeadCodeAnalyzer,
DeadCodeKind,
)
-from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
+from repowise.core.analysis.dead_code.risk_factors import (
+ RISK_CAP_CONFIDENCE,
+ UNPROVEN_EXPORT_CONFIDENCE,
+)
from tests.unit.dead_code._helpers import _build_graph, _old_date
_EXPORT_ONLY = {
@@ -160,8 +163,8 @@ def test_registry_target_in_dynamic_package_is_downgraded_not_deletion_ready():
def test_control_without_dynamic_machinery_keeps_high_confidence():
- """Same-named symbol in a clean package: the clamp is per-package, and a
- genuinely unused export still reads as deletion-ready."""
+ """Same-named symbol in a clean package: the clamp is per-package, so a
+ genuinely unused export keeps its own verdict."""
graph = _registry_graph()
source_map = {
"pkg/loader.py": _LOADER_SRC.encode(),
@@ -171,8 +174,8 @@ def test_control_without_dynamic_machinery_keeps_high_confidence():
report = _analyzer(graph, source_map=source_map).analyze(dict(_EXPORT_ONLY))
control = _export(report, "XmlSerializer", file_path="other/serializers.py")
- assert control.confidence == pytest.approx(0.7)
- assert control.safe_to_delete
+ # No importer names its symbols, so it keeps the unproven tier, uncapped.
+ assert control.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
def test_callback_registration_is_downgraded():
@@ -228,8 +231,8 @@ def test_callback_registration_is_downgraded():
assert not dynamic.safe_to_delete
control = _export(report, "flush_cache", file_path="plain/helpers.py")
- assert control.confidence == pytest.approx(0.7)
- assert control.safe_to_delete
+ # No importer names its symbols, so it keeps the unproven tier, uncapped.
+ assert control.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
def test_resolved_dynamic_edge_still_skips_the_symbol():
@@ -320,8 +323,8 @@ def test_refutation_is_identity_aware_across_same_named_symbols():
assert "JsonSerializer" in names # only the unpinned sibling remains
finding = _export(report, "JsonSerializer", file_path="other/serializers.py")
# ...and the sibling keeps its ordinary verdict (stale-commit promotion).
- assert finding.confidence == pytest.approx(0.7)
- assert finding.safe_to_delete
+ # No importer names its symbols, so it keeps the unproven tier, uncapped.
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
def test_marker_only_downgrades_and_edge_only_skips():
diff --git a/tests/unit/dead_code/test_export_evidence.py b/tests/unit/dead_code/test_export_evidence.py
new file mode 100644
index 000000000..b82fdd3be
--- /dev/null
+++ b/tests/unit/dead_code/test_export_evidence.py
@@ -0,0 +1,134 @@
+"""An unused export is deletion-ready only when a use would have been visible.
+
+"No importer names this symbol" says something only when the file's importers
+name what they take. A C ``#include`` or a C# ``using`` names nothing, and a
+file with no importer at all gives nothing to compare against, so both stay
+below the deletion-ready threshold. C and C++ never reach it: the preprocessor
+uses a ``typedef struct _X {...} X`` tag through ``X`` and a function through a
+``#define`` alias, neither of which an edge records.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer, DeadCodeKind
+from repowise.core.analysis.dead_code.risk_factors import (
+ SAFE_CONFIDENCE_THRESHOLD,
+ UNPROVEN_EXPORT_CONFIDENCE,
+)
+from tests.unit.dead_code._helpers import _build_graph
+
+_EXPORTS_ONLY = {
+ "detect_unreachable_files": False,
+ "detect_unused_internals": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+}
+
+
+def _sym(name: str, language: str, kind: str = "function") -> dict:
+ return {
+ "name": name,
+ "kind": kind,
+ "visibility": "public",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 3,
+ "language": language,
+ }
+
+
+def _export(path: str, language: str, importer_edge: dict | None, kind: str = "function"):
+ nodes = {
+ path: {"language": language, "symbols": [_sym("used_one", language, kind), _sym("lonely", language, kind)]},
+ "app/main.x": {"language": language, "is_entry_point": True},
+ }
+ edges = [("app/main.x", path, importer_edge)] if importer_edge is not None else []
+ report = DeadCodeAnalyzer(_build_graph(nodes, edges)).analyze(dict(_EXPORTS_ONLY))
+ [finding] = [
+ f for f in report.findings
+ if f.kind is DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "lonely"
+ ]
+ return finding
+
+
+def test_naming_importer_makes_the_export_deletion_ready():
+ finding = _export(
+ "lib/util.py", "python", {"edge_type": "imports", "imported_names": ["used_one"]}
+ )
+ assert finding.confidence == pytest.approx(1.0)
+ assert finding.safe_to_delete
+
+
+def test_file_with_no_importer_is_not_deletion_ready():
+ finding = _export("lib/util.py", "python", None)
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
+ assert finding.confidence < SAFE_CONFIDENCE_THRESHOLD
+ assert not finding.safe_to_delete
+
+
+def test_importer_that_names_nothing_is_no_evidence():
+ # A C ``#include``: the edge exists, but carries no names to be absent from.
+ finding = _export("src/unwind.h", "c", {"edge_type": "imports", "imported_names": []})
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
+ assert not finding.safe_to_delete
+
+
[email protected]("language", ["c", "cpp", "objectivec"])
+def test_preprocessed_languages_are_never_deletion_ready(language):
+ # Even when a type reference names a sibling symbol of the same header.
+ finding = _export(
+ "src/unwinder.h",
+ language,
+ {"edge_type": "type_use", "imported_names": ["used_one"]},
+ kind="struct",
+ )
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
+ assert not finding.safe_to_delete
+
+
+def test_importer_naming_a_namespace_is_no_evidence():
+ # A C# ``using Peek.Common.Extensions`` edge carries the namespace segment,
+ # which names no symbol of the file.
+ finding = _export(
+ "src/Extensions/SizeExtensions.cs",
+ "csharp",
+ {"edge_type": "imports", "imported_names": ["Extensions"]},
+ kind="class",
+ )
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
+ assert not finding.safe_to_delete
+
+
+def test_extension_method_container_is_not_deletion_ready():
+ # ``sig.GetConventions()`` calls the method without naming the class, so a
+ # type reference to a sibling enum says nothing about the container.
+ path = "src/Interop/CallingConventions.cs"
+ nodes = {
+ path: {
+ "language": "csharp",
+ "symbols": [
+ _sym("CallingConventions", "csharp", "enum"),
+ _sym("CallingConventionExtensions", "csharp", "class"),
+ ],
+ },
+ "src/Jit.cs": {"language": "csharp", "is_entry_point": True},
+ }
+ graph = _build_graph(
+ nodes,
+ [("src/Jit.cs", path, {"edge_type": "type_use", "imported_names": ["CallingConventions"]})],
+ )
+ method_id = f"{path}::CallingConventionExtensions::GetConventions"
+ graph.add_node(
+ method_id,
+ node_type="symbol",
+ kind="method",
+ name="GetConventions",
+ signature="GetConventions(this MethodSignature signature) -> CallingConventions",
+ )
+ graph.add_edge(f"{path}::CallingConventionExtensions", method_id, edge_type="has_method")
+ report = DeadCodeAnalyzer(graph).analyze(dict(_EXPORTS_ONLY))
+ [finding] = [f for f in report.findings if f.symbol_name == "CallingConventionExtensions"]
+ assert finding.confidence == pytest.approx(UNPROVEN_EXPORT_CONFIDENCE)
+ assert not finding.safe_to_delete
diff --git a/tests/unit/dead_code/test_interfaces.py b/tests/unit/dead_code/test_interfaces.py
index b07712aff..01c769a3e 100644
--- a/tests/unit/dead_code/test_interfaces.py
+++ b/tests/unit/dead_code/test_interfaces.py
@@ -6,6 +6,7 @@ from repowise.core.analysis.dead_code import (
DeadCodeAnalyzer,
DeadCodeKind,
)
+from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
from tests.unit.dead_code._helpers import _build_graph
@@ -176,9 +177,9 @@ def test_pascal_unused_export_is_not_blanket_capped():
if f.kind == DeadCodeKind.UNUSED_EXPORT and f.symbol_name == "TConsoleBuffer"
]
assert pascal_findings, "expected a finding for TConsoleBuffer"
- assert any(f.confidence >= 0.7 and f.safe_to_delete for f in pascal_findings), (
- "a genuinely-unused Pascal symbol with no risk factors should still be able to "
- f"reach safe-to-delete confidence, got {[(f.confidence, f.safe_to_delete) for f in pascal_findings]}"
+ assert any(f.confidence > RISK_CAP_CONFIDENCE for f in pascal_findings), (
+ "a genuinely-unused Pascal symbol with no risk factors should not be capped "
+ f"to the review tier, got {[(f.confidence, f.safe_to_delete) for f in pascal_findings]}"
)
@@ -291,6 +292,5 @@ def test_release_in_non_com_language_not_clamped():
com_findings = [f for f in report.findings if f.symbol_name == "Release"]
for f in com_findings:
# If it surfaces at all, it must do so under the *normal*
- # rule — not under the COM clamp specifically. The normal
- # rule yields 0.7 / 1.0 depending on file-level importers.
- assert f.confidence >= 0.7 or f.confidence < 0.4
+ # rule, not under the COM clamp, which would cap it to the review tier.
+ assert f.confidence > RISK_CAP_CONFIDENCE