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(health): count a file's dependents from code edges, not co-change history (#2679)

Swati Ahuja86b390ec43f5
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
index be4e89aff..9a20e402b 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hidden_coupling.py
@@ -64,6 +64,23 @@ def _severity_for(correlation: float, co_count: int) -> Severity:
return Severity.MEDIUM
+def _reason(partner_path: str, support: int, self_commits: int, partner_commits: int) -> str:
+ """The sentence a finding prints, over the denominator the ratio used.
+
+ The ratio divides by the smaller commit count, so the sentence names that
+ count and whose it is; quoting the other file's total beside the ratio
+ printed impossible pairs like "6 of its 54 commits (50%)".
+ """
+ if self_commits <= partner_commits:
+ denom, whose = self_commits, "this file's"
+ else:
+ denom, whose = partner_commits, "its"
+ return (
+ f"{partner_path} changed with this file in {support} of {whose} "
+ f"{denom} commits ({support / denom:.0%}) but no static dependency exists"
+ )
+
+
class HiddenCouplingDetector:
name = "hidden_coupling"
category = "organizational"
@@ -93,7 +110,9 @@ class HiddenCouplingDetector:
if total_self < _MIN_COMMITS or partner_total < _MIN_COMMITS:
continue
denom = min(total_self, partner_total)
- if denom <= 0:
+ # More shared commits than the smaller file has commits is a
+ # record the walk could not have written; there is no ratio to show.
+ if denom <= 0 or partner.support > denom:
continue
correlation = partner.support / denom
if correlation < _MIN_CORRELATION:
@@ -130,11 +149,7 @@ class HiddenCouplingDetector:
"self_commits": total_self,
"partner_commits": partner_total,
},
- reason=(
- f"{partner_path} changed with this file in {support} of its "
- f"{total_self} commits ({correlation:.0%}) but no static "
- "dependency exists"
- ),
+ reason=_reason(partner_path, support, total_self, partner_total),
)
)
return findings
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 1e3e4c656..037298e27 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -36,6 +36,7 @@ from ...ingestion.package_roots import module_for as _module_for
from ...ingestion.package_roots import package_roots_from_paths as _package_roots
from ...ingestion.package_roots import scan_package_roots as _scan_package_roots
from ...test_paths import paired_test_names
+from ..dead_code.file_reachability import file_dependency_neighbors
from ..graph_view import HasEdge, ImportEdgeView
from ..test_reachability import files_reached_by_tests, files_with_paired_tests
from .asserts.lexicon import AssertVocabulary
@@ -447,6 +448,11 @@ def _compute_repo_function_mod_p80(
return _percentile_p80(counts)
+def _dependents_count(graph: Any, path: str) -> int:
+ """Distinct files that depend on *path* in code; co-change is history, not a dependent."""
+ return len(set(file_dependency_neighbors(graph, path, incoming=True)))
+
+
def _compute_repo_dependents_p80(parsed_files: list[Any], graph: Any) -> int | None:
"""Repo-wide 80th percentile of file-level in-degree (dependents).
@@ -466,10 +472,7 @@ def _compute_repo_dependents_p80(parsed_files: list[Any], graph: Any) -> int | N
path = pf.file_info.path
if path not in graph:
continue
- try:
- deg = int(graph.in_degree(path))
- except Exception:
- continue
+ deg = _dependents_count(graph, path)
if deg > 0:
counts.append(deg)
return _percentile_p80(counts)
@@ -1076,10 +1079,7 @@ class HealthAnalyzer:
path = s.file_path
if path in out or path not in self.graph:
continue
- try:
- out[path] = float(self.graph.in_degree(path))
- except Exception:
- out[path] = 0.0
+ out[path] = float(_dependents_count(self.graph, path))
return out
def _apply_cross_file_oracles(self, walked: list[tuple[Any, FileComplexity]]) -> None:
@@ -1310,11 +1310,8 @@ class HealthAnalyzer:
nloc = fcx.file_nloc
dependents_count = 0
- if self.graph is not None and file_path in self.graph:
- try:
- dependents_count = int(self.graph.in_degree(file_path))
- except Exception:
- dependents_count = 0
+ if self.graph is not None:
+ dependents_count = _dependents_count(self.graph, file_path)
cov = self.coverage_map.get(file_path)
if cov is None:
diff --git a/tests/unit/health/test_dependents_count.py b/tests/unit/health/test_dependents_count.py
new file mode 100644
index 000000000..f1dc3733a
--- /dev/null
+++ b/tests/unit/health/test_dependents_count.py
@@ -0,0 +1,58 @@
+"""A file's dependents are the files that depend on it in code, not its co-change partners.
+
+The graph carries ``co_changes`` edges beside the import edges, so a raw
+in-degree counted every file ever committed alongside this one as a dependent.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.health import HealthAnalyzer
+from repowise.core.analysis.health.engine import _dependents_count
+from repowise.core.analysis.health.models import Severity
+from repowise.core.ingestion.parser import parse_file
+from repowise.core.ingestion.traverser import FileTraverser
+
+_TARGET = "src/parser.py"
+
+
+def _graph(importers: int, co_change_partners: int) -> nx.DiGraph:
+ g = nx.DiGraph()
+ g.add_node(_TARGET, node_type="file", language="python")
+ for i in range(importers):
+ g.add_edge(f"src/consumer_{i}.py", _TARGET, edge_type="imports")
+ for i in range(co_change_partners):
+ # Co-change is undirected history; the builder records both directions.
+ g.add_edge(f"src/sibling_{i}.py", _TARGET, edge_type="co_changes")
+ g.add_edge(_TARGET, f"src/sibling_{i}.py", edge_type="co_changes")
+ # The file's own symbols are containment, not dependents.
+ g.add_edge(_TARGET, f"{_TARGET}::parse", edge_type="defines")
+ g.nodes[f"{_TARGET}::parse"]["node_type"] = "symbol"
+ return g
+
+
+def test_two_importers_and_fifty_co_change_partners_is_two_dependents():
+ graph = _graph(importers=2, co_change_partners=50)
+ assert graph.in_degree(_TARGET) == 52 # the number the engine used to report
+ assert _dependents_count(graph, _TARGET) == 2
+
+
+def test_the_engine_reports_importers_only(tmp_path):
+ """End to end: untested_hotspot prints the count the engine handed it."""
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "parser.py").write_text("def parse(s):\n return s\n", encoding="utf-8")
+ parsed = [
+ parse_file(f, (tmp_path / f.path).read_bytes()) for f in FileTraverser(tmp_path).traverse()
+ ]
+ report = HealthAnalyzer(
+ _graph(importers=4, co_change_partners=50),
+ parsed_files=parsed,
+ git_meta_map={
+ _TARGET: {"is_hotspot": True, "commit_count_90d": 30, "commit_count_total": 30}
+ },
+ ).analyze()
+ [finding] = [f for f in report.findings if f.biomarker_type == "untested_hotspot"]
+ assert finding.reason.split("— ")[-1] == "4 dependents"
+ # Ten or more dependents would have made it critical; four at 0% is high.
+ assert finding.severity == Severity.HIGH
diff --git a/tests/unit/health/test_hidden_coupling.py b/tests/unit/health/test_hidden_coupling.py
index af0f6df3d..f9c1259a8 100644
--- a/tests/unit/health/test_hidden_coupling.py
+++ b/tests/unit/health/test_hidden_coupling.py
@@ -2,7 +2,9 @@
from __future__ import annotations
+import itertools
import json
+import re
from repowise.core.analysis.health.biomarkers import FileContext
from repowise.core.analysis.health.biomarkers.hidden_coupling import (
@@ -289,3 +291,52 @@ def test_ratio_reads_the_record_not_the_repo_wide_commit_total():
assert finding.details["self_commits"] == 10
assert finding.details["partner_commits"] == 10
assert finding.details["correlation"] == 0.9
+
+
+_REASON = re.compile(
+ r"^(?P<partner>\S+) changed with this file in (?P<support>\d+) of "
+ r"(?P<whose>this file's|its) (?P<denom>\d+) commits \((?P<pct>\d+)%\) "
+ r"but no static dependency exists$"
+)
+
+
+def test_printed_counts_are_the_ones_the_ratio_used():
+ """Every sentence quotes support over the denominator the ratio divided by.
+
+ Exhaustive over a grid rather than sampled: the printed pair used to be the
+ shared count over this file's total while the percentage divided by the
+ smaller of the two totals, which read as "6 of its 54 commits (50%)".
+ """
+ seen = 0
+ for self_commits, partner_commits, support in itertools.product(
+ range(5, 16), range(5, 16), range(0, 20)
+ ):
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": support},
+ self_commits=self_commits,
+ repo_commits={"src/billing.py": partner_commits},
+ )
+ for finding in HiddenCouplingDetector().detect(ctx):
+ m = _REASON.match(finding.reason)
+ assert m, finding.reason
+ printed_support, denom = int(m["support"]), int(m["denom"])
+ assert printed_support == support
+ assert denom == min(self_commits, partner_commits)
+ assert m["whose"] == ("this file's" if self_commits <= partner_commits else "its")
+ assert printed_support <= denom
+ assert int(m["pct"]) == round(100 * printed_support / denom)
+ assert finding.details["correlation"] == round(printed_support / denom, 3)
+ seen += 1
+ assert seen > 100 # the grid reached the detector, not only its gates
+
+
+def test_more_shared_commits_than_the_smaller_file_has_is_not_reported():
+ """A record claiming 12 shared commits for a file with 10 has no honest ratio."""
+ ctx = _ctx(
+ "src/payments.py",
+ partners={"src/billing.py": 12},
+ self_commits=10,
+ repo_commits={"src/billing.py": 30},
+ )
+ assert HiddenCouplingDetector().detect(ctx) == []