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.

feat(performance): add causal opportunities (#1777)

Raghav Chamadiyacb09aa5335ae
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index fa3860d99..67161b044 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -45,6 +45,7 @@ from .incremental import (
_build_update_vector_store,
_load_stored_function_mod_p80,
_load_stored_git_meta,
+ _load_stored_performance_callers,
_rebuild_graph_and_git,
_refresh_knowledge_graph,
_run_partial_analysis,
@@ -1230,6 +1231,7 @@ def run_update(
file_diffs,
source_map,
stored_git_meta=_load_stored_git_meta(repo_path),
+ stored_performance_callers=_load_stored_performance_callers(repo_path, file_diffs),
repo_function_mod_p80=_load_stored_function_mod_p80(repo_path),
)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
index 9527f3984..5bd9395ef 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
@@ -172,6 +172,15 @@ def _load_stored_function_mod_p80(repo_path: Any) -> int | None:
return run_async(load_stored_function_mod_p80(repo_path, log=console.print))
+def _load_stored_performance_callers(repo_path: Any, file_diffs: list[Any]) -> set[str] | None:
+ """Old-side caller evidence for changed/deleted performance sinks."""
+ from repowise.core.pipeline.incremental import load_stored_performance_callers
+
+ changed_paths = {diff.path for diff in file_diffs}
+ changed_paths.update(diff.old_path for diff in file_diffs if getattr(diff, "old_path", None))
+ return run_async(load_stored_performance_callers(repo_path, changed_paths, log=console.print))
+
+
def _run_partial_analysis(
repo_path: Any,
graph_builder: Any,
@@ -180,6 +189,7 @@ def _run_partial_analysis(
file_diffs: list,
source_map: dict[str, bytes] | None = None,
stored_git_meta: dict[str, dict] | None = None,
+ stored_performance_callers: set[str] | None = None,
repo_function_mod_p80: int | None = None,
) -> tuple[Any, Any]:
"""Run partial code-health + repo-wide dead-code analysis.
@@ -200,6 +210,7 @@ def _run_partial_analysis(
file_diffs,
source_map=source_map,
stored_git_meta=stored_git_meta,
+ stored_performance_callers=stored_performance_callers,
repo_function_mod_p80=repo_function_mod_p80,
log=console.print,
)
diff --git a/packages/core/src/repowise/core/analysis/execution_flows.py b/packages/core/src/repowise/core/analysis/execution_flows.py
index 0a68c35a2..9fb4d42e9 100644
--- a/packages/core/src/repowise/core/analysis/execution_flows.py
+++ b/packages/core/src/repowise/core/analysis/execution_flows.py
@@ -15,6 +15,10 @@ from typing import Literal, get_args
import networkx as nx
import structlog
+from repowise.core.analysis.execution_graph import (
+ is_excluded_execution_path,
+ is_walkable_execution_edge,
+)
from repowise.core.ids import file_path_of
log = structlog.get_logger(__name__)
@@ -27,28 +31,19 @@ _MIN_ENTRY_POINT_SCORE = 0.3
# Name patterns for entry point scoring (compiled once)
_TIER1_NAMES = re.compile(
- r"^(main|run|start|serve|cli|__main__|app|execute|bootstrap|init)$", re.IGNORECASE,
+ r"^(main|run|start|serve|cli|__main__|app|execute|bootstrap|init)$",
+ re.IGNORECASE,
)
_TIER2_NAMES = re.compile(
- r"^(handle_|on_|dispatch_|process_|route_|do_)", re.IGNORECASE,
+ r"^(handle_|on_|dispatch_|process_|route_|do_)",
+ re.IGNORECASE,
)
_TIER3_NAMES = re.compile(
- r"^(get_|create_|execute_|invoke_|fetch_|submit_|send_|post_)", re.IGNORECASE,
-)
-
-# Files to exclude from entry point scoring — test, demo, fixture, etc.
-_EXCLUDE_PATH_PATTERNS = re.compile(
- r"("
- r"test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|"
- r"fixture[s]?[/.]|mock[s]?[/.]|stub[s]?[/.]|fake[s]?[/.]|"
- r"demo[_/.]|example[s]?[/.]|sample[s]?[/.]|"
- r"benchmark[s]?[/.]|_bench\.|"
- r"scripts?/"
- r")",
+ r"^(get_|create_|execute_|invoke_|fetch_|submit_|send_|post_)",
re.IGNORECASE,
)
-
+# Files to exclude from entry point scoring — test, demo, fixture, etc.
# ---------------------------------------------------------------------------
# Why a trace stopped
# ---------------------------------------------------------------------------
@@ -71,7 +66,7 @@ FlowTermination = Literal[
"confidence_filtered",
# Every successor was a test/demo/fixture node.
"excluded_target",
- # No outgoing call edges were recorded. Deliberately not called a leaf: a
+ # No outgoing execution edges were recorded. Deliberately not called a leaf: a
# symbol whose calls we failed to resolve looks exactly like this, and
# asserting the code has no callees is the claim we cannot make.
"no_callees",
@@ -174,7 +169,9 @@ def _build_call_degree_maps(
out_deg: dict[str, int] = defaultdict(int)
in_deg: dict[str, int] = defaultdict(int)
for u, v, d in graph.edges(data=True):
- if d.get("edge_type") == "calls":
+ if is_walkable_execution_edge(
+ d.get("edge_type"), d.get("resolution_origin"), d.get("confidence")
+ ):
out_deg[u] += 1
in_deg[v] += 1
return out_deg, in_deg
@@ -192,7 +189,7 @@ def _is_excluded_node(graph: nx.DiGraph, node_id: str) -> bool:
"""
data = graph.nodes.get(node_id, {})
file_path = data.get("file_path") or file_path_of(node_id) or ""
- return bool(_EXCLUDE_PATH_PATTERNS.search(file_path))
+ return is_excluded_execution_path(file_path)
def _score_entry_point(
@@ -209,7 +206,7 @@ def _score_entry_point(
if data.get("node_type") == "external":
return 0.0
file_path = data.get("file_path", "") or ""
- if _EXCLUDE_PATH_PATTERNS.search(file_path):
+ if is_excluded_execution_path(file_path):
return 0.0
# Signal 1: Fan-out ratio (weight 0.35)
@@ -277,21 +274,23 @@ class _Successors:
def _get_call_successors(
- node_id: str, graph: nx.DiGraph, out_deg: dict[str, int],
+ node_id: str,
+ graph: nx.DiGraph,
+ out_deg: dict[str, int],
) -> _Successors:
"""Get outgoing call targets, sorted by out-degree descending.
Test/demo/fixture nodes are dropped so traces stay on production code
- even when a call edge mis-resolves to a test fake (e.g. a fake
+ even when an execution edge mis-resolves to a test fake (e.g. a fake
``fetchall`` in a unit test).
"""
successors = []
low_confidence: Counter = Counter()
excluded = 0
for _, target, d in graph.out_edges(node_id, data=True):
- if d.get("edge_type") != "calls":
- continue
- if d.get("confidence", 0) < 0.5:
+ if not is_walkable_execution_edge(
+ d.get("edge_type"), d.get("resolution_origin"), d.get("confidence")
+ ):
low_confidence[d.get("resolution_origin") or "unlabelled"] += 1
continue
if _is_excluded_node(graph, target):
@@ -311,7 +310,7 @@ def _bfs_trace(
config: FlowConfig,
out_deg: dict[str, int],
) -> ExecutionFlow | None:
- """Trace from an entry point following call edges.
+ """Trace from an entry point following reliable execution edges.
Follows the highest-fan-out successor at each step to build
the primary execution path.
@@ -376,9 +375,7 @@ def _bfs_trace(
communities_visited=communities_seen,
termination=termination,
termination_detail=(
- dict(successors.low_confidence)
- if termination == "confidence_filtered"
- else {}
+ dict(successors.low_confidence) if termination == "confidence_filtered" else {}
),
)
@@ -417,7 +414,7 @@ def trace_execution_flows(
"""Trace execution flows from top-scored entry points.
Args:
- graph: The full dependency graph with symbol nodes and call edges.
+ graph: The full dependency graph with symbol nodes and execution edges.
community_map: {node_id: community_id} from community detection.
config: Optional flow tracing configuration.
@@ -429,7 +426,9 @@ def trace_execution_flows(
if graph.number_of_nodes() == 0:
return ExecutionFlowReport(
- total_entry_points_scored=0, total_flows=0, flows=[],
+ total_entry_points_scored=0,
+ total_flows=0,
+ flows=[],
)
out_deg, in_deg = _build_call_degree_maps(graph)
@@ -457,7 +456,7 @@ def trace_execution_flows(
# whether it produced a long enough trace below.
entry_point_scores = {node_id: score for node_id, score in candidates}
- top_candidates = candidates[:config.max_flows]
+ top_candidates = candidates[: config.max_flows]
# Trace from each candidate
flows: list[ExecutionFlow] = []
diff --git a/packages/core/src/repowise/core/analysis/execution_graph.py b/packages/core/src/repowise/core/analysis/execution_graph.py
index a049ac53e..5a1a35c5e 100644
--- a/packages/core/src/repowise/core/analysis/execution_graph.py
+++ b/packages/core/src/repowise/core/analysis/execution_graph.py
@@ -16,6 +16,7 @@ do not pay for their own graph build or sort.
from __future__ import annotations
+import re
from collections import deque
from collections.abc import Callable, Hashable, Iterable, Mapping
from dataclasses import dataclass
@@ -24,6 +25,13 @@ from typing import Any, Literal, TypeVar
from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES
UNRELIABLE_EXECUTION_ORIGINS = frozenset({"global_unique"})
+_EXCLUDED_EXECUTION_PATHS = re.compile(
+ r"(test[s_/]|_test\.|\.test\.|\.spec\.|__tests__|conftest|"
+ r"fixture[s]?[/.]|mock[s]?[/.]|stub[s]?[/.]|fake[s]?[/.]|"
+ r"demo[_/.]|example[s]?[/.]|sample[s]?[/.]|benchmark[s]?[/.]|"
+ r"_bench\.|scripts?/)",
+ re.IGNORECASE,
+)
CallTargetBasis = Literal["call-site", "name-fallback"]
_KeyT = TypeVar("_KeyT", bound=Hashable)
@@ -45,6 +53,30 @@ def is_reliable_execution_edge(edge_type: str | None, resolution_origin: str | N
)
+def is_reliable_call_edge(edge_type: str | None, resolution_origin: str | None = None) -> bool:
+ """Whether an edge is a resolved call, excluding weaker execution relations."""
+ return edge_type == "calls" and resolution_origin not in UNRELIABLE_EXECUTION_ORIGINS
+
+
+def is_walkable_execution_edge(
+ edge_type: str | None,
+ resolution_origin: str | None = None,
+ confidence: float | None = None,
+ *,
+ minimum_confidence: float = 0.5,
+) -> bool:
+ """Execution-flow edge policy shared by memory, DB, and export adapters."""
+ return (
+ is_reliable_execution_edge(edge_type, resolution_origin)
+ and float(confidence or 0.0) >= minimum_confidence
+ )
+
+
+def is_excluded_execution_path(path: str) -> bool:
+ """Whether a flow target is test/demo/fixture/tooling material."""
+ return bool(_EXCLUDED_EXECUTION_PATHS.search(path))
+
+
def _append_unique(
adjacency: dict[_KeyT, list[str]],
source: _KeyT,
@@ -279,6 +311,62 @@ class ExecutionGraphIndex:
"name-fallback",
)
+ def affected_files(
+ self,
+ changed_files: Iterable[str],
+ *,
+ forward_depth: int = 3,
+ reverse_depth: int = 4,
+ ) -> set[str]:
+ """Files whose bounded execution facts can change with *changed_files*.
+
+ Forward closure covers a changed caller with an unchanged sink; reverse
+ closure covers unchanged loop owners whose sink/helper changed. Both
+ traversals are multi-source and visit each reached node once, avoiding
+ a graph walk per finding.
+ """
+ changed = set(changed_files)
+ seeds = {symbol for path in changed for symbol in self.declares.get(path, ())}
+ affected = set(changed)
+
+ def walk(adjacency: Mapping[str, Iterable[str]], start: set[str], depth: int) -> set[str]:
+ if depth <= 0 or not start:
+ return set(start)
+ seen = set(start)
+ queue: deque[tuple[str, int]] = deque((seed, 0) for seed in sorted(start))
+ while queue:
+ node, distance = queue.popleft()
+ affected.add(file_of_symbol(node))
+ if distance >= depth:
+ continue
+ for neighbor in adjacency.get(node, ()):
+ affected.add(file_of_symbol(neighbor))
+ if neighbor not in seen:
+ seen.add(neighbor)
+ queue.append((neighbor, distance + 1))
+ return seen
+
+ forward_reached = walk(self.forward, seeds, forward_depth)
+ # Reverse from the entire reached frontier, not only the changed
+ # symbols. If A and B both call an unchanged sink, changing A must pull
+ # B into the recomputed causal group so its totals stay authoritative.
+ walk(self.reverse, forward_reached, reverse_depth)
+ return affected
+
+ def forward_reachable(self, seeds: Iterable[str], *, max_depth: int | None = None) -> set[str]:
+ """Reliable execution nodes reachable from all *seeds* in one BFS."""
+ reached = set(seeds)
+ queue: deque[tuple[str, int]] = deque((seed, 0) for seed in sorted(reached))
+ while queue:
+ node, depth = queue.popleft()
+ if max_depth is not None and depth >= max_depth:
+ continue
+ for target in self.forward.get(node, ()):
+ if target not in reached:
+ reached.add(target)
+ queue.append((target, depth + 1))
+ return reached
+
@dataclass(frozen=True, slots=True)
class ReachInfo:
@@ -344,7 +432,10 @@ __all__ = [
"ExecutionGraphIndex",
"ReachInfo",
"file_of_symbol",
+ "is_excluded_execution_path",
+ "is_reliable_call_edge",
"is_reliable_execution_edge",
+ "is_walkable_execution_edge",
"module_node_id",
"path_to_sink",
"reachable_to_sink",
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py b/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py
index 029fcc5ca..7f0fbcbff 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py
@@ -80,6 +80,7 @@ class BlockingIoUnderLockDetector:
"boundary_kind": hit.detail,
"cross_function": True,
"path": list(hit.path),
+ "resolution_basis": hit.resolution_basis,
},
reason=(
f"{phrasing} is reached while a lock is held, through "
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
index 796ded42d..cf5c7c1f3 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
@@ -91,6 +91,7 @@ class IoInLoopDetector:
"boundary_kind": hit.detail,
"cross_function": True,
"path": list(hit.path),
+ "resolution_basis": hit.resolution_basis,
},
reason=(
f"{phrasing} is reached once per loop iteration through "
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index 2ea2fb79f..942dac289 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -208,6 +208,11 @@ class PerfHit:
# chain ``A -> B -> ... -> sink`` (PR4). Empty for same-function hits —
# its emptiness is what distinguishes the two cases downstream.
path: tuple[str, ...] = ()
+ # How the first interprocedural hop was resolved. ``direct`` is the
+ # same-function default; cross-function bridges set ``call-site`` or the
+ # labelled legacy ``name-fallback``. Ranking can therefore use provenance
+ # without re-reading or re-walking the graph.
+ resolution_basis: str = "direct"
# Set by the dataflow promotion pass (``perf.promotion``) when intra-
# procedural reaching definitions PROVE the enclosing loop carries no data
# dependence between iterations, turning an advisory "if the iterations are
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 49a5122c0..883563ce3 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -49,14 +49,17 @@ from .perf import (
CallGraphIndex,
PerfRanker,
apply_perf_promotions,
+ build_performance_opportunities,
collect_blocking_io_under_lock,
collect_centrality_gated,
collect_crossfn_io_in_loop,
+ link_performance_findings,
)
from .refactoring import (
RefactoringContext,
RefactoringSuggestion,
detect_refactorings,
+ performance_fix_suggestions,
rank_suggestions,
)
from .refactoring.graph_signals import build_file_scc_index, build_methods_by_file
@@ -93,7 +96,10 @@ log = structlog.get_logger(__name__)
# values are wrong again on an index stamped 2 - this time in both directions.
# 4: performance now uses reliable execution edges and exact call-site identity,
# so cross-function findings produced by the calls-only graph must be refreshed.
-HEALTH_ANALYZER_VERSION = 4
+# 5: raw performance findings gain stable causal linkage and structured
+# performance-fix plans; incremental execution slices widen to preserve those
+# interprocedural interpretations.
+HEALTH_ANALYZER_VERSION = 5
# Method-level smells that make the dataflow / Extract Method pass worthwhile.
# Only files carrying one of these get a CFG + def/use + reaching pass built.
@@ -123,8 +129,6 @@ def _log_duplication_diagnostics(report: DuplicationReport) -> None:
log.debug("health_duplication_limits", **diag)
-
-
def _read_source_lines(abs_path: str) -> list[str] | None:
"""Read a file's source as 1-indexed lines for the Extract Helper snippet.
@@ -305,6 +309,7 @@ class HealthAnalyzer:
self,
graph: Any, # networkx.DiGraph
git_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,
module_map: dict[str, str] | None = None,
@@ -313,6 +318,7 @@ class HealthAnalyzer:
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
+ self.performance_git_meta_map = performance_git_meta_map or self.git_meta_map
self.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,
@@ -357,13 +363,9 @@ class HealthAnalyzer:
``analysis.test_reachability``.
"""
if self._tests_reach_cache is None:
- test_files = {
- pf.file_info.path for pf in self.parsed_files if pf.file_info.is_test
- }
+ test_files = {pf.file_info.path for pf in self.parsed_files if pf.file_info.is_test}
index = self._execution_graph()
- self._tests_reach_cache = files_reached_by_tests(
- index or CallGraphIndex(), test_files
- )
+ self._tests_reach_cache = files_reached_by_tests(index or CallGraphIndex(), test_files)
return self._tests_reach_cache
def _package_boundaries(self, analyzed_paths: set[str]) -> set[str]:
@@ -557,6 +559,17 @@ class HealthAnalyzer:
else:
kpis = {}
+ self._mark_perf_entry_reachability(findings)
+ link_performance_findings(findings)
+ opportunities = build_performance_opportunities(findings)
+ if refactoring_enabled and "performance_fix" not in disabled_refactorings:
+ suggestions.extend(
+ performance_fix_suggestions(
+ opportunities,
+ nloc_by_file={metric.file_path: metric.nloc for metric in metrics},
+ min_confidence=refactoring_min_confidence,
+ )
+ )
suggestions = rank_suggestions(
suggestions, centrality=self._refactoring_centrality(suggestions)
)
@@ -740,6 +753,17 @@ class HealthAnalyzer:
else:
kpis = {}
+ self._mark_perf_entry_reachability(findings)
+ link_performance_findings(findings)
+ opportunities = build_performance_opportunities(findings)
+ if refactoring_enabled and "performance_fix" not in disabled_refactorings:
+ suggestions.extend(
+ performance_fix_suggestions(
+ opportunities,
+ nloc_by_file={metric.file_path: metric.nloc for metric in metrics},
+ min_confidence=refactoring_min_confidence,
+ )
+ )
suggestions = rank_suggestions(
suggestions, centrality=self._refactoring_centrality(suggestions)
)
@@ -805,7 +829,7 @@ class HealthAnalyzer:
):
for path, hits in src.items():
by_file.setdefault(path, []).extend(hits)
- ranker = PerfRanker(index, self.git_meta_map)
+ ranker = PerfRanker(index, self.performance_git_meta_map)
for path, hits in collect_centrality_gated(walked, ranker).items():
by_file.setdefault(path, []).extend(hits)
for _pf, fcx in walked:
@@ -816,6 +840,29 @@ class HealthAnalyzer:
log.debug("health_crossfn_perf_failed", error=str(exc))
return
+ def _mark_perf_entry_reachability(self, findings: list[HealthFindingData]) -> None:
+ """Stamp reliable entry reachability without walking once per row."""
+ index = self._execution_graph()
+ if index is None or self.graph is None:
+ return
+ entry_files: set[str] = set()
+ try:
+ for node_id, data in self.graph.nodes(data=True):
+ if data.get("node_type") == "file" and data.get("is_entry_point"):
+ entry_files.add(node_id)
+ except Exception:
+ return
+ seeds = {symbol for path in entry_files for symbol in index.declares.get(path, ())}
+ if not seeds:
+ return
+ reachable = index.forward_reachable(seeds)
+ for finding in findings:
+ if finding.dimension != "performance":
+ continue
+ path = finding.details.get("path")
+ if isinstance(path, list) and path:
+ finding.details["reliable_entry_reachability"] = path[0] in reachable
+
def _function_blame_rows(self, walked: list[tuple[Any, FileComplexity]]) -> list[dict]:
"""Build the per-function blame rollup from the walked files + the
FULL-tier blame indexes attached to ``git_meta_map``.
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index 59d50d462..d92befb1c 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -86,3 +86,8 @@ class HealthReport:
# to the ``coverage_files`` table. Empty when no coverage was ingested.
coverage_files: list[Any] = field(default_factory=list)
coverage_format: str | None = None
+ # Incremental writers replace all dimensions only for ``authoritative_paths``.
+ # ``performance_authoritative_paths`` may be wider: the bounded execution
+ # closure whose performance rows/plans were recomputed for full parity.
+ authoritative_paths: set[str] = field(default_factory=set)
+ performance_authoritative_paths: set[str] = field(default_factory=set)
diff --git a/packages/core/src/repowise/core/analysis/health/perf/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
index 2fc06c919..b47a540d1 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
@@ -21,6 +21,12 @@ from .crossfn import collect_crossfn_io_in_loop
from .dialects import PERF_DIALECTS, BasePerfDialect
from .gated import collect_blocking_io_under_lock, collect_centrality_gated
from .io_boundaries import collect_io_names
+from .opportunities import (
+ PerformanceFix,
+ PerformanceOpportunity,
+ build_performance_opportunities,
+ link_performance_findings,
+)
from .promotion import apply_perf_promotions
from .ranking import PerfRanker
from .reachability import ReachInfo, path_to_sink, reachable_to_sink
@@ -30,12 +36,16 @@ __all__ = [
"BasePerfDialect",
"CallGraphIndex",
"PerfRanker",
+ "PerformanceFix",
+ "PerformanceOpportunity",
"ReachInfo",
"apply_perf_promotions",
+ "build_performance_opportunities",
"collect_blocking_io_under_lock",
"collect_centrality_gated",
"collect_crossfn_io_in_loop",
"collect_io_names",
+ "link_performance_findings",
"path_to_sink",
"reachable_to_sink",
]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
index db607c5c0..8660076ff 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
@@ -154,7 +154,7 @@ def _hits_for_function(
for target_name, call_line in fact.loop_call_targets:
if target_name in seen:
continue
- targets, _basis = index.resolve_call_targets(a_sid, call_line, target_name)
+ targets, basis = index.resolve_call_targets(a_sid, call_line, target_name)
for callee in targets:
info = reach.get(callee)
if info is None:
@@ -171,6 +171,7 @@ def _hits_for_function(
function=fact.function,
detail=kind,
path=(a_sid, *chain),
+ resolution_basis=basis,
)
)
break
diff --git a/packages/core/src/repowise/core/analysis/health/perf/gated.py b/packages/core/src/repowise/core/analysis/health/perf/gated.py
index fd2d90afc..5e2203fd5 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/gated.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py
@@ -175,7 +175,7 @@ def _lock_hits_for_function(
for target_name, call_line in fact.lock_call_targets:
if target_name in seen:
continue
- targets, _basis = index.resolve_call_targets(a_sid, call_line, target_name)
+ targets, basis = index.resolve_call_targets(a_sid, call_line, target_name)
for callee in targets:
info = reach.get(callee)
if info is None:
@@ -193,6 +193,7 @@ def _lock_hits_for_function(
detail=kind,
func_start=fact.func_start,
path=(a_sid, *chain),
+ resolution_basis=basis,
)
)
break
diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
new file mode 100644
index 000000000..046f1586c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
@@ -0,0 +1,373 @@
+"""Deterministic causal read model over raw performance findings.
+
+Raw health findings remain the line-level source of truth. This module folds
+them once into bounded, ranked opportunities so repeated caller paths to one
+sink lead an agent to one intervention. It is deliberately persistence-
+agnostic: analyzer dataclasses, ORM rows, and lightweight SQL rows are accepted
+through the same attribute adapter.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from collections import defaultdict
+from dataclasses import dataclass
+from math import log2
+from typing import Any, Literal
+
+from repowise.core.test_paths import is_test_related_path
+
+ExecutionContext = Literal["production", "tooling", "test"]
+FixSafety = Literal["proven", "advisory"]
+FixStrategy = Literal[
+ "parallelize_independent_awaits",
+ "replace_membership_collection",
+ "buffer_string_accumulation",
+ "hoist_loop_invariant_resource",
+ "batch_or_prefetch_io",
+ "shrink_lock_scope",
+]
+
+_TOOLING_PARTS = frozenset(
+ {".github", "benchmarks", "build", "devtools", "scripts", "tooling", "tools"}
+)
+_BOUNDARY_POINTS = {"subprocess": 5, "network": 4, "db": 4, "lock": 3, "filesystem": 2}
+_MULTIPLIER_POINTS = {
+ "nested_loop_with_io": 6,
+ "nested_loop_quadratic": 6,
+ "blocking_io_under_lock": 5,
+ "io_in_loop": 4,
+ "serial_await_in_loop": 4,
+ "resource_construction_in_loop": 4,
+ "membership_test_against_list_in_loop": 3,
+ "string_concat_in_loop": 3,
+ "lock_in_loop": 2,
+}
+_CONTEXT_POINTS = {"production": 3, "tooling": 2, "test": 1}
+_PROVENANCE_POINTS = {"call-site": 3, "direct": 3, "reliable-edge": 2, "name-fallback": 0}
+
+
+@dataclass(frozen=True, slots=True)
+class PerformanceFix:
+ strategy: FixStrategy
+ safety: FixSafety
+ rationale: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {"strategy": self.strategy, "safety": self.safety, "rationale": self.rationale}
+
+
+@dataclass(frozen=True, slots=True)
+class PerformanceOpportunity:
+ opportunity_id: str
+ biomarker_type: str
+ biomarker_types: tuple[str, ...]
+ boundary_kind: str | None
+ execution_context: ExecutionContext
+ terminal_sink: str | None
+ shared_path_suffix: tuple[str, ...]
+ intervention_symbol: str | None
+ affected_call_sites_total: int
+ affected_files_total: int
+ observations_total: int
+ evidence: tuple[dict[str, Any], ...]
+ evidence_truncated: bool
+ reliable_entry_reachability: bool | None
+ provenance: str
+ rank_score: int
+ rank_factors: dict[str, int]
+ fix: PerformanceFix | None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "opportunity_id": self.opportunity_id,
+ "biomarker_type": self.biomarker_type,
+ "biomarker_types": list(self.biomarker_types),
+ "boundary_kind": self.boundary_kind,
+ "execution_context": self.execution_context,
+ "terminal_sink": self.terminal_sink,
+ "shared_path_suffix": list(self.shared_path_suffix),
+ "intervention_symbol": self.intervention_symbol,
+ "affected_call_sites_total": self.affected_call_sites_total,
+ "affected_files_total": self.affected_files_total,
+ "observations_total": self.observations_total,
+ "evidence": list(self.evidence),
+ "evidence_truncated": self.evidence_truncated,
+ "reliable_entry_reachability": self.reliable_entry_reachability,
+ "provenance": self.provenance,
+ "rank_score": self.rank_score,
+ "rank_factors": dict(self.rank_factors),
+ "fix": self.fix.as_dict() if self.fix else None,
+ }
+
+
+def _attr(row: Any, name: str, default: Any = None) -> Any:
+ if isinstance(row, dict):
+ return row.get(name, default)
+ return getattr(row, name, default)
+
+
+def _details(row: Any) -> dict[str, Any]:
+ value = _attr(row, "details", None)
+ if isinstance(value, dict):
+ return value
+ raw = _attr(row, "details_json", None)
+ if isinstance(raw, str):
+ try:
+ loaded = json.loads(raw)
+ return loaded if isinstance(loaded, dict) else {}
+ except (TypeError, ValueError):
+ return {}
+ return {}
+
+
+def execution_context(file_path: str) -> ExecutionContext:
+ if is_test_related_path(file_path):
+ return "test"
+ parts = {part.lower() for part in file_path.replace("\\", "/").split("/")}
+ if parts & _TOOLING_PARTS or "/cli/" in f"/{file_path.lower().replace(chr(92), '/')}/":
+ return "tooling"
+ return "production"
+
+
+def _stable_id(key: tuple[Any, ...]) -> str:
+ payload = json.dumps(key, separators=(",", ":"), ensure_ascii=True)
+ return "perf_" + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:20]
+
+
+def _cost_shape(marker: str) -> str:
+ """Compatibility family for observations that may share one intervention."""
+ if marker in {"io_in_loop", "nested_loop_with_io"}:
+ return "repeated_io"
+ return marker
+
+
+def _causal_key(row: Any) -> tuple[Any, ...]:
+ details = _details(row)
+ marker = str(_attr(row, "biomarker_type", ""))
+ file_path = str(_attr(row, "file_path", ""))
+ context = execution_context(file_path)
+ path = tuple(str(node) for node in details.get("path", ()) if isinstance(node, str))
+ boundary = details.get("boundary_kind") or None
+ if details.get("cross_function") and path:
+ # Membership is immutable under caller churn: a new caller changes the
+ # evidence and common suffix, never the identity of the shared cause.
+ return ("cross-function", context, _cost_shape(marker), boundary, path[-1])
+ return (
+ "local",
+ context,
+ marker,
+ boundary,
+ file_path,
+ _attr(row, "function_name", None),
+ _attr(row, "line_start", None),
+ )
+
+
+def opportunity_id_for_finding(row: Any) -> str:
+ return _stable_id(_causal_key(row))
+
+
+def link_performance_findings(findings: list[Any]) -> None:
+ """Attach the causal id to analyzer findings before they are persisted."""
+ for finding in findings:
+ if _attr(finding, "dimension", None) != "performance":
+ continue
+ details = _details(finding)
+ details["opportunity_id"] = opportunity_id_for_finding(finding)
+
+
+def _shared_suffix(paths: list[tuple[str, ...]]) -> tuple[str, ...]:
+ if not paths:
+ return ()
+ common: list[str] = []
+ for nodes in zip(*(reversed(path) for path in paths), strict=False):
+ if len(set(nodes)) != 1:
+ break
+ common.append(nodes[0])
+ return tuple(reversed(common))
+
+
+def _evidence(row: Any, details: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "file_path": str(_attr(row, "file_path", "")),
+ "function_name": _attr(row, "function_name", None),
+ "line_start": _attr(row, "line_start", None),
+ "line_end": _attr(row, "line_end", None),
+ "path": list(details.get("path", ())),
+ "provenance": details.get("resolution_basis", "direct"),
+ }
+
+
+def _fix_for(
+ marker: str,
+ markers: tuple[str, ...],
+ boundary: str | None,
+ details: list[dict[str, Any]],
+ *,
+ cross_function: bool,
+ shared_suffix: tuple[str, ...],
+) -> PerformanceFix | None:
+ if marker == "serial_await_in_loop" and all(d.get("dataflow_verified") for d in details):
+ return PerformanceFix(
+ "parallelize_independent_awaits",
+ "proven",
+ "Dataflow proves that every observed loop carries no cross-iteration dependence.",
+ )
+ if marker == "membership_test_against_list_in_loop":
+ return PerformanceFix(
+ "replace_membership_collection",
+ "advisory",
+ "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
+ )
+ if marker == "string_concat_in_loop":
+ return PerformanceFix(
+ "buffer_string_accumulation",
+ "advisory",
+ "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
+ )
+ if set(markers) <= {"io_in_loop", "nested_loop_with_io"} and boundary in {
+ "db",
+ "network",
+ }:
+ if cross_function and len(shared_suffix) < 2:
+ # A generic terminal resource/API shared by otherwise unrelated
+ # callers (for example ``get_session``) is evidence of repeated
+ # cost, but not proof that editing that sink is one coherent
+ # intervention. Keep the opportunity visible without claiming a
+ # batch plan.
+ return None
+ return PerformanceFix(
+ "batch_or_prefetch_io",
+ "advisory",
+ "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ )
+ if marker == "blocking_io_under_lock":
+ path_starts = {
+ path[0] for detail in details if (path := detail.get("path")) and isinstance(path, list)
+ }
+ if cross_function and len(path_starts) != 1:
+ return None
+ return PerformanceFix(
+ "shrink_lock_scope",
+ "advisory",
+ "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
+ )
+ if marker == "resource_construction_in_loop" and all(
+ d.get("resource_invariant") is True for d in details
+ ):
+ return PerformanceFix(
+ "hoist_loop_invariant_resource",
+ "proven",
+ "Dataflow proves construction arguments and lifetime are loop invariant.",
+ )
+ return None
+
+
+def build_performance_opportunities(
+ findings: list[Any], *, evidence_limit: int = 8
+) -> list[PerformanceOpportunity]:
+ """Group and rank performance rows in one deterministic pass."""
+ groups: dict[tuple[Any, ...], list[Any]] = defaultdict(list)
+ for row in findings:
+ if _attr(row, "dimension", None) == "performance":
+ groups[_causal_key(row)].append(row)
+
+ opportunities: list[PerformanceOpportunity] = []
+ cap = max(0, evidence_limit)
+ for key, rows in groups.items():
+ rows.sort(
+ key=lambda row: (
+ str(_attr(row, "file_path", "")),
+ _attr(row, "line_start", None) or 0,
+ str(_attr(row, "function_name", "")),
+ )
+ )
+ detail_rows = [_details(row) for row in rows]
+ paths = [
+ tuple(str(node) for node in details.get("path", ()) if isinstance(node, str))
+ for details in detail_rows
+ if details.get("path")
+ ]
+ suffix = _shared_suffix(paths)
+ markers = tuple(sorted({str(_attr(row, "biomarker_type", "")) for row in rows}))
+ marker = min(markers, key=lambda value: (-_MULTIPLIER_POINTS.get(value, 1), value))
+ boundary = detail_rows[0].get("boundary_kind") or None
+ context = execution_context(str(_attr(rows[0], "file_path", "")))
+ sites = {
+ (
+ str(_attr(row, "file_path", "")),
+ _attr(row, "line_start", None),
+ _attr(row, "function_name", None),
+ )
+ for row in rows
+ }
+ files = {site[0] for site in sites}
+ reach_values = {d.get("reliable_entry_reachability") for d in detail_rows}
+ reachable: bool | None = (
+ True if True in reach_values else (False if reach_values == {False} else None)
+ )
+ provenances = {str(d.get("resolution_basis", "direct")) for d in detail_rows}
+ provenance = min(provenances, key=lambda value: (_PROVENANCE_POINTS.get(value, 0), value))
+ factors = {
+ "multiplier_shape": _MULTIPLIER_POINTS.get(marker, 1),
+ "boundary_kind": _BOUNDARY_POINTS.get(boundary or "", 0),
+ "execution_context": _CONTEXT_POINTS[context],
+ "entry_reachability": 3 if reachable is True else 0,
+ "affected_call_sites": min(8, int(log2(len(sites) + 1) * 2)),
+ "provenance": _PROVENANCE_POINTS.get(provenance, 0),
+ }
+ evidence = tuple(
+ _evidence(row, details)
+ for row, details in zip(rows[:cap], detail_rows[:cap], strict=True)
+ )
+ opportunities.append(
+ PerformanceOpportunity(
+ opportunity_id=_stable_id(key),
+ biomarker_type=marker,
+ biomarker_types=markers,
+ boundary_kind=boundary,
+ execution_context=context,
+ terminal_sink=paths[0][-1] if paths else None,
+ shared_path_suffix=suffix,
+ intervention_symbol=suffix[0] if suffix else None,
+ affected_call_sites_total=len(sites),
+ affected_files_total=len(files),
+ observations_total=len(rows),
+ evidence=evidence,
+ evidence_truncated=len(rows) > cap,
+ reliable_entry_reachability=reachable,
+ provenance=provenance,
+ rank_score=sum(factors.values()),
+ rank_factors=factors,
+ fix=_fix_for(
+ marker,
+ markers,
+ boundary,
+ detail_rows,
+ cross_function=key[0] == "cross-function",
+ shared_suffix=suffix,
+ ),
+ )
+ )
+ opportunities.sort(
+ key=lambda item: (
+ -item.rank_score,
+ -item.affected_call_sites_total,
+ item.opportunity_id,
+ )
+ )
+ return opportunities
+
+
+__all__ = [
+ "FixSafety",
+ "FixStrategy",
+ "PerformanceFix",
+ "PerformanceOpportunity",
+ "build_performance_opportunities",
+ "execution_context",
+ "link_performance_findings",
+ "opportunity_id_for_finding",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
index 7cebdcd7b..69cf339ce 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/__init__.py
@@ -27,6 +27,7 @@ from .models import (
RefactoringContext,
RefactoringSuggestion,
)
+from .performance_fix import performance_fix_suggestions
from .rank import rank_suggestions
from .registry import (
RefactoringDetector,
@@ -44,6 +45,7 @@ __all__ = [
"build_file_scc_index",
"detect_refactorings",
"effort_bucket",
+ "performance_fix_suggestions",
"rank_suggestions",
"register",
"registered_detectors",
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 bce009cbb..f3d84460e 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
@@ -30,6 +30,8 @@ from __future__ import annotations
from typing import Any
+from repowise.core.analysis.execution_graph import is_reliable_call_edge
+
from ....test_paths import is_test_related_path
from .models import RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, effort_bucket, register
@@ -178,7 +180,10 @@ class MoveMethodDetector(RefactoringDetector):
# Group the method's class-owned callees by the class they belong to.
accessed_by_class: dict[str, set[str]] = {}
for _u, callee, edata in graph.out_edges(method_id, data=True):
- if edata.get("edge_type") != "calls" or callee == method_id:
+ if (
+ not is_reliable_call_edge(edata.get("edge_type"), edata.get("resolution_origin"))
+ or callee == method_id
+ ):
continue
owner = _owning_class_id(graph, callee)
if owner is None:
@@ -275,7 +280,7 @@ class MoveMethodDetector(RefactoringDetector):
count = 0
if method_id in graph:
for _u, _v, data in graph.in_edges(method_id, data=True):
- if data.get("edge_type") == "calls":
+ if is_reliable_call_edge(data.get("edge_type"), data.get("resolution_origin")):
count += 1
return count
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py b/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py
new file mode 100644
index 000000000..525ab6345
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/performance_fix.py
@@ -0,0 +1,104 @@
+"""Structured refactoring plans for safely describable performance fixes."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+
+from repowise.core.analysis.execution_graph import file_of_symbol
+
+from ..perf.opportunities import PerformanceOpportunity
+from .models import RefactoringSuggestion
+from .registry import effort_bucket
+
+
+def performance_fix_suggestions(
+ opportunities: Iterable[PerformanceOpportunity],
+ *,
+ nloc_by_file: Mapping[str, int] | None = None,
+ min_confidence: str | None = None,
+) -> list[RefactoringSuggestion]:
+ """Convert opportunities with a safe strategy into one closed plan type.
+
+ This is intentionally a repo-level service, not a per-file detector: one
+ cross-function cause can address observations in many caller files.
+ """
+ nloc_by_file = nloc_by_file or {}
+ confidence_order = {"low": 0, "medium": 1, "high": 2}
+ floor = confidence_order.get((min_confidence or "").lower(), 0)
+ out: list[RefactoringSuggestion] = []
+ for opportunity in opportunities:
+ fix = opportunity.fix
+ if fix is None or not opportunity.evidence:
+ continue
+ confidence = "high" if fix.safety == "proven" else "medium"
+ if confidence_order[confidence] < floor:
+ continue
+ anchor = opportunity.evidence[0]
+ intervention = opportunity.intervention_symbol
+ if fix.strategy == "shrink_lock_scope" and anchor.get("path"):
+ # The lock owner is the first node in the proven lock-to-I/O path;
+ # editing a shared downstream sink would not shorten its critical
+ # section. Opportunity construction only emits this plan when all
+ # grouped paths have the same owner.
+ intervention = anchor["path"][0]
+ target_file = file_of_symbol(intervention) if intervention else anchor["file_path"]
+ locations = [
+ {
+ "file_path": item["file_path"],
+ "function_name": item.get("function_name"),
+ "line_start": item.get("line_start"),
+ "line_end": item.get("line_end"),
+ }
+ for item in opportunity.evidence
+ ]
+ paths = [item["path"] for item in opportunity.evidence if item.get("path")]
+ out.append(
+ RefactoringSuggestion(
+ refactoring_type="performance_fix",
+ file_path=target_file,
+ target_symbol=intervention or str(anchor.get("function_name") or target_file),
+ line_start=(
+ anchor.get("line_start") if target_file == anchor["file_path"] else None
+ ),
+ line_end=(anchor.get("line_end") if target_file == anchor["file_path"] else None),
+ plan={
+ "opportunity_id": opportunity.opportunity_id,
+ "strategy": fix.strategy,
+ "safety": fix.safety,
+ "intervention_symbol": intervention,
+ "affected_locations": locations,
+ "affected_locations_total": opportunity.affected_call_sites_total,
+ "paths": paths,
+ "paths_total": opportunity.observations_total,
+ "evidence_truncated": opportunity.evidence_truncated,
+ },
+ evidence={
+ "biomarker_type": opportunity.biomarker_type,
+ "biomarker_types": list(opportunity.biomarker_types),
+ "boundary_kind": opportunity.boundary_kind,
+ "execution_context": opportunity.execution_context,
+ "provenance": opportunity.provenance,
+ "reliable_entry_reachability": opportunity.reliable_entry_reachability,
+ "rank_score": opportunity.rank_score,
+ "rank_factors": opportunity.rank_factors,
+ "rationale": fix.rationale,
+ "observations_total": opportunity.observations_total,
+ "affected_files_total": opportunity.affected_files_total,
+ },
+ # Performance is a separate score dimension and its findings
+ # intentionally carry zero defect-health impact.
+ impact_delta=0.0,
+ effort_bucket=effort_bucket(int(nloc_by_file.get(target_file, 0))),
+ blast_radius={
+ "files": sorted({item["file_path"] for item in opportunity.evidence}),
+ "file_count": opportunity.affected_files_total,
+ "call_sites": opportunity.affected_call_sites_total,
+ },
+ confidence=confidence,
+ source_biomarker=opportunity.biomarker_type,
+ )
+ )
+ return out
+
+
+__all__ = ["performance_fix_suggestions"]
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
index c0e5645ce..32e89a71c 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/split_file.py
@@ -51,6 +51,8 @@ from __future__ import annotations
from collections import Counter, defaultdict
from typing import Any
+from repowise.core.analysis.execution_graph import is_reliable_call_edge
+
from ....test_paths import is_test_related_path
from .models import RefactoringContext, RefactoringSuggestion
from .registry import RefactoringDetector, effort_bucket, register
@@ -452,7 +454,12 @@ class SplitFileDetector(RefactoringDetector):
if owner not in node_set:
continue
for _u, callee, edata in graph.out_edges(sid, data=True):
- if edata.get("edge_type") != "calls" or callee == sid:
+ if (
+ not is_reliable_call_edge(
+ edata.get("edge_type"), edata.get("resolution_origin")
+ )
+ or callee == sid
+ ):
continue
if callee in owner_of:
cowner = owner_of[callee]
@@ -709,7 +716,9 @@ class SplitFileDetector(RefactoringDetector):
dependent_files: set[str] = set()
for sid in defined:
for u, _v, edata in graph.in_edges(sid, data=True):
- if edata.get("edge_type") != "calls":
+ if not is_reliable_call_edge(
+ edata.get("edge_type"), edata.get("resolution_origin")
+ ):
continue
f = graph.nodes.get(u, {}).get("file_path")
if f and f != ctx.file_path:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index 816d41702..4b76cb2b3 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -398,9 +398,7 @@ async def get_deduction_by_path(
return totals
-def sort_metrics_worst_first(
- rows: list[Any], deduction_by_path: dict[str, float]
-) -> list[Any]:
+def sort_metrics_worst_first(rows: list[Any], deduction_by_path: dict[str, float]) -> list[Any]:
"""Order per-file metrics worst-first: ``(score asc, deduction desc, path)``.
``score`` alone cannot rank the band that matters. It clamps at 1.0, so on
@@ -904,6 +902,7 @@ async def upsert_health_findings(
findings: list[Any],
*,
file_paths: list[str],
+ dimension: str | None = None,
) -> None:
"""Replace open findings **only for the given file paths**.
@@ -912,19 +911,36 @@ async def upsert_health_findings(
"""
if not file_paths:
return
- existing = await session.execute(
- select(HealthFinding).where(
- HealthFinding.repository_id == repository_id,
- HealthFinding.status == "open",
- HealthFinding.file_path.in_(file_paths),
- )
- )
+ predicates = [
+ HealthFinding.repository_id == repository_id,
+ HealthFinding.status == "open",
+ HealthFinding.file_path.in_(file_paths),
+ ]
+ if dimension is not None:
+ predicates.append(HealthFinding.dimension == dimension)
+ existing = await session.execute(select(HealthFinding).where(*predicates))
for row in existing.scalars().all():
await session.delete(row)
await session.flush()
- for i in range(0, len(findings), _BATCH_SIZE):
- batch = findings[i : i + _BATCH_SIZE]
+ allowed = set(file_paths)
+ scoped = [
+ finding
+ for finding in findings
+ if (finding.file_path if hasattr(finding, "file_path") else finding.get("file_path"))
+ in allowed
+ and (
+ dimension is None
+ or (
+ getattr(finding, "dimension", None)
+ if hasattr(finding, "dimension")
+ else finding.get("dimension")
+ )
+ == dimension
+ )
+ ]
+ for i in range(0, len(scoped), _BATCH_SIZE):
+ batch = scoped[i : i + _BATCH_SIZE]
for f in batch:
if hasattr(f, "biomarker_type"):
severity = f.severity
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
index 5c55271f2..ae324511c 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py
@@ -81,6 +81,7 @@ async def upsert_refactoring_suggestions(
suggestions: list[Any],
*,
file_paths: list[str],
+ refactoring_type: str | None = None,
) -> None:
"""Replace open suggestions **only for the given file paths**.
@@ -92,18 +93,28 @@ async def upsert_refactoring_suggestions(
if not file_paths:
return
allowed = set(file_paths)
- existing = await session.execute(
- select(RefactoringSuggestion).where(
- RefactoringSuggestion.repository_id == repository_id,
- RefactoringSuggestion.status == "open",
- RefactoringSuggestion.file_path.in_(file_paths),
- )
- )
+ predicates = [
+ RefactoringSuggestion.repository_id == repository_id,
+ RefactoringSuggestion.status == "open",
+ RefactoringSuggestion.file_path.in_(file_paths),
+ ]
+ if refactoring_type is not None:
+ predicates.append(RefactoringSuggestion.refactoring_type == refactoring_type)
+ existing = await session.execute(select(RefactoringSuggestion).where(*predicates))
for row in existing.scalars().all():
await session.delete(row)
await session.flush()
- scoped = [s for s in suggestions if _finding_file_path(s) in allowed]
+ scoped = [
+ s
+ for s in suggestions
+ if _finding_file_path(s) in allowed
+ and (
+ refactoring_type is None
+ or (s.refactoring_type if hasattr(s, "refactoring_type") else s.get("refactoring_type"))
+ == refactoring_type
+ )
+ ]
for i in range(0, len(scoped), _BATCH_SIZE):
batch = scoped[i : i + _BATCH_SIZE]
for s in batch:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 17e99de08..0e44727ee 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -379,6 +379,70 @@ async def load_stored_git_meta(
return None
+async def load_stored_performance_callers(
+ repo_path: Any,
+ changed_paths: set[str],
+ *,
+ log: LogFn | None = None,
+) -> set[str] | None:
+ """Load callers whose persisted performance paths touched changed files.
+
+ The current graph cannot retain an edge to a deleted or renamed symbol.
+ One bounded store read supplies that old-side reverse evidence so partial
+ analysis can remove stale caller findings. ``None`` means the store was
+ unavailable and therefore must not widen authoritative persistence scope.
+ """
+ log = log or _noop_log
+ if not changed_paths:
+ return set()
+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():
+ return None
+ try:
+ import json
+
+ from sqlalchemy import select
+
+ from repowise.core.persistence import create_engine, get_session
+ from repowise.core.persistence.crud import get_repository_by_path
+ from repowise.core.persistence.database import (
+ create_session_factory,
+ resolve_db_url,
+ )
+ from repowise.core.persistence.models import HealthFinding
+
+ engine = create_engine(resolve_db_url(repo_path))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is None:
+ return None
+ rows = (
+ await session.execute(
+ select(HealthFinding.file_path, HealthFinding.details_json).where(
+ HealthFinding.repository_id == repo.id,
+ HealthFinding.status == "open",
+ HealthFinding.dimension == "performance",
+ )
+ )
+ ).all()
+ finally:
+ await engine.dispose()
+ callers: set[str] = set()
+ for file_path, details_json in rows:
+ try:
+ path = json.loads(details_json or "{}").get("path", ())
+ except (TypeError, ValueError, AttributeError):
+ continue
+ if any(
+ isinstance(node, str) and node.split("::", 1)[0] in changed_paths for node in path
+ ):
+ callers.add(file_path)
+ return callers
+ except Exception as exc:
+ log(f"[yellow]Stored performance callers unavailable: {exc}[/yellow]")
+ return None
+
+
async def load_stored_function_mod_p80(repo_path: Any, *, log: LogFn | None = None) -> int | None:
"""Load the repo-wide p80 of per-function modification counts.
@@ -438,6 +502,7 @@ def run_partial_analysis(
*,
source_map: dict[str, bytes] | None = None,
stored_git_meta: dict[str, dict] | None = None,
+ stored_performance_callers: set[str] | None = None,
repo_function_mod_p80: int | None = None,
log: LogFn | None = None,
) -> tuple[Any, Any]:
@@ -449,15 +514,18 @@ def run_partial_analysis(
*source_map* is ingestion's ``{path: raw bytes}`` for this rebuild; the
dead-code prepasses read it instead of re-reading the repo from disk.
- *stored_git_meta* is the persisted per-file git metadata, supplied to the
- dead-code analyzer *only*. ``git_meta_map`` holds this run's freshly
+ *stored_git_meta* is the persisted per-file git metadata. ``git_meta_map`` holds this run's freshly
indexed rows, which on an incremental update means the changed files and
nothing else; every other file would otherwise be scored against an empty
dict and land on the ``commit_count_90d == 0`` rung of the confidence
- ladder at 0.7 / ``safe_to_delete=True``. It is deliberately NOT merged into
- ``git_meta_map`` itself: the partial health analysis reads that map's
- entries as a repo-wide aggregate, so widening it there would silently move
- health scores (the same reason the idle-decay rows are kept out of it).
+ ladder at 0.7 / ``safe_to_delete=True``. It is supplied whole to dead-code
+ and to performance ranking, but deliberately not merged into health's
+ general ``git_meta_map``: widening that aggregate would silently move
+ nonperformance scores (the same reason idle-decay rows stay out of it).
+
+ *stored_performance_callers* is the old-side caller set recovered in one
+ store read. It keeps deletion and rename updates authoritative when the
+ rebuilt graph can no longer contain the removed execution edge.
*repo_function_mod_p80* is the repo-wide 80th percentile of per-function
modification counts, loaded from the persisted ``git_function_blame``
@@ -478,18 +546,37 @@ def run_partial_analysis(
# but only files in ``changed_paths`` produce new findings/metrics.
partial_health_report = None
try:
+ # Performance is interprocedural. Recompute one bounded bidirectional
+ # execution closure so a changed caller can still see an unchanged sink
+ # and an unchanged caller can react to a changed sink. The index is
+ # built once; this is a multi-source walk, not one walk per finding.
+ from repowise.core.analysis.execution_graph import ExecutionGraphIndex
from repowise.core.analysis.health import HealthAnalyzer
from repowise.core.analysis.health.config import HealthConfig
+ _health_changed = {
+ fd.path for fd in file_diffs if fd.status in ("added", "modified", "renamed")
+ }
+ parsed_paths = {pf.file_info.path for pf in parsed_files}
+ execution_index = ExecutionGraphIndex(graph_builder.graph())
+ _performance_changed = execution_index.affected_files(_health_changed) & parsed_paths
+ if stored_performance_callers is not None:
+ historical_callers = stored_performance_callers & parsed_paths
+ _performance_changed |= (
+ execution_index.affected_files(historical_callers) & parsed_paths
+ )
+ _health_scope = _health_changed | _performance_changed
_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,
)
- _health_changed = {fd.path for fd in file_diffs if fd.status in ("added", "modified")}
- if _health_changed:
+ if _health_scope:
_hcfg = HealthConfig.load(repo_path)
_analyzer_config = (
_hcfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])
@@ -498,11 +585,38 @@ def run_partial_analysis(
)
partial_health_report = _health_analyzer.analyze(
_analyzer_config,
- changed_files=_health_changed,
+ changed_files=_health_scope,
repo_function_mod_p80=repo_function_mod_p80,
)
+ # The closure exists only to refresh interprocedural performance.
+ # Preserve the historical changed-file scope for every other
+ # dimension, metric, blame row, and refactoring detector.
+ partial_health_report.authoritative_paths = set(_health_changed)
+ partial_health_report.performance_authoritative_paths = set(_performance_changed)
+ partial_health_report.metrics = [
+ metric
+ for metric in partial_health_report.metrics
+ if metric.file_path in _health_changed
+ ]
+ partial_health_report.findings = [
+ finding
+ for finding in partial_health_report.findings
+ if finding.file_path in _health_changed or finding.dimension == "performance"
+ ]
+ partial_health_report.refactoring_suggestions = [
+ suggestion
+ for suggestion in partial_health_report.refactoring_suggestions
+ if suggestion.file_path in _health_changed
+ or suggestion.refactoring_type == "performance_fix"
+ ]
+ partial_health_report.function_blame_rows = [
+ row
+ for row in partial_health_report.function_blame_rows
+ if row.get("file_path") in _health_changed
+ ]
log(
- f"Health analysis (partial): [cyan]{len(_health_changed)} files[/cyan], "
+ f"Health analysis (partial): [cyan]{len(_health_changed)} changed[/cyan], "
+ f"[cyan]{len(_performance_changed)} performance-affected[/cyan], "
f"[yellow]{len(partial_health_report.findings)} findings[/yellow]"
)
except Exception as exc:
@@ -752,27 +866,51 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Non
upsert_refactoring_suggestions,
)
- changed_paths = sorted({m.file_path for m in report.metrics or []})
- if not changed_paths:
- return
- await upsert_health_metrics(
- session,
- repo_id,
- report.metrics or [],
- analyzed_commit=await _analyzed_commit(session, repo_id),
+ changed_paths = sorted(
+ set(getattr(report, "authoritative_paths", None) or ())
+ or {m.file_path for m in report.metrics or []}
)
- await upsert_health_findings(
- session, repo_id, list(report.findings or []), file_paths=changed_paths
+ performance_paths = sorted(
+ set(getattr(report, "performance_authoritative_paths", None) or ()) - set(changed_paths)
)
+ if not changed_paths and not performance_paths:
+ return
+ if changed_paths:
+ await upsert_health_metrics(
+ session,
+ repo_id,
+ report.metrics or [],
+ analyzed_commit=await _analyzed_commit(session, repo_id),
+ )
+ await upsert_health_findings(
+ session, repo_id, list(report.findings or []), file_paths=changed_paths
+ )
+ if performance_paths:
+ await upsert_health_findings(
+ session,
+ repo_id,
+ list(report.findings or []),
+ file_paths=performance_paths,
+ dimension="performance",
+ )
# Refactoring suggestions for the changed files only (unchanged files keep
# theirs). Scoped delete-then-insert across the full changed-file set, so a
# file that became clean has its stale suggestions removed.
- await upsert_refactoring_suggestions(
- session,
- repo_id,
- list(getattr(report, "refactoring_suggestions", None) or []),
- file_paths=changed_paths,
- )
+ if changed_paths:
+ await upsert_refactoring_suggestions(
+ session,
+ repo_id,
+ list(getattr(report, "refactoring_suggestions", None) or []),
+ file_paths=changed_paths,
+ )
+ if performance_paths:
+ await upsert_refactoring_suggestions(
+ session,
+ repo_id,
+ list(getattr(report, "refactoring_suggestions", None) or []),
+ file_paths=performance_paths,
+ refactoring_type="performance_fix",
+ )
# Per-function blame rollup for the changed files (keeps git_function_blame
# current between full indexes; FULL git tier only — empty otherwise).
fn_blame_rows = getattr(report, "function_blame_rows", None)
@@ -1236,7 +1374,6 @@ async def persist_incremental_index(
repo = await upsert_repository(session, name=repo_path.name, local_path=str(repo_path))
repo_id = repo.id
-
# Delete rows of pages retired since this index was built. This
# path never regenerates a repo-wide page, so nothing else here
# would ever visit one to notice it should be gone, and for a user
@@ -1253,9 +1390,7 @@ async def persist_incremental_index(
# regenerates a cycle page, so asking the rebuilt graph whether
# the cycle still exists is the only way a fixed cycle's page
# can ever be retired for a user who only runs `update`.
- swept_page_ids += await sweep_absent_cycle_pages(
- session, repo_id, graph_builder
- )
+ swept_page_ids += await sweep_absent_cycle_pages(session, repo_id, graph_builder)
except Exception as exc:
_skip("Retired page sweep", exc)
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 36b2fcc3b..139957e6f 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -432,6 +432,7 @@ async def _incremental_repo_update(
from ..pipeline.incremental import (
load_stored_function_mod_p80,
load_stored_git_meta,
+ load_stored_performance_callers,
)
stored_git_meta = await load_stored_git_meta(repo_path, log=_log.info)
@@ -439,6 +440,13 @@ async def _incremental_repo_update(
# pass scores the Function Hotspot gate against the full repo instead of
# this run's changed-files subset (issue #1484).
stored_function_mod_p80 = await load_stored_function_mod_p80(repo_path, log=_log.info)
+ performance_changed_paths = {diff.path for diff in file_diffs}
+ performance_changed_paths.update(
+ diff.old_path for diff in file_diffs if getattr(diff, "old_path", None)
+ )
+ stored_performance_callers = await load_stored_performance_callers(
+ repo_path, performance_changed_paths, log=_log.info
+ )
partial_health_report, dead_code_report = run_partial_analysis(
repo_path,
@@ -448,6 +456,7 @@ async def _incremental_repo_update(
file_diffs,
source_map=source_map,
stored_git_meta=stored_git_meta,
+ stored_performance_callers=stored_performance_callers,
repo_function_mod_p80=stored_function_mod_p80,
log=_log.info,
)
diff --git a/packages/server/src/repowise/server/mcp_server/_graph_utils.py b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
index 34a656738..3d36d96e7 100644
--- a/packages/server/src/repowise/server/mcp_server/_graph_utils.py
+++ b/packages/server/src/repowise/server/mcp_server/_graph_utils.py
@@ -10,11 +10,12 @@ import json
from collections import Counter
from typing import Any
-from repowise.core.analysis.execution_flows import (
- _EXCLUDE_PATH_PATTERNS,
- FlowTermination,
- classify_termination,
+from repowise.core.analysis.execution_flows import FlowTermination, classify_termination
+from repowise.core.analysis.execution_graph import (
+ is_excluded_execution_path,
+ is_walkable_execution_edge,
)
+from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES
from repowise.core.persistence.crud import (
get_graph_edges_for_node,
get_graph_nodes_by_ids,
@@ -29,11 +30,11 @@ def _node_id_is_excluded(node_id: str) -> bool:
"""True if a ``path::Name`` node id lives in a test/demo/fixture path.
Uses the same pattern as the core entry-point scorer so server-side
- traces never wander into test fakes that a mis-resolved call edge points
+ traces never wander into test fakes that a mis-resolved execution edge points
at (e.g. a fake ``fetchall``).
"""
path = node_id.split("::", 1)[0] if "::" in node_id else node_id
- return bool(_EXCLUDE_PATH_PATTERNS.search(path))
+ return is_excluded_execution_path(path)
def parse_community_meta(node: GraphNode) -> dict[str, Any]:
@@ -116,16 +117,18 @@ async def bfs_trace(
repo_id,
current,
direction="callees",
- edge_types=["calls"],
+ edge_types=sorted(EXECUTION_EDGE_TYPES),
limit=_CALLEE_FETCH_LIMIT + 1,
)
edges = rows[:_CALLEE_FETCH_LIMIT]
# Rows arrive most-confident first, so a tail below the floor is
# provably unwalkable and hides nothing: only a cut whose last kept row
# is still walkable leaves a real unknown.
- truncated = len(rows) > _CALLEE_FETCH_LIMIT and (
- edges[-1].confidence or 0.0
- ) >= 0.5
+ truncated = len(rows) > _CALLEE_FETCH_LIMIT and is_walkable_execution_edge(
+ edges[-1].edge_type,
+ edges[-1].resolution_origin,
+ edges[-1].confidence,
+ )
revisited = 0
low_confidence = Counter()
excluded = 0
@@ -136,7 +139,7 @@ async def bfs_trace(
for e in edges:
tid = e.target_node_id
conf = e.confidence if e.confidence is not None else 0.0
- if conf < 0.5:
+ if not is_walkable_execution_edge(e.edge_type, e.resolution_origin, e.confidence):
low_confidence[e.resolution_origin or "unlabelled"] += 1
continue
if _node_id_is_excluded(tid):
@@ -169,9 +172,7 @@ async def bfs_trace(
truncated=truncated,
)
termination["reason"] = reason
- termination["detail"] = (
- dict(low_confidence) if reason == "confidence_filtered" else {}
- )
+ termination["detail"] = dict(low_confidence) if reason == "confidence_filtered" else {}
return trace
@@ -290,10 +291,12 @@ def build_visual_context(
touches_tgt = bool(neighbors & tgt_community_nodes)
if touches_src and touches_tgt:
meta = node_meta.get(node_id)
- bridge_nodes.append({
- "node": node_id,
- "pagerank": meta.pagerank if meta else 0.0,
- })
+ bridge_nodes.append(
+ {
+ "node": node_id,
+ "pagerank": meta.pagerank if meta else 0.0,
+ }
+ )
bridge_nodes.sort(key=lambda x: x["pagerank"], reverse=True)
context["bridge_suggestions"] = bridge_nodes[:5]
else:
@@ -301,8 +304,8 @@ def build_visual_context(
# --- Connectivity summary ---
components = list(nx.weakly_connected_components(graph))
- src_comp = next((c for c in components if source in c), set())
- tgt_comp = next((c for c in components if target in c), set())
+ src_comp: set[Any] = next((c for c in components if source in c), set())
+ tgt_comp: set[Any] = next((c for c in components if target in c), set())
actually_disconnected = src_comp != tgt_comp
if actually_disconnected:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 7e5e41b15..de24c5e51 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -18,6 +18,7 @@ from repowise.core.analysis.health.defect_accuracy import compute_defect_accurac
from repowise.core.analysis.health.grading import HEALTHY_MIN, band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics
+from repowise.core.analysis.health.perf.opportunities import build_performance_opportunities
from repowise.core.analysis.health.scoring import hotspot_health
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.suggestions import suggestion_for
@@ -196,7 +197,9 @@ def _serialize_finding(f: HealthFinding) -> dict[str, Any]:
except Exception:
details = {}
dimension = getattr(f, "dimension", None) or "defect"
- rank = {"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {}
+ rank = (
+ {"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {}
+ )
return {
"biomarker_type": f.biomarker_type,
"severity": f.severity,
@@ -306,6 +309,7 @@ _TRUNCATION_MARKER_HEADROOM = 400
# Dotted entries address one level of nesting; the flat ``result.get(k)`` scan
# would never have found them.
_TRIMMABLE_LISTS = (
+ "performance_opportunities",
"refactoring_plans",
"high_leverage_files",
"worst_files",
@@ -472,9 +476,7 @@ def _serialize_metric(
}
-def _attach_coverage_decay(
- payload: list[dict[str, Any]], rows: list[Any], repo_path: str
-) -> None:
+def _attach_coverage_decay(payload: list[dict[str, Any]], rows: list[Any], repo_path: str) -> None:
"""Add a ``decay`` block to each coverage row, in place.
The stored percentage is a measurement taken at one commit and never
@@ -663,9 +665,7 @@ def _directive(
# which healthy files cushion): per-file shares are then bounded by
# 100% and sum to 100% by construction (issue #1437).
"recovers_points": recovers,
- "share_of_repo_gap_pct": (
- round(100.0 * recovers / gap_points, 1) if gap_points else None
- ),
+ "share_of_repo_gap_pct": (round(100.0 * recovers / gap_points, 1) if gap_points else None),
"then": [m.file_path for m in by_leverage[1:3]],
# Projected, not bare. ``include`` adds a block without subtracting the
# dashboard, and five ranked lists at the default ``limit`` compose: the
@@ -932,7 +932,9 @@ async def get_health(
``findings`` means healthy); it survives any ``only``.
include: ``biomarkers`` | ``refactoring`` | ``trend`` | ``coverage`` |
``accuracy`` | ``signals`` | ``churn_complexity`` |
- ``performance``/``defect``/``maintainability`` (dimension). Only
+ ``performance``/``defect``/``maintainability`` (dimension).
+ ``performance`` also adds the causal ``performance_opportunities``
+ head, while raw findings remain available for line inspection. Only
*adds*, and the ranked lists compose — pair with ``only``, e.g.
``include=['refactoring'], only=['refactoring_plans']``. Over-cap
responses are trimmed (``_meta.truncated_to_fit``).
@@ -974,6 +976,7 @@ async def get_health(
# block that carries findings survives the projection.
wants_findings = wants("findings") or wants("top_findings")
wants_test_findings = wants("test_findings")
+ wants_performance_opportunities = wants("performance_opportunities")
# Everything downstream of the test/production split, in one place.
#
# Keep this list exhaustive. The read it gates is not free (the column list
@@ -1129,6 +1132,14 @@ async def get_health(
]
if "performance" in dimension_filter:
lite_cols.append(HealthFinding.details_json)
+ if wants_performance_opportunities:
+ lite_cols.extend(
+ [
+ HealthFinding.function_name,
+ HealthFinding.line_start,
+ HealthFinding.line_end,
+ ]
+ )
lite_rows = list(
(
await session.execute(
@@ -1707,6 +1718,16 @@ async def get_health(
"recent": recent_kpis(snapshots, limit=10),
}
+ if "performance" in include_set and wants_performance_opportunities:
+ opportunities = build_performance_opportunities(
+ [row for row in lead_rows if _in_dimensions(row, {"performance"})],
+ evidence_limit=8,
+ )
+ result["performance_opportunities"] = [
+ opportunity.as_dict() for opportunity in opportunities[:limit]
+ ]
+ result["performance_opportunities_total"] = len(opportunities)
+
if "coverage" in include_set:
# Drop the bulky covered-lines arrays from dashboard mode; full
# detail is available in targeted mode.
diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.py
index 9f8174543..91eeb5680 100644
--- a/packages/server/src/repowise/server/routers/graph/full_graph.py
+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py
@@ -7,6 +7,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import load_only
+from repowise.core.analysis.execution_graph import is_walkable_execution_edge
from repowise.core.persistence import crud
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like
@@ -61,7 +62,7 @@ def _flow_member_ids(
"""
adjacency: dict[str, list[GraphEdge]] = {}
for e in edges:
- if e.edge_type == "calls":
+ if is_walkable_execution_edge(e.edge_type, e.resolution_origin, e.confidence):
adjacency.setdefault(e.source_node_id, []).append(e)
members: set[str] = set()
@@ -74,7 +75,7 @@ def _flow_member_ids(
for e in adjacency.get(current, ()):
tid = e.target_node_id
conf = e.confidence if e.confidence is not None else 0.0
- if tid in visited or conf < 0.5 or _node_id_is_excluded(tid):
+ if tid in visited or _node_id_is_excluded(tid):
continue
if conf > best_conf:
best_conf = conf
diff --git a/tests/unit/analysis/test_execution_flows.py b/tests/unit/analysis/test_execution_flows.py
index e09d69bf5..ded77d4af 100644
--- a/tests/unit/analysis/test_execution_flows.py
+++ b/tests/unit/analysis/test_execution_flows.py
@@ -82,6 +82,33 @@ def test_trace_skips_test_nodes():
assert not any("tests/" in node for node in flow.trace)
+def test_trace_uses_dispatch_edges_and_rejects_unreliable_origins():
+ graph = _chain_graph()
+ graph.remove_edge("src/app.py::a", "src/app.py::b")
+ graph.add_edge(
+ "src/app.py::a",
+ "src/app.py::b",
+ edge_type="dispatches_to",
+ confidence=0.9,
+ resolution_origin="framework",
+ )
+ graph.add_edge(
+ "src/app.py::a",
+ "src/app.py::c",
+ edge_type="calls",
+ confidence=1.0,
+ resolution_origin="global_unique",
+ )
+ report = trace_execution_flows(graph, {}, FlowConfig(min_flow_depth=1))
+ main_flow = next(flow for flow in report.flows if flow.entry_point_id == "src/app.py::main")
+ assert main_flow.trace[:4] == [
+ "src/app.py::main",
+ "src/app.py::a",
+ "src/app.py::b",
+ "src/app.py::c",
+ ]
+
+
def test_min_flow_depth_filters_trivial_flows():
"""A lone single-call entry point is not reported as a flow by default."""
g = nx.DiGraph()
diff --git a/tests/unit/analysis/test_execution_graph.py b/tests/unit/analysis/test_execution_graph.py
index a4297cbe9..ba8abfa90 100644
--- a/tests/unit/analysis/test_execution_graph.py
+++ b/tests/unit/analysis/test_execution_graph.py
@@ -102,3 +102,49 @@ def test_refreshed_caller_does_not_fallback_for_an_unresolved_call_site():
(),
"call-site",
)
+
+
+def test_affected_files_covers_changed_caller_and_changed_sink_in_one_bounded_walk():
+ graph = nx.DiGraph()
+ for path, name in (("caller.py", "run"), ("helper.py", "load"), ("sink.py", "fetch")):
+ sid = f"{path}::{name}"
+ _symbol(graph, sid, path, name, 1, 10)
+ graph.add_edge(path, sid, edge_type="defines")
+ graph.add_edge("caller.py::run", "helper.py::load", edge_type="calls", confidence=0.9)
+ graph.add_edge("helper.py::load", "sink.py::fetch", edge_type="dispatches_to", confidence=0.9)
+ index = ExecutionGraphIndex(graph)
+
+ assert index.affected_files({"caller.py"}) == {"caller.py", "helper.py", "sink.py"}
+ assert index.affected_files({"sink.py"}) == {"caller.py", "helper.py", "sink.py"}
+
+
+def test_affected_files_does_not_cross_unreliable_edges():
+ graph = nx.DiGraph()
+ for path, name in (("caller.py", "run"), ("sink.py", "fetch")):
+ sid = f"{path}::{name}"
+ _symbol(graph, sid, path, name, 1, 10)
+ graph.add_edge(path, sid, edge_type="defines")
+ graph.add_edge(
+ "caller.py::run",
+ "sink.py::fetch",
+ edge_type="calls",
+ confidence=0.9,
+ resolution_origin="global_unique",
+ )
+ assert ExecutionGraphIndex(graph).affected_files({"sink.py"}) == {"sink.py"}
+
+
+def test_affected_files_changed_caller_includes_siblings_of_reached_sink():
+ graph = nx.DiGraph()
+ for path in ("a.py", "b.py", "sink.py"):
+ sid = f"{path}::run"
+ _symbol(graph, sid, path, "run", 1, 10)
+ graph.add_edge(path, sid, edge_type="defines")
+ graph.add_edge("a.py::run", "sink.py::run", edge_type="calls", confidence=0.9)
+ graph.add_edge("b.py::run", "sink.py::run", edge_type="calls", confidence=0.9)
+
+ assert ExecutionGraphIndex(graph).affected_files({"a.py"}) == {
+ "a.py",
+ "b.py",
+ "sink.py",
+ }
diff --git a/tests/unit/health/test_perf_incremental_parity.py b/tests/unit/health/test_perf_incremental_parity.py
new file mode 100644
index 000000000..eee8f561a
--- /dev/null
+++ b/tests/unit/health/test_perf_incremental_parity.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import json
+import uuid
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.execution_graph import ExecutionGraphIndex
+from repowise.core.analysis.health import HealthAnalyzer
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.persistence.database import create_engine, create_session_factory, init_db
+from repowise.core.persistence.models import HealthFinding
+from repowise.core.pipeline.incremental import load_stored_performance_callers
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _repo(tmp_path: Path):
+ files = {
+ "db.py": (
+ "from sqlalchemy import select\n\n"
+ "def fetch_one(session, rid):\n"
+ " return session.execute(select(rid))\n"
+ ),
+ "service.py": (
+ "from db import fetch_one\n\n"
+ "def fetch_all(session, ids):\n"
+ " for rid in ids:\n"
+ " fetch_one(session, rid)\n"
+ ),
+ "service_b.py": (
+ "from db import fetch_one\n\n"
+ "def fetch_more(session, ids):\n"
+ " for rid in ids:\n"
+ " fetch_one(session, rid)\n"
+ ),
+ "unrelated.py": "def pure(value):\n return value + 1\n",
+ }
+ for name, source in files.items():
+ (tmp_path / name).write_text(source, encoding="utf-8")
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ parsed = []
+ for info in FileTraverser(tmp_path).traverse():
+ item = parser.parse_file(info, Path(info.abs_path).read_bytes())
+ builder.add_file(item)
+ parsed.append(item)
+ return parsed, builder.build()
+
+
+def _performance_signature(report):
+ return sorted(
+ (
+ finding.file_path,
+ finding.biomarker_type,
+ finding.line_start,
+ finding.details.get("opportunity_id"),
+ tuple(finding.details.get("path", ())),
+ )
+ for finding in report.findings
+ if finding.dimension == "performance"
+ )
+
+
[email protected]("changed_file", ["service.py", "db.py"])
+def test_changed_caller_and_changed_sink_match_full_performance_analysis(
+ tmp_path: Path, changed_file: str
+):
+ parsed, graph = _repo(tmp_path)
+ full = HealthAnalyzer(graph, parsed_files=parsed, repo_root=tmp_path).analyze()
+ scope = ExecutionGraphIndex(graph).affected_files({changed_file})
+ partial = HealthAnalyzer(graph, parsed_files=parsed, repo_root=tmp_path).analyze(
+ changed_files=scope
+ )
+
+ assert scope == {"service.py", "service_b.py", "db.py"}
+ assert _performance_signature(partial) == _performance_signature(full)
+ full_plans = [
+ suggestion.plan
+ for suggestion in full.refactoring_suggestions
+ if suggestion.refactoring_type == "performance_fix"
+ ]
+ partial_plans = [
+ suggestion.plan
+ for suggestion in partial.refactoring_suggestions
+ if suggestion.refactoring_type == "performance_fix"
+ ]
+ assert partial_plans == full_plans
+
+
+async def test_old_side_performance_paths_recover_callers_of_deleted_sink(tmp_path: Path):
+ (tmp_path / ".repowise").mkdir()
+ db_path = (tmp_path / ".repowise" / "wiki.db").as_posix()
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path}")
+ await init_db(engine)
+ factory = create_session_factory(engine)
+ async with factory() as session:
+ repo = await insert_repo(session, local_path=str(tmp_path))
+ session.add(
+ HealthFinding(
+ id=uuid.uuid4().hex,
+ repository_id=repo.id,
+ file_path="caller.py",
+ biomarker_type="io_in_loop",
+ severity="medium",
+ function_name="run",
+ line_start=4,
+ line_end=4,
+ details_json=json.dumps(
+ {
+ "cross_function": True,
+ "boundary_kind": "db",
+ "path": ["caller.py::run", "deleted.py::fetch"],
+ }
+ ),
+ health_impact=0.0,
+ reason="old N+1",
+ dimension="performance",
+ status="open",
+ )
+ )
+ await session.commit()
+
+ assert await load_stored_performance_callers(tmp_path, {"deleted.py"}) == {"caller.py"}
+ await engine.dispose()
diff --git a/tests/unit/health/test_perf_opportunities.py b/tests/unit/health/test_perf_opportunities.py
new file mode 100644
index 000000000..17a5e1cf5
--- /dev/null
+++ b/tests/unit/health/test_perf_opportunities.py
@@ -0,0 +1,232 @@
+from __future__ import annotations
+
+from repowise.core.analysis.health.models import HealthFindingData, Severity
+from repowise.core.analysis.health.perf.opportunities import (
+ build_performance_opportunities,
+ link_performance_findings,
+)
+from repowise.core.analysis.health.refactoring.performance_fix import (
+ performance_fix_suggestions,
+)
+
+
+def _finding(
+ path: str,
+ line: int,
+ *,
+ marker: str = "io_in_loop",
+ boundary: str = "db",
+ call_path: tuple[str, ...] = (),
+ **details: object,
+) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type=marker,
+ severity=Severity.MEDIUM,
+ file_path=path,
+ function_name="run",
+ line_start=line,
+ line_end=line,
+ details={
+ "boundary_kind": boundary,
+ "cross_function": bool(call_path),
+ "path": list(call_path),
+ **details,
+ },
+ health_impact=0.0,
+ dimension="performance",
+ )
+
+
+def test_shared_sink_groups_once_links_raw_rows_and_selects_lowest_shared_intervention():
+ rows = [
+ _finding("a.py", 10, call_path=("a.py::run", "shared.py::load", "git.py::head")),
+ _finding("b.py", 20, call_path=("b.py::run", "shared.py::load", "git.py::head")),
+ ]
+
+ link_performance_findings(rows)
+ opportunities = build_performance_opportunities(rows)
+
+ assert len(opportunities) == 1
+ opportunity = opportunities[0]
+ assert opportunity.observations_total == 2
+ assert opportunity.affected_call_sites_total == 2
+ assert opportunity.affected_files_total == 2
+ assert opportunity.shared_path_suffix == ("shared.py::load", "git.py::head")
+ assert opportunity.intervention_symbol == "shared.py::load"
+ assert {row.details["opportunity_id"] for row in rows} == {opportunity.opportunity_id}
+
+
+def test_grouping_and_order_are_input_order_independent():
+ rows = [
+ _finding("z.py", 4, marker="string_concat_in_loop", boundary=""),
+ _finding("a.py", 2, call_path=("a.py::run", "db.py::fetch")),
+ _finding("b.py", 3, call_path=("b.py::run", "db.py::fetch")),
+ ]
+ forward = build_performance_opportunities(rows)
+ reverse = build_performance_opportunities(list(reversed(rows)))
+ assert [item.as_dict() for item in forward] == [item.as_dict() for item in reverse]
+
+
+def test_cross_function_id_survives_new_caller_and_stronger_multiplier_observation():
+ first = _finding("a.py", 2, call_path=("a.py::run", "db.py::fetch"))
+ original = build_performance_opportunities([first])[0]
+ added = _finding(
+ "b.py",
+ 3,
+ marker="nested_loop_with_io",
+ call_path=("b.py::run", "db.py::fetch"),
+ )
+ expanded = build_performance_opportunities([added, first])[0]
+ assert expanded.opportunity_id == original.opportunity_id
+ assert expanded.biomarker_types == ("io_in_loop", "nested_loop_with_io")
+ assert expanded.observations_total == 2
+
+
+def test_capped_evidence_retains_true_totals():
+ rows = [
+ _finding(f"caller_{index}.py", index, call_path=(f"caller_{index}.py::run", "db.py::fetch"))
+ for index in range(1, 7)
+ ]
+ opportunity = build_performance_opportunities(rows, evidence_limit=2)[0]
+ assert len(opportunity.evidence) == 2
+ assert opportunity.evidence_truncated is True
+ assert opportunity.observations_total == 6
+ assert opportunity.affected_call_sites_total == 6
+ assert opportunity.affected_files_total == 6
+
+
+def test_strategy_preconditions_distinguish_proven_advisory_and_no_plan():
+ verified = build_performance_opportunities(
+ [
+ _finding(
+ "async.py",
+ 5,
+ marker="serial_await_in_loop",
+ boundary="network",
+ dataflow_verified=True,
+ )
+ ]
+ )[0]
+ ambiguous = build_performance_opportunities(
+ [_finding("async.py", 6, marker="serial_await_in_loop", boundary="network")]
+ )[0]
+ batching = build_performance_opportunities(
+ [_finding("db.py", 7, call_path=("db.py::run", "db.py::fetch"))]
+ )[0]
+ filesystem = build_performance_opportunities(
+ [
+ _finding(
+ "fs.py",
+ 8,
+ boundary="filesystem",
+ call_path=("fs.py::run", "fs.py::read"),
+ )
+ ]
+ )[0]
+
+ assert verified.fix and verified.fix.strategy == "parallelize_independent_awaits"
+ assert verified.fix.safety == "proven"
+ assert ambiguous.fix is None
+ assert batching.fix and batching.fix.strategy == "batch_or_prefetch_io"
+ assert batching.fix.safety == "advisory"
+ assert filesystem.fix is None
+
+ membership = build_performance_opportunities(
+ [_finding("lookup.py", 9, marker="membership_test_against_list_in_loop", boundary="")]
+ )[0]
+ concat = build_performance_opportunities(
+ [_finding("text.py", 10, marker="string_concat_in_loop", boundary="")]
+ )[0]
+ assert membership.fix and membership.fix.safety == "advisory"
+ assert concat.fix and concat.fix.safety == "advisory"
+
+
+def test_generic_sink_without_shared_caller_stays_advisory_without_a_plan():
+ opportunity = build_performance_opportunities(
+ [
+ _finding("a.py", 2, call_path=("a.py::run", "db.py::get_session")),
+ _finding("b.py", 3, call_path=("b.py::run", "db.py::get_session")),
+ ]
+ )[0]
+
+ assert opportunity.shared_path_suffix == ("db.py::get_session",)
+ assert opportunity.fix is None
+
+
+def test_incompatible_cross_function_cost_shapes_never_share_a_fix():
+ rows = [
+ _finding("loop.py", 2, call_path=("loop.py::run", "db.py::fetch")),
+ _finding(
+ "lock.py",
+ 3,
+ marker="blocking_io_under_lock",
+ call_path=("lock.py::critical", "db.py::fetch"),
+ ),
+ ]
+
+ opportunities = build_performance_opportunities(rows)
+ assert len(opportunities) == 2
+ assert {item.biomarker_type for item in opportunities} == {
+ "io_in_loop",
+ "blocking_io_under_lock",
+ }
+
+
+def test_lock_fix_targets_the_single_lock_owner_not_the_shared_sink():
+ opportunity = build_performance_opportunities(
+ [
+ _finding(
+ "lock.py",
+ 3,
+ marker="blocking_io_under_lock",
+ call_path=("lock.py::critical", "db.py::fetch"),
+ )
+ ]
+ )[0]
+ plan = performance_fix_suggestions([opportunity])[0]
+
+ assert plan.plan["strategy"] == "shrink_lock_scope"
+ assert plan.target_symbol == "lock.py::critical"
+
+
+def test_distinct_lock_owners_sharing_a_sink_do_not_claim_one_lock_fix():
+ opportunity = build_performance_opportunities(
+ [
+ _finding(
+ "a.py",
+ 3,
+ marker="blocking_io_under_lock",
+ call_path=("a.py::critical", "db.py::fetch"),
+ ),
+ _finding(
+ "b.py",
+ 4,
+ marker="blocking_io_under_lock",
+ call_path=("b.py::critical", "db.py::fetch"),
+ ),
+ ]
+ )[0]
+
+ assert opportunity.fix is None
+
+
+def test_performance_fix_plan_carries_closed_strategy_and_true_totals():
+ opportunity = build_performance_opportunities(
+ [
+ _finding("a.py", 10, call_path=("a.py::run", "shared.py::load", "db.py::fetch")),
+ _finding("b.py", 20, call_path=("b.py::run", "shared.py::load", "db.py::fetch")),
+ ],
+ evidence_limit=1,
+ )[0]
+ plans = performance_fix_suggestions([opportunity], nloc_by_file={"shared.py": 80})
+ assert len(plans) == 1
+ plan = plans[0]
+ assert plan.refactoring_type == "performance_fix"
+ assert plan.file_path == "shared.py"
+ assert plan.target_symbol == "shared.py::load"
+ assert plan.plan["strategy"] == "batch_or_prefetch_io"
+ assert plan.plan["safety"] == "advisory"
+ assert plan.plan["affected_locations_total"] == 2
+ assert plan.plan["paths_total"] == 2
+ assert plan.plan["evidence_truncated"] is True
+ assert performance_fix_suggestions([opportunity], min_confidence="high") == []
diff --git a/tests/unit/health/test_refactoring_move_method.py b/tests/unit/health/test_refactoring_move_method.py
index 773395784..c8143623c 100644
--- a/tests/unit/health/test_refactoring_move_method.py
+++ b/tests/unit/health/test_refactoring_move_method.py
@@ -81,6 +81,22 @@ def test_feature_envy_suggests_move_to_target_class():
assert s.confidence == "high"
+def test_unreliable_calls_cannot_prove_feature_envy():
+ graph = _envy_graph()
+ for _source, _target, data in graph.edges(data=True):
+ if data.get("edge_type") == "calls":
+ data["resolution_origin"] = "global_unique"
+ assert _detect(graph, "c.py") == []
+
+
+def test_noncall_execution_edges_cannot_prove_feature_envy():
+ graph = _envy_graph()
+ for _source, _target, data in graph.edges(data=True):
+ if data.get("edge_type") == "calls":
+ data["edge_type"] = "dispatches_to"
+ assert _detect(graph, "c.py") == []
+
+
def test_method_that_uses_its_own_class_is_not_envious():
g = _envy_graph()
# envious now also calls 2 of its own class's members → no longer clearly
diff --git a/tests/unit/health/test_refactoring_split_file.py b/tests/unit/health/test_refactoring_split_file.py
index fd2f00c2c..214f71ffd 100644
--- a/tests/unit/health/test_refactoring_split_file.py
+++ b/tests/unit/health/test_refactoring_split_file.py
@@ -240,6 +240,26 @@ def test_blast_radius_lists_external_referrers():
assert br["import_rewrites"] == br["dependent_count"] # python → shim language
+def test_blast_radius_does_not_count_noncall_execution_edges_as_callers():
+ g = _two_cluster_graph()
+ g.add_node(
+ "framework.py::binding",
+ node_type="symbol",
+ kind="function",
+ name="binding",
+ file_path="framework.py",
+ )
+ g.add_edge(
+ "framework.py::binding",
+ "big.py::alpha_0",
+ edge_type="framework_binds",
+ resolution_origin="framework",
+ )
+
+ plan = _detect(g, "big.py")[0]
+ assert "framework.py" not in plan.blast_radius["dependent_files"]
+
+
def test_go_split_needs_no_import_rewrites():
out = _detect(_two_cluster_graph("pkg/big.go"), "pkg/big.go", language="go")
assert len(out) == 1
diff --git a/tests/unit/persistence/test_health_dimensions_crud.py b/tests/unit/persistence/test_health_dimensions_crud.py
index 5f0839a7e..77ff721b1 100644
--- a/tests/unit/persistence/test_health_dimensions_crud.py
+++ b/tests/unit/persistence/test_health_dimensions_crud.py
@@ -19,6 +19,7 @@ from repowise.core.persistence.crud.analysis import (
get_health_metrics,
save_health_findings,
save_health_metrics,
+ upsert_health_findings,
upsert_health_metrics,
)
from tests.unit.persistence.helpers import insert_repo
@@ -121,6 +122,60 @@ async def test_save_health_findings_persists_dimension(async_session):
assert by_type["change_entropy"].dimension == "defect"
+async def test_dimension_scoped_upsert_preserves_other_findings(async_session):
+ repo = await insert_repo(async_session)
+ base = [
+ HealthFindingData(
+ biomarker_type="change_entropy",
+ severity=Severity.HIGH,
+ file_path="a.py",
+ function_name=None,
+ line_start=1,
+ line_end=1,
+ details={},
+ health_impact=1.0,
+ dimension="defect",
+ ),
+ HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path="a.py",
+ function_name="run",
+ line_start=2,
+ line_end=2,
+ details={"opportunity_id": "old"},
+ health_impact=0.0,
+ dimension="performance",
+ ),
+ ]
+ await save_health_findings(async_session, repo.id, base)
+ replacement = HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity=Severity.MEDIUM,
+ file_path="a.py",
+ function_name="run",
+ line_start=3,
+ line_end=3,
+ details={"opportunity_id": "new"},
+ health_impact=0.0,
+ dimension="performance",
+ )
+ await upsert_health_findings(
+ async_session,
+ repo.id,
+ [replacement],
+ file_paths=["a.py"],
+ dimension="performance",
+ )
+ await async_session.commit()
+ rows = await get_health_findings(async_session, repo.id)
+ assert {(row.biomarker_type, row.line_start) for row in rows} == {
+ ("change_entropy", 1),
+ ("io_in_loop", 3),
+ }
+
+
@pytest.mark.asyncio
async def test_get_health_findings_accepts_comma_separated_biomarker_types(async_session):
"""One request can pull several biomarker types (the panels batch this way);
@@ -155,7 +210,5 @@ async def test_get_health_findings_accepts_comma_separated_biomarker_types(async
}
# Single value still behaves as an exact match.
- single = await get_health_findings(
- async_session, repo.id, biomarker_type="change_entropy"
- )
+ single = await get_health_findings(async_session, repo.id, biomarker_type="change_entropy")
assert {r.biomarker_type for r in single} == {"change_entropy"}
diff --git a/tests/unit/persistence/test_refactoring_suggestions_crud.py b/tests/unit/persistence/test_refactoring_suggestions_crud.py
index 2ec5143af..ba41b8e39 100644
--- a/tests/unit/persistence/test_refactoring_suggestions_crud.py
+++ b/tests/unit/persistence/test_refactoring_suggestions_crud.py
@@ -7,6 +7,8 @@ columns, so a future edit that forgets a field is caught.
from __future__ import annotations
+from types import SimpleNamespace
+
import pytest
from repowise.core.analysis.health.refactoring import RefactoringSuggestion
@@ -131,3 +133,64 @@ async def test_upsert_only_touches_given_files(async_session):
await async_session.commit()
rows = await get_refactoring_suggestions(async_session, repo.id)
assert [r.target_symbol for r in rows] == ["Bar"]
+
+
+async def test_type_scoped_upsert_preserves_nonperformance_plans(async_session):
+ repo = await insert_repo(async_session)
+ performance = _suggestion(
+ "a.py",
+ "a.py::fetch",
+ refactoring_type="performance_fix",
+ source_biomarker="io_in_loop",
+ plan={"strategy": "batch_or_prefetch_io"},
+ )
+ await save_refactoring_suggestions(
+ async_session,
+ repo.id,
+ [_suggestion("a.py", "Foo"), performance],
+ )
+ await upsert_refactoring_suggestions(
+ async_session,
+ repo.id,
+ [],
+ file_paths=["a.py"],
+ refactoring_type="performance_fix",
+ )
+ await async_session.commit()
+ rows = await get_refactoring_suggestions(async_session, repo.id)
+ assert [(row.refactoring_type, row.target_symbol) for row in rows] == [("extract_class", "Foo")]
+
+
+async def test_performance_only_partial_scope_clears_stale_plan(async_session):
+ from repowise.core.pipeline.incremental import persist_partial_health
+
+ repo = await insert_repo(async_session)
+ await save_refactoring_suggestions(
+ async_session,
+ repo.id,
+ [
+ _suggestion("caller.py", "Foo"),
+ _suggestion(
+ "caller.py",
+ "caller.py::run",
+ refactoring_type="performance_fix",
+ source_biomarker="io_in_loop",
+ ),
+ ],
+ )
+ report = SimpleNamespace(
+ authoritative_paths=set(),
+ performance_authoritative_paths={"caller.py"},
+ metrics=[],
+ findings=[],
+ refactoring_suggestions=[],
+ function_blame_rows=[],
+ )
+
+ await persist_partial_health(async_session, repo.id, report)
+ await async_session.commit()
+
+ rows = await get_refactoring_suggestions(async_session, repo.id)
+ assert [(row.refactoring_type, row.target_symbol) for row in rows] == [("extract_class", "Foo")]
diff --git a/tests/unit/server/mcp/test_perf_rank.py b/tests/unit/server/mcp/test_perf_rank.py
index 9af6a796e..a2da3967a 100644
--- a/tests/unit/server/mcp/test_perf_rank.py
+++ b/tests/unit/server/mcp/test_perf_rank.py
@@ -38,7 +38,9 @@ def test_every_performance_biomarker_carries_a_weight() -> None:
below ``string_concat_in_loop`` and nobody would see it. This is the
mechanism that makes adding one loud.
"""
- registered = {b.name for b in registered_biomarkers() if getattr(b, "category", "") == "performance"}
+ registered = {
+ b.name for b in registered_biomarkers() if getattr(b, "category", "") == "performance"
+ }
assert registered, "no performance detectors registered — the check is vacuous"
assert registered <= set(_PERF_MARKER_POINTS), (
f"unweighted performance biomarkers: {sorted(registered - set(_PERF_MARKER_POINTS))}"
@@ -252,6 +254,58 @@ async def test_perf_rank_is_absent_from_every_other_dimension(setup_mcp, perf_fi
assert all("perf_rank" in f for f in by_dim["performance"])
+async def test_narrow_projection_leads_with_one_shared_causal_opportunity(
+ setup_mcp, perf_findings, session
+):
+ import json
+
+ from repowise.core.persistence.models import HealthFinding
+ from repowise.server.mcp_server import get_health
+
+ for index, caller in enumerate(("src/a.py", "src/b.py"), start=10):
+ session.add(
+ HealthFinding(
+ id=str(uuid.uuid4()),
+ repository_id=perf_findings,
+ file_path=caller,
+ biomarker_type="io_in_loop",
+ severity="medium",
+ function_name="run",
+ line_start=index,
+ line_end=index,
+ details_json=json.dumps(
+ {
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": [f"{caller}::run", "src/shared.py::load", "src/db.py::fetch"],
+ "resolution_basis": "call-site",
+ }
+ ),
+ health_impact=0.0,
+ reason="shared N+1",
+ dimension="performance",
+ status="open",
+ )
+ )
+ await session.flush()
+
+ result = await get_health(include=["performance"], only=["performance_opportunities"], limit=50)
+ shared = [
+ item
+ for item in result["performance_opportunities"]
+ if item["terminal_sink"] == "src/db.py::fetch"
+ ]
+ assert len(shared) == 1
+ assert shared[0]["intervention_symbol"] == "src/shared.py::load"
+ assert shared[0]["affected_call_sites_total"] == 2
+ assert shared[0]["observations_total"] == 2
+ assert {item["line_start"] for item in shared[0]["evidence"]} == {10, 11}
+ assert {item["function_name"] for item in shared[0]["evidence"]} == {"run"}
+ assert result["performance_opportunities_total"] >= 1
+ assert "top_findings" not in result
+
+
@pytest.mark.asyncio
async def test_the_default_dashboard_does_not_pay_for_the_ranking_read(
setup_mcp, perf_findings, monkeypatch
diff --git a/tests/unit/server/test_graph_flow_policy.py b/tests/unit/server/test_graph_flow_policy.py
new file mode 100644
index 000000000..570615fa9
--- /dev/null
+++ b/tests/unit/server/test_graph_flow_policy.py
@@ -0,0 +1,37 @@
+from types import SimpleNamespace
+
+from repowise.server.routers.graph.full_graph import _flow_member_ids
+
+
+def _edge(source: str, target: str, edge_type: str, **attrs):
+ return SimpleNamespace(
+ source_node_id=source,
+ target_node_id=target,
+ edge_type=edge_type,
+ confidence=attrs.get("confidence", 0.9),
+ resolution_origin=attrs.get("resolution_origin"),
+ )
+
+
+def test_export_flow_reservation_uses_the_shared_execution_policy():
+ edges = [
+ _edge("src/a.py::run", "src/b.py::base", "calls"),
+ _edge(
+ "src/b.py::base",
+ "src/c.py::impl",
+ "dispatches_to",
+ resolution_origin="framework",
+ ),
+ _edge(
+ "src/b.py::base",
+ "src/guess.py::wrong",
+ "calls",
+ confidence=1.0,
+ resolution_origin="global_unique",
+ ),
+ ]
+ assert _flow_member_ids(edges, ["src/a.py::run"]) == {
+ "src/a.py",
+ "src/b.py",
+ "src/c.py",
+ }