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.

perf(health): remove repo-sized per-file work from the refactoring detectors (#893)

Raghav Chamadiya09234ee8f91f
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
index f473c4e51..3e538d040 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -110,6 +110,18 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
stmts = block.named_children
n = len(stmts)
is_body = block.id == body_container.id
+ # One subtree walk per statement, then O(1) metrics per span via
+ # prefix sums. _span_metrics processes each span statement's subtree
+ # independently, so a span's decision count is the sum over its
+ # statements and its jump bit the OR — walking each statement once
+ # replaces the per-span re-walks that made this loop O(n^2 * subtree).
+ if n >= _MIN_STMTS:
+ dec_prefix = [0]
+ jump_prefix = [0]
+ for st in stmts:
+ d, jmp = _span_metrics([st], decision_kinds, jump_kinds, scope_kinds)
+ dec_prefix.append(dec_prefix[-1] + d)
+ jump_prefix.append(jump_prefix[-1] + (1 if jmp else 0))
for i in range(n):
for j in range(i, n):
evaluated += 1
@@ -127,10 +139,11 @@ def find_extractions(analysis: FunctionAnalysis, lmap: LanguageNodeMap) -> list[
and stmts[j].type not in tail_stmt_kinds
):
continue
- span = stmts[i : j + 1]
- decisions, has_jump = _span_metrics(span, decision_kinds, jump_kinds, scope_kinds)
+ decisions = dec_prefix[j + 1] - dec_prefix[i]
+ has_jump = jump_prefix[j + 1] > jump_prefix[i]
if has_jump or decisions < _MIN_CCN_REMOVED:
continue
+ span = stmts[i : j + 1]
slice_nloc = sum(st.end_point[0] - st.start_point[0] + 1 for st in span)
if slice_nloc < _MIN_SLICE_NLOC:
continue
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 47a302b7e..38b7fd286 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -52,7 +52,7 @@ from .refactoring import (
detect_refactorings,
rank_suggestions,
)
-from .refactoring.graph_signals import build_file_scc_index
+from .refactoring.graph_signals import build_file_scc_index, build_methods_by_file
from .scoring import attach_impacts, compute_kpis, remap_severities, score_file
log = structlog.get_logger(__name__)
@@ -367,6 +367,7 @@ class HealthAnalyzer:
# Repo-wide SCC index (import cycles), computed once and threaded into
# each file's RefactoringContext so Break Cycle never recomputes it.
file_scc_index = build_file_scc_index(self.graph)
+ methods_by_file = build_methods_by_file(self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
suggestions: list[RefactoringSuggestion] = []
@@ -434,6 +435,7 @@ class HealthAnalyzer:
refactoring_enabled=refactoring_enabled,
refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
+ methods_by_file=methods_by_file,
dataflow_cache=dataflow_cache,
)
metrics.append(file_metric)
@@ -577,6 +579,7 @@ class HealthAnalyzer:
refactoring_enabled: bool = bool(cfg.get("refactoring_enabled", True))
refactoring_min_confidence: str | None = cfg.get("refactoring_min_confidence")
file_scc_index = build_file_scc_index(self.graph)
+ methods_by_file = build_methods_by_file(self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
suggestions: list[RefactoringSuggestion] = []
@@ -606,6 +609,7 @@ class HealthAnalyzer:
refactoring_enabled=refactoring_enabled,
refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
+ methods_by_file=methods_by_file,
dataflow_cache=dataflow_cache,
)
metrics.append(file_metric)
@@ -782,6 +786,7 @@ class HealthAnalyzer:
refactoring_enabled: bool = True,
refactoring_min_confidence: str | None = None,
file_scc_index: dict[str, tuple[str, ...]] | None = None,
+ methods_by_file: dict[str, tuple[str, ...]] | None = None,
dataflow_cache: FileDataflowCache | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:
file_path = pf.file_info.path
@@ -899,6 +904,9 @@ class HealthAnalyzer:
module_map=self.module_map,
graph=self.graph,
file_scc=(file_scc_index or {}).get(file_path),
+ file_methods=(
+ methods_by_file.get(file_path, ()) if methods_by_file is not None else None
+ ),
function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),
blame_index=blame_index,
)
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
index 64e9e83cb..21fbb77a5 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/graph_signals.py
@@ -66,14 +66,54 @@ def cycle_edges(graph: Any, members: tuple[str, ...]) -> list[tuple[str, str]]:
Deterministic (sorted). Self-loops and edges leaving the cycle are
excluded — only the edges that keep the cycle strongly connected.
+ Every qualifying edge originates at a member, so walking each member's
+ out-edges covers the same set as a full-graph edge scan at a fraction
+ of the cost (this runs once per cycle-member file).
"""
if graph is None:
return []
member_set = set(members)
edges: list[tuple[str, str]] = []
- for u, v, data in graph.edges(data=True):
- if u == v or u not in member_set or v not in member_set:
+ for u in members:
+ if u not in graph:
continue
- if data.get("edge_type") in _CYCLE_EDGE_TYPES:
- edges.append((u, v))
+ for _u, v, data in graph.out_edges(u, data=True):
+ if u == v or v not in member_set:
+ continue
+ if data.get("edge_type") in _CYCLE_EDGE_TYPES:
+ edges.append((u, v))
return sorted(set(edges))
+
+
+def build_methods_by_file(graph: Any) -> dict[str, tuple[str, ...]]:
+ """Methods defined in each file, precomputed in one graph sweep.
+
+ Mirrors ``MoveMethodDetector._methods_in_file`` for every file at once:
+ a file's ``defines``-edge methods are authoritative; a file with none
+ falls back to the ``file::``-prefix scan over symbol nodes. Doing both
+ in one pass here replaces a per-file full-node scan that dominated the
+ health evaluate loop on large repos. Files with no methods are absent.
+ """
+ if graph is None:
+ return {}
+ edge_map: dict[str, set[str]] = {}
+ prefix_map: dict[str, set[str]] = {}
+ for node_id, data in graph.nodes(data=True):
+ if (
+ data.get("node_type") == "symbol"
+ and data.get("kind") == "method"
+ and "::" in node_id
+ ):
+ prefix_map.setdefault(node_id.split("::", 1)[0], set()).add(node_id)
+ for u, v, data in graph.edges(data=True):
+ if data.get("edge_type") != "defines":
+ continue
+ node = graph.nodes[v] if v in graph else None
+ if node is not None and node.get("kind") == "method":
+ edge_map.setdefault(u, set()).add(v)
+ out: dict[str, tuple[str, ...]] = {}
+ for file_path in set(edge_map) | set(prefix_map):
+ methods = edge_map.get(file_path) or prefix_map.get(file_path) or set()
+ if methods:
+ out[file_path] = tuple(sorted(methods))
+ return out
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/models.py b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
index 94db84ed7..6a39b3133 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/models.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/models.py
@@ -125,6 +125,12 @@ class RefactoringContext:
# engine precomputes the repo's SCC index once and threads the per-file
# slice in, so Break Cycle never recomputes SCCs per file.
file_scc: tuple[str, ...] | None = None
+ # Symbol ids of the methods defined in this file, sliced from the repo-wide
+ # index the engine precomputes once (``graph_signals.build_methods_by_file``),
+ # so Move Method never scans the whole graph per file. ``None`` means the
+ # index was not provided (direct detector use) — the detector then derives
+ # the list from the graph itself, exactly as before.
+ file_methods: tuple[str, ...] | None = None
# Per-flagged-function dataflow analyses (``dataflow.FunctionAnalysis``
# records, typed ``Any`` to avoid importing the dataflow layer into the
# model). The engine builds these only for files carrying a method-level
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
index 8c487dc3d..9614863ad 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/move_method.py
@@ -118,7 +118,10 @@ class MoveMethodDetector(RefactoringDetector):
if graph is None or _is_test_path(ctx.file_path):
return []
- methods = self._methods_in_file(graph, ctx.file_path)
+ if ctx.file_methods is not None:
+ methods = list(ctx.file_methods)
+ else:
+ methods = self._methods_in_file(graph, ctx.file_path)
if not methods:
return []
diff --git a/tests/unit/health/test_refactoring_break_cycle.py b/tests/unit/health/test_refactoring_break_cycle.py
index d7b2c27a7..d9a84d38d 100644
--- a/tests/unit/health/test_refactoring_break_cycle.py
+++ b/tests/unit/health/test_refactoring_break_cycle.py
@@ -135,3 +135,45 @@ def test_co_change_edges_do_not_form_a_cycle():
g.add_edge("a.py", "b.py", edge_type="imports")
g.add_edge("b.py", "a.py", edge_type="co_changes")
assert build_file_scc_index(g) == {}
+
+
+# -- cycle_edges equivalence ------------------------------------------------------
+#
+# cycle_edges walks each member's out-edges; it must match a brute-force scan
+# of every graph edge (the original implementation) on any input.
+
+
+def test_cycle_edges_matches_full_edge_scan():
+ from repowise.core.analysis.health.refactoring.graph_signals import (
+ _CYCLE_EDGE_TYPES,
+ cycle_edges,
+ )
+
+ g = _import_graph(
+ [
+ ("a.py", "b.py"),
+ ("b.py", "c.py"),
+ ("c.py", "a.py"),
+ ("c.py", "d.py"), # leaves the cycle
+ ("x.py", "a.py"), # enters the cycle from outside
+ ]
+ )
+ g.add_edge("a.py", "a.py", edge_type="imports") # self-loop, excluded
+ g.add_edge("b.py", "a.py", edge_type="co_changes") # non-cycle edge type
+ g.add_edge("a.py", "c.py", edge_type="type_use")
+
+ members = ("a.py", "b.py", "c.py", "ghost.py") # a member absent from the graph
+
+ def reference(graph, mem):
+ member_set = set(mem)
+ edges = []
+ for u, v, data in graph.edges(data=True):
+ if u == v or u not in member_set or v not in member_set:
+ continue
+ if data.get("edge_type") in _CYCLE_EDGE_TYPES:
+ edges.append((u, v))
+ return sorted(set(edges))
+
+ assert cycle_edges(g, members) == reference(g, members)
+ assert cycle_edges(g, ()) == []
+ assert cycle_edges(None, members) == []
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 6dda349de..0077805be 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -136,6 +136,193 @@ def test_extractions_are_deterministic():
assert serialize() == first
+# -- prefix-sum equivalence -------------------------------------------------------
+#
+# find_extractions computes span metrics via per-statement prefix sums. This
+# reference reimplements the original per-span _span_metrics enumeration; the
+# two must produce identical candidate lists on any input.
+
+
+def _find_extractions_reference(analysis, lmap):
+ from repowise.core.analysis.health.dataflow.slice import (
+ _MAX_CANDIDATES,
+ _MAX_PARAMS,
+ _MAX_RETURNS,
+ _MIN_CCN_REMOVED,
+ _MIN_SLICE_NLOC,
+ _MIN_STMTS,
+ Extraction,
+ _all_blocks,
+ _infer_in_out,
+ _sorted,
+ _span_metrics,
+ _unwrap_container,
+ _var_lines,
+ )
+
+ fn_node = analysis.fn_node
+ if fn_node is None:
+ return []
+ body = fn_node.child_by_field_name("body")
+ if body is None:
+ return []
+ body_container = _unwrap_container(body, lmap.block_kinds)
+ def_lines, use_lines = _var_lines(analysis.def_use)
+ decision_kinds = (
+ lmap.branch_kinds
+ | lmap.loop_kinds
+ | lmap.case_kinds
+ | lmap.catch_kinds
+ | lmap.boolean_operator_kinds
+ )
+ jump_kinds = lmap.return_kinds | lmap.raise_kinds | lmap.break_kinds | lmap.continue_kinds
+ scope_kinds = lmap.function_kinds | lmap.lambda_kinds
+ tail_stmt_kinds = (
+ lmap.statement_wrapper_kinds | lmap.local_decl_kinds
+ if lmap.statement_wrapper_kinds
+ else None
+ )
+
+ out = []
+ evaluated = 0
+ for block in _all_blocks(fn_node, lmap.block_kinds, scope_kinds):
+ stmts = block.named_children
+ n = len(stmts)
+ is_body = block.id == body_container.id
+ for i in range(n):
+ for j in range(i, n):
+ evaluated += 1
+ if evaluated > _MAX_CANDIDATES:
+ return _sorted(out)
+ length = j - i + 1
+ if length < _MIN_STMTS:
+ continue
+ if is_body and length == n:
+ continue
+ if (
+ tail_stmt_kinds is not None
+ and j == n - 1
+ and stmts[j].type not in tail_stmt_kinds
+ ):
+ continue
+ span = stmts[i : j + 1]
+ decisions, has_jump = _span_metrics(span, decision_kinds, jump_kinds, scope_kinds)
+ if has_jump or decisions < _MIN_CCN_REMOVED:
+ continue
+ slice_nloc = sum(st.end_point[0] - st.start_point[0] + 1 for st in span)
+ if slice_nloc < _MIN_SLICE_NLOC:
+ continue
+ s = span[0].start_point[0] + 1
+ e = span[-1].end_point[0] + 1
+ params, returns = _infer_in_out(def_lines, use_lines, s, e)
+ if len(params) > _MAX_PARAMS or len(returns) > _MAX_RETURNS:
+ continue
+ out.append(
+ Extraction(
+ start_line=s,
+ end_line=e,
+ params=params,
+ returns=returns,
+ slice_nloc=slice_nloc,
+ ccn_removed=decisions,
+ )
+ )
+ return _sorted(out)
+
+
+_NESTED = """
+def transform(items, flags):
+ out = []
+ for it in items:
+ if it in flags:
+ for k in range(3):
+ if k and it:
+ out.append((it, k))
+ else:
+ while it > 0:
+ it -= 1
+ out.append(it)
+ def helper(v):
+ if v:
+ return -v
+ return v
+ total = 0
+ for o in out:
+ total += helper(o if isinstance(o, int) else o[1])
+ if total > 10 or len(out) > 5:
+ total = total // 2
+ return total
+"""
+
+_JUMPY = """
+def scan(rows):
+ hits = 0
+ for r in rows:
+ if r is None:
+ continue
+ if r < 0:
+ break
+ hits += 1
+ try:
+ rate = hits / len(rows)
+ except ZeroDivisionError:
+ rate = 0.0
+ if rate > 0.5:
+ hits += 1
+ return hits, rate
+"""
+
+
[email protected]("src", [_PROCESS, _NESTED, _JUMPY])
+def test_prefix_sum_matches_per_span_reference(src):
+ lmap = get_language_map("python")
+ fn = _first(src)
+ assert find_extractions(fn, lmap) == _find_extractions_reference(fn, lmap)
+
+
+def test_prefix_sum_matches_per_span_reference_go():
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing")
+ if _get_language("go") is None:
+ pytest.skip("tree-sitter language pack missing for go")
+ src = textwrap.dedent(
+ """
+ package main
+
+ func Transform(items []int, limit int) int {
+ total := 0
+ count := 0
+ for _, it := range items {
+ if it > limit {
+ total += it
+ count++
+ } else {
+ total -= it
+ }
+ }
+ avg := 0
+ if count > 0 {
+ avg = total / count
+ }
+ for i := 0; i < avg; i++ {
+ if i%2 == 0 {
+ total += i
+ }
+ }
+ return total
+ }
+ """
+ )
+ res = analyze_file("m.go", "go", src.encode(), flagged_only=False)
+ if res.stats.functions_seen == 0:
+ pytest.skip("go parse unavailable")
+ lmap = get_language_map("go")
+ for fn in res.functions:
+ assert find_extractions(fn, lmap) == _find_extractions_reference(fn, lmap)
+
+
# -- detector -------------------------------------------------------------------
diff --git a/tests/unit/health/test_refactoring_move_method.py b/tests/unit/health/test_refactoring_move_method.py
index b502fa0b5..773395784 100644
--- a/tests/unit/health/test_refactoring_move_method.py
+++ b/tests/unit/health/test_refactoring_move_method.py
@@ -181,3 +181,65 @@ def test_deterministic_and_stable_order():
second = [s.target_symbol for s in _detect(g, "c.py")]
assert first == second
assert len(first) == 2
+
+
+# -- methods-by-file index equivalence -------------------------------------------
+#
+# The engine precomputes graph_signals.build_methods_by_file once per pass; it
+# must agree with the detector's own per-file derivation (defines edges with a
+# prefix-scan fallback) for every file, and the detector must produce the same
+# suggestions whichever path supplies the methods.
+
+
+def _index_fixture_graph() -> nx.DiGraph:
+ g = _envy_graph()
+ # A fallback-only file: method symbol nodes with NO defines edges.
+ g.add_node("legacy.py", node_type="file")
+ g.add_node(
+ "legacy.py::L.only",
+ node_type="symbol",
+ kind="method",
+ name="only",
+ parent_name="L",
+ file_path="legacy.py",
+ )
+ # A methodless file and a non-method symbol that must never appear.
+ g.add_node("empty.py", node_type="file")
+ g.add_node("t.py::free_fn", node_type="symbol", kind="function", name="free_fn")
+ return g
+
+
+def test_methods_index_matches_per_file_derivation():
+ from repowise.core.analysis.health.refactoring.graph_signals import build_methods_by_file
+
+ g = _index_fixture_graph()
+ index = build_methods_by_file(g)
+ det = MoveMethodDetector()
+ files = [n for n, d in g.nodes(data=True) if d.get("node_type") == "file"]
+ assert files
+ for f in files:
+ assert list(index.get(f, ())) == det._methods_in_file(g, f)
+ # The fallback-only file is served by the prefix scan.
+ assert index["legacy.py"] == ("legacy.py::L.only",)
+ assert "empty.py" not in index
+
+
+def test_detector_equal_with_and_without_provided_index():
+ from repowise.core.analysis.health.refactoring.graph_signals import build_methods_by_file
+
+ g = _envy_graph()
+ index = build_methods_by_file(g)
+ for f in ("c.py", "t.py"):
+ derived = MoveMethodDetector().detect(_ctx(g, f))
+ provided = MoveMethodDetector().detect(
+ RefactoringContext(
+ file_path=f,
+ language="python",
+ nloc=40,
+ graph=g,
+ file_methods=index.get(f, ()),
+ )
+ )
+ assert [(s.target_symbol, s.plan) for s in provided] == [
+ (s.target_symbol, s.plan) for s in derived
+ ]