Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(performance): require centrality for the hot-path gate (#2007)
Raghav Chamadiyada01cc950718
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex c85c76afa..618982d2c 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -288,7 +288,6 @@ class HealthAnalyzer:self,graph: Any, # networkx.DiGraphgit_meta_map: dict[str, dict] | None = None,- performance_git_meta_map: dict[str, dict] | None = None,parsed_files: list[Any] | None = None,coverage_map: dict[str, dict[str, Any]] | None = None,community_label_map: dict[str, str] | None = None,@@ -298,7 +297,6 @@ class HealthAnalyzer:) -> None:self.graph = graphself.git_meta_map = git_meta_map or {}- self.performance_git_meta_map = performance_git_meta_map or self.git_meta_mapself.parsed_files = list(parsed_files or [])# Per-file coverage keyed by repo-relative POSIX path. Each value# is ``{line_coverage_pct, branch_coverage_pct, covered_lines,@@ -803,9 +801,9 @@ class HealthAnalyzer:Each is appended onto the matching file's ``perf_hits`` in place so thebiomarkers handle every case through one path. Failure-isolated and neverblocks the report. The cross-function passes are a no-op without a graph;- the centrality-gated pass ALWAYS runs — when no graph/git signal is- available nothing is hot, so it emits nothing (precision-first: we never- ship a centrality-gated marker we cannot establish centrality for).+ the centrality-gated pass ALWAYS runs — without a graph nothing is+ hot, so it emits nothing (precision-first: we never ship a+ centrality-gated marker we cannot establish centrality for)."""try:index = self._execution_graph()@@ -817,7 +815,7 @@ class HealthAnalyzer:):for path, hits in src.items():by_file.setdefault(path, []).extend(hits)- ranker = PerfRanker(index, self.performance_git_meta_map)+ ranker = PerfRanker(index)for path, hits in collect_centrality_gated(walked, ranker).items():by_file.setdefault(path, []).extend(hits)for _pf, fcx in walked:diff --git a/packages/core/src/repowise/core/analysis/health/perf/ranking.py b/packages/core/src/repowise/core/analysis/health/perf/ranking.pyindex 65b8bf27c..30e85ab4c 100644--- a/packages/core/src/repowise/core/analysis/health/perf/ranking.py+++ b/packages/core/src/repowise/core/analysis/health/perf/ranking.py@@ -1,29 +1,28 @@"""The severity ranker, reusable as a precision GATE.The performance pillar already ranks findings by *blast radius*: a hit in a-widely-called, churny function matters more than the same hit in a cold leaf.-The ranker is also used as a **precision gate**, not only a sort key. Some-patterns are noisy when flagged everywhere (a bare O(n^2) nested loop; a-blocking I/O call outside any loop) but become high-signal the moment they sit-in a hot, request-reachable function. The gate fires those markers *only there*.+widely-called function matters more than the same hit in a cold leaf. The+ranker is also used as a **precision gate**, not only a sort key. Some patterns+are noisy when flagged everywhere (a bare O(n^2) nested loop; a blocking I/O+call outside any loop) but become high-signal the moment they sit in a hot,+request-reachable function. The gate fires those markers *only there*.-"Hot" combines two whole-program signals a file-local linter cannot compute:+"Hot" is one whole-program signal a file-local linter cannot compute:- * **centrality** — the function's symbol node has a top-quintile number of+ * **centrality** - the function's symbol node has a top-quintile number ofdistinct direct predecessors in the reliable execution graph (the- ``CallGraphIndex`` in-degree). A widely-reached function is on many request paths, so a latency- or quadratic cost there is paid often. Direct in-degree is a deterministic,- ``O(E)`` proxy for request-reachability; transitive fan-in would be stronger- but is quadratic to compute per function.- * **churn** — the function's *file* is a git hotspot (``is_hotspot``) or sits- in the repo's top-quintile of commit volume. Churny code is read and changed- often, so a cost there is both more likely to bite and more worth fixing.--Either signal alone makes a function hot (logical OR): a hub utility with no-churn is still hot by centrality; a frequently-rewritten handler with few static-callers is still hot by churn. When neither the graph nor git metadata is-available the gate degrades to "nothing is hot" — the markers behind it simply-do not fire, never a false positive.+ ``CallGraphIndex`` in-degree). A widely-reached function is on many request+ paths, so a latency or quadratic cost there is paid often. Direct in-degree+ is a deterministic, ``O(E)`` proxy for request-reachability; transitive+ fan-in would be stronger but is quadratic to compute per function.++Churn is deliberately not a second arm. How often a file is edited is not how+often it runs, so it cannot support the request-reachability these markers+assert in their own reason text. Churn still earns rank in+``opportunity_rank``; it does not decide whether a finding exists.++Without a graph the gate degrades to "nothing is hot" - the markers behind it+simply do not fire, never a false positive."""from __future__ import annotations@@ -49,47 +48,28 @@ def _percentile_threshold(values: list[int], pct: float) -> int:class PerfRanker:"""Decides whether a function is *hot* enough for a centrality-gated marker.- Build once per ``analyze()`` from the shared :class:`CallGraphIndex` and the- engine's ``git_meta_map``; call :meth:`is_hot` per candidate hit. Both the- centrality threshold (top-quintile caller count) and the churn threshold- (top-quintile commit volume) are computed up front from the repo-wide- distributions, so the gate adapts to the repo instead of assuming a fixed- bar.+ Build once per ``analyze()`` from the shared :class:`CallGraphIndex`; call+ :meth:`is_hot` per candidate hit. The centrality threshold (top-quintile+ caller count) is computed up front from the repo-wide distribution, so the+ gate adapts to the repo instead of assuming a fixed bar."""- __slots__ = ("_churn_p80", "_hot_in_degree", "_hotspot_files", "_index", "_meta")+ __slots__ = ("_hot_in_degree", "_index")def __init__(self,index: CallGraphIndex | None,- git_meta_map: dict[str, dict] | None,*,centrality_pct: float = 0.8,- churn_pct: float = 0.8,) -> None:self._index = index- self._meta = git_meta_map or {}# Centrality bar: the top-quintile direct-caller count over functions- # that have at least one caller. ``max(2, ...)`` keeps a tiny graph from- # calling a function with a single caller "central".+ # that have at least one caller. ``max(2, ...)`` keeps a shallow graph+ # from calling a function with a single caller "central".in_degrees = [d for d in (index.in_degree.values() if index else ()) if d >= 1]self._hot_in_degree = max(2, _percentile_threshold(in_degrees, centrality_pct))- # Churn bar + the explicit hotspot set, both off git metadata.- commit_counts: list[int] = []- hotspot_files: set[str] = set()- for path, meta in self._meta.items():- if not isinstance(meta, dict):- continue- if meta.get("is_hotspot"):- hotspot_files.add(path)- c = meta.get("commit_count_total")- if isinstance(c, int) and c > 0:- commit_counts.append(c)- self._churn_p80 = _percentile_threshold(commit_counts, churn_pct)- self._hotspot_files = hotspot_files-# -- the gate -------------------------------------------------------------def is_central(self, path: str, func_start: int) -> bool:@@ -101,17 +81,9 @@ class PerfRanker:return Falsereturn self._index.in_degree.get(sid, 0) >= self._hot_in_degree- def is_churny(self, path: str) -> bool:- """True if ``path`` is a git hotspot or in the top commit-volume quintile."""- if path in self._hotspot_files:- return True- meta = self._meta.get(path)- if not isinstance(meta, dict):- return False- c = meta.get("commit_count_total")- return isinstance(c, int) and c >= self._churn_p80-def is_hot(self, path: str, func_start: int) -> bool:- """The OR gate: central OR churny ⇒ worth flagging a noisy-when-ungated- marker here. Pure when neither graph nor git metadata is available."""- return self.is_central(path, func_start) or self.is_churny(path)+ """Central enough to carry a marker that claims request-reachability.++ Pure when no graph is available: nothing is hot, so nothing fires.+ """+ return self.is_central(path, func_start)diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex ad41b5733..b52e8d52a 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -645,9 +645,6 @@ def run_partial_analysis(_health_analyzer = HealthAnalyzer(graph_builder.graph(),git_meta_map=git_meta_map,- # Only centrality-gated performance reads this merged map. Other- # health signals keep the established change-scoped git semantics.- performance_git_meta_map={**(stored_git_meta or {}), **git_meta_map},parsed_files=parsed_files,duplication_cache_dir=Path(repo_path) / ".repowise",repo_root=repo_path,diff --git a/tests/unit/health/test_perf_phase7b.py b/tests/unit/health/test_perf_phase7b.pyindex dc76f0fcf..5a7f46b71 100644--- a/tests/unit/health/test_perf_phase7b.py+++ b/tests/unit/health/test_perf_phase7b.py@@ -218,25 +218,52 @@ _HOT_SRC = ()-def test_centrality_gate_fires_in_a_churny_file():+def test_centrality_gate_is_silent_on_churn_alone():+ """Churn is not reachability, so it cannot carry these markers alone.++ A git hotspot with no callers was hot on its own until the gate required+ centrality. How often a file is edited is not how often it runs.+ """walked = _walked("svc.py", _HOT_SRC)- # No graph, but the file is a git hotspot -> churny -> hot.- ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})- out = collect_centrality_gated(walked, ranker)- kinds = sorted(h.kind for h in out.get("svc.py", []))- assert kinds == ["hot_path_sync_io", "nested_loop_quadratic"]- assert out["svc.py"][0].detail or True # hot_path carries the boundary kind+ ranker = PerfRanker(None)+ assert collect_centrality_gated(walked, ranker) == {}-def test_centrality_gate_silent_without_any_hot_signal():+def test_centrality_gate_silent_without_a_graph():walked = _walked("cold.py", _HOT_SRC)- # No graph, no git metadata -> nothing is hot -> no gated markers ship.- ranker = PerfRanker(None, {})+ # No graph -> nothing is central -> no gated markers ship.+ ranker = PerfRanker(None)assert collect_centrality_gated(walked, ranker) == {}+def test_centrality_gate_fires_for_a_central_function_end_to_end():+ """The surviving arm still ships both gated markers."""+ g = nx.MultiDiGraph()+ g.add_node(+ "svc.py::hot", node_type="symbol", name="hot", file_path="svc.py", start_line=2, end_line=6+ )+ for i in range(4):+ cid = f"c.py::caller{i}"+ g.add_node(+ cid,+ node_type="symbol",+ name=f"caller{i}",+ file_path="c.py",+ start_line=10 + i,+ end_line=11 + i,+ )+ g.add_edge(cid, "svc.py::hot", edge_type="calls")+ walked = _walked("svc.py", _HOT_SRC)+ out = collect_centrality_gated(walked, PerfRanker(CallGraphIndex(g)))+ assert sorted(h.kind for h in out.get("svc.py", [])) == [+ "hot_path_sync_io",+ "nested_loop_quadratic",+ ]++def test_centrality_gate_fires_for_a_central_function():- # A symbol with top-quintile caller count is "central" even without churn.+ # A symbol with top-quintile caller count is central; a single-caller leaf+ # is not, which is the floor at work on a graph this small.g = nx.MultiDiGraph()g.add_node("svc.py::hot", node_type="symbol", name="hot", file_path="svc.py", start_line=1, end_line=6@@ -254,7 +281,7 @@ def test_centrality_gate_fires_for_a_central_function():)g.add_edge(cid, "svc.py::hot", edge_type="calls")callers.append(cid)- # A cold leaf with a single caller — must NOT be central.+ # A cold leaf with a single caller: must NOT be central.g.add_node("svc.py::cold",node_type="symbol",@@ -266,7 +293,7 @@ def test_centrality_gate_fires_for_a_central_function():g.add_edge(callers[0], "svc.py::cold", edge_type="calls")index = CallGraphIndex(g)- ranker = PerfRanker(index, {})+ ranker = PerfRanker(index)assert ranker.is_central("svc.py", 1) is Trueassert ranker.is_central("svc.py", 20) is False